repo
stringclasses 1
value | test_patch
stringlengths 335
66.3k
| issue_numbers
listlengths 1
2
| version
stringclasses 9
values | base_commit
stringlengths 40
40
| problem_statement
stringlengths 33
13k
| instance_id
stringlengths 24
25
| pull_number
int64 183
1.64k
| patch
stringlengths 448
420k
| hints_text
stringlengths 0
64.4k
| created_at
stringlengths 20
20
| environment_setup_commit
stringclasses 10
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
asterinas/asterinas
|
diff --git /dev/null b/test/apps/pthread/pthread_signal_test.c
new file mode 100644
--- /dev/null
+++ b/test/apps/pthread/pthread_signal_test.c
@@ -0,0 +1,109 @@
+// SPDX-License-Identifier: MPL-2.0
+// A regression test for the futex lost wakeup bug fixed in https://github.com/asterinas/asterinas/pull/1642
+
+#include <pthread.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <signal.h>
+#include <stdatomic.h>
+
+pthread_mutex_t mutex;
+atomic_int sync_flag = ATOMIC_VAR_INIT(0); // Atomic flag for synchronization
+
+// Signal handler for SIGUSR1
+void signal_handler(int signum)
+{
+ atomic_store(&sync_flag, 2);
+}
+
+// Thread function that tries to lock the mutex and waits if it is locked
+void *thread_function(void *arg)
+{
+ printf("Thread: Trying to lock mutex...\n");
+
+ // Set the atomic flag to signal the main thread
+ atomic_store(&sync_flag, 1);
+
+ // Try to lock the mutex
+ pthread_mutex_lock(&mutex);
+ printf("Thread: Got the mutex!\n");
+
+ printf("Thread: Exiting.\n");
+ pthread_mutex_unlock(&mutex);
+
+ // Set the atomic flag to signal the main thread
+ atomic_store(&sync_flag, 3);
+ return NULL;
+}
+
+int main()
+{
+ pthread_t thread;
+
+ // Initialize mutex
+ if (pthread_mutex_init(&mutex, NULL) != 0) {
+ perror("Mutex initialization failed");
+ return -1;
+ }
+
+ // Set up signal handler for SIGUSR1
+ struct sigaction sa;
+ sa.sa_handler = signal_handler;
+ sa.sa_flags = 0;
+ sigemptyset(&sa.sa_mask);
+ if (sigaction(SIGUSR1, &sa, NULL) == -1) {
+ perror("sigaction failed");
+ return -1;
+ }
+
+ // Main thread locks the mutex
+ pthread_mutex_lock(&mutex);
+ printf("Main thread: Mutex locked.\n");
+
+ // Create the second thread
+ if (pthread_create(&thread, NULL, thread_function, NULL) != 0) {
+ perror("Thread creation failed");
+ return -1;
+ }
+
+ // Detach the thread to allow it to run independently
+ if (pthread_detach(thread) != 0) {
+ perror("Thread detachment failed");
+ return -1;
+ }
+
+ // Wait for the second thread to prepare
+ while (atomic_load(&sync_flag) != 1) {
+ }
+ sleep(1);
+
+ // Send signal to the second thread
+ pthread_kill(thread, SIGUSR1);
+ printf("Main thread: Signal sent to the thread.\n");
+
+ // Wait for the second thread to process signal
+ while (atomic_load(&sync_flag) != 2) {
+ }
+ sleep(1);
+
+ // Unlock the mutex
+ pthread_mutex_unlock(&mutex);
+ printf("Main thread: Mutex unlocked.\n");
+
+ // Wait for the second thread to exit
+ int count = 3;
+ while (atomic_load(&sync_flag) != 3 && count--) {
+ sleep(1);
+ }
+ if (atomic_load(&sync_flag) != 3) {
+ printf("ERROR: Thread does not exit after timeout.\n");
+ exit(EXIT_FAILURE);
+ }
+
+ // Destroy mutex
+ pthread_mutex_destroy(&mutex);
+
+ printf("All tests passed.\n");
+ return 0;
+}
|
[
"1587"
] |
0.9
|
9da6af03943c15456cdfd781021820a7da78ea40
|
`futex_wait_bitset()` should remove `futex_item` when `pause_timeout()` fails
### Describe the bug
1. When signaled or timeout, the `futex_item` is not removed from the `futex_bucket`, which can lead to lost-wakeup.
2. `waiter.pause_timeout()` returns `Ok(())` upon waking up from a signal, which can lead to incorrect handling of the wake-up event.
https://github.com/asterinas/asterinas/blob/11382524d1d23cc6d41adf977a72138baa39e38d/kernel/src/process/posix_thread/futex.rs#L76
|
asterinas__asterinas-1642
| 1,642
|
diff --git a/kernel/src/process/posix_thread/futex.rs b/kernel/src/process/posix_thread/futex.rs
--- a/kernel/src/process/posix_thread/futex.rs
+++ b/kernel/src/process/posix_thread/futex.rs
@@ -253,7 +253,9 @@ impl FutexBucket {
}
let item = item_cursor.remove().unwrap();
- item.wake();
+ if !item.wake() {
+ continue;
+ }
count += 1;
}
diff --git a/kernel/src/process/posix_thread/futex.rs b/kernel/src/process/posix_thread/futex.rs
--- a/kernel/src/process/posix_thread/futex.rs
+++ b/kernel/src/process/posix_thread/futex.rs
@@ -253,7 +253,9 @@ impl FutexBucket {
}
let item = item_cursor.remove().unwrap();
- item.wake();
+ if !item.wake() {
+ continue;
+ }
count += 1;
}
diff --git a/kernel/src/process/posix_thread/futex.rs b/kernel/src/process/posix_thread/futex.rs
--- a/kernel/src/process/posix_thread/futex.rs
+++ b/kernel/src/process/posix_thread/futex.rs
@@ -323,8 +325,9 @@ impl FutexItem {
(futex_item, waiter)
}
- pub fn wake(&self) {
- self.waker.wake_up();
+ #[must_use]
+ pub fn wake(&self) -> bool {
+ self.waker.wake_up()
}
pub fn match_up(&self, another: &Self) -> bool {
diff --git a/kernel/src/process/posix_thread/futex.rs b/kernel/src/process/posix_thread/futex.rs
--- a/kernel/src/process/posix_thread/futex.rs
+++ b/kernel/src/process/posix_thread/futex.rs
@@ -323,8 +325,9 @@ impl FutexItem {
(futex_item, waiter)
}
- pub fn wake(&self) {
- self.waker.wake_up();
+ #[must_use]
+ pub fn wake(&self) -> bool {
+ self.waker.wake_up()
}
pub fn match_up(&self, another: &Self) -> bool {
diff --git /dev/null b/test/apps/pthread/pthread_signal_test.c
new file mode 100644
--- /dev/null
+++ b/test/apps/pthread/pthread_signal_test.c
@@ -0,0 +1,109 @@
+// SPDX-License-Identifier: MPL-2.0
+// A regression test for the futex lost wakeup bug fixed in https://github.com/asterinas/asterinas/pull/1642
+
+#include <pthread.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <signal.h>
+#include <stdatomic.h>
+
+pthread_mutex_t mutex;
+atomic_int sync_flag = ATOMIC_VAR_INIT(0); // Atomic flag for synchronization
+
+// Signal handler for SIGUSR1
+void signal_handler(int signum)
+{
+ atomic_store(&sync_flag, 2);
+}
+
+// Thread function that tries to lock the mutex and waits if it is locked
+void *thread_function(void *arg)
+{
+ printf("Thread: Trying to lock mutex...\n");
+
+ // Set the atomic flag to signal the main thread
+ atomic_store(&sync_flag, 1);
+
+ // Try to lock the mutex
+ pthread_mutex_lock(&mutex);
+ printf("Thread: Got the mutex!\n");
+
+ printf("Thread: Exiting.\n");
+ pthread_mutex_unlock(&mutex);
+
+ // Set the atomic flag to signal the main thread
+ atomic_store(&sync_flag, 3);
+ return NULL;
+}
+
+int main()
+{
+ pthread_t thread;
+
+ // Initialize mutex
+ if (pthread_mutex_init(&mutex, NULL) != 0) {
+ perror("Mutex initialization failed");
+ return -1;
+ }
+
+ // Set up signal handler for SIGUSR1
+ struct sigaction sa;
+ sa.sa_handler = signal_handler;
+ sa.sa_flags = 0;
+ sigemptyset(&sa.sa_mask);
+ if (sigaction(SIGUSR1, &sa, NULL) == -1) {
+ perror("sigaction failed");
+ return -1;
+ }
+
+ // Main thread locks the mutex
+ pthread_mutex_lock(&mutex);
+ printf("Main thread: Mutex locked.\n");
+
+ // Create the second thread
+ if (pthread_create(&thread, NULL, thread_function, NULL) != 0) {
+ perror("Thread creation failed");
+ return -1;
+ }
+
+ // Detach the thread to allow it to run independently
+ if (pthread_detach(thread) != 0) {
+ perror("Thread detachment failed");
+ return -1;
+ }
+
+ // Wait for the second thread to prepare
+ while (atomic_load(&sync_flag) != 1) {
+ }
+ sleep(1);
+
+ // Send signal to the second thread
+ pthread_kill(thread, SIGUSR1);
+ printf("Main thread: Signal sent to the thread.\n");
+
+ // Wait for the second thread to process signal
+ while (atomic_load(&sync_flag) != 2) {
+ }
+ sleep(1);
+
+ // Unlock the mutex
+ pthread_mutex_unlock(&mutex);
+ printf("Main thread: Mutex unlocked.\n");
+
+ // Wait for the second thread to exit
+ int count = 3;
+ while (atomic_load(&sync_flag) != 3 && count--) {
+ sleep(1);
+ }
+ if (atomic_load(&sync_flag) != 3) {
+ printf("ERROR: Thread does not exit after timeout.\n");
+ exit(EXIT_FAILURE);
+ }
+
+ // Destroy mutex
+ pthread_mutex_destroy(&mutex);
+
+ printf("All tests passed.\n");
+ return 0;
+}
|
The [wakeup test](https://github.com/torvalds/linux/blob/2d5404caa8c7bb5c4e0435f94b28834ae5456623/kernel/futex/waitwake.c#L671-L673) must take precedence over the [pending signals test](https://github.com/torvalds/linux/blob/2d5404caa8c7bb5c4e0435f94b28834ae5456623/kernel/futex/waitwake.c#L678-L683).
This is the real cause of the failed CI due to 6421fd0b36aafb3fcd9a8f12d5bc6e89f3f86546, cc https://github.com/asterinas/asterinas/pull/1577.
I also wonder if we can remove the `pause_timeout` API and let the futex use the normal `pause_until` API, but I am not sure since I have not read the futex implementation.
> can lead to lost-wakeup.
This should only result in spurious wake?
|
2024-11-26T12:04:42Z
|
9da6af03943c15456cdfd781021820a7da78ea40
|
asterinas/asterinas
|
diff --git a/ostd/src/arch/x86/trap/trap.S b/ostd/src/arch/x86/trap/trap.S
--- a/ostd/src/arch/x86/trap/trap.S
+++ b/ostd/src/arch/x86/trap/trap.S
@@ -57,6 +57,7 @@ trap_handler_table:
.section .text
.global trap_common
trap_common:
+ cld # clear DF before calling/returning to any C function to conform to x86-64 calling convention
push rax
mov ax, [rsp + 4*8] # load cs
and ax, 0x3 # test
|
[
"1606"
] |
0.9
|
5f35189a51ebc54298ea2cb0e4d53afe4e4e75eb
|
Shift overflow in `CpuSet` (`bit_idx` out of range)
### Describe the bug
A kernel panic is triggered due to a shift overflow. The `bit_idx` value is huge: `bit_idx=18446603338235158984`, which seems like an address (`0xffff8000780aa1c8`).
https://github.com/asterinas/asterinas/blob/e6c613f53841983765a7b3c56ea9958775c76199/ostd/src/cpu/set.rs#L105
Other variable values:
```txt
part_idx=18446603338241563904
part=18446603338235158976
bit_idx=18446603338235158984
BITS_PER_PART=64
```
I cannot find where the `CpuSet` can be corrupted. I guess it might related to a stack issue, as `SmallVec` is stored on the stack.
### To Reproduce
```
for i in `seq 1000000`; do ./memset || (echo $i && break); done`
```
<details><summary>memset.c ( **dynamically linked** , staticly linked will trigger segv described in #1603) </summary>
```c
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
int main() {
// Get the current program break address (end of the data segment)
void *initial_brk = sbrk(0);
//printf("Initial brk: %p\n", initial_brk);
// Define the size of memory we want to allocate
size_t allocation_size = 0xDC0; // 0x4dcdc0 - 0x4dc000 = 0xDC0
// Extend the program break by allocation_size bytes
void *new_brk = sbrk(allocation_size);
if (new_brk == (void *) -1) {
perror("sbrk failed");
return 1;
}
//printf("New brk: %p\n", sbrk(0));
// Fill the allocated range with -1 (0xFF)
memset(initial_brk, -1, allocation_size);
// Verify the memory range is filled with -1
unsigned char *ptr = (unsigned char *)initial_brk;
for (size_t i = 0; i < allocation_size; i++) {
assert(ptr[i] == 0xFF); // -1 is represented as 0xFF in memory
}
//printf("Memory range successfully filled and verified.\n");
return 0;
}
```
</details>
### Environment
ac71234b8964a664111dbf038ba75f36e1b0d740
### Logs
<details><summary>gdb logs</summary>
```gdb
#0 ostd::panic::print_stack_trace () at src/console.rs:25
#1 0xffffffff8804b9e9 in aster_nix::thread::oops::panic_handler (info=0xffffdffffe597850) at src/thread/oops.rs:124
#2 0xffffffff8804aa5a in aster_nix::thread::oops::__ostd_panic_handler (info=0xffffdffffe597850) at src/thread/oops.rs:82
#3 0xffffffff8804900a in aster_nix_osdk_bin::panic (info=0xffffdffffe597850) at src/main.rs:11
#4 0xffffffff889e3544 in core::panicking::panic_fmt (fmt=...) at src/panicking.rs:74
#5 0xffffffff889d342e in core::panicking::panic_const::panic_const_shl_overflow () at src/panicking.rs:181
#6 0xffffffff887b79e6 in ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure#0} (bit_idx=18446603338235158984) at src/cpu/set.rs:105
#7 0xffffffff887b77ab in core::ops::function::impls::{impl#3}::call_mut<(usize), ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (self=0xffffdffffe5979a8, args=...)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:294
#8 0xffffffff887aaab3 in core::iter::traits::iterator::Iterator::find_map::check::{closure#0}<usize, ostd::cpu::CpuId, &mut ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (x=18446603338235158984)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2903
#9 0xffffffff887b3e71 in core::iter::traits::iterator::Iterator::try_fold<core::ops::range::Range<usize>, (), core::iter::traits::iterator::Iterator::find_map::check::{closure_env#0}<usize, ostd::cpu::CpuId, &mut ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>, core::ops::control_flow::ControlFlow<ostd::cpu::CpuId, ()>> (self=0xffffdffffe597db0, init=(), f=...)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2406
--Type <RET> for more, q to quit, c to continue without paging--
#10 0xffffffff887b3dd2 in core::iter::traits::iterator::Iterator::find_map<core::ops::range::Range<usize>, ostd::cpu::CpuId, &mut ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (self=0xffffdffffe597db0, f=0xffffdffffe597dc0)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2909
#11 0xffffffff887b4271 in core::iter::adapters::filter_map::{impl#2}::next<ostd::cpu::CpuId, core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (self=0xffffdffffe597db0)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/filter_map.rs:64
#12 0xffffffff888829b3 in core::ops::function::FnOnce::call_once<fn(&mut core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>) -> core::option::Option<ostd::cpu::CpuId>, (&mut core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>)> ()
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:250
#13 0xffffffff88890a3c in core::iter::adapters::flatten::and_then_or_clear<core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>, ostd::cpu::CpuId, fn(&mut core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>) -> core::option::Option<ostd::cpu::CpuId>> (opt=0xffffdffffe597da8, f=0xdffffe597d20ffff)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/flatten.rs:838
#14 0xffffffff8889086c in core::iter::adapters::flatten::{impl#35}::next<core::iter::adapters::map::Map<core::iter::adapters::enumerate::En--Type <RET> for more, q to quit, c to continue without paging--
umerate<core::slice::iter::Iter<u64>>, ostd::cpu::set::{impl#0}::iter::{closure_env#0}>, core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>> (self=0xffffdffffe597da8)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/flatten.rs:605
#15 0xffffffff8889084a in core::iter::adapters::flatten::{impl#3}::next<core::iter::adapters::enumerate::Enumerate<core::slice::iter::Iter<u64>>, core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>, ostd::cpu::set::{impl#0}::iter::{closure_env#0}> (self=0xffffdffffe597da8)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/flatten.rs:64
#16 0xffffffff883de192 in aster_nix::sched::priority_scheduler::PreemptScheduler<aster_nix::thread::Thread, ostd::task::Task>::select_cpu<aster_nix::thread::Thread, ostd::task::Task> (self=0xffffffff88d83540 <ostd::mm::heap_allocator::init::HEAP_SPACE+185664>,
entity=0xffffdffffe597f50) at src/sched/priority_scheduler.rs:69
#17 0xffffffff883de444 in aster_nix::sched::priority_scheduler::{impl#1}::enqueue<aster_nix::thread::Thread, ostd::task::Task> (
self=0xffffffff88d83540 <ostd::mm::heap_allocator::init::HEAP_SPACE+185664>, task=...,
flags=ostd::task::scheduler::EnqueueFlags::Wake) at src/sched/priority_scheduler.rs:93
#18 0xffffffff88829b1a in ostd::task::scheduler::unpark_target (runnable=...) at src/task/scheduler/mod.rs:159
#19 0xffffffff887a9e7c in ostd::sync::wait::Waker::wake_up (self=0xffff800078731e10) at src/sync/wait.rs:263
#20 0xffffffff882f2ee2 in aster_nix::time::wait::{impl#6}::wait_until_or_timeout_cancelled::{closure#0}::{closure#0}<aster_nix::time::wait::{impl#7}::wait_until_or_timeout_cancelled::{closure_env#0}<aster_nix::thread::work_queue::worker_pool::{impl#3}::run_monitor_loop::{closur--Type <RET> for more, q to quit, c to continue without paging--
e_env#0}, (), aster_nix::time::wait::WaitTimeout::wait_until_or_timeout::{closure_env#0}<ostd::sync::wait::WaitQueue, aster_nix::thread::work_queue::worker_pool::{impl#3}::run_monitor_loop::{closure_env#0}, &core::time::Duration, ()>>, (), aster_nix::time::wait::WaitTimeout::wait_until_or_timeout::{closure_env#0}<ostd::sync::wait::WaitQueue, aster_nix::thread::work_queue::worker_pool::{impl#3}::run_monitor_loop::{closure_env#0}, &core::time::Duration, ()>> () at src/time/wait.rs:163
#21 0xffffffff887adea6 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffff8000786c5b98, args=())
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468
#22 0xffffffff882d20e0 in aster_nix::time::core::timer::interval_timer_callback (timer=0xffff800078731600) at src/time/core/timer.rs:137
#23 0xffffffff883129ca in aster_nix::time::core::timer::{impl#0}::set_timeout::{closure#0} () at src/time/core/timer.rs:89
#24 0xffffffff887adea6 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffff800078732de0, args=())
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468
#25 0xffffffff882d286a in aster_nix::time::core::timer::TimerManager::process_expired_timers (
self=0xffffffff88d83650 <ostd::mm::heap_allocator::init::HEAP_SPACE+185936>) at src/time/core/timer.rs:206
#26 0xffffffff8839b392 in aster_nix::time::clocks::system_wide::init_jiffies_clock_manager::{closure#1} ()
at src/time/clocks/system_wide.rs:273
#27 0xffffffff887adea6 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffffffff88d89eb0 <ostd::mm::heap_allocator::init::HEAP_SPACE+212656>, args=())
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468
--Type <RET> for more, q to quit, c to continue without paging--
#28 0xffffffff8815ba95 in aster_nix::time::softirq::timer_softirq_handler () at src/time/softirq.rs:31
#29 0xffffffff8832cf1e in core::ops::function::Fn::call<fn(), ()> ()
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:79
#30 0xffffffff887adea6 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffffffff88d55650 <aster_softirq::LINES+32>, args=())
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468
#31 0xffffffff886418bc in aster_softirq::process_pending () at src/lib.rs:165
#32 0xffffffff8863cc5e in core::ops::function::Fn::call<fn(), ()> ()
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:79
#33 0xffffffff887adea6 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffffffff88d55930 <ostd::trap::handler::BOTTOM_HALF_HANDLER>, args=())
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468
#34 0xffffffff887ae899 in ostd::trap::handler::process_bottom_half () at src/trap/handler.rs:42
#35 0xffffffff887ae90c in ostd::trap::handler::call_irq_callback_functions (trap_frame=0xffffdffffe598a40, irq_number=33)
at src/trap/handler.rs:56
#36 0xffffffff88834b8b in ostd::arch::x86::trap::trap_handler (f=0xffffdffffe598a40) at src/arch/x86/trap/mod.rs:251
#37 0xffffffff8882c232 in __from_kernel ()
#38 0x0000000000000000 in ?? ()
```
</details>
cpu_affinity (frame 16):
```
(gdb) p (*entity.thread.ptr.pointer).data.cpu_affinity
$8 = ostd::cpu::set::AtomicCpuSet {bits: smallvec::SmallVec<[core::sync::atomic::AtomicU64; 2]> {capacity: 1, data: smallvec::SmallVecData<[core::sync::atomic::AtomicU64; 2]>::Inline(core::mem::maybe_uninit::MaybeUninit<[core::sync::atomic::AtomicU64; 2]> {uninit: (), value: core::mem::manually_drop::ManuallyDrop<[core::sync::atomic::AtomicU64; 2]> {value: [
core::sync::atomic::AtomicU64 {v: core::cell::UnsafeCell<u64> {value: 1}},
core::sync::atomic::AtomicU64 {v: core::cell::UnsafeCell<u64> {value: 18446708889337447720}}]}})}}
```
|
asterinas__asterinas-1637
| 1,637
|
diff --git a/ostd/src/arch/x86/trap/trap.S b/ostd/src/arch/x86/trap/trap.S
--- a/ostd/src/arch/x86/trap/trap.S
+++ b/ostd/src/arch/x86/trap/trap.S
@@ -57,6 +57,7 @@ trap_handler_table:
.section .text
.global trap_common
trap_common:
+ cld # clear DF before calling/returning to any C function to conform to x86-64 calling convention
push rax
mov ax, [rsp + 4*8] # load cs
and ax, 0x3 # test
|
I did some debugging. It seems that using stack data in IRQs (like `SmallVec` in this case) might not be safe. Below is a summary of my findings to assist with further debugging.
### Create a test case to reproduce the bug reliably
Test case: `test/apps/dynamic/execve.c`
<details>
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[], char *environ[]) {
int number = 0;
// If there is an argument, parse it as a number.
if (argc > 1) {
number = atoi(argv[1]); // Convert argument to integer.
}
// Print the current number.
printf("%d\n", number);
// Increment the number.
number++;
// Prepare arguments for execve.
char new_number[16];
snprintf(new_number, sizeof(new_number), "%d", number); // Convert number to string.
char *new_argv[] = {argv[0], new_number, NULL}; // New argument list.
// Re-execute the program with the new arguments.
if (execve(argv[0], new_argv, environ) == -1) {
perror("execve failed");
exit(EXIT_FAILURE);
}
return 0; // This line should never be reached if execve is successful.
}
```
</details>
Makefile: `test/apps/dynamic/Makefile`
<details>
```
include ../test_common.mk
EXTRA_C_FLAGS :=
```
</details>
### Stop at panic
Run gdb server and client:
```sh
make gdb_server
make gdb_client # in another tmux pane
```
Set a breakpoint and continue in gdb:
```
b panic_const_shl_overflow
c
```
Run the testcase in qemu:
```
/test/dynamic/execve
```
Panic is likely to occur between 7000 and 10000 rounds (in my environment).
### Show backtraces
Show current backtrace:
```
bt
```
<details>
```
#0 core::panicking::panic_const::panic_const_shl_overflow () at src/panicking.rs:181
#1 0xffffffff88861456 in ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure#0} (bit_idx=18446603338107140168)
at src/cpu/set.rs:105
#2 0xffffffff8886122b in core::ops::function::impls::{impl#3}::call_mut<(usize), ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (self=0xffffdfffffd7d8d8, args=...)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:294
#3 0xffffffff8888f5d3 in core::iter::traits::iterator::Iterator::find_map::check::{closure#0}<usize, ostd::cpu::CpuId, &mut ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (x=18446603338107140168)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2903
#4 0xffffffff8887b3a1 in core::iter::traits::iterator::Iterator::try_fold<core::ops::range::Range<usize>, (), core::iter::traits::iterator::Iterator::find_map::check::{closure_env#0}<usize, ostd::cpu::CpuId, &mut ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>, core::ops::control_flow::ControlFlow<ostd::cpu::CpuId, ()>> (self=0xffffdfffffd7dce0, init=(), f=...)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2406
#5 0xffffffff8887b302 in core::iter::traits::iterator::Iterator::find_map<core::ops::range::Range<usize>, ostd::cpu::CpuId, &mut ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (self=0xffffdfffffd7dce0, f=0xffffdfffffd7dcf0)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2909
#6 0xffffffff8886a931 in core::iter::adapters::filter_map::{impl#2}::next<ostd::cpu::CpuId, core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (self=0xffffdfffffd7dce0)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/filter_map.rs:64
#7 0xffffffff8887e673 in core::ops::function::FnOnce::call_once<fn(&mut core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>) -> core::option::Option<ostd::cpu::CpuId>, (&mut core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>)> ()
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:250
#8 0xffffffff8887771c in core::iter::adapters::flatten::and_then_or_clear<core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>, ostd::cpu::CpuId, fn(&mut core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>) -> core::option::Option<ostd::cpu::CpuId>> (opt=0xffffdfffffd7dcd8, f=0xdfffffd7dc50ffff)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/flatten.rs:838
#9 0xffffffff8887754c in core::iter::adapters::flatten::{impl#35}::next<core::iter::adapters::map::Map<core::iter::adapters::enumerate::Enumerate<core::slice::iter::Iter<u64>>, ostd::cpu::set::{impl#0}::iter::{closure_env#0}>, core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>> (
self=0xffffdfffffd7dcd8)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/flatten.rs:605
#10 0xffffffff8887752a in core::iter::adapters::flatten::{impl#3}::next<core::iter::adapters::enumerate::Enumerate<core::slice::iter::Iter<u64>>, core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>, ostd::cpu::set::{impl#0}::iter::{closure_env#0}> (self=0xffffdfffffd7dcd8)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/flatten.rs:64
#11 0xffffffff8826cc12 in aster_nix::sched::priority_scheduler::PreemptScheduler<aster_nix::thread::Thread, ostd::task::Task>::select_cpu<aster_nix::thread::Thread, ostd::task::Task> (
self=0xffffffff88d83540 <ostd::mm::heap_allocator::init::HEAP_SPACE+492864>, entity=0xffffdfffffd7de80)
at src/sched/priority_scheduler.rs:69
#12 0xffffffff8826cec4 in aster_nix::sched::priority_scheduler::{impl#1}::enqueue<aster_nix::thread::Thread, ostd::task::Task>
(self=0xffffffff88d83540 <ostd::mm::heap_allocator::init::HEAP_SPACE+492864>, task=...,
flags=ostd::task::scheduler::EnqueueFlags::Wake) at src/sched/priority_scheduler.rs:93
#13 0xffffffff88861b8a in ostd::task::scheduler::unpark_target (runnable=...) at src/task/scheduler/mod.rs:159
#14 0xffffffff88846c3c in ostd::sync::wait::Waker::wake_up (self=0xffff8000706f3790) at src/sync/wait.rs:263
#15 0xffffffff88153612 in aster_nix::time::wait::{impl#6}::wait_until_or_timeout_cancelled::{closure#0}::{closure#0}<aster_nix::time::wait::{impl#7}::wait_until_or_timeout_cancelled::{closure_env#0}<aster_nix::thread::work_queue::worker_pool::{impl#3}::run_monitor_loop::{closure_env#0}, (), aster_nix::time::wait::WaitTimeout::wait_until_or_timeout::{closure_env#0}<ostd::sync::wait::WaitQueue, aster_nix::thread::work_queue::worker_pool::{impl#3}::run_monitor_loop::{closure_env#0}, &core::time::Duration, ()>>, (), aster_nix::time::wait::WaitTimeout::wait_until_or_timeout::{closure_env#0}<ostd::sync::wait::WaitQueue, aster_nix::thread::work_queue::worker_pool::{impl#3}::run_monitor_loop::{closure_env#0}, &core::time::Duration, ()>> ()
at src/time/wait.rs:163
#16 0xffffffff88865186 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffff8000706c1e18, args=())
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468
#17 0xffffffff880b5720 in aster_nix::time::core::timer::interval_timer_callback (timer=0xffff8000706f3880)
at src/time/core/timer.rs:137
#18 0xffffffff8827ef2a in aster_nix::time::core::timer::{impl#0}::set_timeout::{closure#0} () at src/time/core/timer.rs:89
#19 0xffffffff88865186 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffff8000706f2260, args=())
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468
#20 0xffffffff880b5eaa in aster_nix::time::core::timer::TimerManager::process_expired_timers (
self=0xffffffff88d83650 <ostd::mm::heap_allocator::init::HEAP_SPACE+493136>) at src/time/core/timer.rs:206
#21 0xffffffff882eaa82 in aster_nix::time::clocks::system_wide::init_jiffies_clock_manager::{closure#1} ()
at src/time/clocks/system_wide.rs:273
#22 0xffffffff88865186 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffffffff88d89eb0 <ostd::mm::heap_allocator::init::HEAP_SPACE+519856>,
args=())
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468
#23 0xffffffff88163515 in aster_nix::time::softirq::timer_softirq_handler () at src/time/softirq.rs:31
#24 0xffffffff8836578e in core::ops::function::Fn::call<fn(), ()> ()
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:79
#25 0xffffffff88865186 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffffffff88d09650 <aster_softirq::LINES+32>, args=())
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468
#26 0xffffffff88607d1c in aster_softirq::process_pending () at src/lib.rs:165
#27 0xffffffff8860558e in core::ops::function::Fn::call<fn(), ()> ()
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:79
#28 0xffffffff88865186 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffffffff88d09970 <ostd::trap::handler::BOTTOM_HALF_HANDLER>, args=())
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468
#29 0xffffffff887996e9 in ostd::trap::handler::process_bottom_half () at src/trap/handler.rs:42
#30 0xffffffff8879975c in ostd::trap::handler::call_irq_callback_functions (trap_frame=0xffffdfffffd7e970, irq_number=33)
at src/trap/handler.rs:56
#31 0xffffffff887c86ab in ostd::arch::x86::trap::trap_handler (f=0xffffdfffffd7e970) at src/arch/x86/trap/mod.rs:251
#32 0xffffffff88838e66 in __from_kernel ()
#33 0x0000000000000000 in ?? ()
```
</details>
In the backtrace, we can see the trap originates from `0xffffffff88838e66` in `__from_kernel ()` (frame `32`). Specifically, the address `0xffffffff88838e66` is the start address of `trap_return`.
Go back to frame `32` and show registers:
```
frame 32
info reg
```
<details>
```
rax 0xffff8000706c1f00 -140735602221312
rbx 0x0 0
rcx 0x1 1
rdx 0xffff800070693848 -140735602411448
rsi 0xffff800070693848 -140735602411448
rdi 0xffffffff88a560a0 -2002427744
rbp 0x0 0x0
rsp 0xffffdfffffd7e970 0xffffdfffffd7e970
r8 0x0 0
r9 0x1000 4096
r10 0x1bd000 1822720
r11 0xffffdfffffd998a8 -35184374605656
r12 0x0 0
r13 0x0 0
r14 0x0 0
r15 0x0 0
rip 0xffffffff88838e66 0xffffffff88838e66 <trap_return>
eflags 0x200486 [ ID IOPL=0 DF SF PF ]
cs 0x8 8
ss 0x38 56
ds 0x0 0
es 0x0 0
fs 0x0 0
gs 0x0 0
fs_base 0x7ffffff07780 140737487337344
gs_base 0xffffffff88d08000 -1999601664
k_gs_base 0x0 0
cr0 0x80010033 [ PG WP NE ET MP PE ]
cr2 0x7ffffff04fdc 140737487327196
cr3 0x7cf59000 [ PDBR=511833 PCID=0 ]
cr4 0x506e8 [ OSXSAVE FSGSBASE OSXMMEXCPT OSFXSR PGE MCE PAE DE ]
cr8 0x0 0
efer 0xd01 [ NXE LMA LME SCE ]
--- fpu regs ignored ---
```
</details>
Discard all stack frames from this trap and return to `trap_return`:
```
frame 0
set $rsp=0xffffdfffffd7e970
set $rip=0xffffffff88838e66
b *$rip
b *$rip+1
```
Step to the `iret` instruction:
```
si
# Press `Enter` repeatedly to step until reaching the `iret` instruction
```
Show the stack to find the return address:
```
x/20gx $rsp
```
<details>
```
0xffffdfffffd7d900: 0x0000000000000000 0x0000000000000021
0xffffdfffffd7d910: 0x0000000000000000 **0xffffffff889c725e**
0xffffdfffffd7d920: 0x0000000000000030 0x0000000000210682
0xffffdfffffd7d930: 0xffffdfffffd7d940 0x0000000000000038
0xffffdfffffd7d940: 0x0000000000000038 0x0100000000000002
0xffffdfffffd7d950: 0xffff8000706a4047 0x000000000000002f
0xffffdfffffd7d960: 0x0100000000000007 0x0000000000000000
0xffffdfffffd7d970: 0x0000000000000006 0x0000000000000000
0xffffdfffffd7d980: 0x000000000000002f 0x0000000000000030
0xffffdfffffd7d990: 0xffff8000706a4010 0xffff8000706a4018
```
</details>
Set a breakpoint at the return address:
```
b *0xffffffff889c725e
# Output: Breakpoint 3 at 0xffffffff889c725e: file src/mem/x86_64.rs, line 68.
```
Step to the original trap address:
```
si
```
Show the backtrace and registers:
```
bt
```
<details>
```
#0 0xffffffff889c7253 in compiler_builtins::mem::impls::copy_backward (dest=0xffff8000706a4020, src=0xffff8000706a4018,
count=56) at src/mem/x86_64.rs:68
#1 compiler_builtins::mem::memmove (dest=0xffff8000706a4020, src=0xffff8000706a4018, n=56) at src/mem/mod.rs:37
#2 0xffffffff889ca0f7 in compiler_builtins::mem::memmove::memmove (dest=0xffff8000706a4020, src=0xffff8000706a4018, n=56)
at src/macros.rs:480
#3 0xffffffff887d465c in core::intrinsics::copy<core::mem::maybe_uninit::MaybeUninit<usize>> (src=0xffff8000706a4018,
dst=0xffff8000706a4020, count=7)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/intrinsics.rs:3419
#4 alloc::collections::btree::node::slice_insert<usize> (slice=..., idx=2, val=1888256)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/collections/btree/node.rs:1791
#5 0xffffffff884acab6 in alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut, usize, aster_nix::vm::vmar::vm_mapping::VmMapping, alloc::collections::btree::node::marker::Leaf>, alloc::collections::btree::node::marker::Edge>::insert_fit<usize, aster_nix::vm::vmar::vm_mapping::VmMapping> (self=...,
key=1888256, val=...)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/collections/btree/node.rs:919
#6 0xffffffff884bf1ff in alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut, usize, aster_nix::vm::vmar::vm_mapping::VmMapping, alloc::collections::btree::node::marker::Leaf>, alloc::collections::btree::node::marker::Edge>::insert<usize, aster_nix::vm::vmar::vm_mapping::VmMapping, alloc::alloc::Global>
(self=..., key=1888256, val=..., alloc=...)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/collections/btree/node.rs:945
#7 0xffffffff884b64f7 in alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut, usize, aster_nix::vm::vmar::vm_mapping::VmMapping, alloc::collections::btree::node::marker::Leaf>, alloc::collections::btree::node::marker::Edge>::insert_recursing<usize, aster_nix::vm::vmar::vm_mapping::VmMapping, alloc::alloc::Global, alloc::collections::btree::map::entry::{impl#8}::insert::{closure_env#0}<usize, aster_nix::vm::vmar::vm_mapping::VmMapping, alloc::alloc::Global>> (self=..., key=1888256, value=..., alloc=..., split_root=...)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/collections/btree/node.rs:1046
#8 0xffffffff88292b65 in alloc::collections::btree::map::entry::VacantEntry<usize, aster_nix::vm::vmar::vm_mapping::VmMapping, alloc::alloc::Global>::insert<usize, aster_nix::vm::vmar::vm_mapping::VmMapping, alloc::alloc::Global> (self=..., value=...)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/collections/btree/map/entry.rs:364
#9 0xffffffff8825a89d in alloc::collections::btree::map::BTreeMap<usize, aster_nix::vm::vmar::vm_mapping::VmMapping, alloc::alloc::Global>::insert<usize, aster_nix::vm::vmar::vm_mapping::VmMapping, alloc::alloc::Global> (self=0xffff8000706c01d0,
key=1888256, value=...)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/collections/btree/map.rs:993
#10 0xffffffff881c9ab2 in aster_nix::vm::vmar::interval_set::IntervalSet<usize, aster_nix::vm::vmar::vm_mapping::VmMapping>::insert<usize, aster_nix::vm::vmar::vm_mapping::VmMapping> (self=0xffff8000706c01d0, item=...) at src/vm/vmar/interval_set.rs:55
#11 0xffffffff88418a44 in aster_nix::vm::vmar::Vmar_::add_mapping (self=0xffff8000706c0190, mapping=...)
at src/vm/vmar/mod.rs:387
#12 0xffffffff8840f92f in aster_nix::vm::vmar::vm_mapping::VmarMapOptions<aster_rights::TRightSet<typeflags_util::set::Cons<aster_rights::Signal, typeflags_util::set::Cons<aster_rights::Exec, typeflags_util::set::Cons<aster_rights::Write, typeflags_util::set::Cons<aster_rights::Read, typeflags_util::set::Cons<aster_rights::Dup, typeflags_util::set::Nil>>>>>>, aster_rights::Rights>::build<aster_rights::TRightSet<typeflags_util::set::Cons<aster_rights::Signal, typeflags_util::set::Cons<aster_rights::Exec, typeflags_util::set::Cons<aster_rights::Write, typeflags_util::set::Cons<aster_rights::Read, typeflags_util::set::Cons<aster_rights::Dup, typeflags_util::set::Nil>>>>>>, aster_rights::Rights> (self=...) at src/vm/vmar/vm_mapping.rs:575
#13 0xffffffff882d06b3 in aster_nix::syscall::mmap::do_sys_mmap (addr=1888256, len=360448, vm_perms=..., option=..., fd=3,
offset=1822720, ctx=0xffffdfffffd998a8) at src/syscall/mmap.rs:155
#14 0xffffffff882cf051 in aster_nix::syscall::mmap::sys_mmap (addr=1888256, len=360448, perms=1, flags=2066, fd=3,
offset=1822720, ctx=0xffffdfffffd998a8) at src/syscall/mmap.rs:29
#15 0xffffffff88187633 in aster_nix::syscall::arch::x86::syscall_dispatch (syscall_number=9, args=...,
ctx=0xffffdfffffd998a8, user_ctx=0xffffdfffffd993d0) at src/syscall/mod.rs:221
#16 0xffffffff8818196e in aster_nix::syscall::handle_syscall (ctx=0xffffdfffffd998a8, user_ctx=0xffffdfffffd993d0)
at src/syscall/mod.rs:322
#17 0xffffffff8830c3dc in aster_nix::thread::task::create_new_user_task::user_task_entry () at src/thread/task.rs:70
#18 0xffffffff88368346 in core::ops::function::FnOnce::call_once<fn(), ()> ()
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:250
#19 0xffffffff8814f0c7 in unwinding::panicking::catch_unwind::do_call<fn(), ()> (data=0xffffdfffffd99c50)
at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/unwinding-0.2.3/src/panicking.rs:54
#20 0xffffffff8814ff68 in __rust_try ()
#21 0xffffffff8814efbf in unwinding::panicking::catch_unwind<unwinding::panic::RustPanic, (), fn()> (f=0xffdfffffd99c5020)
at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/unwinding-0.2.3/src/panicking.rs:42
#22 0xffffffff8840e022 in unwinding::panic::catch_unwind<(), fn()> (f=0xffffff885ffc5600)
at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/unwinding-0.2.3/src/panic.rs:87
#23 0xffffffff885ffc56 in aster_nix::thread::oops::catch_panics_as_oops<fn(), ()> (f=0x100) at src/thread/oops.rs:54
#24 0xffffffff88083d1c in aster_nix::thread::task::create_new_user_task::{closure#0} () at src/thread/task.rs:95
#25 0xffffffff8836664e in core::ops::function::FnOnce::call_once<aster_nix::thread::task::create_new_user_task::{closure_env#0}, ()> ()
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:250
#26 0xffffffff888651e8 in alloc::boxed::{impl#48}::call_once<(), (dyn core::ops::function::FnOnce<(), Output=()> + core::marker::Send), alloc::alloc::Global> (self=..., args=())
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2454
#27 0xffffffff88835a87 in ostd::task::{impl#1}::build::kernel_task_entry () at src/task/mod.rs:175
#28 0x00000a000d004e00 in ?? ()
```
</details>
```
info reg
```
<details>
```
rax 0x0 0
rbx 0x0 0
rcx 0x0 0
rdx 0x7 7
rsi 0xffff8000706a404f -140735602343857
rdi 0xffff8000706a4057 -140735602343849
rbp 0x0 0x0
rsp 0xffffdfffffd7ea30 0xffffdfffffd7ea30
r8 0x37 55
r9 0x1000 4096
r10 0x1bd000 1822720
r11 0xffffdfffffd998a8 -35184374605656
r12 0x0 0
r13 0x0 0
r14 0x0 0
r15 0x0 0
rip 0xffffffff889c7253 0xffffffff889c7253 <compiler_builtins::mem::memmove+451>
eflags 0x200682 [ ID IOPL=0 DF IF SF ]
cs 0x30 48
ss 0x38 56
ds 0x0 0
es 0x0 0
fs 0x0 0
--Type <RET> for more, q to quit, c to continue without paging--
gs 0x0 0
fs_base 0x7ffffff07780 140737487337344
gs_base 0xffffffff88d08000 -1999601664
k_gs_base 0x0 0
cr0 0x80010033 [ PG WP NE ET MP PE ]
cr2 0x7ffffff04fdc 140737487327196
cr3 0x7cf59000 [ PDBR=511833 PCID=0 ]
cr4 0x506e8 [ OSXSAVE FSGSBASE OSXMMEXCPT OSFXSR PGE MCE PAE DE ]
cr8 0x0 0
efer 0xd01 [ NXE LMA LME SCE ]
--- fpu regs ignored ---
```
</details>
From the backtrace, we can see that execution is in the middle of `memmove`, indicating that the data might not have been completely moved. I have tested it twice, and both backtraces were the same.
It makes me doubtful about `SmallVec` implementation. Maybe try a fixed array like `[u64; 4]` and see if it reproduces?
The bug still exists. Here is my patch:
<details>
```diff
diff --git a/ostd/src/cpu/set.rs b/ostd/src/cpu/set.rs
index dc751090..86f9236b 100644
--- a/ostd/src/cpu/set.rs
+++ b/ostd/src/cpu/set.rs
@@ -4,7 +4,7 @@
use core::sync::atomic::{AtomicU64, Ordering};
-use smallvec::SmallVec;
+// use smallvec::SmallVec;
use static_assertions::const_assert_eq;
use super::{num_cpus, CpuId};
@@ -13,13 +13,13 @@ use super::{num_cpus, CpuId};
#[derive(Clone, Debug, Default)]
pub struct CpuSet {
// A bitset representing the CPUs in the system.
- bits: SmallVec<[InnerPart; NR_PARTS_NO_ALLOC]>,
+ bits: [u64; 4],
}
type InnerPart = u64;
const BITS_PER_PART: usize = core::mem::size_of::<InnerPart>() * 8;
-const NR_PARTS_NO_ALLOC: usize = 2;
+// const NR_PARTS_NO_ALLOC: usize = 2;
const fn part_idx(cpu_id: CpuId) -> usize {
cpu_id.as_usize() / BITS_PER_PART
@@ -51,7 +51,8 @@ impl CpuSet {
let part_idx = part_idx(cpu_id);
let bit_idx = bit_idx(cpu_id);
if part_idx >= self.bits.len() {
- self.bits.resize(part_idx + 1, 0);
+ panic!("cannot resize");
+ // self.bits.resize(part_idx + 1, 0);
}
self.bits[part_idx] |= 1 << bit_idx;
}
@@ -115,8 +116,13 @@ impl CpuSet {
/// Only for internal use. The set cannot contain non-existent CPUs.
fn with_capacity_val(num_cpus: usize, val: InnerPart) -> Self {
let num_parts = parts_for_cpus(num_cpus);
- let mut bits = SmallVec::with_capacity(num_parts);
- bits.resize(num_parts, val);
+ if num_parts > 4 {
+ panic!("should not bigger than 4");
+ }
+ let mut bits = [0; 4];
+ for i in 0..num_parts {
+ bits[i] = val;
+ }
Self { bits }
}
@@ -143,16 +149,43 @@ impl From<CpuId> for CpuSet {
/// operation contains multiple CPUs, the ordering is not guaranteed.
#[derive(Debug)]
pub struct AtomicCpuSet {
- bits: SmallVec<[AtomicInnerPart; NR_PARTS_NO_ALLOC]>,
+ bits: [AtomicInnerPart; 4],
}
type AtomicInnerPart = AtomicU64;
const_assert_eq!(core::mem::size_of::<AtomicInnerPart>() * 8, BITS_PER_PART);
+impl From<CpuSet> for AtomicCpuSet {
+ fn from(cpu_set: CpuSet) -> Self {
+ // Map each `u64` in `cpu_set.bits` to an `AtomicInnerPart`
+ let atomic_bits: [AtomicInnerPart; 4] = [
+ AtomicInnerPart::new(0),
+ AtomicInnerPart::new(0),
+ AtomicInnerPart::new(0),
+ AtomicInnerPart::new(0),
+ ];
+
+ for (i, &bit) in cpu_set.bits.iter().enumerate() {
+ atomic_bits[i].store(bit, Ordering::SeqCst);
+ }
+
+ AtomicCpuSet { bits: atomic_bits }
+ }
+}
+
+fn atomic_array_to_u64_array(array: &[AtomicU64; 4]) -> [u64; 4] {
+ [
+ array[0].load(Ordering::SeqCst),
+ array[1].load(Ordering::SeqCst),
+ array[2].load(Ordering::SeqCst),
+ array[3].load(Ordering::SeqCst),
+ ]
+}
+
impl AtomicCpuSet {
/// Creates a new `AtomicCpuSet` with an initial value.
pub fn new(value: CpuSet) -> Self {
- let bits = value.bits.into_iter().map(AtomicU64::new).collect();
+ let bits = AtomicCpuSet::from(value).bits;
Self { bits }
}
@@ -161,11 +194,7 @@ impl AtomicCpuSet {
/// This operation can only be done in the [`Ordering::Relaxed`] memory
/// order. It cannot be used to synchronize anything between CPUs.
pub fn load(&self) -> CpuSet {
- let bits = self
- .bits
- .iter()
- .map(|part| part.load(Ordering::Relaxed))
- .collect();
+ let bits = atomic_array_to_u64_array(&self.bits);
CpuSet { bits }
}
```
</details>
The backtrace:
<details>
```
#0 ostd::panic::print_stack_trace () at src/panic.rs:62
#1 0xffffffff88291c99 in aster_nix::thread::oops::panic_handler (info=0xffffdfffffd7b8a0) at src/thread/oops.rs:124
#2 0xffffffff88290d0a in aster_nix::thread::oops::__ostd_panic_handler (info=0xffffdfffffd7b8a0) at src/thread/oops.rs:82
#3 0xffffffff8804900a in aster_nix_osdk_bin::panic (info=0xffffdfffffd7b8a0) at src/main.rs:11
#4 0xffffffff889a2934 in core::panicking::panic_fmt (fmt=...) at src/panicking.rs:74
#5 0xffffffff8899281e in core::panicking::panic_const::panic_const_shl_overflow () at src/panicking.rs:181
#6 0xffffffff887a3326 in ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure#0} (bit_idx=18446603338107140168)
at src/cpu/set.rs:106
#7 0xffffffff887a30fb in core::ops::function::impls::{impl#3}::call_mut<(usize), ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (self=0xffffdfffffd7b9f8, args=...)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:294
#8 0xffffffff888891c3 in core::iter::traits::iterator::Iterator::find_map::check::{closure#0}<usize, ostd::cpu::CpuId, &mut ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (x=18446603338107140168)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2903
#9 0xffffffff88876e91 in core::iter::traits::iterator::Iterator::try_fold<core::ops::range::Range<usize>, (), core::iter::traits::iterator::Iterator::find_map::check::{closure_env#0}<usize, ostd::cpu::CpuId, &mut ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>, core::ops::control_flow::ControlFlow<ostd::cpu::CpuId, ()>> (self=0xffffdfffffd7be00, init=(), f=...)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2406
#10 0xffffffff88876df2 in core::iter::traits::iterator::Iterator::find_map<core::ops::range::Range<usize>, ostd::cpu::CpuId, &mut ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (self=0xffffdfffffd7be00, f=0xffffdfffffd7be10)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2909
#11 0xffffffff88867341 in core::iter::adapters::filter_map::{impl#2}::next<ostd::cpu::CpuId, core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (self=0xffffdfffffd7be00)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/filter_map.rs:64
#12 0xffffffff8887a943 in core::ops::function::FnOnce::call_once<fn(&mut core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>) -> core::option::Option<ostd::cpu::CpuId>, (&mut core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>)> ()
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:250
#13 0xffffffff888738bc in core::iter::adapters::flatten::and_then_or_clear<core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>, ostd::cpu::CpuId, fn(&mut core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>) -> core::option::Option<ostd::cpu::CpuId>> (opt=0xffffdfffffd7bdf8, f=0xdfffffd7bd70ffff)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/flatten.rs:838
#14 0xffffffff888736ec in core::iter::adapters::flatten::{impl#35}::next<core::iter::adapters::map::Map<core::iter::adapters::e--Type <RET> for more, q to quit, c to continue without paging--
numerate::Enumerate<core::slice::iter::Iter<u64>>, ostd::cpu::set::{impl#0}::iter::{closure_env#0}>, core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>> (
self=0xffffdfffffd7bdf8)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/flatten.rs:605
#15 0xffffffff888736ca in core::iter::adapters::flatten::{impl#3}::next<core::iter::adapters::enumerate::Enumerate<core::slice::iter::Iter<u64>>, core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>, ostd::cpu::set::{impl#0}::iter::{closure_env#0}> (self=0xffffdfffffd7bdf8)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/flatten.rs:64
#16 0xffffffff882f367a in aster_nix::sched::priority_scheduler::PreemptScheduler<aster_nix::thread::Thread, ostd::task::Task>::select_cpu<aster_nix::thread::Thread, ostd::task::Task> (
self=0xffffffff88d83540 <ostd::mm::heap_allocator::init::HEAP_SPACE+517440>, entity=0xffffdfffffd7bfa0)
at src/sched/priority_scheduler.rs:69
#17 0xffffffff882f3924 in aster_nix::sched::priority_scheduler::{impl#1}::enqueue<aster_nix::thread::Thread, ostd::task::Task>
(self=0xffffffff88d83540 <ostd::mm::heap_allocator::init::HEAP_SPACE+517440>, task=...,
flags=ostd::task::scheduler::EnqueueFlags::Wake) at src/sched/priority_scheduler.rs:93
#18 0xffffffff8885de1a in ostd::task::scheduler::unpark_target (runnable=...) at src/task/scheduler/mod.rs:159
#19 0xffffffff88844c6c in ostd::sync::wait::Waker::wake_up (self=0xffff8000706e7410) at src/sync/wait.rs:263
#20 0xffffffff8812b072 in aster_nix::time::wait::{impl#6}::wait_until_or_timeout_cancelled::{closure#0}::{closure#0}<aster_nix::time::wait::{impl#7}::wait_until_or_timeout_cancelled::{closure_env#0}<aster_nix::thread::work_queue::worker_pool::{impl#3}::run_monitor_loop::{closure_env#0}, (), aster_nix::time::wait::WaitTimeout::wait_until_or_timeout::{closure_env#0}<ostd::sync::wait::WaitQueue, aster_nix::thread::work_queue::worker_pool::{impl#3}::run_monitor_loop::{closure_env#0}, &core::time::Duration, ()>>, (), aster_nix::time::wait::WaitTimeout::wait_until_or_timeout::{closure_env#0}<ostd::sync::wait::WaitQueue, aster_nix::thread::work_queue::worker_pool::{impl#3}::run_monitor_loop::{closure_env#0}, &core::time::Duration, ()>> ()
at src/time/wait.rs:163
#21 0xffffffff88861416 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffff8000706c1e18, args=())
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468
#22 0xffffffff88269f20 in aster_nix::time::core::timer::interval_timer_callback (timer=0xffff8000706e76c0)
at src/time/core/timer.rs:137
#23 0xffffffff88267eda in aster_nix::time::core::timer::{impl#0}::set_timeout::{closure#0} () at src/time/core/timer.rs:89
#24 0xffffffff88861416 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffff8000706e74e0, args=())
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468
#25 0xffffffff8826a6aa in aster_nix::time::core::timer::TimerManager::process_expired_timers (
self=0xffffffff88d83650 <ostd::mm::heap_allocator::init::HEAP_SPACE+517712>) at src/time/core/timer.rs:206
#26 0xffffffff885d7ed2 in aster_nix::time::clocks::system_wide::init_jiffies_clock_manager::{closure#1} ()
at src/time/clocks/system_wide.rs:273
#27 0xffffffff88861416 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffffffff88d89eb0 <ostd::mm::heap_allocator::init::HEAP_SPACE+544432>,
args=())
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468
#28 0xffffffff882bdc25 in aster_nix::time::softirq::timer_softirq_handler () at src/time/softirq.rs:31
#29 0xffffffff88355cfe in core::ops::function::Fn::call<fn(), ()> ()
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:79
#30 0xffffffff88861416 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffffffff88d02650 <aster_softirq::LINES+32>, args=())
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468
#31 0xffffffff88607a6c in aster_softirq::process_pending () at src/lib.rs:165
#32 0xffffffff886052de in core::ops::function::Fn::call<fn(), ()> ()
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:79
#33 0xffffffff88861416 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffffffff88d029a0 <ostd::trap::handler::BOTTOM_HALF_HANDLER>, args=())
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468
#34 0xffffffff88799109 in ostd::trap::handler::process_bottom_half () at src/trap/handler.rs:42
#35 0xffffffff8879917c in ostd::trap::handler::call_irq_callback_functions (trap_frame=0xffffdfffffd7ca90, irq_number=33)
at src/trap/handler.rs:56
#36 0xffffffff887c82db in ostd::arch::x86::trap::trap_handler (f=0xffffdfffffd7ca90) at src/arch/x86/trap/mod.rs:251
#37 0xffffffff888a6c6e in __from_kernel ()
#38 0x0000000000000000 in ?? ()
```
</details>
`cpu_affinity` in frame `16`
```
(gdb) p (*entity.thread.ptr.pointer).data.cpu_affinity
$1 = ostd::cpu::set::AtomicCpuSet {bits: [core::sync::atomic::AtomicU64 {v: core::cell::UnsafeCell<u64> {value: 1}},
core::sync::atomic::AtomicU64 {v: core::cell::UnsafeCell<u64> {value: 0}},
core::sync::atomic::AtomicU64 {v: core::cell::UnsafeCell<u64> {value: 0}},
core::sync::atomic::AtomicU64 {v: core::cell::UnsafeCell<u64> {value: 0}}]}
```
Backtrace before the trap:
<details>
```
#0 0xffffffff889c17bf in compiler_builtins::mem::impls::copy_backward (dest=0xffff8000706e3818, src=0xffff8000706e3810,
count=16) at src/mem/x86_64.rs:68
#1 compiler_builtins::mem::memmove (dest=0xffff8000706e3818, src=0xffff8000706e3810, n=16) at src/mem/mod.rs:37
#2 0xffffffff889c4647 in compiler_builtins::mem::memmove::memmove (dest=0xffff8000706e3818, src=0xffff8000706e3810, n=16)
at src/macros.rs:480
#3 0xffffffff88453f7c in core::intrinsics::copy<core::mem::maybe_uninit::MaybeUninit<u64>> (src=0xffff8000706e3810,
dst=0xffff8000706e3818, count=2)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/intrinsics.rs:3419
#4 alloc::collections::btree::node::slice_insert<u64> (slice=..., idx=1, val=56)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/collections/btree/node.rs:1791
#5 0xffffffff8849e157 in alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut, aster_nix::process::process_vm::init_stack::aux_vec::AuxKey, u64, alloc::collections::btree::node::marker::Leaf>, alloc::collections::btree::node::marker::Edge>::insert_fit<aster_nix::process::process_vm::init_stack::aux_vec::AuxKey, u64> (self=..., key=aster_nix::process::process_vm::init_stack::aux_vec::AuxKey::AT_PHENT, val=56)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/collections/btree/node.rs:920
#6 0xffffffff884b228b in alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut, aster_nix::process::process_vm::init_stack::aux_vec::AuxKey, u64, alloc::collections::btree::node::marker::Leaf>, alloc::collections::btree::node::marker::Edge>::insert<aster_nix::process::process_vm::init_stack::aux_vec::AuxKey, u64, alloc::alloc::Global> (self=..., key=aster_nix::process::process_vm::init_stack::aux_vec::AuxKey::AT_PHENT, val=56,
alloc=...)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/collections/btree/node.rs:945
#7 0xffffffff884a4ff0 in alloc::collections::btree::node::Handle<alloc::collections::btree::node::NodeRef<alloc::collections::btree::node::marker::Mut, aster_nix::process::process_vm::init_stack::aux_vec::AuxKey, u64, alloc::collections::btree::node::marker::Leaf>, alloc::collections::btree::node::marker::Edge>::insert_recursing<aster_nix::process::process_vm::init_stack::aux_vec::AuxKey, u64, alloc::alloc::Global, alloc::collections::btree::map::entry::{impl#8}::insert::{closure_env#0}<aster_nix::process::process_vm::init_stack::aux_vec::AuxKey, u64, alloc::alloc::Global>> (self=...,
key=aster_nix::process::process_vm::init_stack::aux_vec::AuxKey::AT_PHENT, value=56, alloc=..., split_root=...)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/collections/btree/node.rs:1046
#8 0xffffffff88277e1c in alloc::collections::btree::map::entry::VacantEntry<aster_nix::process::process_vm::init_stack::aux_vec::AuxKey, u64, alloc::alloc::Global>::insert<aster_nix::process::process_vm::init_stack::aux_vec::AuxKey, u64, alloc::alloc::Global> (self=..., value=56)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/collections/btree/map/entry.rs:364
#9 0xffffffff8827454d in alloc::collections::btree::map::entry::Entry<aster_nix::process::process_vm::init_stack::aux_vec::AuxKey, u64, alloc::alloc::Global>::or_insert<aster_nix::process::process_vm::init_stack::aux_vec::AuxKey, u64, alloc::alloc::Global> (self=..., default=56)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/collections/btree/map/entry.rs:163
#10 0xffffffff885d3dc1 in aster_nix::process::process_vm::init_stack::aux_vec::AuxVec::set (self=0xffffdfffffd7d6f0,
key=aster_nix::process::process_vm::init_stack::aux_vec::AuxKey::AT_PHENT, val=56)
at src/process/process_vm/init_stack/aux_vec.rs:77
#11 0xffffffff8810f07c in aster_nix::process::program_loader::elf::load_elf::init_aux_vec (elf=0xffffdfffffd7de98,
elf_map_addr=335790080, ldso_base=...) at src/process/program_loader/elf/load_elf.rs:394
#12 0xffffffff8810bc4b in aster_nix::process::program_loader::elf::load_elf::init_and_map_vmos (
process_vm=0xffff8000706a3810, ldso=..., parsed_elf=0xffffdfffffd7de98, elf_file=0xffffdfffffd7de88)
at src/process/program_loader/elf/load_elf.rs:134
#13 0xffffffff8810a6ec in aster_nix::process::program_loader::elf::load_elf::load_elf_to_vm (process_vm=0xffff8000706a3810,
file_header=..., elf_file=..., fs_resolver=0xffff8000706c00c8, argv=..., envp=...)
at src/process/program_loader/elf/load_elf.rs:46
#14 0xffffffff881f6f76 in aster_nix::process::program_loader::load_program_to_vm (process_vm=0xffff8000706a3810,
elf_file=..., argv=..., envp=..., fs_resolver=0xffff8000706c00c8, recursion_limit=1)
at src/process/program_loader/mod.rs:66
#15 0xffffffff881e5b76 in aster_nix::syscall::execve::do_execve (elf_file=..., argv_ptr_ptr=140737487793456,
envp_ptr_ptr=140737487793824, ctx=0xffffdfffffd998a8, user_context=0xffffdfffffd993d0) at src/syscall/execve.rs:117
#16 0xffffffff881e3fe3 in aster_nix::syscall::execve::sys_execve (filename_ptr=140737487794071, argv_ptr_ptr=140737487793456,
envp_ptr_ptr=140737487793824, ctx=0xffffdfffffd998a8, user_context=0xffffdfffffd993d0) at src/syscall/execve.rs:33
#17 0xffffffff881b1879 in aster_nix::syscall::arch::x86::syscall_dispatch (syscall_number=59, args=...,
ctx=0xffffdfffffd998a8, user_ctx=0xffffdfffffd993d0) at src/syscall/mod.rs:175
#18 0xffffffff880bda9e in aster_nix::syscall::handle_syscall (ctx=0xffffdfffffd998a8, user_ctx=0xffffdfffffd993d0)
at src/syscall/mod.rs:322
#19 0xffffffff8819456c in aster_nix::thread::task::create_new_user_task::user_task_entry () at src/thread/task.rs:70
#20 0xffffffff883588d6 in core::ops::function::FnOnce::call_once<fn(), ()> ()
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:250
#21 0xffffffff880db0e7 in unwinding::panicking::catch_unwind::do_call<fn(), ()> (data=0xffffdfffffd99c50)
at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/unwinding-0.2.3/src/panicking.rs:54
#22 0xffffffff880db508 in __rust_try ()
#23 0xffffffff880dafdf in unwinding::panicking::catch_unwind<unwinding::panic::RustPanic, (), fn()> (f=0xffdfffffd99c5000)
at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/unwinding-0.2.3/src/panicking.rs:42
#24 0xffffffff882fe622 in unwinding::panic::catch_unwind<(), fn()> (f=0xffffff880c3a262c)
at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/unwinding-0.2.3/src/panic.rs:87
#25 0xffffffff880c3a26 in aster_nix::thread::oops::catch_panics_as_oops<fn(), ()> (f=0x100) at src/thread/oops.rs:54
#26 0xffffffff8814a55c in aster_nix::thread::task::create_new_user_task::{closure#0} () at src/thread/task.rs:95
#27 0xffffffff88356bbe in core::ops::function::FnOnce::call_once<aster_nix::thread::task::create_new_user_task::{closure_env#0}, ()> ()
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:250
#28 0xffffffff88861478 in alloc::boxed::{impl#48}::call_once<(), (dyn core::ops::function::FnOnce<(), Output=()> + core::marker::Send), alloc::alloc::Global> (self=..., args=())
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2454
#29 0xffffffff888370f7 in ostd::task::{impl#1}::build::kernel_task_entry () at src/task/mod.rs:175
#30 0x2000650068007400 in ?? ()
```
</details>
> The bug still exists. Here is my patch:
Seems proper. So I don't have a clue for now.
Since you have mentioned nested traps in a comment of #1611 , I am wondering if the red zone of the current stack was corrupted by the nested trap. Try recompile Asterinas with [`no-redzone=true`](https://doc.rust-lang.org/rustc/codegen-options/index.html#no-redzone) and see if the problem disappears.
---
Edit: Check out the cargo flags in [the OSDK source code](https://github.com/asterinas/asterinas/blob/f1aae232341bda78aa7bf1906e3d00df160962a8/osdk/src/commands/build/mod.rs#L205). The `no-redzone` option is not specified. According to the rustc book, when unspecified, whether the option is enabled by default is determined by the target. Our target for x86 is `x86_64-unknown-none`.
> On x86_64-unknown-none, extern "C" uses the [standard System V calling convention](https://gitlab.com/x86-psABIs/x86-64-ABI), without red zones.
So it looks like that only extern "C" functions have no red zones, but normal Rust functions have. And I don't think our assembly code in `trap.s` or other trap-related code skips the red zones. So nested traps will corrupt red zones.
@cqs21 What is your judgement on this issue? You are more familiar with the trap and system call handling code.
> I am wondering if the red zone of the current stack was corrupted by the nested trap.
@tatetian Indeed, the CPU and the exception handler overwrite the data in the red zone, and we cannot avoid this in `trap.S`, since the hardware automatically pushes registers and error code onto the stack.
The bug still occurs (the error slightly changed from `panic_const_shl_overflow` to `panic_const_mul_overflow`).
```
(gdb) p/x part_idx
$2 = 0xffffffff8841661f
```
https://github.com/asterinas/asterinas/blob/f1aae232341bda78aa7bf1906e3d00df160962a8/ostd/src/cpu/set.rs#L106
Below is my patch:
```
diff --git a/osdk/src/commands/build/bin.rs b/osdk/src/commands/build/bin.rs
index 042a2bd2..6b15d9ef 100644
--- a/osdk/src/commands/build/bin.rs
+++ b/osdk/src/commands/build/bin.rs
@@ -178,6 +178,8 @@ fn install_setup_with_arch(
let target_feature_args = match arch {
SetupInstallArch::X86_64 => {
concat!(
+ "-Cno-redzone=y",
+ "-Ccode-model=kernel",
"-Ctarget-feature=",
"+crt-static",
",-adx",
```
<details>
```
#0 ostd::panic::print_stack_trace () at src/panic.rs:62
#1 0xffffffff881baec9 in aster_nix::thread::oops::panic_handler (info=0xffffdfffffd7dd80) at src/thread/oops.rs:124
#2 0xffffffff881b9f3a in aster_nix::thread::oops::__ostd_panic_handler (info=0xffffdfffffd7dd80) at src/thread/oops.rs:82
#3 0xffffffff8804900a in aster_nix_osdk_bin::panic (info=0xffffdfffffd7dd80) at src/main.rs:11
#4 0xffffffff889a88c4 in core::panicking::panic_fmt (fmt=...) at src/panicking.rs:74
#5 0xffffffff889986be in core::panicking::panic_const::panic_const_mul_overflow () at src/panicking.rs:181
#6 0xffffffff8878259e in ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure#0} (bit_idx=0) at src/cpu/set.rs:106
#7 0xffffffff8878223b in core::ops::function::impls::{impl#3}::call_mut<(usize), ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (self=0xffffdfffffd7ded8, args=...)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:294
#8 0xffffffff887e27a3 in core::iter::traits::iterator::Iterator::find_map::check::{closure#0}<usize, ostd::cpu::CpuId, &mut ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (x=0)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2903
#9 0xffffffff88823361 in core::iter::traits::iterator::Iterator::try_fold<core::ops::range::Range<usize>, (), core::iter::traits::iterator::Iterator::find_map::check::{closure_env#0}<usize, ostd::cpu::CpuId, &mut ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>, core::ops::control_flow::ControlFlow<ostd::cpu::CpuId, ()>> (self=0xffffdfffffd7e2e0, init=(), f=...)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2406
#10 0xffffffff888232c2 in core::iter::traits::iterator::Iterator::find_map<core::ops::range::Range<usize>, ostd::cpu::CpuId, &mut ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (self=0xffffdfffffd7e2e0, f=0xffffdfffffd7e2f0)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/traits/iterator.rs:2909
#11 0xffffffff8878f241 in core::iter::adapters::filter_map::{impl#2}::next<ostd::cpu::CpuId, core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}> (self=0xffffdfffffd7e2e0)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/filter_map.rs:64
#12 0xffffffff887f41c3 in core::ops::function::FnOnce::call_once<fn(&mut core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>) -> core::option::Option<ostd::cpu::CpuId>, (&mut core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>)> ()
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:250
#13 0xffffffff8880fd8c in core::iter::adapters::flatten::and_then_or_clear<core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>, ostd::cpu::CpuId, fn(&mut core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>) -> core::option::Option<ostd::cpu::CpuId>> (opt=0xffffdfffffd7e2d8, f=0xdfffffd7e250ffff)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/flatten.rs:838
#14 0xffffffff8880fbbc in core::iter::adapters::flatten::{impl#35}::next<core::iter::adapters::map::Map<core::iter::adapters::enumerate::Enumerate<core::slice::iter::Iter<u64>>, ostd::cpu::set::{impl#0}::iter::{closure_env#0}>, core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>> (self=0xffffdfffffd7e2d8)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/flatten.rs:605
#15 0xffffffff8880fb9a in core::iter::adapters::flatten::{impl#3}::next<core::iter::adapters::enumerate::Enumerate<core::slice::iter::Iter<u64>>, core::iter::adapters::filter_map::FilterMap<core::ops::range::Range<usize>, ostd::cpu::set::{impl#0}::iter::{closure#0}::{closure_env#0}>, ostd::cpu::set::{impl#0}::iter::{closure_env#0}> (self=0xffffdfffffd7e2d8)
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/iter/adapters/flatten.rs:64
#16 0xffffffff88415062 in aster_nix::sched::priority_scheduler::PreemptScheduler<aster_nix::thread::Thread, ostd::task::Task>::select_cpu<aster_nix::thread::Thread, ostd::task::Task> (self=0xffffffff88d83540 <ostd::mm::heap_allocator::init::HEAP_SPACE+488768>,
entity=0xffffdfffffd7e480) at src/sched/priority_scheduler.rs:69
#17 0xffffffff88415314 in aster_nix::sched::priority_scheduler::{impl#1}::enqueue<aster_nix::thread::Thread, ostd::task::Task> (
self=0xffffffff88d83540 <ostd::mm::heap_allocator::init::HEAP_SPACE+488768>, task=...,
flags=ostd::task::scheduler::EnqueueFlags::Wake) at src/sched/priority_scheduler.rs:93
#18 0xffffffff88770f6a in ostd::task::scheduler::unpark_target (runnable=...) at src/task/scheduler/mod.rs:159
#19 0xffffffff887c2c5c in ostd::sync::wait::Waker::wake_up (self=0xffff8000706f3a50) at src/sync/wait.rs:263
#20 0xffffffff88103982 in aster_nix::time::wait::{impl#6}::wait_until_or_timeout_cancelled::{closure#0}::{closure#0}<aster_nix::time::wait::{impl#7}::wait_until_or_timeout_cancelled::{closure_env#0}<aster_nix::thread::work_queue::worker_pool::{impl#3}::run_monitor_loop::{closure_env#0}, (), aster_nix::time::wait::WaitTimeout::wait_until_or_timeout::{closure_env#0}<ostd::sync::wait::WaitQueue, aster_nix::thread::work_queue::worker_pool::{impl#3}::run_monitor_loop::{closure_env#0}, &core::time::Duration, ()>>, (), aster_nix::time::wait::WaitTimeout::wait_until_or_timeout::{closure_env#0}<ostd::sync::wait::WaitQueue, aster_nix::thread::work_queue::worker_pool::{impl#3}::run_monitor_loop::{closure_env#0}, &core::time::Duration, ()>> () at src/time/wait.rs:163
#21 0xffffffff888a97e6 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffff800070687f98, args=())
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468
#22 0xffffffff882d9c20 in aster_nix::time::core::timer::interval_timer_callback (timer=0xffff8000706f2600) at src/time/core/timer.rs:137
#23 0xffffffff880f77da in aster_nix::time::core::timer::{impl#0}::set_timeout::{closure#0} () at src/time/core/timer.rs:89
#24 0xffffffff888a97e6 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffff8000706f39e0, args=())
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468
#25 0xffffffff882da3aa in aster_nix::time::core::timer::TimerManager::process_expired_timers (
self=0xffffffff88d83650 <ostd::mm::heap_allocator::init::HEAP_SPACE+489040>) at src/time/core/timer.rs:206
#26 0xffffffff880954f2 in aster_nix::time::clocks::system_wide::init_jiffies_clock_manager::{closure#1} ()
at src/time/clocks/system_wide.rs:273
#27 0xffffffff888a97e6 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffffffff88d89f30 <ostd::mm::heap_allocator::init::HEAP_SPACE+515888>, args=())
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468
#28 0xffffffff882934f5 in aster_nix::time::softirq::timer_softirq_handler () at src/time/softirq.rs:31
#29 0xffffffff88112b4e in core::ops::function::Fn::call<fn(), ()> ()
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:79
#30 0xffffffff888a97e6 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffffffff88d0a650 <aster_softirq::LINES+32>, args=())
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468
#31 0xffffffff88606d2c in aster_softirq::process_pending () at src/lib.rs:165
#32 0xffffffff8860892e in core::ops::function::Fn::call<fn(), ()> ()
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:79
#33 0xffffffff888a97e6 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffffffff88e0c538 <ostd::trap::handler::BOTTOM_HALF_HANDLER>, args=())
at /root/.rustup/toolchains/nightly-2024-10-12-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2468
#34 0xffffffff887acf99 in ostd::trap::handler::process_bottom_half () at src/trap/handler.rs:42
#35 0xffffffff887ad00c in ostd::trap::handler::call_irq_callback_functions (trap_frame=0xffffdfffffd7ef70, irq_number=33)
at src/trap/handler.rs:56
#36 0xffffffff8877b89b in ostd::arch::x86::trap::trap_handler (f=0xffffdfffffd7ef70) at src/arch/x86/trap/mod.rs:251
#37 0xffffffff887c121a in __from_kernel ()
#38 0x0000000000000000 in ?? ()
```
</details>
But it makes sense because we should disable the red zone.
We also need to review the compile flags used in OSDK, as they appear to differ from the ones specified in the [Linux Makefile](https://github.com/torvalds/linux/blob/43fb83c17ba2d63dfb798f0be7453ed55ca3f9c2/arch/x86/Makefile) (`-Cno-redzone=y -Ccode-model=kernel -Ctarget-feature=-sse,-sse2,-sse3,-ssse3,-sse4.1,-sse4.2,-avx,-avx2`).
https://github.com/asterinas/asterinas/blob/f1aae232341bda78aa7bf1906e3d00df160962a8/osdk/src/commands/build/bin.rs#L178-L196
@tangruize No, I don't think that we should add the `no-redzone` option to `osdk/src/build/bin.rs`, which affects the build of the `linux-bzimage-setup` tool, not the kernel code itself. The kernel code is built in the `build_kernel_elf` function in `osdk/src/build/mod.rs`.
> We also need to review the compile flags used in OSDK, as they appear to differ from the ones specified in the [Linux Makefile](https://github.com/torvalds/linux/blob/43fb83c17ba2d63dfb798f0be7453ed55ca3f9c2/arch/x86/Makefile) (-Cno-redzone=y -Ccode-model=kernel -Ctarget-feature=-sse,-sse2,-sse3,-ssse3,-sse4.1,-sse4.2,-avx,-avx2).
Other CPU features such has sse and avx are disabled by default for the `x86_64-unknown-none` target.
> By default, Rust code generated for this target does not use any vector or floating-point registers (e.g. SSE, AVX). This allows the generated code to run in environments, such as kernels, which may need to avoid the use of such registers or which may have special considerations about the use of such registers (e.g. saving and restoring them to avoid breaking userspace code using the same registers). You can change code generation to use additional CPU features via the -C target-feature= codegen options to rustc, or via the #[target_feature] mechanism within Rust code.
The bug still occurs. It seems we should investigate why the panic always occurs during `memmove` ~~in `mmap` syscall~~.
@tangruize Regardless of whether the bug is fixed or not, we should disable redzones. Could you submit a PR for this fix?
We should also check if signal handling considers the red zone of user-space programs. We can open another issue or PR to address all the red zone things.
> We should also check if signal handling considers the red zone of user-space programs. We can open another issue or PR to address all the red zone things.
These are two separate problems and the user signal handling logic has correctly skipped the red zone in user space.
https://github.com/asterinas/asterinas/blob/495c93c2ada285d8abe44e7a6abd9e7adf0917b3/kernel/src/process/signal/mod.rs#L159-L160
Given that the bug always occurs in the `copy_backward` function of `memmove`, let's investigate [the function's implementation](https://github.com/rust-lang/compiler-builtins/blob/a09218f1c4d23ffbd97d68f0fefb5feed2469dc5/src/mem/x86_64.rs#L64-L89):
```rust
#[inline(always)]
pub unsafe fn copy_backward(dest: *mut u8, src: *const u8, count: usize) {
let (pre_byte_count, qword_count, byte_count) = rep_param(dest, count);
// We can't separate this block due to std/cld
asm!(
"std",
"rep movsb",
"sub $7, %rsi",
"sub $7, %rdi",
"mov {qword_count}, %rcx",
"rep movsq",
"test {pre_byte_count:e}, {pre_byte_count:e}",
"add $7, %rsi",
"add $7, %rdi",
"mov {pre_byte_count:e}, %ecx",
"rep movsb",
"cld",
pre_byte_count = in(reg) pre_byte_count,
qword_count = in(reg) qword_count,
inout("ecx") byte_count => _,
inout("rdi") dest.add(count - 1) => _,
inout("rsi") src.add(count - 1) => _,
// We modify flags, but we restore it afterwards
options(att_syntax, nostack, preserves_flags)
);
}
```
The function uses `std` (set `DF`) and `cld` (clear `DF`).
In the trap stack, the `DF` flag is set:
```
eflags 0x200486 [ ID IOPL=0 DF SF PF ]
```
In another run, I set a breakpoint before the shift instruction (which doesn't cause shift overflow), the `DF` flag is not set:
```
eflags 0x200082 [ ID IOPL=0 SF ]
```
We need to check if the `DF` flag is properly managed during traps (Note: [Linux clears both the `DF` and `AC` flags](https://github.com/torvalds/linux/blob/28eb75e178d389d325f1666e422bc13bbbb9804c/arch/x86/entry/entry_64.S), but we may not need to clear the `AC` flag because [SMAP](https://en.wikipedia.org/wiki/Supervisor_Mode_Access_Prevention) is currently not enabled).
I've tested this patch. The bug no longer occurs. But I'm not sure if the instruction is placed at the right location:
```diff
diff --git a/ostd/src/arch/x86/trap/trap.S b/ostd/src/arch/x86/trap/trap.S
index 7ab5ede4..f6096b57 100644
--- a/ostd/src/arch/x86/trap/trap.S
+++ b/ostd/src/arch/x86/trap/trap.S
@@ -124,6 +124,7 @@ __from_kernel:
push rax
mov rdi, rsp
+ cld
call trap_handler
.global trap_return
```
@cqs21 Could you assist @tangruize on this issue?
> I've tested this patch. The bug no longer occurs. But I'm not sure if the instruction is placed at the right location.
@tangruize Good job! The trap path from user should also be covered. Maybe place it at the beginning of `trap_common`. Thanks.
https://github.com/asterinas/asterinas/blob/5f35189a51ebc54298ea2cb0e4d53afe4e4e75eb/ostd/src/arch/x86/trap/trap.S#L59-L63
|
2024-11-24T15:05:40Z
|
9da6af03943c15456cdfd781021820a7da78ea40
|
asterinas/asterinas
|
diff --git a/kernel/src/fs/pipe.rs b/kernel/src/fs/pipe.rs
--- a/kernel/src/fs/pipe.rs
+++ b/kernel/src/fs/pipe.rs
@@ -247,7 +247,7 @@ mod test {
W: Fn(Arc<PipeWriter>) + Sync + Send + 'static,
R: Fn(Arc<PipeReader>) + Sync + Send + 'static,
{
- let channel = Channel::with_capacity(1);
+ let channel = Channel::with_capacity(2);
let (writer, readr) = channel.split();
let writer = PipeWriter::new(writer, StatusFlags::empty()).unwrap();
diff --git a/kernel/src/fs/pipe.rs b/kernel/src/fs/pipe.rs
--- a/kernel/src/fs/pipe.rs
+++ b/kernel/src/fs/pipe.rs
@@ -313,13 +313,13 @@ mod test {
fn test_write_full() {
test_blocking(
|writer| {
- assert_eq!(writer.write(&mut reader_from(&[1, 2])).unwrap(), 1);
+ assert_eq!(writer.write(&mut reader_from(&[1, 2, 3])).unwrap(), 2);
assert_eq!(writer.write(&mut reader_from(&[2])).unwrap(), 1);
},
|reader| {
- let mut buf = [0; 2];
- assert_eq!(reader.read(&mut writer_from(&mut buf)).unwrap(), 1);
- assert_eq!(&buf[..1], &[1]);
+ let mut buf = [0; 3];
+ assert_eq!(reader.read(&mut writer_from(&mut buf)).unwrap(), 2);
+ assert_eq!(&buf[..2], &[1, 2]);
assert_eq!(reader.read(&mut writer_from(&mut buf)).unwrap(), 1);
assert_eq!(&buf[..1], &[2]);
},
diff --git a/kernel/src/fs/pipe.rs b/kernel/src/fs/pipe.rs
--- a/kernel/src/fs/pipe.rs
+++ b/kernel/src/fs/pipe.rs
@@ -343,7 +343,7 @@ mod test {
fn test_write_closed() {
test_blocking(
|writer| {
- assert_eq!(writer.write(&mut reader_from(&[1, 2])).unwrap(), 1);
+ assert_eq!(writer.write(&mut reader_from(&[1, 2, 3])).unwrap(), 2);
assert_eq!(
writer.write(&mut reader_from(&[2])).unwrap_err().error(),
Errno::EPIPE
diff --git a/kernel/src/fs/pipe.rs b/kernel/src/fs/pipe.rs
--- a/kernel/src/fs/pipe.rs
+++ b/kernel/src/fs/pipe.rs
@@ -354,6 +354,24 @@ mod test {
);
}
+ #[ktest]
+ fn test_write_atomicity() {
+ test_blocking(
+ |writer| {
+ assert_eq!(writer.write(&mut reader_from(&[1])).unwrap(), 1);
+ assert_eq!(writer.write(&mut reader_from(&[1, 2])).unwrap(), 2);
+ },
+ |reader| {
+ let mut buf = [0; 3];
+ assert_eq!(reader.read(&mut writer_from(&mut buf)).unwrap(), 1);
+ assert_eq!(&buf[..1], &[1]);
+ assert_eq!(reader.read(&mut writer_from(&mut buf)).unwrap(), 2);
+ assert_eq!(&buf[..2], &[1, 2]);
+ },
+ Ordering::WriteThenRead,
+ );
+ }
+
fn reader_from(buf: &[u8]) -> VmReader {
VmReader::from(buf).to_fallible()
}
diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs
--- a/kernel/src/fs/utils/channel.rs
+++ b/kernel/src/fs/utils/channel.rs
@@ -22,6 +22,19 @@ pub struct Channel<T> {
consumer: Consumer<T>,
}
+/// Maximum number of bytes guaranteed to be written to a pipe atomically.
+///
+/// If the number of bytes to be written is less than the threshold, the write must be atomic.
+/// A non-blocking atomic write may fail with `EAGAIN`, even if there is room for a partial write.
+/// In other words, a partial write is not allowed for an atomic write.
+///
+/// For more details, see the description of `PIPE_BUF` in
+/// <https://man7.org/linux/man-pages/man7/pipe.7.html>.
+#[cfg(not(ktest))]
+const PIPE_BUF: usize = 4096;
+#[cfg(ktest)]
+const PIPE_BUF: usize = 2;
+
impl<T> Channel<T> {
/// Creates a new channel with the given capacity.
///
|
[
"1554"
] |
0.9
|
11382524d1d23cc6d41adf977a72138baa39e38d
|
PIPE implementation does not guarantee atomic writes for up to PIPE_BUF bytes
### Describe the bug
The current implementation of the PIPE in Asterinas does not ensure that writes of up to PIPE_BUF bytes are atomic.
### To Reproduce
Apply the following patch and run `test/pipe/pipe_atomicity`
<details><summary>patch file</summary>
```diff
diff --git a/test/apps/pipe/pipe_atomicity.c b/test/apps/pipe/pipe_atomicity.c
new file mode 100644
index 00000000..1e473d78
--- /dev/null
+++ b/test/apps/pipe/pipe_atomicity.c
@@ -0,0 +1,36 @@
+// SPDX-License-Identifier: MPL-2.0
+
+#define _GNU_SOURCE
+
+#include "../network/test.h"
+#include <signal.h>
+#include <string.h>
+#include <sys/poll.h>
+#include <unistd.h>
+
+static int rfd, wfd;
+
+FN_SETUP(short_read_and_write)
+{
+ int fildes[2];
+
+ CHECK(pipe(fildes));
+ rfd = fildes[0];
+ wfd = fildes[1];
+
+}
+END_SETUP()
+
+FN_TEST(atomicity)
+{
+ char buf[511] = { 0 };
+
+ // for (int i = 0; i < 130; i++)
+ // TEST_RES(write(wfd, buf, 511), _ret == 511);
+ for (int i = 0; i < 130; i++)
+ {
+ ssize_t res = write(wfd, buf, 511);
+ printf("i=%d, res=%ld\n", i, res);
+ }
+}
+END_TEST()
```
</details>
### Expected behavior
In the current Asterinas implementation, writing 511 bytes results in partial writes (128 bytes) after 128 iterations, while the Linux implementation blocks after 127 iterations:

### Environment
branch: [7ddfd42](https://github.com/asterinas/asterinas/tree/7ddfd42baa210656127044995d8707fde74fab4d)
|
asterinas__asterinas-1559
| 1,559
|
diff --git a/kernel/src/fs/pipe.rs b/kernel/src/fs/pipe.rs
--- a/kernel/src/fs/pipe.rs
+++ b/kernel/src/fs/pipe.rs
@@ -247,7 +247,7 @@ mod test {
W: Fn(Arc<PipeWriter>) + Sync + Send + 'static,
R: Fn(Arc<PipeReader>) + Sync + Send + 'static,
{
- let channel = Channel::with_capacity(1);
+ let channel = Channel::with_capacity(2);
let (writer, readr) = channel.split();
let writer = PipeWriter::new(writer, StatusFlags::empty()).unwrap();
diff --git a/kernel/src/fs/pipe.rs b/kernel/src/fs/pipe.rs
--- a/kernel/src/fs/pipe.rs
+++ b/kernel/src/fs/pipe.rs
@@ -313,13 +313,13 @@ mod test {
fn test_write_full() {
test_blocking(
|writer| {
- assert_eq!(writer.write(&mut reader_from(&[1, 2])).unwrap(), 1);
+ assert_eq!(writer.write(&mut reader_from(&[1, 2, 3])).unwrap(), 2);
assert_eq!(writer.write(&mut reader_from(&[2])).unwrap(), 1);
},
|reader| {
- let mut buf = [0; 2];
- assert_eq!(reader.read(&mut writer_from(&mut buf)).unwrap(), 1);
- assert_eq!(&buf[..1], &[1]);
+ let mut buf = [0; 3];
+ assert_eq!(reader.read(&mut writer_from(&mut buf)).unwrap(), 2);
+ assert_eq!(&buf[..2], &[1, 2]);
assert_eq!(reader.read(&mut writer_from(&mut buf)).unwrap(), 1);
assert_eq!(&buf[..1], &[2]);
},
diff --git a/kernel/src/fs/pipe.rs b/kernel/src/fs/pipe.rs
--- a/kernel/src/fs/pipe.rs
+++ b/kernel/src/fs/pipe.rs
@@ -343,7 +343,7 @@ mod test {
fn test_write_closed() {
test_blocking(
|writer| {
- assert_eq!(writer.write(&mut reader_from(&[1, 2])).unwrap(), 1);
+ assert_eq!(writer.write(&mut reader_from(&[1, 2, 3])).unwrap(), 2);
assert_eq!(
writer.write(&mut reader_from(&[2])).unwrap_err().error(),
Errno::EPIPE
diff --git a/kernel/src/fs/pipe.rs b/kernel/src/fs/pipe.rs
--- a/kernel/src/fs/pipe.rs
+++ b/kernel/src/fs/pipe.rs
@@ -354,6 +354,24 @@ mod test {
);
}
+ #[ktest]
+ fn test_write_atomicity() {
+ test_blocking(
+ |writer| {
+ assert_eq!(writer.write(&mut reader_from(&[1])).unwrap(), 1);
+ assert_eq!(writer.write(&mut reader_from(&[1, 2])).unwrap(), 2);
+ },
+ |reader| {
+ let mut buf = [0; 3];
+ assert_eq!(reader.read(&mut writer_from(&mut buf)).unwrap(), 1);
+ assert_eq!(&buf[..1], &[1]);
+ assert_eq!(reader.read(&mut writer_from(&mut buf)).unwrap(), 2);
+ assert_eq!(&buf[..2], &[1, 2]);
+ },
+ Ordering::WriteThenRead,
+ );
+ }
+
fn reader_from(buf: &[u8]) -> VmReader {
VmReader::from(buf).to_fallible()
}
diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs
--- a/kernel/src/fs/utils/channel.rs
+++ b/kernel/src/fs/utils/channel.rs
@@ -22,6 +22,19 @@ pub struct Channel<T> {
consumer: Consumer<T>,
}
+/// Maximum number of bytes guaranteed to be written to a pipe atomically.
+///
+/// If the number of bytes to be written is less than the threshold, the write must be atomic.
+/// A non-blocking atomic write may fail with `EAGAIN`, even if there is room for a partial write.
+/// In other words, a partial write is not allowed for an atomic write.
+///
+/// For more details, see the description of `PIPE_BUF` in
+/// <https://man7.org/linux/man-pages/man7/pipe.7.html>.
+#[cfg(not(ktest))]
+const PIPE_BUF: usize = 4096;
+#[cfg(ktest)]
+const PIPE_BUF: usize = 2;
+
impl<T> Channel<T> {
/// Creates a new channel with the given capacity.
///
diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs
--- a/kernel/src/fs/utils/channel.rs
+++ b/kernel/src/fs/utils/channel.rs
@@ -114,7 +127,7 @@ impl<T> Producer<T> {
}
fn update_pollee(&self) {
- // In theory, `rb.is_full()`/`rb.is_empty()`, where the `rb` is taken from either
+ // In theory, `rb.free_len()`/`rb.is_empty()`, where the `rb` is taken from either
// `this_end` or `peer_end`, should reflect the same state. However, we need to take the
// correct lock when updating the events to avoid races between the state check and the
// event update.
diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs
--- a/kernel/src/fs/utils/channel.rs
+++ b/kernel/src/fs/utils/channel.rs
@@ -114,7 +127,7 @@ impl<T> Producer<T> {
}
fn update_pollee(&self) {
- // In theory, `rb.is_full()`/`rb.is_empty()`, where the `rb` is taken from either
+ // In theory, `rb.free_len()`/`rb.is_empty()`, where the `rb` is taken from either
// `this_end` or `peer_end`, should reflect the same state. However, we need to take the
// correct lock when updating the events to avoid races between the state check and the
// event update.
diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs
--- a/kernel/src/fs/utils/channel.rs
+++ b/kernel/src/fs/utils/channel.rs
@@ -123,7 +136,7 @@ impl<T> Producer<T> {
let rb = this_end.rb();
if self.is_shutdown() {
// The POLLOUT event is always set in this case. Don't try to remove it.
- } else if rb.is_full() {
+ } else if rb.free_len() < PIPE_BUF {
this_end.pollee.del_events(IoEvents::OUT);
}
drop(rb);
diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs
--- a/kernel/src/fs/utils/channel.rs
+++ b/kernel/src/fs/utils/channel.rs
@@ -123,7 +136,7 @@ impl<T> Producer<T> {
let rb = this_end.rb();
if self.is_shutdown() {
// The POLLOUT event is always set in this case. Don't try to remove it.
- } else if rb.is_full() {
+ } else if rb.free_len() < PIPE_BUF {
this_end.pollee.del_events(IoEvents::OUT);
}
drop(rb);
diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs
--- a/kernel/src/fs/utils/channel.rs
+++ b/kernel/src/fs/utils/channel.rs
@@ -204,7 +217,7 @@ impl<T> Consumer<T> {
}
fn update_pollee(&self) {
- // In theory, `rb.is_full()`/`rb.is_empty()`, where the `rb` is taken from either
+ // In theory, `rb.free_len()`/`rb.is_empty()`, where the `rb` is taken from either
// `this_end` or `peer_end`, should reflect the same state. However, we need to take the
// correct lock when updating the events to avoid races between the state check and the
// event update.
diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs
--- a/kernel/src/fs/utils/channel.rs
+++ b/kernel/src/fs/utils/channel.rs
@@ -204,7 +217,7 @@ impl<T> Consumer<T> {
}
fn update_pollee(&self) {
- // In theory, `rb.is_full()`/`rb.is_empty()`, where the `rb` is taken from either
+ // In theory, `rb.free_len()`/`rb.is_empty()`, where the `rb` is taken from either
// `this_end` or `peer_end`, should reflect the same state. However, we need to take the
// correct lock when updating the events to avoid races between the state check and the
// event update.
diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs
--- a/kernel/src/fs/utils/channel.rs
+++ b/kernel/src/fs/utils/channel.rs
@@ -218,7 +231,7 @@ impl<T> Consumer<T> {
let peer_end = self.peer_end();
let rb = peer_end.rb();
- if !rb.is_full() {
+ if rb.free_len() >= PIPE_BUF {
peer_end.pollee.add_events(IoEvents::OUT);
}
drop(rb);
diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs
--- a/kernel/src/fs/utils/channel.rs
+++ b/kernel/src/fs/utils/channel.rs
@@ -218,7 +231,7 @@ impl<T> Consumer<T> {
let peer_end = self.peer_end();
let rb = peer_end.rb();
- if !rb.is_full() {
+ if rb.free_len() >= PIPE_BUF {
peer_end.pollee.add_events(IoEvents::OUT);
}
drop(rb);
diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs
--- a/kernel/src/fs/utils/channel.rs
+++ b/kernel/src/fs/utils/channel.rs
@@ -307,6 +320,10 @@ impl<R: TRights> Fifo<u8, R> {
#[require(R > Write)]
pub fn write(&self, reader: &mut dyn MultiRead) -> Result<usize> {
let mut rb = self.common.producer.rb();
+ if rb.free_len() < reader.sum_lens() && reader.sum_lens() <= PIPE_BUF {
+ // No sufficient space for an atomic write
+ return Ok(0);
+ }
rb.write_fallible(reader)
}
}
diff --git a/kernel/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs
--- a/kernel/src/fs/utils/channel.rs
+++ b/kernel/src/fs/utils/channel.rs
@@ -307,6 +320,10 @@ impl<R: TRights> Fifo<u8, R> {
#[require(R > Write)]
pub fn write(&self, reader: &mut dyn MultiRead) -> Result<usize> {
let mut rb = self.common.producer.rb();
+ if rb.free_len() < reader.sum_lens() && reader.sum_lens() <= PIPE_BUF {
+ // No sufficient space for an atomic write
+ return Ok(0);
+ }
rb.write_fallible(reader)
}
}
|
This one is easy to fix. Just check if the remaining space in the internal buffer of a pipe is no less than `PIPE_BUF` before actually writing the data.
|
2024-11-05T07:28:33Z
|
9da6af03943c15456cdfd781021820a7da78ea40
|
asterinas/asterinas
|
diff --git a/tools/bump_version.sh b/tools/bump_version.sh
--- a/tools/bump_version.sh
+++ b/tools/bump_version.sh
@@ -106,6 +106,9 @@ DOCS_DIR=${ASTER_SRC_DIR}/docs
OSTD_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/Cargo.toml
OSTD_TEST_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/libs/ostd-test/Cargo.toml
OSTD_MACROS_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/libs/ostd-macros/Cargo.toml
+LINUX_BOOT_PARAMS_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/libs/linux-bzimage/boot-params/Cargo.toml
+LINUX_BZIMAGE_BUILDER_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/libs/linux-bzimage/builder/Cargo.toml
+LINUX_BZIMAGE_SETUP_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/libs/linux-bzimage/setup/Cargo.toml
OSDK_CARGO_TOML_PATH=${ASTER_SRC_DIR}/osdk/Cargo.toml
OSDK_TEST_RUNNER_CARGO_TOML_PATH=${ASTER_SRC_DIR}/osdk/test-kernel/Cargo.toml
VERSION_PATH=${ASTER_SRC_DIR}/VERSION
diff --git a/tools/bump_version.sh b/tools/bump_version.sh
--- a/tools/bump_version.sh
+++ b/tools/bump_version.sh
@@ -125,11 +128,17 @@ new_version=$(bump_version ${current_version})
update_package_version ${OSTD_TEST_CARGO_TOML_PATH}
update_package_version ${OSTD_MACROS_CARGO_TOML_PATH}
update_package_version ${OSTD_CARGO_TOML_PATH}
+update_package_version ${LINUX_BOOT_PARAMS_CARGO_TOML_PATH}
+update_package_version ${LINUX_BZIMAGE_BUILDER_CARGO_TOML_PATH}
+update_package_version ${LINUX_BZIMAGE_SETUP_CARGO_TOML_PATH}
update_dep_version ${OSTD_CARGO_TOML_PATH} ostd-test
+update_dep_version ${OSTD_CARGO_TOML_PATH} linux-boot-params
update_dep_version ${OSTD_CARGO_TOML_PATH} ostd-macros
+update_dep_version ${LINUX_BZIMAGE_SETUP_CARGO_TOML_PATH} linux-boot-params
update_package_version ${OSDK_CARGO_TOML_PATH}
update_package_version ${OSDK_TEST_RUNNER_CARGO_TOML_PATH}
update_dep_version ${OSDK_TEST_RUNNER_CARGO_TOML_PATH} ostd
+update_dep_version ${OSDK_CARGO_TOML_PATH} linux-bzimage-builder
# Automatically bump Cargo.lock files
cargo update -p aster-nix --precise $new_version # For Cargo.lock
diff --git a/tools/github_workflows/publish_osdk_and_ostd.sh b/tools/github_workflows/publish_osdk_and_ostd.sh
--- a/tools/github_workflows/publish_osdk_and_ostd.sh
+++ b/tools/github_workflows/publish_osdk_and_ostd.sh
@@ -67,6 +69,7 @@ TARGETS="x86_64-unknown-none"
for TARGET in $TARGETS; do
do_publish_for ostd/libs/ostd-macros $TARGET
do_publish_for ostd/libs/ostd-test $TARGET
+ do_publish_for ostd/libs/linux-bzimage/setup $TARGET
do_publish_for ostd $TARGET
do_publish_for osdk/test-kernel $TARGET
|
[
"1291"
] |
0.9
|
2af9916de92f8ca1e694bb6ac5e33111bbcf51fd
|
Invalid opcode after relocation for Linux EFI-handover boot
<!-- Thank you for taking the time to report a bug. Your input is valuable to us.
Please replace all the <angle brackets> below with your own information. -->
### Describe the bug
<!-- A clear and concise description of what the bug is. -->
Sometimes the Linux EFI-handover boot will fail due to invalid opcode failure during early booting.
### To Reproduce
With KVM on,
```bash
make run AUTO_TEST=syscall BOOT_PROTOCOL=linux-efi-handover64
```
<!-- Steps to reproduce the behavior. Example:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error -->
### Logs
```
...
Adding bitflags v1.3.2 (latest: v2.6.0)
Adding raw-cpuid v10.7.0 (latest: v11.1.0)
Adding syn v1.0.109 (latest: v2.0.77)
Adding uefi v0.26.0 (latest: v0.31.0)
BdsDxe: loading Boot0001 "UEFI QEMU DVD-ROM QM00005 " from PciRoot(0x0)/Pci(0x1F,0x2)/Sata(0x2,0xFFFF,0x0)
BdsDxe: starting Boot0001 "UEFI QEMU DVD-ROM QM00005 " from PciRoot(0x0)/Pci(0x1F,0x2)/Sata(0x2,0xFFFF,0x0)
[EFI stub] Relocations applied.
!!!! X64 Exception Type - 06(#UD - Invalid Opcode) CPU Apic ID - 00000000 !!!!
RIP - 000000007CBC90F0, CS - 0000000000000038, RFLAGS - 0000000000210217
RAX - 000000007FF12BB9, RCX - 000000007CBC19A8, RDX - 0000000000000001
RBX - 000000007CBC23B8, RSP - 000000007CBC2398, RBP - 0000000000000001
RSI - 000000007CBBBB77, RDI - 000000007CBC2408
R8 - 00000000000000AF, R9 - 0000000000000014, R10 - 000000007E43F78D
R11 - 0000000000000008, R12 - 000000007E43F78D, R13 - 0000000000000008
R14 - 0000000000000002, R15 - 000000007E977518
DS - 0000000000000030, ES - 0000000000000030, FS - 0000000000000030
GS - 0000000000000030, SS - 0000000000000030
CR0 - 0000000080010033, CR2 - 0000000000000000, CR3 - 000000007FC01000
CR4 - 0000000000000668, CR8 - 0000000000000000
DR0 - 0000000000000000, DR1 - 0000000000000000, DR2 - 0000000000000000
DR3 - 0000000000000000, DR6 - 00000000FFFF0FF0, DR7 - 0000000000000400
GDTR - 000000007F9DE000 0000000000000047, LDTR - 0000000000000000
IDTR - 000000007F470018 0000000000000FFF, TR - 0000000000000000
FXSAVE_STATE - 000000007CBC1FF0
```
<!-- If applicable, add log snippets or files to help explain and debug the problem. Please use code blocks (```) to format logs. -->
<!-- Once again, thank you for helping us improve our project! -->
|
asterinas__asterinas-1447
| 1,447
|
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1,6 +1,6 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
-version = 3
+version = 4
[[package]]
name = "acpi"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1,6 +1,6 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
-version = 3
+version = 4
[[package]]
name = "acpi"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -875,9 +875,9 @@ dependencies = [
"log",
"uart_16550",
"uefi",
- "uefi-services",
- "x86_64",
- "xmas-elf 0.8.0",
+ "uefi-raw",
+ "x86_64 0.15.1",
+ "xmas-elf 0.9.1",
]
[[package]]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -875,9 +875,9 @@ dependencies = [
"log",
"uart_16550",
"uefi",
- "uefi-services",
- "x86_64",
- "xmas-elf 0.8.0",
+ "uefi-raw",
+ "x86_64 0.15.1",
+ "xmas-elf 0.9.1",
]
[[package]]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -953,7 +953,7 @@ dependencies = [
"log",
"multiboot2-common",
"ptr_meta",
- "uefi-raw 0.8.0",
+ "uefi-raw",
]
[[package]]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -953,7 +953,7 @@ dependencies = [
"log",
"multiboot2-common",
"ptr_meta",
- "uefi-raw 0.8.0",
+ "uefi-raw",
]
[[package]]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1119,7 +1119,7 @@ dependencies = [
"unwinding",
"volatile",
"x86",
- "x86_64",
+ "x86_64 0.14.11",
"xarray",
]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1119,7 +1119,7 @@ dependencies = [
"unwinding",
"volatile",
"x86",
- "x86_64",
+ "x86_64 0.14.11",
"xarray",
]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1238,6 +1238,12 @@ dependencies = [
"syn 1.0.109",
]
+[[package]]
+name = "qemu-exit"
+version = "3.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8bb0fd6580eeed0103c054e3fba2c2618ff476943762f28a645b63b8692b21c9"
+
[[package]]
name = "quote"
version = "1.0.37"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1238,6 +1238,12 @@ dependencies = [
"syn 1.0.109",
]
+[[package]]
+name = "qemu-exit"
+version = "3.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8bb0fd6580eeed0103c054e3fba2c2618ff476943762f28a645b63b8692b21c9"
+
[[package]]
name = "quote"
version = "1.0.37"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1470,7 +1476,7 @@ dependencies = [
"iced-x86",
"lazy_static",
"raw-cpuid",
- "x86_64",
+ "x86_64 0.14.11",
]
[[package]]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1470,7 +1476,7 @@ dependencies = [
"iced-x86",
"lazy_static",
"raw-cpuid",
- "x86_64",
+ "x86_64 0.14.11",
]
[[package]]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1572,50 +1578,41 @@ dependencies = [
[[package]]
name = "ucs2"
-version = "0.3.2"
+version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bad643914094137d475641b6bab89462505316ec2ce70907ad20102d28a79ab8"
+checksum = "df79298e11f316400c57ec268f3c2c29ac3c4d4777687955cd3d4f3a35ce7eba"
dependencies = [
"bit_field",
]
[[package]]
name = "uefi"
-version = "0.26.0"
+version = "0.32.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "07ead9f748a4646479b850add36b527113a80e80a7e0f44d7b0334291850dcc5"
+checksum = "91f17ea8502a6bd414acb2bf5194f90ca4c48e33a2d18cb57eab3294d2050d99"
dependencies = [
"bitflags 2.6.0",
+ "cfg-if",
"log",
"ptr_meta",
+ "qemu-exit",
"ucs2",
"uefi-macros",
- "uefi-raw 0.5.0",
+ "uefi-raw",
"uguid",
]
[[package]]
name = "uefi-macros"
-version = "0.13.0"
+version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "26a7b1c2c808c3db854a54d5215e3f7e7aaf5dcfbce095598cba6af29895695d"
+checksum = "c19ee3a01d435eda42cb9931269b349d28a1762f91ddf01c68d276f74b957cc3"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.77",
]
-[[package]]
-name = "uefi-raw"
-version = "0.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "864ac69eadd877bfb34e7814be1928122ed0057d9f975169a56ee496aa7bdfd7"
-dependencies = [
- "bitflags 2.6.0",
- "ptr_meta",
- "uguid",
-]
-
[[package]]
name = "uefi-raw"
version = "0.8.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1572,50 +1578,41 @@ dependencies = [
[[package]]
name = "ucs2"
-version = "0.3.2"
+version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bad643914094137d475641b6bab89462505316ec2ce70907ad20102d28a79ab8"
+checksum = "df79298e11f316400c57ec268f3c2c29ac3c4d4777687955cd3d4f3a35ce7eba"
dependencies = [
"bit_field",
]
[[package]]
name = "uefi"
-version = "0.26.0"
+version = "0.32.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "07ead9f748a4646479b850add36b527113a80e80a7e0f44d7b0334291850dcc5"
+checksum = "91f17ea8502a6bd414acb2bf5194f90ca4c48e33a2d18cb57eab3294d2050d99"
dependencies = [
"bitflags 2.6.0",
+ "cfg-if",
"log",
"ptr_meta",
+ "qemu-exit",
"ucs2",
"uefi-macros",
- "uefi-raw 0.5.0",
+ "uefi-raw",
"uguid",
]
[[package]]
name = "uefi-macros"
-version = "0.13.0"
+version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "26a7b1c2c808c3db854a54d5215e3f7e7aaf5dcfbce095598cba6af29895695d"
+checksum = "c19ee3a01d435eda42cb9931269b349d28a1762f91ddf01c68d276f74b957cc3"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.77",
]
-[[package]]
-name = "uefi-raw"
-version = "0.5.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "864ac69eadd877bfb34e7814be1928122ed0057d9f975169a56ee496aa7bdfd7"
-dependencies = [
- "bitflags 2.6.0",
- "ptr_meta",
- "uguid",
-]
-
[[package]]
name = "uefi-raw"
version = "0.8.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1627,17 +1624,6 @@ dependencies = [
"uguid",
]
-[[package]]
-name = "uefi-services"
-version = "0.23.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a79fcb420624743c895bad0f9480fbc2f64e7c8d8611fb1ada6bdd799942feb4"
-dependencies = [
- "cfg-if",
- "log",
- "uefi",
-]
-
[[package]]
name = "uguid"
version = "2.1.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1627,17 +1624,6 @@ dependencies = [
"uguid",
]
-[[package]]
-name = "uefi-services"
-version = "0.23.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a79fcb420624743c895bad0f9480fbc2f64e7c8d8611fb1ada6bdd799942feb4"
-dependencies = [
- "cfg-if",
- "log",
- "uefi",
-]
-
[[package]]
name = "uguid"
version = "2.1.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1751,6 +1737,18 @@ dependencies = [
"volatile",
]
+[[package]]
+name = "x86_64"
+version = "0.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4bc79523af8abf92fb1a970c3e086c5a343f6bcc1a0eb890f575cbb3b45743df"
+dependencies = [
+ "bit_field",
+ "bitflags 2.6.0",
+ "rustversion",
+ "volatile",
+]
+
[[package]]
name = "xarray"
version = "0.1.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1751,6 +1737,18 @@ dependencies = [
"volatile",
]
+[[package]]
+name = "x86_64"
+version = "0.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4bc79523af8abf92fb1a970c3e086c5a343f6bcc1a0eb890f575cbb3b45743df"
+dependencies = [
+ "bit_field",
+ "bitflags 2.6.0",
+ "rustversion",
+ "volatile",
+]
+
[[package]]
name = "xarray"
version = "0.1.0"
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -89,7 +89,7 @@ endif
ifeq ($(BOOT_PROTOCOL), linux-efi-handover64)
CARGO_OSDK_ARGS += --grub-mkrescue=/usr/bin/grub-mkrescue
CARGO_OSDK_ARGS += --grub-boot-protocol="linux"
-CARGO_OSDK_ARGS += --encoding gzip
+CARGO_OSDK_ARGS += --encoding raw # FIXME: GZIP self-decompression triggers CPU faults
else ifeq ($(BOOT_PROTOCOL), linux-legacy32)
CARGO_OSDK_ARGS += --linux-x86-legacy-boot
CARGO_OSDK_ARGS += --grub-boot-protocol="linux"
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -89,7 +89,7 @@ endif
ifeq ($(BOOT_PROTOCOL), linux-efi-handover64)
CARGO_OSDK_ARGS += --grub-mkrescue=/usr/bin/grub-mkrescue
CARGO_OSDK_ARGS += --grub-boot-protocol="linux"
-CARGO_OSDK_ARGS += --encoding gzip
+CARGO_OSDK_ARGS += --encoding raw # FIXME: GZIP self-decompression triggers CPU faults
else ifeq ($(BOOT_PROTOCOL), linux-legacy32)
CARGO_OSDK_ARGS += --linux-x86-legacy-boot
CARGO_OSDK_ARGS += --grub-boot-protocol="linux"
diff --git a/osdk/Cargo.toml b/osdk/Cargo.toml
--- a/osdk/Cargo.toml
+++ b/osdk/Cargo.toml
@@ -9,15 +9,8 @@ repository = "https://github.com/asterinas/asterinas"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
-[dependencies.linux-bzimage-builder]
-# The path for local development
-path = "../ostd/libs/linux-bzimage/builder"
-# The version specified here is used for publishing on crates.io.
-# Please update this version when publishing the cargo-osdk crate
-# if there have been any changes to the dependent crate.
-version = "0.2.0"
-
[dependencies]
+linux-bzimage-builder = { version = "0.2.0", path = "../ostd/libs/linux-bzimage/builder" }
clap = { version = "4.4.17", features = ["cargo", "derive"] }
chrono = "0.4.38"
env_logger = "0.11.0"
diff --git a/osdk/Cargo.toml b/osdk/Cargo.toml
--- a/osdk/Cargo.toml
+++ b/osdk/Cargo.toml
@@ -9,15 +9,8 @@ repository = "https://github.com/asterinas/asterinas"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
-[dependencies.linux-bzimage-builder]
-# The path for local development
-path = "../ostd/libs/linux-bzimage/builder"
-# The version specified here is used for publishing on crates.io.
-# Please update this version when publishing the cargo-osdk crate
-# if there have been any changes to the dependent crate.
-version = "0.2.0"
-
[dependencies]
+linux-bzimage-builder = { version = "0.2.0", path = "../ostd/libs/linux-bzimage/builder" }
clap = { version = "4.4.17", features = ["cargo", "derive"] }
chrono = "0.4.38"
env_logger = "0.11.0"
diff --git a/osdk/src/commands/build/bin.rs b/osdk/src/commands/build/bin.rs
--- a/osdk/src/commands/build/bin.rs
+++ b/osdk/src/commands/build/bin.rs
@@ -167,7 +167,37 @@ fn install_setup_with_arch(
let target_dir = std::fs::canonicalize(target_dir).unwrap();
let mut cmd = Command::new("cargo");
- cmd.env("RUSTFLAGS", "-Ccode-model=kernel -Crelocation-model=pie -Ctarget-feature=+crt-static -Zplt=yes -Zrelax-elf-relocations=yes -Crelro-level=full");
+ let mut rustflags = vec![
+ "-Cdebuginfo=2",
+ "-Ccode-model=kernel",
+ "-Crelocation-model=pie",
+ "-Zplt=yes",
+ "-Zrelax-elf-relocations=yes",
+ "-Crelro-level=full",
+ ];
+ let target_feature_args = match arch {
+ SetupInstallArch::X86_64 => {
+ concat!(
+ "-Ctarget-feature=",
+ "+crt-static",
+ ",-adx",
+ ",-aes",
+ ",-avx",
+ ",-avx2",
+ ",-fxsr",
+ ",-sse",
+ ",-sse2",
+ ",-sse3",
+ ",-sse4.1",
+ ",-sse4.2",
+ ",-ssse3",
+ ",-xsave",
+ )
+ }
+ SetupInstallArch::Other(_) => "-Ctarget-feature=+crt-static",
+ };
+ rustflags.push(target_feature_args);
+ cmd.env("RUSTFLAGS", rustflags.join(" "));
cmd.arg("install").arg("linux-bzimage-setup");
cmd.arg("--force");
cmd.arg("--root").arg(install_dir.as_ref());
diff --git a/osdk/src/commands/build/bin.rs b/osdk/src/commands/build/bin.rs
--- a/osdk/src/commands/build/bin.rs
+++ b/osdk/src/commands/build/bin.rs
@@ -167,7 +167,37 @@ fn install_setup_with_arch(
let target_dir = std::fs::canonicalize(target_dir).unwrap();
let mut cmd = Command::new("cargo");
- cmd.env("RUSTFLAGS", "-Ccode-model=kernel -Crelocation-model=pie -Ctarget-feature=+crt-static -Zplt=yes -Zrelax-elf-relocations=yes -Crelro-level=full");
+ let mut rustflags = vec![
+ "-Cdebuginfo=2",
+ "-Ccode-model=kernel",
+ "-Crelocation-model=pie",
+ "-Zplt=yes",
+ "-Zrelax-elf-relocations=yes",
+ "-Crelro-level=full",
+ ];
+ let target_feature_args = match arch {
+ SetupInstallArch::X86_64 => {
+ concat!(
+ "-Ctarget-feature=",
+ "+crt-static",
+ ",-adx",
+ ",-aes",
+ ",-avx",
+ ",-avx2",
+ ",-fxsr",
+ ",-sse",
+ ",-sse2",
+ ",-sse3",
+ ",-sse4.1",
+ ",-sse4.2",
+ ",-ssse3",
+ ",-xsave",
+ )
+ }
+ SetupInstallArch::Other(_) => "-Ctarget-feature=+crt-static",
+ };
+ rustflags.push(target_feature_args);
+ cmd.env("RUSTFLAGS", rustflags.join(" "));
cmd.arg("install").arg("linux-bzimage-setup");
cmd.arg("--force");
cmd.arg("--root").arg(install_dir.as_ref());
diff --git a/osdk/src/commands/build/bin.rs b/osdk/src/commands/build/bin.rs
--- a/osdk/src/commands/build/bin.rs
+++ b/osdk/src/commands/build/bin.rs
@@ -175,10 +205,9 @@ fn install_setup_with_arch(
let crate_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let setup_dir = crate_dir.join("../ostd/libs/linux-bzimage/setup");
cmd.arg("--path").arg(setup_dir);
+ } else {
+ cmd.arg("--version").arg(env!("CARGO_PKG_VERSION"));
}
- // Remember to upgrade this version if new version of linux-bzimage-setup is released.
- const LINUX_BZIMAGE_SETUP_VERSION: &str = "0.1.0";
- cmd.arg("--version").arg(LINUX_BZIMAGE_SETUP_VERSION);
cmd.arg("--target").arg(match arch {
SetupInstallArch::X86_64 => "x86_64-unknown-none",
SetupInstallArch::Other(path) => path.to_str().unwrap(),
diff --git a/osdk/src/commands/build/bin.rs b/osdk/src/commands/build/bin.rs
--- a/osdk/src/commands/build/bin.rs
+++ b/osdk/src/commands/build/bin.rs
@@ -175,10 +205,9 @@ fn install_setup_with_arch(
let crate_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let setup_dir = crate_dir.join("../ostd/libs/linux-bzimage/setup");
cmd.arg("--path").arg(setup_dir);
+ } else {
+ cmd.arg("--version").arg(env!("CARGO_PKG_VERSION"));
}
- // Remember to upgrade this version if new version of linux-bzimage-setup is released.
- const LINUX_BZIMAGE_SETUP_VERSION: &str = "0.1.0";
- cmd.arg("--version").arg(LINUX_BZIMAGE_SETUP_VERSION);
cmd.arg("--target").arg(match arch {
SetupInstallArch::X86_64 => "x86_64-unknown-none",
SetupInstallArch::Other(path) => path.to_str().unwrap(),
diff --git a/ostd/Cargo.toml b/ostd/Cargo.toml
--- a/ostd/Cargo.toml
+++ b/ostd/Cargo.toml
@@ -28,7 +28,7 @@ inherit-methods-macro = { git = "https://github.com/asterinas/inherit-methods-ma
int-to-c-enum = { path = "../kernel/libs/int-to-c-enum", version = "0.1.0" }
intrusive-collections = { version = "0.9.6", features = ["nightly"] }
lazy_static = { version = "1.0", features = ["spin_no_std"] }
-linux-boot-params = { path = "libs/linux-bzimage/boot-params", version = "0.1.0" }
+linux-boot-params = { version = "0.1.0", path = "libs/linux-bzimage/boot-params" }
log = "0.4"
num = { version = "0.4", default-features = false }
num-derive = { version = "0.4", default-features = false }
diff --git a/ostd/Cargo.toml b/ostd/Cargo.toml
--- a/ostd/Cargo.toml
+++ b/ostd/Cargo.toml
@@ -28,7 +28,7 @@ inherit-methods-macro = { git = "https://github.com/asterinas/inherit-methods-ma
int-to-c-enum = { path = "../kernel/libs/int-to-c-enum", version = "0.1.0" }
intrusive-collections = { version = "0.9.6", features = ["nightly"] }
lazy_static = { version = "1.0", features = ["spin_no_std"] }
-linux-boot-params = { path = "libs/linux-bzimage/boot-params", version = "0.1.0" }
+linux-boot-params = { version = "0.1.0", path = "libs/linux-bzimage/boot-params" }
log = "0.4"
num = { version = "0.4", default-features = false }
num-derive = { version = "0.4", default-features = false }
diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs
--- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs
+++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs
@@ -8,7 +8,7 @@
//! The reference to the Linux PE header definition:
//! <https://github.com/torvalds/linux/blob/master/include/linux/pe.h>
-use std::{mem::size_of, ops::Range};
+use std::{mem::size_of, vec};
use bytemuck::{Pod, Zeroable};
use serde::Serialize;
diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs
--- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs
+++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs
@@ -8,7 +8,7 @@
//! The reference to the Linux PE header definition:
//! <https://github.com/torvalds/linux/blob/master/include/linux/pe.h>
-use std::{mem::size_of, ops::Range};
+use std::{mem::size_of, vec};
use bytemuck::{Pod, Zeroable};
use serde::Serialize;
diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs
--- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs
+++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs
@@ -202,80 +202,6 @@ struct PeSectionHdr {
flags: u32,
}
-struct ImageSectionAddrInfo {
- pub text: Range<SetupVA>,
- pub data: Range<SetupVA>,
- pub bss: Range<SetupVA>,
- /// All the readonly but loaded sections.
- pub rodata: Range<SetupVA>,
-}
-
-impl ImageSectionAddrInfo {
- fn from(elf: &xmas_elf::ElfFile) -> Self {
- let mut text_start = None;
- let mut text_end = None;
- let mut data_start = None;
- let mut data_end = None;
- let mut bss_start = None;
- let mut bss_end = None;
- let mut rodata_start = None;
- let mut rodata_end = None;
- for program in elf.program_iter() {
- if program.get_type().unwrap() == xmas_elf::program::Type::Load {
- let offset = SetupVA::from(program.virtual_addr() as usize);
- let length = program.mem_size() as usize;
- if program.flags().is_execute() {
- text_start = Some(offset);
- text_end = Some(offset + length);
- } else if program.flags().is_write() {
- data_start = Some(offset);
- data_end = Some(offset + program.file_size() as usize);
- bss_start = Some(offset + program.file_size() as usize);
- bss_end = Some(offset + length);
- } else if program.flags().is_read() {
- rodata_start = Some(offset);
- rodata_end = Some(offset + length);
- }
- }
- }
-
- Self {
- text: text_start.unwrap()..text_end.unwrap(),
- data: data_start.unwrap()..data_end.unwrap(),
- bss: bss_start.unwrap()..bss_end.unwrap(),
- rodata: rodata_start.unwrap()..rodata_end.unwrap(),
- }
- }
-
- fn text_virt_size(&self) -> usize {
- self.text.end - self.text.start
- }
-
- fn text_file_size(&self) -> usize {
- SetupFileOffset::from(self.text.end) - SetupFileOffset::from(self.text.start)
- }
-
- fn data_virt_size(&self) -> usize {
- self.data.end - self.data.start
- }
-
- fn data_file_size(&self) -> usize {
- SetupFileOffset::from(self.data.end) - SetupFileOffset::from(self.data.start)
- }
-
- fn bss_virt_size(&self) -> usize {
- self.bss.end - self.bss.start
- }
-
- fn rodata_virt_size(&self) -> usize {
- self.rodata.end - self.rodata.start
- }
-
- fn rodata_file_size(&self) -> usize {
- SetupFileOffset::from(self.rodata.end) - SetupFileOffset::from(self.rodata.start)
- }
-}
-
pub struct ImagePeCoffHeaderBuf {
pub header_at_zero: Vec<u8>,
pub relocs: (SetupFileOffset, Vec<u8>),
diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs
--- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs
+++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs
@@ -202,80 +202,6 @@ struct PeSectionHdr {
flags: u32,
}
-struct ImageSectionAddrInfo {
- pub text: Range<SetupVA>,
- pub data: Range<SetupVA>,
- pub bss: Range<SetupVA>,
- /// All the readonly but loaded sections.
- pub rodata: Range<SetupVA>,
-}
-
-impl ImageSectionAddrInfo {
- fn from(elf: &xmas_elf::ElfFile) -> Self {
- let mut text_start = None;
- let mut text_end = None;
- let mut data_start = None;
- let mut data_end = None;
- let mut bss_start = None;
- let mut bss_end = None;
- let mut rodata_start = None;
- let mut rodata_end = None;
- for program in elf.program_iter() {
- if program.get_type().unwrap() == xmas_elf::program::Type::Load {
- let offset = SetupVA::from(program.virtual_addr() as usize);
- let length = program.mem_size() as usize;
- if program.flags().is_execute() {
- text_start = Some(offset);
- text_end = Some(offset + length);
- } else if program.flags().is_write() {
- data_start = Some(offset);
- data_end = Some(offset + program.file_size() as usize);
- bss_start = Some(offset + program.file_size() as usize);
- bss_end = Some(offset + length);
- } else if program.flags().is_read() {
- rodata_start = Some(offset);
- rodata_end = Some(offset + length);
- }
- }
- }
-
- Self {
- text: text_start.unwrap()..text_end.unwrap(),
- data: data_start.unwrap()..data_end.unwrap(),
- bss: bss_start.unwrap()..bss_end.unwrap(),
- rodata: rodata_start.unwrap()..rodata_end.unwrap(),
- }
- }
-
- fn text_virt_size(&self) -> usize {
- self.text.end - self.text.start
- }
-
- fn text_file_size(&self) -> usize {
- SetupFileOffset::from(self.text.end) - SetupFileOffset::from(self.text.start)
- }
-
- fn data_virt_size(&self) -> usize {
- self.data.end - self.data.start
- }
-
- fn data_file_size(&self) -> usize {
- SetupFileOffset::from(self.data.end) - SetupFileOffset::from(self.data.start)
- }
-
- fn bss_virt_size(&self) -> usize {
- self.bss.end - self.bss.start
- }
-
- fn rodata_virt_size(&self) -> usize {
- self.rodata.end - self.rodata.start
- }
-
- fn rodata_file_size(&self) -> usize {
- SetupFileOffset::from(self.rodata.end) - SetupFileOffset::from(self.rodata.start)
- }
-}
-
pub struct ImagePeCoffHeaderBuf {
pub header_at_zero: Vec<u8>,
pub relocs: (SetupFileOffset, Vec<u8>),
diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs
--- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs
+++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs
@@ -350,17 +276,53 @@ pub(crate) fn make_pe_coff_header(setup_elf: &[u8], image_size: usize) -> ImageP
},
};
- let addr_info = ImageSectionAddrInfo::from(&elf);
-
// PE section headers
- let sec_hdrs = [
- // .reloc
- PeSectionHdr {
+ let mut sec_hdrs = get_pe_sec_headers_from(&elf);
+
+ sec_hdrs.push(PeSectionHdr::new_reloc(
+ relocs.len() as u32,
+ usize::from(SetupVA::from(reloc_offset)) as u32,
+ relocs.len() as u32,
+ usize::from(reloc_offset) as u32,
+ ));
+
+ // Write the MS-DOS header
+ bin.extend_from_slice(&MZ_MAGIC.to_le_bytes());
+ // Write the MS-DOS stub at 0x3c
+ bin.extend_from_slice(&[0x0; 0x3c - 0x2]);
+ // Write the PE header offset, the header is right after the offset field
+ bin.extend_from_slice(&(0x3cu32 + size_of::<u32>() as u32).to_le_bytes());
+
+ // Write the PE header
+ pe_hdr.sections = sec_hdrs.len() as u16;
+ bin.extend_from_slice(bytemuck::bytes_of(&pe_hdr));
+ // Write the PE32+ optional header
+ bin.extend_from_slice(bytemuck::bytes_of(&pe_opt_hdr));
+ bin.extend_from_slice(bytemuck::bytes_of(&pe_opt_hdr_data_dirs));
+ // Write the PE section headers
+ for sec_hdr in sec_hdrs {
+ bin.extend_from_slice(bytemuck::bytes_of(&sec_hdr));
+ }
+
+ ImagePeCoffHeaderBuf {
+ header_at_zero: bin,
+ relocs: (reloc_offset, relocs),
+ }
+}
+
+impl PeSectionHdr {
+ fn new_reloc(
+ virtual_size: u32,
+ virtual_address: u32,
+ raw_data_size: u32,
+ data_addr: u32,
+ ) -> Self {
+ Self {
name: [b'.', b'r', b'e', b'l', b'o', b'c', 0, 0],
- virtual_size: relocs.len() as u32,
- virtual_address: usize::from(SetupVA::from(reloc_offset)) as u32,
- raw_data_size: relocs.len() as u32,
- data_addr: usize::from(reloc_offset) as u32,
+ virtual_size,
+ virtual_address,
+ raw_data_size,
+ data_addr,
relocs: 0,
line_numbers: 0,
num_relocs: 0,
diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs
--- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs
+++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs
@@ -350,17 +276,53 @@ pub(crate) fn make_pe_coff_header(setup_elf: &[u8], image_size: usize) -> ImageP
},
};
- let addr_info = ImageSectionAddrInfo::from(&elf);
-
// PE section headers
- let sec_hdrs = [
- // .reloc
- PeSectionHdr {
+ let mut sec_hdrs = get_pe_sec_headers_from(&elf);
+
+ sec_hdrs.push(PeSectionHdr::new_reloc(
+ relocs.len() as u32,
+ usize::from(SetupVA::from(reloc_offset)) as u32,
+ relocs.len() as u32,
+ usize::from(reloc_offset) as u32,
+ ));
+
+ // Write the MS-DOS header
+ bin.extend_from_slice(&MZ_MAGIC.to_le_bytes());
+ // Write the MS-DOS stub at 0x3c
+ bin.extend_from_slice(&[0x0; 0x3c - 0x2]);
+ // Write the PE header offset, the header is right after the offset field
+ bin.extend_from_slice(&(0x3cu32 + size_of::<u32>() as u32).to_le_bytes());
+
+ // Write the PE header
+ pe_hdr.sections = sec_hdrs.len() as u16;
+ bin.extend_from_slice(bytemuck::bytes_of(&pe_hdr));
+ // Write the PE32+ optional header
+ bin.extend_from_slice(bytemuck::bytes_of(&pe_opt_hdr));
+ bin.extend_from_slice(bytemuck::bytes_of(&pe_opt_hdr_data_dirs));
+ // Write the PE section headers
+ for sec_hdr in sec_hdrs {
+ bin.extend_from_slice(bytemuck::bytes_of(&sec_hdr));
+ }
+
+ ImagePeCoffHeaderBuf {
+ header_at_zero: bin,
+ relocs: (reloc_offset, relocs),
+ }
+}
+
+impl PeSectionHdr {
+ fn new_reloc(
+ virtual_size: u32,
+ virtual_address: u32,
+ raw_data_size: u32,
+ data_addr: u32,
+ ) -> Self {
+ Self {
name: [b'.', b'r', b'e', b'l', b'o', b'c', 0, 0],
- virtual_size: relocs.len() as u32,
- virtual_address: usize::from(SetupVA::from(reloc_offset)) as u32,
- raw_data_size: relocs.len() as u32,
- data_addr: usize::from(reloc_offset) as u32,
+ virtual_size,
+ virtual_address,
+ raw_data_size,
+ data_addr,
relocs: 0,
line_numbers: 0,
num_relocs: 0,
diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs
--- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs
+++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs
@@ -370,14 +332,21 @@ pub(crate) fn make_pe_coff_header(setup_elf: &[u8], image_size: usize) -> ImageP
| PeSectionHdrFlags::MEM_DISCARDABLE)
.bits
| PeSectionHdrFlagsAlign::_1Bytes as u32,
- },
- // .text
- PeSectionHdr {
+ }
+ }
+
+ fn new_text(
+ virtual_size: u32,
+ virtual_address: u32,
+ raw_data_size: u32,
+ data_addr: u32,
+ ) -> Self {
+ Self {
name: [b'.', b't', b'e', b'x', b't', 0, 0, 0],
- virtual_size: addr_info.text_virt_size() as u32,
- virtual_address: usize::from(addr_info.text.start) as u32,
- raw_data_size: addr_info.text_file_size() as u32,
- data_addr: usize::from(SetupFileOffset::from(addr_info.text.start)) as u32,
+ virtual_size,
+ virtual_address,
+ raw_data_size,
+ data_addr,
relocs: 0,
line_numbers: 0,
num_relocs: 0,
diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs
--- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs
+++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs
@@ -370,14 +332,21 @@ pub(crate) fn make_pe_coff_header(setup_elf: &[u8], image_size: usize) -> ImageP
| PeSectionHdrFlags::MEM_DISCARDABLE)
.bits
| PeSectionHdrFlagsAlign::_1Bytes as u32,
- },
- // .text
- PeSectionHdr {
+ }
+ }
+
+ fn new_text(
+ virtual_size: u32,
+ virtual_address: u32,
+ raw_data_size: u32,
+ data_addr: u32,
+ ) -> Self {
+ Self {
name: [b'.', b't', b'e', b'x', b't', 0, 0, 0],
- virtual_size: addr_info.text_virt_size() as u32,
- virtual_address: usize::from(addr_info.text.start) as u32,
- raw_data_size: addr_info.text_file_size() as u32,
- data_addr: usize::from(SetupFileOffset::from(addr_info.text.start)) as u32,
+ virtual_size,
+ virtual_address,
+ raw_data_size,
+ data_addr,
relocs: 0,
line_numbers: 0,
num_relocs: 0,
diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs
--- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs
+++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs
@@ -387,14 +356,21 @@ pub(crate) fn make_pe_coff_header(setup_elf: &[u8], image_size: usize) -> ImageP
| PeSectionHdrFlags::MEM_EXECUTE)
.bits
| PeSectionHdrFlagsAlign::_16Bytes as u32,
- },
- // .data
- PeSectionHdr {
+ }
+ }
+
+ fn new_data(
+ virtual_size: u32,
+ virtual_address: u32,
+ raw_data_size: u32,
+ data_addr: u32,
+ ) -> Self {
+ Self {
name: [b'.', b'd', b'a', b't', b'a', 0, 0, 0],
- virtual_size: addr_info.data_virt_size() as u32,
- virtual_address: usize::from(addr_info.data.start) as u32,
- raw_data_size: addr_info.data_file_size() as u32,
- data_addr: usize::from(SetupFileOffset::from(addr_info.data.start)) as u32,
+ virtual_size,
+ virtual_address,
+ raw_data_size,
+ data_addr,
relocs: 0,
line_numbers: 0,
num_relocs: 0,
diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs
--- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs
+++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs
@@ -387,14 +356,21 @@ pub(crate) fn make_pe_coff_header(setup_elf: &[u8], image_size: usize) -> ImageP
| PeSectionHdrFlags::MEM_EXECUTE)
.bits
| PeSectionHdrFlagsAlign::_16Bytes as u32,
- },
- // .data
- PeSectionHdr {
+ }
+ }
+
+ fn new_data(
+ virtual_size: u32,
+ virtual_address: u32,
+ raw_data_size: u32,
+ data_addr: u32,
+ ) -> Self {
+ Self {
name: [b'.', b'd', b'a', b't', b'a', 0, 0, 0],
- virtual_size: addr_info.data_virt_size() as u32,
- virtual_address: usize::from(addr_info.data.start) as u32,
- raw_data_size: addr_info.data_file_size() as u32,
- data_addr: usize::from(SetupFileOffset::from(addr_info.data.start)) as u32,
+ virtual_size,
+ virtual_address,
+ raw_data_size,
+ data_addr,
relocs: 0,
line_numbers: 0,
num_relocs: 0,
diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs
--- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs
+++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs
@@ -404,59 +380,69 @@ pub(crate) fn make_pe_coff_header(setup_elf: &[u8], image_size: usize) -> ImageP
| PeSectionHdrFlags::MEM_WRITE)
.bits
| PeSectionHdrFlagsAlign::_16Bytes as u32,
- },
- // .bss
- PeSectionHdr {
- name: [b'.', b'b', b's', b's', 0, 0, 0, 0],
- virtual_size: addr_info.bss_virt_size() as u32,
- virtual_address: usize::from(addr_info.bss.start) as u32,
- raw_data_size: 0,
- data_addr: 0,
- relocs: 0,
- line_numbers: 0,
- num_relocs: 0,
- num_lin_numbers: 0,
- flags: (PeSectionHdrFlags::CNT_UNINITIALIZED_DATA
- | PeSectionHdrFlags::MEM_READ
- | PeSectionHdrFlags::MEM_WRITE)
- .bits
- | PeSectionHdrFlagsAlign::_16Bytes as u32,
- },
- // .rodata
- PeSectionHdr {
+ }
+ }
+
+ fn new_rodata(
+ virtual_size: u32,
+ virtual_address: u32,
+ raw_data_size: u32,
+ data_addr: u32,
+ ) -> Self {
+ Self {
name: [b'.', b'r', b'o', b'd', b'a', b't', b'a', 0],
- virtual_size: addr_info.rodata_virt_size() as u32,
- virtual_address: usize::from(addr_info.rodata.start) as u32,
- raw_data_size: addr_info.rodata_file_size() as u32,
- data_addr: usize::from(SetupFileOffset::from(addr_info.rodata.start)) as u32,
+ virtual_size,
+ virtual_address,
+ raw_data_size,
+ data_addr,
relocs: 0,
line_numbers: 0,
num_relocs: 0,
num_lin_numbers: 0,
flags: (PeSectionHdrFlags::CNT_INITIALIZED_DATA | PeSectionHdrFlags::MEM_READ).bits
| PeSectionHdrFlagsAlign::_16Bytes as u32,
- },
- ];
- // Write the MS-DOS header
- bin.extend_from_slice(&MZ_MAGIC.to_le_bytes());
- // Write the MS-DOS stub at 0x3c
- bin.extend_from_slice(&[0x0; 0x3c - 0x2]);
- // Write the PE header offset, the header is right after the offset field
- bin.extend_from_slice(&(0x3cu32 + size_of::<u32>() as u32).to_le_bytes());
-
- // Write the PE header
- pe_hdr.sections = sec_hdrs.len() as u16;
- bin.extend_from_slice(bytemuck::bytes_of(&pe_hdr));
- // Write the PE32+ optional header
- bin.extend_from_slice(bytemuck::bytes_of(&pe_opt_hdr));
- bin.extend_from_slice(bytemuck::bytes_of(&pe_opt_hdr_data_dirs));
- // Write the PE section headers
- for sec_hdr in sec_hdrs {
- bin.extend_from_slice(bytemuck::bytes_of(&sec_hdr));
+ }
}
+}
- ImagePeCoffHeaderBuf {
- header_at_zero: bin,
- relocs: (reloc_offset, relocs),
+fn get_pe_sec_headers_from(elf: &xmas_elf::ElfFile) -> Vec<PeSectionHdr> {
+ let mut result = vec![];
+
+ for program in elf.program_iter() {
+ if program.get_type().unwrap() == xmas_elf::program::Type::Load {
+ let offset = SetupVA::from(program.virtual_addr() as usize);
+ let length = program.mem_size() as usize;
+
+ if program.flags().is_execute() {
+ result.push(PeSectionHdr::new_text(
+ length as u32,
+ usize::from(offset) as u32,
+ length as u32,
+ usize::from(SetupFileOffset::from(offset)) as u32,
+ ));
+ } else if program.flags().is_write() {
+ // We don't care about `.bss` sections since the binary is
+ // expanded to raw.
+ if program.file_size() == 0 {
+ continue;
+ }
+
+ result.push(PeSectionHdr::new_data(
+ length as u32,
+ usize::from(offset) as u32,
+ length as u32,
+ usize::from(SetupFileOffset::from(offset)) as u32,
+ ));
+ } else if program.flags().is_read() {
+ result.push(PeSectionHdr::new_rodata(
+ length as u32,
+ usize::from(offset) as u32,
+ length as u32,
+ usize::from(SetupFileOffset::from(offset)) as u32,
+ ));
+ }
+ }
}
+
+ result
}
diff --git a/ostd/libs/linux-bzimage/builder/src/pe_header.rs b/ostd/libs/linux-bzimage/builder/src/pe_header.rs
--- a/ostd/libs/linux-bzimage/builder/src/pe_header.rs
+++ b/ostd/libs/linux-bzimage/builder/src/pe_header.rs
@@ -404,59 +380,69 @@ pub(crate) fn make_pe_coff_header(setup_elf: &[u8], image_size: usize) -> ImageP
| PeSectionHdrFlags::MEM_WRITE)
.bits
| PeSectionHdrFlagsAlign::_16Bytes as u32,
- },
- // .bss
- PeSectionHdr {
- name: [b'.', b'b', b's', b's', 0, 0, 0, 0],
- virtual_size: addr_info.bss_virt_size() as u32,
- virtual_address: usize::from(addr_info.bss.start) as u32,
- raw_data_size: 0,
- data_addr: 0,
- relocs: 0,
- line_numbers: 0,
- num_relocs: 0,
- num_lin_numbers: 0,
- flags: (PeSectionHdrFlags::CNT_UNINITIALIZED_DATA
- | PeSectionHdrFlags::MEM_READ
- | PeSectionHdrFlags::MEM_WRITE)
- .bits
- | PeSectionHdrFlagsAlign::_16Bytes as u32,
- },
- // .rodata
- PeSectionHdr {
+ }
+ }
+
+ fn new_rodata(
+ virtual_size: u32,
+ virtual_address: u32,
+ raw_data_size: u32,
+ data_addr: u32,
+ ) -> Self {
+ Self {
name: [b'.', b'r', b'o', b'd', b'a', b't', b'a', 0],
- virtual_size: addr_info.rodata_virt_size() as u32,
- virtual_address: usize::from(addr_info.rodata.start) as u32,
- raw_data_size: addr_info.rodata_file_size() as u32,
- data_addr: usize::from(SetupFileOffset::from(addr_info.rodata.start)) as u32,
+ virtual_size,
+ virtual_address,
+ raw_data_size,
+ data_addr,
relocs: 0,
line_numbers: 0,
num_relocs: 0,
num_lin_numbers: 0,
flags: (PeSectionHdrFlags::CNT_INITIALIZED_DATA | PeSectionHdrFlags::MEM_READ).bits
| PeSectionHdrFlagsAlign::_16Bytes as u32,
- },
- ];
- // Write the MS-DOS header
- bin.extend_from_slice(&MZ_MAGIC.to_le_bytes());
- // Write the MS-DOS stub at 0x3c
- bin.extend_from_slice(&[0x0; 0x3c - 0x2]);
- // Write the PE header offset, the header is right after the offset field
- bin.extend_from_slice(&(0x3cu32 + size_of::<u32>() as u32).to_le_bytes());
-
- // Write the PE header
- pe_hdr.sections = sec_hdrs.len() as u16;
- bin.extend_from_slice(bytemuck::bytes_of(&pe_hdr));
- // Write the PE32+ optional header
- bin.extend_from_slice(bytemuck::bytes_of(&pe_opt_hdr));
- bin.extend_from_slice(bytemuck::bytes_of(&pe_opt_hdr_data_dirs));
- // Write the PE section headers
- for sec_hdr in sec_hdrs {
- bin.extend_from_slice(bytemuck::bytes_of(&sec_hdr));
+ }
}
+}
- ImagePeCoffHeaderBuf {
- header_at_zero: bin,
- relocs: (reloc_offset, relocs),
+fn get_pe_sec_headers_from(elf: &xmas_elf::ElfFile) -> Vec<PeSectionHdr> {
+ let mut result = vec![];
+
+ for program in elf.program_iter() {
+ if program.get_type().unwrap() == xmas_elf::program::Type::Load {
+ let offset = SetupVA::from(program.virtual_addr() as usize);
+ let length = program.mem_size() as usize;
+
+ if program.flags().is_execute() {
+ result.push(PeSectionHdr::new_text(
+ length as u32,
+ usize::from(offset) as u32,
+ length as u32,
+ usize::from(SetupFileOffset::from(offset)) as u32,
+ ));
+ } else if program.flags().is_write() {
+ // We don't care about `.bss` sections since the binary is
+ // expanded to raw.
+ if program.file_size() == 0 {
+ continue;
+ }
+
+ result.push(PeSectionHdr::new_data(
+ length as u32,
+ usize::from(offset) as u32,
+ length as u32,
+ usize::from(SetupFileOffset::from(offset)) as u32,
+ ));
+ } else if program.flags().is_read() {
+ result.push(PeSectionHdr::new_rodata(
+ length as u32,
+ usize::from(offset) as u32,
+ length as u32,
+ usize::from(SetupFileOffset::from(offset)) as u32,
+ ));
+ }
+ }
}
+
+ result
}
diff --git a/ostd/libs/linux-bzimage/setup/Cargo.toml b/ostd/libs/linux-bzimage/setup/Cargo.toml
--- a/ostd/libs/linux-bzimage/setup/Cargo.toml
+++ b/ostd/libs/linux-bzimage/setup/Cargo.toml
@@ -16,16 +16,16 @@ path = "src/main.rs"
cfg-if = "1.0.0"
core2 = { version = "0.4.0", default-features = false, features = ["nightly"] }
libflate = { version = "2.1.0", default-features = false }
-linux-boot-params = { path = "../boot-params", version = "0.1.0" }
+linux-boot-params = { version = "0.1.0", path = "../boot-params" }
uart_16550 = "0.3.0"
-xmas-elf = "0.8.0"
+xmas-elf = "0.9.1"
[target.x86_64-unknown-none.dependencies]
bitflags = "2.4.1"
log = "0.4.20"
-uefi = "0.26.0"
-uefi-services = "0.23.0"
-x86_64 = "0.14.11"
+uefi = { version = "0.32.0", features = ["global_allocator", "panic_handler", "logger", "qemu"]}
+uefi-raw = "0.8.0"
+x86_64 = "0.15.1"
[features]
default = []
diff --git a/ostd/libs/linux-bzimage/setup/Cargo.toml b/ostd/libs/linux-bzimage/setup/Cargo.toml
--- a/ostd/libs/linux-bzimage/setup/Cargo.toml
+++ b/ostd/libs/linux-bzimage/setup/Cargo.toml
@@ -16,16 +16,16 @@ path = "src/main.rs"
cfg-if = "1.0.0"
core2 = { version = "0.4.0", default-features = false, features = ["nightly"] }
libflate = { version = "2.1.0", default-features = false }
-linux-boot-params = { path = "../boot-params", version = "0.1.0" }
+linux-boot-params = { version = "0.1.0", path = "../boot-params" }
uart_16550 = "0.3.0"
-xmas-elf = "0.8.0"
+xmas-elf = "0.9.1"
[target.x86_64-unknown-none.dependencies]
bitflags = "2.4.1"
log = "0.4.20"
-uefi = "0.26.0"
-uefi-services = "0.23.0"
-x86_64 = "0.14.11"
+uefi = { version = "0.32.0", features = ["global_allocator", "panic_handler", "logger", "qemu"]}
+uefi-raw = "0.8.0"
+x86_64 = "0.15.1"
[features]
default = []
diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs
--- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs
+++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs
@@ -2,19 +2,17 @@
use linux_boot_params::BootParams;
use uefi::{
- data_types::Handle,
+ boot::{exit_boot_services, open_protocol_exclusive},
+ mem::memory_map::{MemoryMap, MemoryMapOwned},
+ prelude::*,
proto::loaded_image::LoadedImage,
- table::{
- boot::MemoryMap,
- cfg::{ACPI2_GUID, ACPI_GUID},
- Boot, Runtime, SystemTable,
- },
};
+use uefi_raw::table::system::SystemTable;
use super::{
decoder::decode_payload,
paging::{Ia32eFlags, PageNumber, PageTableCreator},
- relocation::apply_rela_dyn_relocations,
+ relocation::apply_rela_relocations,
};
// Suppress warnings since using todo!.
diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs
--- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs
+++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs
@@ -2,19 +2,17 @@
use linux_boot_params::BootParams;
use uefi::{
- data_types::Handle,
+ boot::{exit_boot_services, open_protocol_exclusive},
+ mem::memory_map::{MemoryMap, MemoryMapOwned},
+ prelude::*,
proto::loaded_image::LoadedImage,
- table::{
- boot::MemoryMap,
- cfg::{ACPI2_GUID, ACPI_GUID},
- Boot, Runtime, SystemTable,
- },
};
+use uefi_raw::table::system::SystemTable;
use super::{
decoder::decode_payload,
paging::{Ia32eFlags, PageNumber, PageTableCreator},
- relocation::apply_rela_dyn_relocations,
+ relocation::apply_rela_relocations,
};
// Suppress warnings since using todo!.
diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs
--- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs
+++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs
@@ -22,77 +20,92 @@ use super::{
#[allow(unused_variables)]
#[allow(clippy::diverging_sub_expression)]
#[export_name = "efi_stub_entry"]
-extern "sysv64" fn efi_stub_entry(handle: Handle, mut system_table: SystemTable<Boot>) -> ! {
- unsafe {
- system_table.boot_services().set_image_handle(handle);
- }
- uefi_services::init(&mut system_table).unwrap();
+extern "sysv64" fn efi_stub_entry(handle: Handle, system_table: *const SystemTable) -> ! {
+ // SAFETY: handle and system_table are valid pointers. It is only called once.
+ unsafe { system_init(handle, system_table) };
+
+ uefi::helpers::init().unwrap();
let boot_params = todo!("Use EFI boot services to fill boot params");
- efi_phase_boot(handle, system_table, boot_params);
+ efi_phase_boot(boot_params);
}
#[export_name = "efi_handover_entry"]
extern "sysv64" fn efi_handover_entry(
handle: Handle,
- mut system_table: SystemTable<Boot>,
+ system_table: *const SystemTable,
boot_params_ptr: *mut BootParams,
) -> ! {
- unsafe {
- system_table.boot_services().set_image_handle(handle);
- }
- uefi_services::init(&mut system_table).unwrap();
+ // SAFETY: handle and system_table are valid pointers. It is only called once.
+ unsafe { system_init(handle, system_table) };
+
+ uefi::helpers::init().unwrap();
// SAFETY: boot_params is a valid pointer.
let boot_params = unsafe { &mut *boot_params_ptr };
- efi_phase_boot(handle, system_table, boot_params)
+ efi_phase_boot(boot_params)
}
-fn efi_phase_boot(
- handle: Handle,
- system_table: SystemTable<Boot>,
- boot_params: &mut BootParams,
-) -> ! {
- // SAFETY: this init function is only called once.
- unsafe { crate::console::init() };
+/// Initialize the system.
+///
+/// # Safety
+///
+/// This function should be called only once with valid parameters before all
+/// operations.
+unsafe fn system_init(handle: Handle, system_table: *const SystemTable) {
+ // SAFETY: This is the right time to initialize the console and it is only
+ // called once here before all console operations.
+ unsafe {
+ crate::console::init();
+ }
- // SAFETY: this is the right time to apply relocations.
- unsafe { apply_rela_dyn_relocations() };
+ // SAFETY: This is the right time to apply relocations.
+ unsafe { apply_rela_relocations() };
- uefi_services::println!("[EFI stub] Relocations applied.");
+ // SAFETY: The handle and system_table are valid pointers. They are passed
+ // from the UEFI firmware. They are only called once.
+ unsafe {
+ boot::set_image_handle(handle);
+ uefi::table::set_system_table(system_table);
+ }
+}
+
+fn efi_phase_boot(boot_params: &mut BootParams) -> ! {
+ uefi::println!("[EFI stub] Relocations applied.");
+ uefi::println!(
+ "[EFI stub] Stub loaded at {:#x?}",
+ crate::x86::get_image_loaded_offset()
+ );
// Fill the boot params with the RSDP address if it is not provided.
if boot_params.acpi_rsdp_addr == 0 {
- boot_params.acpi_rsdp_addr = get_rsdp_addr(&system_table);
+ boot_params.acpi_rsdp_addr = get_rsdp_addr();
}
// Load the kernel payload to memory.
let payload = crate::get_payload(boot_params);
let kernel = decode_payload(payload);
- uefi_services::println!("[EFI stub] Loading payload.");
+ uefi::println!("[EFI stub] Loading payload.");
crate::loader::load_elf(&kernel);
- uefi_services::println!("[EFI stub] Exiting EFI boot services.");
+ uefi::println!("[EFI stub] Exiting EFI boot services.");
let memory_type = {
- let boot_services = system_table.boot_services();
- let Ok(loaded_image) = boot_services.open_protocol_exclusive::<LoadedImage>(handle) else {
+ let Ok(loaded_image) = open_protocol_exclusive::<LoadedImage>(boot::image_handle()) else {
panic!("Failed to open LoadedImage protocol");
};
loaded_image.data_type()
};
- let (system_table, memory_map) = system_table.exit_boot_services(memory_type);
+ // SAFETY: All allocations in the boot services phase are not used after
+ // this point.
+ let memory_map = unsafe { exit_boot_services(memory_type) };
- efi_phase_runtime(system_table, memory_map, boot_params);
+ efi_phase_runtime(memory_map, boot_params);
}
-fn efi_phase_runtime(
- _system_table: SystemTable<Runtime>,
- memory_map: MemoryMap<'static>,
- boot_params: &mut BootParams,
-) -> ! {
+fn efi_phase_runtime(memory_map: MemoryMapOwned, boot_params: &mut BootParams) -> ! {
unsafe {
crate::console::print_str("[EFI stub] Entered runtime services.\n");
}
diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs
--- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs
+++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs
@@ -22,77 +20,92 @@ use super::{
#[allow(unused_variables)]
#[allow(clippy::diverging_sub_expression)]
#[export_name = "efi_stub_entry"]
-extern "sysv64" fn efi_stub_entry(handle: Handle, mut system_table: SystemTable<Boot>) -> ! {
- unsafe {
- system_table.boot_services().set_image_handle(handle);
- }
- uefi_services::init(&mut system_table).unwrap();
+extern "sysv64" fn efi_stub_entry(handle: Handle, system_table: *const SystemTable) -> ! {
+ // SAFETY: handle and system_table are valid pointers. It is only called once.
+ unsafe { system_init(handle, system_table) };
+
+ uefi::helpers::init().unwrap();
let boot_params = todo!("Use EFI boot services to fill boot params");
- efi_phase_boot(handle, system_table, boot_params);
+ efi_phase_boot(boot_params);
}
#[export_name = "efi_handover_entry"]
extern "sysv64" fn efi_handover_entry(
handle: Handle,
- mut system_table: SystemTable<Boot>,
+ system_table: *const SystemTable,
boot_params_ptr: *mut BootParams,
) -> ! {
- unsafe {
- system_table.boot_services().set_image_handle(handle);
- }
- uefi_services::init(&mut system_table).unwrap();
+ // SAFETY: handle and system_table are valid pointers. It is only called once.
+ unsafe { system_init(handle, system_table) };
+
+ uefi::helpers::init().unwrap();
// SAFETY: boot_params is a valid pointer.
let boot_params = unsafe { &mut *boot_params_ptr };
- efi_phase_boot(handle, system_table, boot_params)
+ efi_phase_boot(boot_params)
}
-fn efi_phase_boot(
- handle: Handle,
- system_table: SystemTable<Boot>,
- boot_params: &mut BootParams,
-) -> ! {
- // SAFETY: this init function is only called once.
- unsafe { crate::console::init() };
+/// Initialize the system.
+///
+/// # Safety
+///
+/// This function should be called only once with valid parameters before all
+/// operations.
+unsafe fn system_init(handle: Handle, system_table: *const SystemTable) {
+ // SAFETY: This is the right time to initialize the console and it is only
+ // called once here before all console operations.
+ unsafe {
+ crate::console::init();
+ }
- // SAFETY: this is the right time to apply relocations.
- unsafe { apply_rela_dyn_relocations() };
+ // SAFETY: This is the right time to apply relocations.
+ unsafe { apply_rela_relocations() };
- uefi_services::println!("[EFI stub] Relocations applied.");
+ // SAFETY: The handle and system_table are valid pointers. They are passed
+ // from the UEFI firmware. They are only called once.
+ unsafe {
+ boot::set_image_handle(handle);
+ uefi::table::set_system_table(system_table);
+ }
+}
+
+fn efi_phase_boot(boot_params: &mut BootParams) -> ! {
+ uefi::println!("[EFI stub] Relocations applied.");
+ uefi::println!(
+ "[EFI stub] Stub loaded at {:#x?}",
+ crate::x86::get_image_loaded_offset()
+ );
// Fill the boot params with the RSDP address if it is not provided.
if boot_params.acpi_rsdp_addr == 0 {
- boot_params.acpi_rsdp_addr = get_rsdp_addr(&system_table);
+ boot_params.acpi_rsdp_addr = get_rsdp_addr();
}
// Load the kernel payload to memory.
let payload = crate::get_payload(boot_params);
let kernel = decode_payload(payload);
- uefi_services::println!("[EFI stub] Loading payload.");
+ uefi::println!("[EFI stub] Loading payload.");
crate::loader::load_elf(&kernel);
- uefi_services::println!("[EFI stub] Exiting EFI boot services.");
+ uefi::println!("[EFI stub] Exiting EFI boot services.");
let memory_type = {
- let boot_services = system_table.boot_services();
- let Ok(loaded_image) = boot_services.open_protocol_exclusive::<LoadedImage>(handle) else {
+ let Ok(loaded_image) = open_protocol_exclusive::<LoadedImage>(boot::image_handle()) else {
panic!("Failed to open LoadedImage protocol");
};
loaded_image.data_type()
};
- let (system_table, memory_map) = system_table.exit_boot_services(memory_type);
+ // SAFETY: All allocations in the boot services phase are not used after
+ // this point.
+ let memory_map = unsafe { exit_boot_services(memory_type) };
- efi_phase_runtime(system_table, memory_map, boot_params);
+ efi_phase_runtime(memory_map, boot_params);
}
-fn efi_phase_runtime(
- _system_table: SystemTable<Runtime>,
- memory_map: MemoryMap<'static>,
- boot_params: &mut BootParams,
-) -> ! {
+fn efi_phase_runtime(memory_map: MemoryMapOwned, boot_params: &mut BootParams) -> ! {
unsafe {
crate::console::print_str("[EFI stub] Entered runtime services.\n");
}
diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs
--- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs
+++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs
@@ -218,16 +231,18 @@ fn efi_phase_runtime(
}
}
-fn get_rsdp_addr(boot_table: &SystemTable<Boot>) -> u64 {
- let config_table = boot_table.config_table();
- for entry in config_table {
- // Prefer ACPI2 over ACPI.
- if entry.guid == ACPI2_GUID {
- return entry.address as usize as u64;
- }
- if entry.guid == ACPI_GUID {
- return entry.address as usize as u64;
+fn get_rsdp_addr() -> u64 {
+ use uefi::table::cfg::{ACPI2_GUID, ACPI_GUID};
+ uefi::system::with_config_table(|table| {
+ for entry in table {
+ // Prefer ACPI2 over ACPI.
+ if entry.guid == ACPI2_GUID {
+ return entry.address as usize as u64;
+ }
+ if entry.guid == ACPI_GUID {
+ return entry.address as usize as u64;
+ }
}
- }
- panic!("ACPI RSDP not found");
+ panic!("ACPI RSDP not found");
+ })
}
diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs
--- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs
+++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs
@@ -218,16 +231,18 @@ fn efi_phase_runtime(
}
}
-fn get_rsdp_addr(boot_table: &SystemTable<Boot>) -> u64 {
- let config_table = boot_table.config_table();
- for entry in config_table {
- // Prefer ACPI2 over ACPI.
- if entry.guid == ACPI2_GUID {
- return entry.address as usize as u64;
- }
- if entry.guid == ACPI_GUID {
- return entry.address as usize as u64;
+fn get_rsdp_addr() -> u64 {
+ use uefi::table::cfg::{ACPI2_GUID, ACPI_GUID};
+ uefi::system::with_config_table(|table| {
+ for entry in table {
+ // Prefer ACPI2 over ACPI.
+ if entry.guid == ACPI2_GUID {
+ return entry.address as usize as u64;
+ }
+ if entry.guid == ACPI_GUID {
+ return entry.address as usize as u64;
+ }
}
- }
- panic!("ACPI RSDP not found");
+ panic!("ACPI RSDP not found");
+ })
}
diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/linker.ld b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/linker.ld
--- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/linker.ld
+++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/linker.ld
@@ -40,15 +40,11 @@ SECTIONS
.eh_frame_hdr : {
*(.eh_frame_hdr .eh_frame_hdr.*)
}
-
- .rela.dyn : {
- PROVIDE(__rela_dyn_start = .);
- *(.rela.dyn .rela.dyn.*)
- PROVIDE(__rela_dyn_end = .);
- }
-
- .rela.plt : {
- *(.rela.plt .rela.plt.*)
+
+ .rela : {
+ PROVIDE(__rela_start = .);
+ *(.rela .rela.*)
+ PROVIDE(__rela_end = .);
}
.comment : { *(.comment) }
diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/linker.ld b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/linker.ld
--- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/linker.ld
+++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/linker.ld
@@ -40,15 +40,11 @@ SECTIONS
.eh_frame_hdr : {
*(.eh_frame_hdr .eh_frame_hdr.*)
}
-
- .rela.dyn : {
- PROVIDE(__rela_dyn_start = .);
- *(.rela.dyn .rela.dyn.*)
- PROVIDE(__rela_dyn_end = .);
- }
-
- .rela.plt : {
- *(.rela.plt .rela.plt.*)
+
+ .rela : {
+ PROVIDE(__rela_start = .);
+ *(.rela .rela.*)
+ PROVIDE(__rela_end = .);
}
.comment : { *(.comment) }
diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs
--- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs
+++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs
@@ -18,6 +18,7 @@ const TABLE_ENTRY_COUNT: usize = 512;
bitflags::bitflags! {
#[derive(Clone, Copy)]
+ #[repr(C)]
pub struct Ia32eFlags: u64 {
const PRESENT = 1 << 0;
const WRITABLE = 1 << 1;
diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs
--- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs
+++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs
@@ -18,6 +18,7 @@ const TABLE_ENTRY_COUNT: usize = 512;
bitflags::bitflags! {
#[derive(Clone, Copy)]
+ #[repr(C)]
pub struct Ia32eFlags: u64 {
const PRESENT = 1 << 0;
const WRITABLE = 1 << 1;
diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs
--- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs
+++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs
@@ -32,9 +33,11 @@ bitflags::bitflags! {
}
}
+#[repr(C)]
pub struct Ia32eEntry(u64);
/// The table in the IA32E paging specification that occupies a physical page frame.
+#[repr(C)]
pub struct Ia32eTable([Ia32eEntry; TABLE_ENTRY_COUNT]);
/// A page number. It could be either a physical page number or a virtual page number.
diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs
--- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs
+++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs
@@ -32,9 +33,11 @@ bitflags::bitflags! {
}
}
+#[repr(C)]
pub struct Ia32eEntry(u64);
/// The table in the IA32E paging specification that occupies a physical page frame.
+#[repr(C)]
pub struct Ia32eTable([Ia32eEntry; TABLE_ENTRY_COUNT]);
/// A page number. It could be either a physical page number or a virtual page number.
diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs
--- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs
+++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs
@@ -2,62 +2,68 @@
use crate::x86::get_image_loaded_offset;
-struct Elf64Rela {
- r_offset: u64,
- r_info: u64,
- r_addend: i64,
-}
+/// Apply the relocations in the `.rela.*` sections.
+///
+/// The function will enable dyn Trait objects to work since they rely on
+/// vtable pointers. Vtable won't work without relocations.
+///
+/// We currently support R_X86_64_RELATIVE relocations only. And this type of
+/// relocation seems to be the only existing type if we compile Rust code to
+/// PIE ELF binaries.
+///
+/// # Safety
+///
+/// This function will modify the memory pointed by the relocations. And the
+/// Rust memory safety mechanisms are not aware of these kind of modification.
+/// Failure to do relocations will cause `dyn Trait` objects to break.
+pub unsafe fn apply_rela_relocations() {
+ use core::arch::asm;
+ let image_loaded_offset = get_image_loaded_offset();
+
+ let mut start: usize;
+ let end: usize;
-fn get_rela_array() -> &'static [Elf64Rela] {
- extern "C" {
- fn __rela_dyn_start();
- fn __rela_dyn_end();
+ unsafe {
+ asm!(
+ "lea {}, [rip + __rela_start]",
+ out(reg) start,
+ );
+ asm!(
+ "lea {}, [rip + __rela_end]",
+ out(reg) end,
+ );
}
- let start = __rela_dyn_start as *const Elf64Rela;
- let end = __rela_dyn_end as *const Elf64Rela;
- let len = unsafe { end.offset_from(start) } as usize;
+
#[cfg(feature = "debug_print")]
unsafe {
use crate::console::{print_hex, print_str};
- print_str("[EFI stub debug] .rela.dyn section size = ");
- print_hex(len as u64);
- print_str("; __rela_dyn_start = ");
+ print_str("[EFI stub debug] loaded offset = ");
+ print_hex(image_loaded_offset as u64);
+ print_str("\n");
+ print_str("[EFI stub debug] .rela section start = ");
print_hex(start as u64);
- print_str(", __rela_dyn_end = ");
+ print_str(", end = ");
print_hex(end as u64);
print_str("\n");
}
- // SAFETY: the linker will ensure that the symbols are valid.
- unsafe { core::slice::from_raw_parts(start, len) }
-}
-const R_X86_64_RELATIVE: u32 = 8;
+ #[cfg(feature = "debug_print")]
+ let mut count = 0;
-/// Apply the relocations in the `.rela.dyn` section.
-///
-/// The function will enable dyn Trait objects to work since they rely on vtable pointers. Vtable
-/// won't work without relocations.
-///
-/// We currently support R_X86_64_RELATIVE relocations only. And this type of relocation seems to
-/// be the only existing type if we compile Rust code to PIC ELF binaries.
-///
-/// # Safety
-/// This function will modify the memory pointed by the relocations. And the Rust memory safety
-/// mechanisms are not aware of these kind of modification. Failure to do relocations will cause
-/// dyn Trait objects to break.
-pub unsafe fn apply_rela_dyn_relocations() {
- let image_loaded_offset = get_image_loaded_offset();
- let relas = get_rela_array();
- for rela in relas {
+ while start < end {
+ let rela = (start as *const Elf64Rela).read_volatile();
let r_type = (rela.r_info & 0xffffffff) as u32;
let _r_sym = (rela.r_info >> 32) as usize;
- let r_addend = rela.r_addend;
- let r_offset = rela.r_offset as usize;
- let target = (image_loaded_offset + r_offset as isize) as usize;
+ let r_addend = rela.r_addend as isize;
+ let r_offset = rela.r_offset as isize;
+ let target = image_loaded_offset.wrapping_add(r_offset) as usize;
#[cfg(feature = "debug_print")]
unsafe {
use crate::console::{print_hex, print_str};
- print_str("[EFI stub debug] Applying relocation at offset ");
+ count += 1;
+ print_str("[EFI stub debug] Applying relocation #");
+ print_hex(count as u64);
+ print_str(" at offset ");
print_hex(r_offset as u64);
print_str(", type = ");
print_hex(r_type as u64);
diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs
--- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs
+++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs
@@ -2,62 +2,68 @@
use crate::x86::get_image_loaded_offset;
-struct Elf64Rela {
- r_offset: u64,
- r_info: u64,
- r_addend: i64,
-}
+/// Apply the relocations in the `.rela.*` sections.
+///
+/// The function will enable dyn Trait objects to work since they rely on
+/// vtable pointers. Vtable won't work without relocations.
+///
+/// We currently support R_X86_64_RELATIVE relocations only. And this type of
+/// relocation seems to be the only existing type if we compile Rust code to
+/// PIE ELF binaries.
+///
+/// # Safety
+///
+/// This function will modify the memory pointed by the relocations. And the
+/// Rust memory safety mechanisms are not aware of these kind of modification.
+/// Failure to do relocations will cause `dyn Trait` objects to break.
+pub unsafe fn apply_rela_relocations() {
+ use core::arch::asm;
+ let image_loaded_offset = get_image_loaded_offset();
+
+ let mut start: usize;
+ let end: usize;
-fn get_rela_array() -> &'static [Elf64Rela] {
- extern "C" {
- fn __rela_dyn_start();
- fn __rela_dyn_end();
+ unsafe {
+ asm!(
+ "lea {}, [rip + __rela_start]",
+ out(reg) start,
+ );
+ asm!(
+ "lea {}, [rip + __rela_end]",
+ out(reg) end,
+ );
}
- let start = __rela_dyn_start as *const Elf64Rela;
- let end = __rela_dyn_end as *const Elf64Rela;
- let len = unsafe { end.offset_from(start) } as usize;
+
#[cfg(feature = "debug_print")]
unsafe {
use crate::console::{print_hex, print_str};
- print_str("[EFI stub debug] .rela.dyn section size = ");
- print_hex(len as u64);
- print_str("; __rela_dyn_start = ");
+ print_str("[EFI stub debug] loaded offset = ");
+ print_hex(image_loaded_offset as u64);
+ print_str("\n");
+ print_str("[EFI stub debug] .rela section start = ");
print_hex(start as u64);
- print_str(", __rela_dyn_end = ");
+ print_str(", end = ");
print_hex(end as u64);
print_str("\n");
}
- // SAFETY: the linker will ensure that the symbols are valid.
- unsafe { core::slice::from_raw_parts(start, len) }
-}
-const R_X86_64_RELATIVE: u32 = 8;
+ #[cfg(feature = "debug_print")]
+ let mut count = 0;
-/// Apply the relocations in the `.rela.dyn` section.
-///
-/// The function will enable dyn Trait objects to work since they rely on vtable pointers. Vtable
-/// won't work without relocations.
-///
-/// We currently support R_X86_64_RELATIVE relocations only. And this type of relocation seems to
-/// be the only existing type if we compile Rust code to PIC ELF binaries.
-///
-/// # Safety
-/// This function will modify the memory pointed by the relocations. And the Rust memory safety
-/// mechanisms are not aware of these kind of modification. Failure to do relocations will cause
-/// dyn Trait objects to break.
-pub unsafe fn apply_rela_dyn_relocations() {
- let image_loaded_offset = get_image_loaded_offset();
- let relas = get_rela_array();
- for rela in relas {
+ while start < end {
+ let rela = (start as *const Elf64Rela).read_volatile();
let r_type = (rela.r_info & 0xffffffff) as u32;
let _r_sym = (rela.r_info >> 32) as usize;
- let r_addend = rela.r_addend;
- let r_offset = rela.r_offset as usize;
- let target = (image_loaded_offset + r_offset as isize) as usize;
+ let r_addend = rela.r_addend as isize;
+ let r_offset = rela.r_offset as isize;
+ let target = image_loaded_offset.wrapping_add(r_offset) as usize;
#[cfg(feature = "debug_print")]
unsafe {
use crate::console::{print_hex, print_str};
- print_str("[EFI stub debug] Applying relocation at offset ");
+ count += 1;
+ print_str("[EFI stub debug] Applying relocation #");
+ print_hex(count as u64);
+ print_str(" at offset ");
print_hex(r_offset as u64);
print_str(", type = ");
print_hex(r_type as u64);
diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs
--- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs
+++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs
@@ -67,12 +73,23 @@ pub unsafe fn apply_rela_dyn_relocations() {
}
match r_type {
R_X86_64_RELATIVE => {
- let value = (image_loaded_offset as i64 + r_addend) as usize;
- *(target as *mut usize) = value;
+ let value = image_loaded_offset.wrapping_add(r_addend) as usize;
+ (target as *mut usize).write(value);
}
_ => {
panic!("Unknown relocation type: {}", r_type);
}
}
+ start = start.wrapping_add(core::mem::size_of::<Elf64Rela>());
}
}
+
+const R_X86_64_RELATIVE: u32 = 8;
+
+#[derive(Copy, Clone)]
+#[repr(C)]
+struct Elf64Rela {
+ r_offset: u64,
+ r_info: u64,
+ r_addend: i64,
+}
diff --git a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs
--- a/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs
+++ b/ostd/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs
@@ -67,12 +73,23 @@ pub unsafe fn apply_rela_dyn_relocations() {
}
match r_type {
R_X86_64_RELATIVE => {
- let value = (image_loaded_offset as i64 + r_addend) as usize;
- *(target as *mut usize) = value;
+ let value = image_loaded_offset.wrapping_add(r_addend) as usize;
+ (target as *mut usize).write(value);
}
_ => {
panic!("Unknown relocation type: {}", r_type);
}
}
+ start = start.wrapping_add(core::mem::size_of::<Elf64Rela>());
}
}
+
+const R_X86_64_RELATIVE: u32 = 8;
+
+#[derive(Copy, Clone)]
+#[repr(C)]
+struct Elf64Rela {
+ r_offset: u64,
+ r_info: u64,
+ r_addend: i64,
+}
diff --git a/ostd/libs/linux-bzimage/setup/src/x86/mod.rs b/ostd/libs/linux-bzimage/setup/src/x86/mod.rs
--- a/ostd/libs/linux-bzimage/setup/src/x86/mod.rs
+++ b/ostd/libs/linux-bzimage/setup/src/x86/mod.rs
@@ -16,10 +16,23 @@ const START_OF_SETUP32_VA: usize = 0x100000;
/// The setup is a position-independent executable. We can get the loaded base
/// address from the symbol.
#[inline]
-#[allow(clippy::fn_to_numeric_cast)]
pub fn get_image_loaded_offset() -> isize {
- extern "C" {
- fn start_of_setup32();
+ let address_of_start: usize;
+ #[cfg(target_arch = "x86_64")]
+ unsafe {
+ core::arch::asm!(
+ "lea {}, [rip + start_of_setup32]",
+ out(reg) address_of_start,
+ options(pure, nomem, nostack)
+ );
}
- start_of_setup32 as isize - START_OF_SETUP32_VA as isize
+ #[cfg(target_arch = "x86")]
+ unsafe {
+ core::arch::asm!(
+ "lea {}, [start_of_setup32]",
+ out(reg) address_of_start,
+ options(pure, nomem, nostack)
+ );
+ }
+ address_of_start as isize - START_OF_SETUP32_VA as isize
}
diff --git a/ostd/libs/linux-bzimage/setup/src/x86/mod.rs b/ostd/libs/linux-bzimage/setup/src/x86/mod.rs
--- a/ostd/libs/linux-bzimage/setup/src/x86/mod.rs
+++ b/ostd/libs/linux-bzimage/setup/src/x86/mod.rs
@@ -16,10 +16,23 @@ const START_OF_SETUP32_VA: usize = 0x100000;
/// The setup is a position-independent executable. We can get the loaded base
/// address from the symbol.
#[inline]
-#[allow(clippy::fn_to_numeric_cast)]
pub fn get_image_loaded_offset() -> isize {
- extern "C" {
- fn start_of_setup32();
+ let address_of_start: usize;
+ #[cfg(target_arch = "x86_64")]
+ unsafe {
+ core::arch::asm!(
+ "lea {}, [rip + start_of_setup32]",
+ out(reg) address_of_start,
+ options(pure, nomem, nostack)
+ );
}
- start_of_setup32 as isize - START_OF_SETUP32_VA as isize
+ #[cfg(target_arch = "x86")]
+ unsafe {
+ core::arch::asm!(
+ "lea {}, [start_of_setup32]",
+ out(reg) address_of_start,
+ options(pure, nomem, nostack)
+ );
+ }
+ address_of_start as isize - START_OF_SETUP32_VA as isize
}
diff --git a/tools/bump_version.sh b/tools/bump_version.sh
--- a/tools/bump_version.sh
+++ b/tools/bump_version.sh
@@ -106,6 +106,9 @@ DOCS_DIR=${ASTER_SRC_DIR}/docs
OSTD_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/Cargo.toml
OSTD_TEST_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/libs/ostd-test/Cargo.toml
OSTD_MACROS_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/libs/ostd-macros/Cargo.toml
+LINUX_BOOT_PARAMS_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/libs/linux-bzimage/boot-params/Cargo.toml
+LINUX_BZIMAGE_BUILDER_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/libs/linux-bzimage/builder/Cargo.toml
+LINUX_BZIMAGE_SETUP_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/libs/linux-bzimage/setup/Cargo.toml
OSDK_CARGO_TOML_PATH=${ASTER_SRC_DIR}/osdk/Cargo.toml
OSDK_TEST_RUNNER_CARGO_TOML_PATH=${ASTER_SRC_DIR}/osdk/test-kernel/Cargo.toml
VERSION_PATH=${ASTER_SRC_DIR}/VERSION
diff --git a/tools/bump_version.sh b/tools/bump_version.sh
--- a/tools/bump_version.sh
+++ b/tools/bump_version.sh
@@ -125,11 +128,17 @@ new_version=$(bump_version ${current_version})
update_package_version ${OSTD_TEST_CARGO_TOML_PATH}
update_package_version ${OSTD_MACROS_CARGO_TOML_PATH}
update_package_version ${OSTD_CARGO_TOML_PATH}
+update_package_version ${LINUX_BOOT_PARAMS_CARGO_TOML_PATH}
+update_package_version ${LINUX_BZIMAGE_BUILDER_CARGO_TOML_PATH}
+update_package_version ${LINUX_BZIMAGE_SETUP_CARGO_TOML_PATH}
update_dep_version ${OSTD_CARGO_TOML_PATH} ostd-test
+update_dep_version ${OSTD_CARGO_TOML_PATH} linux-boot-params
update_dep_version ${OSTD_CARGO_TOML_PATH} ostd-macros
+update_dep_version ${LINUX_BZIMAGE_SETUP_CARGO_TOML_PATH} linux-boot-params
update_package_version ${OSDK_CARGO_TOML_PATH}
update_package_version ${OSDK_TEST_RUNNER_CARGO_TOML_PATH}
update_dep_version ${OSDK_TEST_RUNNER_CARGO_TOML_PATH} ostd
+update_dep_version ${OSDK_CARGO_TOML_PATH} linux-bzimage-builder
# Automatically bump Cargo.lock files
cargo update -p aster-nix --precise $new_version # For Cargo.lock
diff --git a/tools/github_workflows/publish_osdk_and_ostd.sh b/tools/github_workflows/publish_osdk_and_ostd.sh
--- a/tools/github_workflows/publish_osdk_and_ostd.sh
+++ b/tools/github_workflows/publish_osdk_and_ostd.sh
@@ -60,6 +60,8 @@ do_publish_for() {
}
do_publish_for osdk
+do_publish_for ostd/libs/linux-bzimage/build
+do_publish_for ostd/libs/linux-bzimage/boot-params
# All supported targets of OSTD, this array should keep consistent with
# `package.metadata.docs.rs.targets` in `ostd/Cargo.toml`.
diff --git a/tools/github_workflows/publish_osdk_and_ostd.sh b/tools/github_workflows/publish_osdk_and_ostd.sh
--- a/tools/github_workflows/publish_osdk_and_ostd.sh
+++ b/tools/github_workflows/publish_osdk_and_ostd.sh
@@ -60,6 +60,8 @@ do_publish_for() {
}
do_publish_for osdk
+do_publish_for ostd/libs/linux-bzimage/build
+do_publish_for ostd/libs/linux-bzimage/boot-params
# All supported targets of OSTD, this array should keep consistent with
# `package.metadata.docs.rs.targets` in `ostd/Cargo.toml`.
diff --git a/tools/github_workflows/publish_osdk_and_ostd.sh b/tools/github_workflows/publish_osdk_and_ostd.sh
--- a/tools/github_workflows/publish_osdk_and_ostd.sh
+++ b/tools/github_workflows/publish_osdk_and_ostd.sh
@@ -67,6 +69,7 @@ TARGETS="x86_64-unknown-none"
for TARGET in $TARGETS; do
do_publish_for ostd/libs/ostd-macros $TARGET
do_publish_for ostd/libs/ostd-test $TARGET
+ do_publish_for ostd/libs/linux-bzimage/setup $TARGET
do_publish_for ostd $TARGET
do_publish_for osdk/test-kernel $TARGET
|
2024-10-14T14:03:58Z
|
9da6af03943c15456cdfd781021820a7da78ea40
|
|
asterinas/asterinas
|
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -226,6 +226,8 @@ ktest: initramfs $(CARGO_OSDK)
@for dir in $(OSDK_CRATES); do \
[ $$dir = "ostd/libs/linux-bzimage/setup" ] && continue; \
(cd $$dir && cargo osdk test) || exit 1; \
+ tail --lines 10 qemu.log | grep -q "^\\[ktest runner\\] All crates tested." \
+ || (echo "Test failed" && exit 1); \
done
.PHONY: docs
|
[
"1399",
"919"
] |
0.9
|
96efd620072a0cbdccc95b58901894111f17bb3a
|
Silently failed ktest in OSTD: untracked_map_unmap
<!-- Thank you for taking the time to report a bug. Your input is valuable to us.
Please replace all the <angle brackets> below with your own information. -->
### Describe the bug
<!-- A clear and concise description of what the bug is. -->
https://github.com/asterinas/asterinas/actions/runs/11101937778/job/30840638910#step:6:634
The ktest `test_untracked_map_unmap` failed, but CI doesn't notice it. The failure is reproducible locally.
### To Reproduce
```bash
cd ostd && cargo osdk test test_untracked_map_unmap
```
[RFC] Safety model about the page tables
# Background
This issue discusses the internal APIs of the page table. More specifically, the following two sets of APIs:
- The APIs provided by `RawPageTableNode`/`PageTableNode`
- Files: [`framework/aster-frame/src/mm/page_table/node.rs`](https://github.com/asterinas/asterinas/blob/main/framework/aster-frame/src/mm/page_table/node.rs)
- The APIs provided by `PageTable`/`Cursor`/`CursorMut`
- Files: [`framework/aster-frame/src/mm/page_table/mod.rs`](https://github.com/asterinas/asterinas/blob/main/framework/aster-frame/src/mm/page_table/mod.rs) and [`framework/aster-frame/src/mm/page_table/cursor.rs`](https://github.com/asterinas/asterinas/blob/main/framework/aster-frame/src/mm/page_table/cursor.rs)
The focus is on what kind of safety guarantees they can provide.
Currently, this question is not clearly answered. For example, consider the following API in `PageTableNode`:
https://github.com/asterinas/asterinas/blob/c6aa9f9ee860bbdcb8bb3444b630aff9f0ac14af/framework/aster-frame/src/mm/page_table/node.rs#L383-L388
This method is marked as unsafe because it can create arbitrary mappings. This is not a valid reason to mark it as unsafe, as the activation of a `RawPageTableNode` is already marked as unsafe, as shown in the following code snippet:
https://github.com/asterinas/asterinas/blob/c6aa9f9ee860bbdcb8bb3444b630aff9f0ac14af/framework/aster-frame/src/mm/page_table/node.rs#L112-L124
_If_ the above reason is considered valid, then _every_ modification method of `PageTableNode` must also be marked as unsafe. This is because a `PageTableNode` does not know its exact position in the page table, so it can be at a critical position (e.g. the kernel text). In such cases, its modification will never be safe in the sense of mapping safety.
https://github.com/asterinas/asterinas/blob/c6aa9f9ee860bbdcb8bb3444b630aff9f0ac14af/framework/aster-frame/src/mm/page_table/node.rs#L372-L373
https://github.com/asterinas/asterinas/blob/c6aa9f9ee860bbdcb8bb3444b630aff9f0ac14af/framework/aster-frame/src/mm/page_table/node.rs#L356-L362
Fortunately, the unsafety of the activation method `RawPageTableNode::activate` should have already captured the mapping safety, so I argue that all other modification methods like `PageTableNode::set_child_untracked` mentioned above should not consider the mapping safety again. However, it should consider the safety of the page tables themselves.
But the safety of the page tables themselves still involves a lot of things, like the following:
- **Property 1**: If any PTE points to another page table, it must point to a valid page table.
- **Property 2**: If any PTE points to a physical page, it can point to either a tracked frame or an untracked region of memory.
- **Property 3**: If any PTE points to a physical page and the current page table node can only represent tracked mappings, the PTE must point to a tracked frame.
- **Property 4**: If any PTE points to a physical page and the current page table node can only represent untracked mappings, the PTE must point to an untracked region of memory.
- **Property 5**: If any PTE points to another page table, it must point to a page table that is on the next page level. If the next page level does not exist, the PTE cannot point to a page table.
The current design does indeed guarantee **Property 1** and **Property 2**, but the APIs need some revision to make them truly safe. However, it runs into difficulties when dropping the page tables, because the page table nodes do not know whether PTEs point to tracked frames or untracked regions of memory. The API change and the difficulties are described below as **Solution 1**.
To address the above difficulties, I think that it is possible to additionally guarantee **Property 3** and **Property 4** through safe APIs of page table nodes. I call this **Solution 2** below.
I don't think that **Property 5** needs to be guaranteed by `PageTableNode`. The reason is that it can be trivially guaranteed by the page table cursors. The page table cursors maintain a fixed-length array, where each slot can have a page table node at a certain level. It is clear enough, so there is little benefit to enforce these guarantees to the page table nodes.
# Solution 0
Do nothing.
**Pros:**
- No more work to do!
**Cons:**
- The current APIs are not as good as I would like them to be, and I think they are hard to maintain.
# Solution 1
The current design guarantees **Property 1** and **Property 2**. However, most of the `PageTableNode` APIs cannot be considered safe because they rely on the correctness of the input argument `in_untracked_range` to be memory safe:
https://github.com/asterinas/asterinas/blob/c6aa9f9ee860bbdcb8bb3444b630aff9f0ac14af/framework/aster-frame/src/mm/page_table/node.rs#L267-L268
For example, if someone passes `in_untracked_range = false` to `PageTableNode::child`, but the corresponding PTE actually points to an untracked memory range, then the untracked memory range will be cast to an tracked frame. This will cause serve memory safety issues.
To solve this problem, it is possible to create a new type called `MaybeTrackedPage`, which can be converted into a tracked frame (via the unsafe `assume_tracked` method) or an untracked region of memory (via the `assume_untracked` method) by the user:
https://github.com/asterinas/asterinas/blob/7f45a1bb29f5bf6d6ddb0d12fdb48dc1ca15852c/framework/aster-frame/src/mm/page_table/node.rs#L253-L268
Then the `PageTableNode::child` method can be made to return a wrapped type of `MaybeTrackedPage` (the `Child` wrapper handles cases where the PTE is empty or points to another page table):
https://github.com/asterinas/asterinas/blob/7f45a1bb29f5bf6d6ddb0d12fdb48dc1ca15852c/framework/aster-frame/src/mm/page_table/node.rs#L447-L448
I think this solution works well, _except_ for the annoying `Drop` implementation. Since the page table node has no way of knowing whether PTEs point to tracked frames or untracked regions of memory, it won't know how to drop them if such PTEs are encountered in the `Drop` method. So far it is assumed that only tracked frames can be dropped, as shown in the following code snippet:
https://github.com/asterinas/asterinas/blob/c6aa9f9ee860bbdcb8bb3444b630aff9f0ac14af/framework/aster-frame/src/mm/page_table/node.rs#L536-L540
But this assumption can easily be wrong. For example, a page table containing untracked regions of memory can be dropped if a huge page overwrites the PTE on a page table:
https://github.com/asterinas/asterinas/blob/c6aa9f9ee860bbdcb8bb3444b630aff9f0ac14af/framework/aster-frame/src/mm/page_table/node.rs#L474-L476
It is possible to work around this problem by adding methods such as `drop_deep_untracked` and `drop_deep_tracked`, which recursively drop all descendants of the current page table node, assuming they contain only tracked frames or untracked regions of memory. Then the `drop` method should not see any PTEs pointing to physical pages.
https://github.com/asterinas/asterinas/blob/7f45a1bb29f5bf6d6ddb0d12fdb48dc1ca15852c/framework/aster-frame/src/mm/page_table/node.rs#L303-L325
However, this solution is not very elegant.
**Pro:**
- It was implemented in #918, see commits "Implement `MaybeTracked{,Page,PageRef}`" and "Clarify the safety model in `PageTableNode`".
**Cons:**
- The dropping implementation is not ideal.
- The cursor (and its users) must be careful about whether the PTE represents tracked frames or untracked regions of memory.
# Solution 2
One possible solution to solve the problem above is to make page table nodes aware whether it contains tracked frames or untracked regions of memory.
I think it is reasonable to make an additional assumption: a page table node cannot _directly_ contain both PTEs to tracked frames and PTEs to regions of memory. This limits the power of the page table a bit, but is still reasonable. On x86-64, each page table node representing a 1GiB mapping can have either tracked frames or untracked regions of memory, but not both, as 2MiB huge pages, which still seems flexible to me.
This information can be recorded in the page metadata, marking each page table as `Tracked` (diretly containing PTEs only to tracked frames), `Untracked` (directly contains PTEs only to untracked regions of memory), or `None` (directly containing no PTEs to physical pages). Then when dropping a page table, it is clear the PTEs can be dropped without problems.
A simple way to enforce the page metadata is to add assertions at the beginning of methods like `PageTableNode::set_child_frame` and `PageTableNode::set_child_untracked`. Compilers may be smart to check once and update a number of PTEs.
Alternatively, I think a better solution is to make page table cursors that operate on tracked frames and untracked regions of memory _different modes_ (like the existing `UserMode` and `KernelMode`). This way, whether a cursor operates on tracked frames or untracked regions can be determined at compile time, instead of at runtime as it is now:
https://github.com/asterinas/asterinas/blob/c6aa9f9ee860bbdcb8bb3444b630aff9f0ac14af/framework/aster-frame/src/mm/page_table/cursor.rs#L278-L282
Then the page table cursor and page table node implementation should be much clearer:
```rust
impl TrackedNode {
fn set_child(&mut self, idx: usize, frame: Frame);
}
impl UntrackedNode {
fn set_child(&mut self, idx: usize, paddr: Paddr);
}
```
```rust
// `TrackedMode` associates with `TrackedNode`
impl<M: TrackedMode> Cursor<M> {
fn map(&mut self, frame: Frame, prop: PageProperty);
}
// `UntrackedMode` associates with `UntrackedNode`
impl<M: UntrackedMode> Cursor {
fn map(&mut self, pa: &Range<Paddr>, prop: PageProperty);
}
```
**Pros:**
- Improves clarity of cursor and node implementation.
- Addresses the above problem.
**Cons:**
- Cursor implementation requires more refactoring.
- Cursor may not be as flexible as it is now, but are there use cases where accesses to tracked frames and untracked regions of memory have be mixed in one cursor?
cc @junyang-zh
|
asterinas__asterinas-1372
| 1,372
|
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -226,6 +226,8 @@ ktest: initramfs $(CARGO_OSDK)
@for dir in $(OSDK_CRATES); do \
[ $$dir = "ostd/libs/linux-bzimage/setup" ] && continue; \
(cd $$dir && cargo osdk test) || exit 1; \
+ tail --lines 10 qemu.log | grep -q "^\\[ktest runner\\] All crates tested." \
+ || (echo "Test failed" && exit 1); \
done
.PHONY: docs
diff --git a/ostd/src/mm/kspace.rs b/ostd/src/mm/kspace.rs
--- a/ostd/src/mm/kspace.rs
+++ b/ostd/src/mm/kspace.rs
@@ -13,13 +13,13 @@
//!
//! ```text
//! +-+ <- the highest used address (0xffff_ffff_ffff_0000)
-//! | | For the kernel code, 1 GiB. Mapped frames are untracked.
+//! | | For the kernel code, 1 GiB. Mapped frames are tracked.
//! +-+ <- 0xffff_ffff_8000_0000
//! | |
//! | | Unused hole.
//! +-+ <- 0xffff_ff00_0000_0000
//! | | For frame metadata, 1 TiB.
-//! | | Mapped frames are untracked.
+//! | | Mapped frames are tracked with handles.
//! +-+ <- 0xffff_fe00_0000_0000
//! | | For vm alloc/io mappings, 1 TiB.
//! | | Mapped frames are tracked with handles.
diff --git a/ostd/src/mm/kspace.rs b/ostd/src/mm/kspace.rs
--- a/ostd/src/mm/kspace.rs
+++ b/ostd/src/mm/kspace.rs
@@ -13,13 +13,13 @@
//!
//! ```text
//! +-+ <- the highest used address (0xffff_ffff_ffff_0000)
-//! | | For the kernel code, 1 GiB. Mapped frames are untracked.
+//! | | For the kernel code, 1 GiB. Mapped frames are tracked.
//! +-+ <- 0xffff_ffff_8000_0000
//! | |
//! | | Unused hole.
//! +-+ <- 0xffff_ff00_0000_0000
//! | | For frame metadata, 1 TiB.
-//! | | Mapped frames are untracked.
+//! | | Mapped frames are tracked with handles.
//! +-+ <- 0xffff_fe00_0000_0000
//! | | For vm alloc/io mappings, 1 TiB.
//! | | Mapped frames are tracked with handles.
diff --git a/ostd/src/mm/kspace.rs b/ostd/src/mm/kspace.rs
--- a/ostd/src/mm/kspace.rs
+++ b/ostd/src/mm/kspace.rs
@@ -104,6 +104,13 @@ pub fn paddr_to_vaddr(pa: Paddr) -> usize {
pa + LINEAR_MAPPING_BASE_VADDR
}
+/// Returns whether the given address should be mapped as tracked.
+///
+/// About what is tracked mapping, see [`crate::mm::page::meta::MapTrackingStatus`].
+pub(crate) fn should_map_as_tracked(addr: Vaddr) -> bool {
+ !LINEAR_MAPPING_VADDR_RANGE.contains(&addr)
+}
+
/// The kernel page table instance.
///
/// It manages the kernel mapping of all address spaces by sharing the kernel part. And it
diff --git a/ostd/src/mm/kspace.rs b/ostd/src/mm/kspace.rs
--- a/ostd/src/mm/kspace.rs
+++ b/ostd/src/mm/kspace.rs
@@ -104,6 +104,13 @@ pub fn paddr_to_vaddr(pa: Paddr) -> usize {
pa + LINEAR_MAPPING_BASE_VADDR
}
+/// Returns whether the given address should be mapped as tracked.
+///
+/// About what is tracked mapping, see [`crate::mm::page::meta::MapTrackingStatus`].
+pub(crate) fn should_map_as_tracked(addr: Vaddr) -> bool {
+ !LINEAR_MAPPING_VADDR_RANGE.contains(&addr)
+}
+
/// The kernel page table instance.
///
/// It manages the kernel mapping of all address spaces by sharing the kernel part. And it
diff --git a/ostd/src/mm/page/meta.rs b/ostd/src/mm/page/meta.rs
--- a/ostd/src/mm/page/meta.rs
+++ b/ostd/src/mm/page/meta.rs
@@ -180,29 +180,50 @@ impl Sealed for FrameMeta {}
/// Make sure the the generic parameters don't effect the memory layout.
#[derive(Debug)]
#[repr(C)]
-pub struct PageTablePageMeta<
+pub(in crate::mm) struct PageTablePageMeta<
E: PageTableEntryTrait = PageTableEntry,
C: PagingConstsTrait = PagingConsts,
> where
[(); C::NR_LEVELS as usize]:,
{
+ /// The number of valid PTEs. It is mutable if the lock is held.
+ pub nr_children: UnsafeCell<u16>,
+ /// The level of the page table page. A page table page cannot be
+ /// referenced by page tables of different levels.
pub level: PagingLevel,
+ /// Whether the pages mapped by the node is tracked.
+ pub is_tracked: MapTrackingStatus,
/// The lock for the page table page.
pub lock: AtomicU8,
- /// The number of valid PTEs. It is mutable if the lock is held.
- pub nr_children: UnsafeCell<u16>,
_phantom: core::marker::PhantomData<(E, C)>,
}
+/// Describe if the physical address recorded in this page table refers to a
+/// page tracked by metadata.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub(in crate::mm) enum MapTrackingStatus {
+ /// The page table node cannot contain references to any pages. It can only
+ /// contain references to child page table nodes.
+ NotApplicable,
+ /// The mapped pages are not tracked by metadata. If any child page table
+ /// nodes exist, they should also be tracked.
+ Untracked,
+ /// The mapped pages are tracked by metadata. If any child page table nodes
+ /// exist, they should also be tracked.
+ Tracked,
+}
+
impl<E: PageTableEntryTrait, C: PagingConstsTrait> PageTablePageMeta<E, C>
where
[(); C::NR_LEVELS as usize]:,
{
- pub fn new_locked(level: PagingLevel) -> Self {
+ pub fn new_locked(level: PagingLevel, is_tracked: MapTrackingStatus) -> Self {
Self {
+ nr_children: UnsafeCell::new(0),
level,
+ is_tracked,
lock: AtomicU8::new(1),
- nr_children: UnsafeCell::new(0),
_phantom: PhantomData,
}
}
diff --git a/ostd/src/mm/page/meta.rs b/ostd/src/mm/page/meta.rs
--- a/ostd/src/mm/page/meta.rs
+++ b/ostd/src/mm/page/meta.rs
@@ -180,29 +180,50 @@ impl Sealed for FrameMeta {}
/// Make sure the the generic parameters don't effect the memory layout.
#[derive(Debug)]
#[repr(C)]
-pub struct PageTablePageMeta<
+pub(in crate::mm) struct PageTablePageMeta<
E: PageTableEntryTrait = PageTableEntry,
C: PagingConstsTrait = PagingConsts,
> where
[(); C::NR_LEVELS as usize]:,
{
+ /// The number of valid PTEs. It is mutable if the lock is held.
+ pub nr_children: UnsafeCell<u16>,
+ /// The level of the page table page. A page table page cannot be
+ /// referenced by page tables of different levels.
pub level: PagingLevel,
+ /// Whether the pages mapped by the node is tracked.
+ pub is_tracked: MapTrackingStatus,
/// The lock for the page table page.
pub lock: AtomicU8,
- /// The number of valid PTEs. It is mutable if the lock is held.
- pub nr_children: UnsafeCell<u16>,
_phantom: core::marker::PhantomData<(E, C)>,
}
+/// Describe if the physical address recorded in this page table refers to a
+/// page tracked by metadata.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub(in crate::mm) enum MapTrackingStatus {
+ /// The page table node cannot contain references to any pages. It can only
+ /// contain references to child page table nodes.
+ NotApplicable,
+ /// The mapped pages are not tracked by metadata. If any child page table
+ /// nodes exist, they should also be tracked.
+ Untracked,
+ /// The mapped pages are tracked by metadata. If any child page table nodes
+ /// exist, they should also be tracked.
+ Tracked,
+}
+
impl<E: PageTableEntryTrait, C: PagingConstsTrait> PageTablePageMeta<E, C>
where
[(); C::NR_LEVELS as usize]:,
{
- pub fn new_locked(level: PagingLevel) -> Self {
+ pub fn new_locked(level: PagingLevel, is_tracked: MapTrackingStatus) -> Self {
Self {
+ nr_children: UnsafeCell::new(0),
level,
+ is_tracked,
lock: AtomicU8::new(1),
- nr_children: UnsafeCell::new(0),
_phantom: PhantomData,
}
}
diff --git a/ostd/src/mm/page/mod.rs b/ostd/src/mm/page/mod.rs
--- a/ostd/src/mm/page/mod.rs
+++ b/ostd/src/mm/page/mod.rs
@@ -119,25 +119,6 @@ impl<M: PageMeta> Page<M> {
}
}
- /// Increase the reference count of the page by one.
- ///
- /// # Safety
- ///
- /// The physical address must represent a valid page.
- ///
- /// And the caller must ensure the metadata slot pointed through the corresponding
- /// virtual address is initialized by holding a reference count of the page firstly.
- /// Otherwise the function may add a reference count to an unused page.
- pub(in crate::mm) unsafe fn inc_ref_count(paddr: Paddr) {
- debug_assert!(paddr % PAGE_SIZE == 0);
- debug_assert!(paddr < MAX_PADDR.load(Ordering::Relaxed) as Paddr);
- let vaddr: Vaddr = mapping::page_to_meta::<PagingConsts>(paddr);
- // SAFETY: The virtual address points to an initialized metadata slot.
- (*(vaddr as *const MetaSlot))
- .ref_count
- .fetch_add(1, Ordering::Relaxed);
- }
-
/// Get the physical address.
pub fn paddr(&self) -> Paddr {
mapping::meta_to_page::<PagingConsts>(self.ptr as Vaddr)
diff --git a/ostd/src/mm/page/mod.rs b/ostd/src/mm/page/mod.rs
--- a/ostd/src/mm/page/mod.rs
+++ b/ostd/src/mm/page/mod.rs
@@ -119,25 +119,6 @@ impl<M: PageMeta> Page<M> {
}
}
- /// Increase the reference count of the page by one.
- ///
- /// # Safety
- ///
- /// The physical address must represent a valid page.
- ///
- /// And the caller must ensure the metadata slot pointed through the corresponding
- /// virtual address is initialized by holding a reference count of the page firstly.
- /// Otherwise the function may add a reference count to an unused page.
- pub(in crate::mm) unsafe fn inc_ref_count(paddr: Paddr) {
- debug_assert!(paddr % PAGE_SIZE == 0);
- debug_assert!(paddr < MAX_PADDR.load(Ordering::Relaxed) as Paddr);
- let vaddr: Vaddr = mapping::page_to_meta::<PagingConsts>(paddr);
- // SAFETY: The virtual address points to an initialized metadata slot.
- (*(vaddr as *const MetaSlot))
- .ref_count
- .fetch_add(1, Ordering::Relaxed);
- }
-
/// Get the physical address.
pub fn paddr(&self) -> Paddr {
mapping::meta_to_page::<PagingConsts>(self.ptr as Vaddr)
diff --git a/ostd/src/mm/page/mod.rs b/ostd/src/mm/page/mod.rs
--- a/ostd/src/mm/page/mod.rs
+++ b/ostd/src/mm/page/mod.rs
@@ -248,20 +229,6 @@ impl DynPage {
Self { ptr }
}
- /// Increase the reference count of the page by one.
- ///
- /// # Safety
- ///
- /// This is the same as [`Page::inc_ref_count`].
- pub(in crate::mm) unsafe fn inc_ref_count(paddr: Paddr) {
- debug_assert!(paddr % PAGE_SIZE == 0);
- debug_assert!(paddr < MAX_PADDR.load(Ordering::Relaxed) as Paddr);
- let vaddr: Vaddr = mapping::page_to_meta::<PagingConsts>(paddr);
- (*(vaddr as *const MetaSlot))
- .ref_count
- .fetch_add(1, Ordering::Relaxed);
- }
-
/// Get the physical address of the start of the page
pub fn paddr(&self) -> Paddr {
mapping::meta_to_page::<PagingConsts>(self.ptr as Vaddr)
diff --git a/ostd/src/mm/page/mod.rs b/ostd/src/mm/page/mod.rs
--- a/ostd/src/mm/page/mod.rs
+++ b/ostd/src/mm/page/mod.rs
@@ -248,20 +229,6 @@ impl DynPage {
Self { ptr }
}
- /// Increase the reference count of the page by one.
- ///
- /// # Safety
- ///
- /// This is the same as [`Page::inc_ref_count`].
- pub(in crate::mm) unsafe fn inc_ref_count(paddr: Paddr) {
- debug_assert!(paddr % PAGE_SIZE == 0);
- debug_assert!(paddr < MAX_PADDR.load(Ordering::Relaxed) as Paddr);
- let vaddr: Vaddr = mapping::page_to_meta::<PagingConsts>(paddr);
- (*(vaddr as *const MetaSlot))
- .ref_count
- .fetch_add(1, Ordering::Relaxed);
- }
-
/// Get the physical address of the start of the page
pub fn paddr(&self) -> Paddr {
mapping::meta_to_page::<PagingConsts>(self.ptr as Vaddr)
diff --git a/ostd/src/mm/page/mod.rs b/ostd/src/mm/page/mod.rs
--- a/ostd/src/mm/page/mod.rs
+++ b/ostd/src/mm/page/mod.rs
@@ -363,3 +330,22 @@ impl Drop for DynPage {
}
}
}
+
+/// Increases the reference count of the page by one.
+///
+/// # Safety
+///
+/// The caller should ensure the following conditions:
+/// 1. The physical address must represent a valid page;
+/// 2. The caller must have already held a reference to the page.
+pub(in crate::mm) unsafe fn inc_page_ref_count(paddr: Paddr) {
+ debug_assert!(paddr % PAGE_SIZE == 0);
+ debug_assert!(paddr < MAX_PADDR.load(Ordering::Relaxed) as Paddr);
+
+ let vaddr: Vaddr = mapping::page_to_meta::<PagingConsts>(paddr);
+ // SAFETY: The virtual address points to an initialized metadata slot.
+ let slot = unsafe { &*(vaddr as *const MetaSlot) };
+ let old = slot.ref_count.fetch_add(1, Ordering::Relaxed);
+
+ debug_assert!(old > 0);
+}
diff --git a/ostd/src/mm/page/mod.rs b/ostd/src/mm/page/mod.rs
--- a/ostd/src/mm/page/mod.rs
+++ b/ostd/src/mm/page/mod.rs
@@ -363,3 +330,22 @@ impl Drop for DynPage {
}
}
}
+
+/// Increases the reference count of the page by one.
+///
+/// # Safety
+///
+/// The caller should ensure the following conditions:
+/// 1. The physical address must represent a valid page;
+/// 2. The caller must have already held a reference to the page.
+pub(in crate::mm) unsafe fn inc_page_ref_count(paddr: Paddr) {
+ debug_assert!(paddr % PAGE_SIZE == 0);
+ debug_assert!(paddr < MAX_PADDR.load(Ordering::Relaxed) as Paddr);
+
+ let vaddr: Vaddr = mapping::page_to_meta::<PagingConsts>(paddr);
+ // SAFETY: The virtual address points to an initialized metadata slot.
+ let slot = unsafe { &*(vaddr as *const MetaSlot) };
+ let old = slot.ref_count.fetch_add(1, Ordering::Relaxed);
+
+ debug_assert!(old > 0);
+}
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -65,17 +65,21 @@
//! table cursor should add additional entry point checks to prevent these defined
//! behaviors if they are not wanted.
-use core::{any::TypeId, marker::PhantomData, mem::ManuallyDrop, ops::Range};
+use core::{any::TypeId, marker::PhantomData, ops::Range};
use align_ext::AlignExt;
use super::{
- page_size, pte_index, Child, KernelMode, PageTable, PageTableEntryTrait, PageTableError,
+ page_size, pte_index, Child, Entry, KernelMode, PageTable, PageTableEntryTrait, PageTableError,
PageTableMode, PageTableNode, PagingConstsTrait, PagingLevel, UserMode,
};
use crate::{
mm::{
- page::{meta::PageTablePageMeta, DynPage, Page},
+ kspace::should_map_as_tracked,
+ page::{
+ meta::{MapTrackingStatus, PageTablePageMeta},
+ DynPage, Page,
+ },
Paddr, PageProperty, Vaddr,
},
task::{disable_preempt, DisabledPreemptGuard},
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -65,17 +65,21 @@
//! table cursor should add additional entry point checks to prevent these defined
//! behaviors if they are not wanted.
-use core::{any::TypeId, marker::PhantomData, mem::ManuallyDrop, ops::Range};
+use core::{any::TypeId, marker::PhantomData, ops::Range};
use align_ext::AlignExt;
use super::{
- page_size, pte_index, Child, KernelMode, PageTable, PageTableEntryTrait, PageTableError,
+ page_size, pte_index, Child, Entry, KernelMode, PageTable, PageTableEntryTrait, PageTableError,
PageTableMode, PageTableNode, PagingConstsTrait, PagingLevel, UserMode,
};
use crate::{
mm::{
- page::{meta::PageTablePageMeta, DynPage, Page},
+ kspace::should_map_as_tracked,
+ page::{
+ meta::{MapTrackingStatus, PageTablePageMeta},
+ DynPage, Page,
+ },
Paddr, PageProperty, Vaddr,
},
task::{disable_preempt, DisabledPreemptGuard},
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -134,6 +138,7 @@ where
va: Vaddr,
/// The virtual address range that is locked.
barrier_va: Range<Vaddr>,
+ #[allow(dead_code)]
preempt_guard: DisabledPreemptGuard,
_phantom: PhantomData<&'a PageTable<M, E, C>>,
}
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -134,6 +138,7 @@ where
va: Vaddr,
/// The virtual address range that is locked.
barrier_va: Range<Vaddr>,
+ #[allow(dead_code)]
preempt_guard: DisabledPreemptGuard,
_phantom: PhantomData<&'a PageTable<M, E, C>>,
}
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -190,12 +195,15 @@ where
break;
}
- let cur_pte = cursor.read_cur_pte();
- if !cur_pte.is_present() || cur_pte.is_last(cursor.level) {
+ let entry = cursor.cur_entry();
+ if !entry.is_node() {
break;
}
+ let Child::PageTable(child_pt) = entry.to_owned() else {
+ unreachable!("Already checked");
+ };
- cursor.level_down();
+ cursor.push_level(child_pt.lock());
// Release the guard of the previous (upper) level.
cursor.guards[cursor.level as usize] = None;
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -190,12 +195,15 @@ where
break;
}
- let cur_pte = cursor.read_cur_pte();
- if !cur_pte.is_present() || cur_pte.is_last(cursor.level) {
+ let entry = cursor.cur_entry();
+ if !entry.is_node() {
break;
}
+ let Child::PageTable(child_pt) = entry.to_owned() else {
+ unreachable!("Already checked");
+ };
- cursor.level_down();
+ cursor.push_level(child_pt.lock());
// Release the guard of the previous (upper) level.
cursor.guards[cursor.level as usize] = None;
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -215,9 +223,9 @@ where
let level = self.level;
let va = self.va;
- match self.cur_child() {
- Child::PageTable(_) => {
- self.level_down();
+ match self.cur_entry().to_owned() {
+ Child::PageTable(pt) => {
+ self.push_level(pt.lock());
continue;
}
Child::None => {
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -215,9 +223,9 @@ where
let level = self.level;
let va = self.va;
- match self.cur_child() {
- Child::PageTable(_) => {
- self.level_down();
+ match self.cur_entry().to_owned() {
+ Child::PageTable(pt) => {
+ self.push_level(pt.lock());
continue;
}
Child::None => {
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -229,7 +237,8 @@ where
Child::Page(page, prop) => {
return Ok(PageTableItem::Mapped { va, page, prop });
}
- Child::Untracked(pa, prop) => {
+ Child::Untracked(pa, plevel, prop) => {
+ debug_assert_eq!(plevel, level);
return Ok(PageTableItem::MappedUntracked {
va,
pa,
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -229,7 +237,8 @@ where
Child::Page(page, prop) => {
return Ok(PageTableItem::Mapped { va, page, prop });
}
- Child::Untracked(pa, prop) => {
+ Child::Untracked(pa, plevel, prop) => {
+ debug_assert_eq!(plevel, level);
return Ok(PageTableItem::MappedUntracked {
va,
pa,
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -249,7 +258,7 @@ where
let page_size = page_size::<C>(self.level);
let next_va = self.va.align_down(page_size) + page_size;
while self.level < self.guard_level && pte_index::<C>(next_va, self.level) == 0 {
- self.level_up();
+ self.pop_level();
}
self.va = next_va;
}
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -249,7 +258,7 @@ where
let page_size = page_size::<C>(self.level);
let next_va = self.va.align_down(page_size) + page_size;
while self.level < self.guard_level && pte_index::<C>(next_va, self.level) == 0 {
- self.level_up();
+ self.pop_level();
}
self.va = next_va;
}
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -283,7 +292,7 @@ where
}
debug_assert!(self.level < self.guard_level);
- self.level_up();
+ self.pop_level();
}
}
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -283,7 +292,7 @@ where
}
debug_assert!(self.level < self.guard_level);
- self.level_up();
+ self.pop_level();
}
}
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -291,70 +300,37 @@ where
self.va
}
- pub fn preempt_guard(&self) -> &DisabledPreemptGuard {
- &self.preempt_guard
- }
-
- /// Goes up a level. We release the current page if it has no mappings since the cursor only moves
- /// forward. And if needed we will do the final cleanup using this method after re-walk when the
- /// cursor is dropped.
+ /// Goes up a level.
+ ///
+ /// We release the current page if it has no mappings since the cursor
+ /// only moves forward. And if needed we will do the final cleanup using
+ /// this method after re-walk when the cursor is dropped.
///
- /// This method requires locks acquired before calling it. The discarded level will be unlocked.
- fn level_up(&mut self) {
+ /// This method requires locks acquired before calling it. The discarded
+ /// level will be unlocked.
+ fn pop_level(&mut self) {
self.guards[(self.level - 1) as usize] = None;
self.level += 1;
// TODO: Drop page tables if page tables become empty.
}
- /// Goes down a level assuming a child page table exists.
- fn level_down(&mut self) {
- debug_assert!(self.level > 1);
-
- let Child::PageTable(nxt_lvl_ptn) = self.cur_child() else {
- panic!("Trying to level down when it is not mapped to a page table");
- };
-
- let nxt_lvl_ptn_locked = nxt_lvl_ptn.lock();
-
+ /// Goes down a level to a child page table.
+ fn push_level(&mut self, child_pt: PageTableNode<E, C>) {
self.level -= 1;
- debug_assert_eq!(self.level, nxt_lvl_ptn_locked.level());
-
- self.guards[(self.level - 1) as usize] = Some(nxt_lvl_ptn_locked);
+ debug_assert_eq!(self.level, child_pt.level());
+ self.guards[(self.level - 1) as usize] = Some(child_pt);
}
- fn cur_node(&self) -> &PageTableNode<E, C> {
- self.guards[(self.level - 1) as usize].as_ref().unwrap()
+ fn should_map_as_tracked(&self) -> bool {
+ (TypeId::of::<M>() == TypeId::of::<KernelMode>()
+ || TypeId::of::<M>() == TypeId::of::<UserMode>())
+ && should_map_as_tracked(self.va)
}
- fn cur_idx(&self) -> usize {
- pte_index::<C>(self.va, self.level)
- }
-
- fn cur_child(&self) -> Child<E, C> {
- self.cur_node()
- .child(self.cur_idx(), self.in_tracked_range())
- }
-
- fn read_cur_pte(&self) -> E {
- self.cur_node().read_pte(self.cur_idx())
- }
-
- /// Tells if the current virtual range must contain untracked mappings.
- ///
- /// _Tracked mappings_ means that the mapped physical addresses (in PTEs) points to pages
- /// tracked by the metadata system. _Tracked mappings_ must be created with page handles.
- /// While _untracked mappings_ solely maps to plain physical addresses.
- ///
- /// In the kernel mode, this is aligned with the definition in [`crate::mm::kspace`].
- /// Only linear mappings in the kernel should be considered as untracked mappings.
- ///
- /// All mappings in the user mode are tracked. And all mappings in the IOMMU
- /// page table are untracked.
- fn in_tracked_range(&self) -> bool {
- TypeId::of::<M>() == TypeId::of::<UserMode>()
- || TypeId::of::<M>() == TypeId::of::<KernelMode>()
- && !crate::mm::kspace::LINEAR_MAPPING_VADDR_RANGE.contains(&self.va)
+ fn cur_entry(&mut self) -> Entry<'_, E, C> {
+ let node = self.guards[(self.level - 1) as usize].as_mut().unwrap();
+ node.entry(pte_index::<C>(self.va, self.level))
}
}
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -291,70 +300,37 @@ where
self.va
}
- pub fn preempt_guard(&self) -> &DisabledPreemptGuard {
- &self.preempt_guard
- }
-
- /// Goes up a level. We release the current page if it has no mappings since the cursor only moves
- /// forward. And if needed we will do the final cleanup using this method after re-walk when the
- /// cursor is dropped.
+ /// Goes up a level.
+ ///
+ /// We release the current page if it has no mappings since the cursor
+ /// only moves forward. And if needed we will do the final cleanup using
+ /// this method after re-walk when the cursor is dropped.
///
- /// This method requires locks acquired before calling it. The discarded level will be unlocked.
- fn level_up(&mut self) {
+ /// This method requires locks acquired before calling it. The discarded
+ /// level will be unlocked.
+ fn pop_level(&mut self) {
self.guards[(self.level - 1) as usize] = None;
self.level += 1;
// TODO: Drop page tables if page tables become empty.
}
- /// Goes down a level assuming a child page table exists.
- fn level_down(&mut self) {
- debug_assert!(self.level > 1);
-
- let Child::PageTable(nxt_lvl_ptn) = self.cur_child() else {
- panic!("Trying to level down when it is not mapped to a page table");
- };
-
- let nxt_lvl_ptn_locked = nxt_lvl_ptn.lock();
-
+ /// Goes down a level to a child page table.
+ fn push_level(&mut self, child_pt: PageTableNode<E, C>) {
self.level -= 1;
- debug_assert_eq!(self.level, nxt_lvl_ptn_locked.level());
-
- self.guards[(self.level - 1) as usize] = Some(nxt_lvl_ptn_locked);
+ debug_assert_eq!(self.level, child_pt.level());
+ self.guards[(self.level - 1) as usize] = Some(child_pt);
}
- fn cur_node(&self) -> &PageTableNode<E, C> {
- self.guards[(self.level - 1) as usize].as_ref().unwrap()
+ fn should_map_as_tracked(&self) -> bool {
+ (TypeId::of::<M>() == TypeId::of::<KernelMode>()
+ || TypeId::of::<M>() == TypeId::of::<UserMode>())
+ && should_map_as_tracked(self.va)
}
- fn cur_idx(&self) -> usize {
- pte_index::<C>(self.va, self.level)
- }
-
- fn cur_child(&self) -> Child<E, C> {
- self.cur_node()
- .child(self.cur_idx(), self.in_tracked_range())
- }
-
- fn read_cur_pte(&self) -> E {
- self.cur_node().read_pte(self.cur_idx())
- }
-
- /// Tells if the current virtual range must contain untracked mappings.
- ///
- /// _Tracked mappings_ means that the mapped physical addresses (in PTEs) points to pages
- /// tracked by the metadata system. _Tracked mappings_ must be created with page handles.
- /// While _untracked mappings_ solely maps to plain physical addresses.
- ///
- /// In the kernel mode, this is aligned with the definition in [`crate::mm::kspace`].
- /// Only linear mappings in the kernel should be considered as untracked mappings.
- ///
- /// All mappings in the user mode are tracked. And all mappings in the IOMMU
- /// page table are untracked.
- fn in_tracked_range(&self) -> bool {
- TypeId::of::<M>() == TypeId::of::<UserMode>()
- || TypeId::of::<M>() == TypeId::of::<KernelMode>()
- && !crate::mm::kspace::LINEAR_MAPPING_VADDR_RANGE.contains(&self.va)
+ fn cur_entry(&mut self) -> Entry<'_, E, C> {
+ let node = self.guards[(self.level - 1) as usize].as_mut().unwrap();
+ node.entry(pte_index::<C>(self.va, self.level))
}
}
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -445,30 +421,38 @@ where
pub unsafe fn map(&mut self, page: DynPage, prop: PageProperty) -> Option<DynPage> {
let end = self.0.va + page.size();
assert!(end <= self.0.barrier_va.end);
- debug_assert!(self.0.in_tracked_range());
// Go down if not applicable.
while self.0.level > C::HIGHEST_TRANSLATION_LEVEL
|| self.0.va % page_size::<C>(self.0.level) != 0
|| self.0.va + page_size::<C>(self.0.level) > end
{
- let pte = self.0.read_cur_pte();
- if pte.is_present() && !pte.is_last(self.0.level) {
- self.0.level_down();
- } else if !pte.is_present() {
- self.level_down_create();
- } else {
- panic!("Mapping a smaller page in an already mapped huge page");
+ debug_assert!(self.0.should_map_as_tracked());
+ let cur_level = self.0.level;
+ let cur_entry = self.0.cur_entry();
+ match cur_entry.to_owned() {
+ Child::PageTable(pt) => {
+ self.0.push_level(pt.lock());
+ }
+ Child::None => {
+ let pt =
+ PageTableNode::<E, C>::alloc(cur_level - 1, MapTrackingStatus::Tracked);
+ let _ = cur_entry.replace(Child::PageTable(pt.clone_raw()));
+ self.0.push_level(pt);
+ }
+ Child::Page(_, _) => {
+ panic!("Mapping a smaller page in an already mapped huge page");
+ }
+ Child::Untracked(_, _, _) => {
+ panic!("Mapping a tracked page in an untracked range");
+ }
}
continue;
}
debug_assert_eq!(self.0.level, page.level());
// Map the current page.
- let idx = self.0.cur_idx();
- let old = self
- .cur_node_mut()
- .replace_child(idx, Child::Page(page, prop), true);
+ let old = self.0.cur_entry().replace(Child::Page(page, prop));
self.0.move_forward();
match old {
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -445,30 +421,38 @@ where
pub unsafe fn map(&mut self, page: DynPage, prop: PageProperty) -> Option<DynPage> {
let end = self.0.va + page.size();
assert!(end <= self.0.barrier_va.end);
- debug_assert!(self.0.in_tracked_range());
// Go down if not applicable.
while self.0.level > C::HIGHEST_TRANSLATION_LEVEL
|| self.0.va % page_size::<C>(self.0.level) != 0
|| self.0.va + page_size::<C>(self.0.level) > end
{
- let pte = self.0.read_cur_pte();
- if pte.is_present() && !pte.is_last(self.0.level) {
- self.0.level_down();
- } else if !pte.is_present() {
- self.level_down_create();
- } else {
- panic!("Mapping a smaller page in an already mapped huge page");
+ debug_assert!(self.0.should_map_as_tracked());
+ let cur_level = self.0.level;
+ let cur_entry = self.0.cur_entry();
+ match cur_entry.to_owned() {
+ Child::PageTable(pt) => {
+ self.0.push_level(pt.lock());
+ }
+ Child::None => {
+ let pt =
+ PageTableNode::<E, C>::alloc(cur_level - 1, MapTrackingStatus::Tracked);
+ let _ = cur_entry.replace(Child::PageTable(pt.clone_raw()));
+ self.0.push_level(pt);
+ }
+ Child::Page(_, _) => {
+ panic!("Mapping a smaller page in an already mapped huge page");
+ }
+ Child::Untracked(_, _, _) => {
+ panic!("Mapping a tracked page in an untracked range");
+ }
}
continue;
}
debug_assert_eq!(self.0.level, page.level());
// Map the current page.
- let idx = self.0.cur_idx();
- let old = self
- .cur_node_mut()
- .replace_child(idx, Child::Page(page, prop), true);
+ let old = self.0.cur_entry().replace(Child::Page(page, prop));
self.0.move_forward();
match old {
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -477,7 +461,7 @@ where
Child::PageTable(_) => {
todo!("Dropping page table nodes while mapping requires TLB flush")
}
- Child::Untracked(_, _) => panic!("Mapping a tracked page in an untracked range"),
+ Child::Untracked(_, _, _) => panic!("Mapping a tracked page in an untracked range"),
}
}
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -477,7 +461,7 @@ where
Child::PageTable(_) => {
todo!("Dropping page table nodes while mapping requires TLB flush")
}
- Child::Untracked(_, _) => panic!("Mapping a tracked page in an untracked range"),
+ Child::Untracked(_, _, _) => panic!("Mapping a tracked page in an untracked range"),
}
}
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -525,25 +509,40 @@ where
|| self.0.va + page_size::<C>(self.0.level) > end
|| pa % page_size::<C>(self.0.level) != 0
{
- let pte = self.0.read_cur_pte();
- if pte.is_present() && !pte.is_last(self.0.level) {
- self.0.level_down();
- } else if !pte.is_present() {
- self.level_down_create();
- } else {
- self.level_down_split();
+ let cur_level = self.0.level;
+ let cur_entry = self.0.cur_entry();
+ match cur_entry.to_owned() {
+ Child::PageTable(pt) => {
+ self.0.push_level(pt.lock());
+ }
+ Child::None => {
+ let pt = PageTableNode::<E, C>::alloc(
+ cur_level - 1,
+ MapTrackingStatus::Untracked,
+ );
+ let _ = cur_entry.replace(Child::PageTable(pt.clone_raw()));
+ self.0.push_level(pt);
+ }
+ Child::Page(_, _) => {
+ panic!("Mapping a smaller page in an already mapped huge page");
+ }
+ Child::Untracked(_, _, _) => {
+ let split_child = cur_entry.split_if_untracked_huge().unwrap();
+ self.0.push_level(split_child);
+ }
}
continue;
}
// Map the current page.
- debug_assert!(!self.0.in_tracked_range());
- let idx = self.0.cur_idx();
+ debug_assert!(!self.0.should_map_as_tracked());
+ let level = self.0.level;
let _ = self
- .cur_node_mut()
- .replace_child(idx, Child::Untracked(pa, prop), false);
+ .0
+ .cur_entry()
+ .replace(Child::Untracked(pa, level, prop));
- let level = self.0.level;
+ // Move forward.
pa += page_size::<C>(level);
self.0.move_forward();
}
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -525,25 +509,40 @@ where
|| self.0.va + page_size::<C>(self.0.level) > end
|| pa % page_size::<C>(self.0.level) != 0
{
- let pte = self.0.read_cur_pte();
- if pte.is_present() && !pte.is_last(self.0.level) {
- self.0.level_down();
- } else if !pte.is_present() {
- self.level_down_create();
- } else {
- self.level_down_split();
+ let cur_level = self.0.level;
+ let cur_entry = self.0.cur_entry();
+ match cur_entry.to_owned() {
+ Child::PageTable(pt) => {
+ self.0.push_level(pt.lock());
+ }
+ Child::None => {
+ let pt = PageTableNode::<E, C>::alloc(
+ cur_level - 1,
+ MapTrackingStatus::Untracked,
+ );
+ let _ = cur_entry.replace(Child::PageTable(pt.clone_raw()));
+ self.0.push_level(pt);
+ }
+ Child::Page(_, _) => {
+ panic!("Mapping a smaller page in an already mapped huge page");
+ }
+ Child::Untracked(_, _, _) => {
+ let split_child = cur_entry.split_if_untracked_huge().unwrap();
+ self.0.push_level(split_child);
+ }
}
continue;
}
// Map the current page.
- debug_assert!(!self.0.in_tracked_range());
- let idx = self.0.cur_idx();
+ debug_assert!(!self.0.should_map_as_tracked());
+ let level = self.0.level;
let _ = self
- .cur_node_mut()
- .replace_child(idx, Child::Untracked(pa, prop), false);
+ .0
+ .cur_entry()
+ .replace(Child::Untracked(pa, level, prop));
- let level = self.0.level;
+ // Move forward.
pa += page_size::<C>(level);
self.0.move_forward();
}
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -580,11 +579,12 @@ where
assert!(end <= self.0.barrier_va.end);
while self.0.va < end {
- let cur_pte = self.0.read_cur_pte();
- let is_tracked = self.0.in_tracked_range();
+ let cur_va = self.0.va;
+ let cur_level = self.0.level;
+ let cur_entry = self.0.cur_entry();
// Skip if it is already absent.
- if !cur_pte.is_present() {
+ if cur_entry.is_none() {
if self.0.va + page_size::<C>(self.0.level) > end {
self.0.va = end;
break;
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -580,11 +579,12 @@ where
assert!(end <= self.0.barrier_va.end);
while self.0.va < end {
- let cur_pte = self.0.read_cur_pte();
- let is_tracked = self.0.in_tracked_range();
+ let cur_va = self.0.va;
+ let cur_level = self.0.level;
+ let cur_entry = self.0.cur_entry();
// Skip if it is already absent.
- if !cur_pte.is_present() {
+ if cur_entry.is_none() {
if self.0.va + page_size::<C>(self.0.level) > end {
self.0.va = end;
break;
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -593,64 +593,61 @@ where
continue;
}
- if self.0.va % page_size::<C>(self.0.level) != 0
- || self.0.va + page_size::<C>(self.0.level) > end
- {
- if !is_tracked {
- // Level down if we are removing part of a huge untracked page.
- self.level_down_split();
- continue;
- }
-
- if cur_pte.is_last(self.0.level) {
- panic!("removing part of a huge page");
- }
-
- // Level down if the current PTE points to a page table and we cannot
- // unmap this page table node entirely.
- self.0.level_down();
-
- // We have got down a level. If there's no mapped PTEs in
- // the current node, we can go back and skip to save time.
- if self.0.guards[(self.0.level - 1) as usize]
- .as_ref()
- .unwrap()
- .nr_children()
- == 0
- {
- self.0.level_up();
- self.0.move_forward();
+ // Go down if not applicable.
+ if cur_va % page_size::<C>(cur_level) != 0 || cur_va + page_size::<C>(cur_level) > end {
+ let child = cur_entry.to_owned();
+ match child {
+ Child::PageTable(pt) => {
+ let pt = pt.lock();
+ // If there's no mapped PTEs in the next level, we can
+ // skip to save time.
+ if pt.nr_children() != 0 {
+ self.0.push_level(pt);
+ } else {
+ if self.0.va + page_size::<C>(self.0.level) > end {
+ self.0.va = end;
+ break;
+ }
+ self.0.move_forward();
+ }
+ }
+ Child::None => {
+ unreachable!("Already checked");
+ }
+ Child::Page(_, _) => {
+ panic!("Removing part of a huge page");
+ }
+ Child::Untracked(_, _, _) => {
+ let split_child = cur_entry.split_if_untracked_huge().unwrap();
+ self.0.push_level(split_child);
+ }
}
continue;
}
// Unmap the current page and return it.
- let idx = self.0.cur_idx();
- let ret = self
- .cur_node_mut()
- .replace_child(idx, Child::None, is_tracked);
- let ret_page_va = self.0.va;
- let ret_page_size = page_size::<C>(self.0.level);
+ let old = cur_entry.replace(Child::None);
self.0.move_forward();
- return match ret {
+ return match old {
Child::Page(page, prop) => PageTableItem::Mapped {
- va: ret_page_va,
+ va: self.0.va,
page,
prop,
},
- Child::Untracked(pa, prop) => PageTableItem::MappedUntracked {
- va: ret_page_va,
- pa,
- len: ret_page_size,
- prop,
- },
- Child::PageTable(node) => {
- let node = ManuallyDrop::new(node);
- let page = Page::<PageTablePageMeta<E, C>>::from_raw(node.paddr());
- PageTableItem::PageTableNode { page: page.into() }
+ Child::Untracked(pa, level, prop) => {
+ debug_assert_eq!(level, self.0.level);
+ PageTableItem::MappedUntracked {
+ va: self.0.va,
+ pa,
+ len: page_size::<C>(level),
+ prop,
+ }
}
+ Child::PageTable(node) => PageTableItem::PageTableNode {
+ page: Page::<PageTablePageMeta<E, C>>::from(node).into(),
+ },
Child::None => unreachable!(),
};
}
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -593,64 +593,61 @@ where
continue;
}
- if self.0.va % page_size::<C>(self.0.level) != 0
- || self.0.va + page_size::<C>(self.0.level) > end
- {
- if !is_tracked {
- // Level down if we are removing part of a huge untracked page.
- self.level_down_split();
- continue;
- }
-
- if cur_pte.is_last(self.0.level) {
- panic!("removing part of a huge page");
- }
-
- // Level down if the current PTE points to a page table and we cannot
- // unmap this page table node entirely.
- self.0.level_down();
-
- // We have got down a level. If there's no mapped PTEs in
- // the current node, we can go back and skip to save time.
- if self.0.guards[(self.0.level - 1) as usize]
- .as_ref()
- .unwrap()
- .nr_children()
- == 0
- {
- self.0.level_up();
- self.0.move_forward();
+ // Go down if not applicable.
+ if cur_va % page_size::<C>(cur_level) != 0 || cur_va + page_size::<C>(cur_level) > end {
+ let child = cur_entry.to_owned();
+ match child {
+ Child::PageTable(pt) => {
+ let pt = pt.lock();
+ // If there's no mapped PTEs in the next level, we can
+ // skip to save time.
+ if pt.nr_children() != 0 {
+ self.0.push_level(pt);
+ } else {
+ if self.0.va + page_size::<C>(self.0.level) > end {
+ self.0.va = end;
+ break;
+ }
+ self.0.move_forward();
+ }
+ }
+ Child::None => {
+ unreachable!("Already checked");
+ }
+ Child::Page(_, _) => {
+ panic!("Removing part of a huge page");
+ }
+ Child::Untracked(_, _, _) => {
+ let split_child = cur_entry.split_if_untracked_huge().unwrap();
+ self.0.push_level(split_child);
+ }
}
continue;
}
// Unmap the current page and return it.
- let idx = self.0.cur_idx();
- let ret = self
- .cur_node_mut()
- .replace_child(idx, Child::None, is_tracked);
- let ret_page_va = self.0.va;
- let ret_page_size = page_size::<C>(self.0.level);
+ let old = cur_entry.replace(Child::None);
self.0.move_forward();
- return match ret {
+ return match old {
Child::Page(page, prop) => PageTableItem::Mapped {
- va: ret_page_va,
+ va: self.0.va,
page,
prop,
},
- Child::Untracked(pa, prop) => PageTableItem::MappedUntracked {
- va: ret_page_va,
- pa,
- len: ret_page_size,
- prop,
- },
- Child::PageTable(node) => {
- let node = ManuallyDrop::new(node);
- let page = Page::<PageTablePageMeta<E, C>>::from_raw(node.paddr());
- PageTableItem::PageTableNode { page: page.into() }
+ Child::Untracked(pa, level, prop) => {
+ debug_assert_eq!(level, self.0.level);
+ PageTableItem::MappedUntracked {
+ va: self.0.va,
+ pa,
+ len: page_size::<C>(level),
+ prop,
+ }
}
+ Child::PageTable(node) => PageTableItem::PageTableNode {
+ page: Page::<PageTablePageMeta<E, C>>::from(node).into(),
+ },
Child::None => unreachable!(),
};
}
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -692,51 +689,46 @@ where
assert!(end <= self.0.barrier_va.end);
while self.0.va < end {
- let cur_pte = self.0.read_cur_pte();
- if !cur_pte.is_present() {
+ let cur_va = self.0.va;
+ let cur_level = self.0.level;
+ let mut cur_entry = self.0.cur_entry();
+
+ // Skip if it is already absent.
+ if cur_entry.is_none() {
self.0.move_forward();
continue;
}
- // Go down if it's not a last node.
- if !cur_pte.is_last(self.0.level) {
- self.0.level_down();
-
- // We have got down a level. If there's no mapped PTEs in
- // the current node, we can go back and skip to save time.
- if self.0.guards[(self.0.level - 1) as usize]
- .as_ref()
- .unwrap()
- .nr_children()
- == 0
- {
- self.0.level_up();
+ // Go down if it's not a last entry.
+ if cur_entry.is_node() {
+ let Child::PageTable(pt) = cur_entry.to_owned() else {
+ unreachable!("Already checked");
+ };
+ let pt = pt.lock();
+ // If there's no mapped PTEs in the next level, we can
+ // skip to save time.
+ if pt.nr_children() != 0 {
+ self.0.push_level(pt);
+ } else {
self.0.move_forward();
}
-
continue;
}
// Go down if the page size is too big and we are protecting part
// of untracked huge pages.
- if self.0.va % page_size::<C>(self.0.level) != 0
- || self.0.va + page_size::<C>(self.0.level) > end
- {
- if self.0.in_tracked_range() {
- panic!("protecting part of a huge page");
- } else {
- self.level_down_split();
- continue;
- }
+ if cur_va % page_size::<C>(cur_level) != 0 || cur_va + page_size::<C>(cur_level) > end {
+ let split_child = cur_entry
+ .split_if_untracked_huge()
+ .expect("Protecting part of a huge page");
+ self.0.push_level(split_child);
+ continue;
}
- let mut pte_prop = cur_pte.prop();
- op(&mut pte_prop);
+ // Protect the current page.
+ cur_entry.protect(op);
- let idx = self.0.cur_idx();
- self.cur_node_mut().protect(idx, pte_prop);
let protected_va = self.0.va..self.0.va + page_size::<C>(self.0.level);
-
self.0.move_forward();
return Some(protected_va);
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -692,51 +689,46 @@ where
assert!(end <= self.0.barrier_va.end);
while self.0.va < end {
- let cur_pte = self.0.read_cur_pte();
- if !cur_pte.is_present() {
+ let cur_va = self.0.va;
+ let cur_level = self.0.level;
+ let mut cur_entry = self.0.cur_entry();
+
+ // Skip if it is already absent.
+ if cur_entry.is_none() {
self.0.move_forward();
continue;
}
- // Go down if it's not a last node.
- if !cur_pte.is_last(self.0.level) {
- self.0.level_down();
-
- // We have got down a level. If there's no mapped PTEs in
- // the current node, we can go back and skip to save time.
- if self.0.guards[(self.0.level - 1) as usize]
- .as_ref()
- .unwrap()
- .nr_children()
- == 0
- {
- self.0.level_up();
+ // Go down if it's not a last entry.
+ if cur_entry.is_node() {
+ let Child::PageTable(pt) = cur_entry.to_owned() else {
+ unreachable!("Already checked");
+ };
+ let pt = pt.lock();
+ // If there's no mapped PTEs in the next level, we can
+ // skip to save time.
+ if pt.nr_children() != 0 {
+ self.0.push_level(pt);
+ } else {
self.0.move_forward();
}
-
continue;
}
// Go down if the page size is too big and we are protecting part
// of untracked huge pages.
- if self.0.va % page_size::<C>(self.0.level) != 0
- || self.0.va + page_size::<C>(self.0.level) > end
- {
- if self.0.in_tracked_range() {
- panic!("protecting part of a huge page");
- } else {
- self.level_down_split();
- continue;
- }
+ if cur_va % page_size::<C>(cur_level) != 0 || cur_va + page_size::<C>(cur_level) > end {
+ let split_child = cur_entry
+ .split_if_untracked_huge()
+ .expect("Protecting part of a huge page");
+ self.0.push_level(split_child);
+ continue;
}
- let mut pte_prop = cur_pte.prop();
- op(&mut pte_prop);
+ // Protect the current page.
+ cur_entry.protect(op);
- let idx = self.0.cur_idx();
- self.cur_node_mut().protect(idx, pte_prop);
let protected_va = self.0.va..self.0.va + page_size::<C>(self.0.level);
-
self.0.move_forward();
return Some(protected_va);
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -785,91 +777,46 @@ where
assert!(src_end <= src.0.barrier_va.end);
while self.0.va < this_end && src.0.va < src_end {
- let cur_pte = src.0.read_cur_pte();
- if !cur_pte.is_present() {
- src.0.move_forward();
- continue;
- }
-
- // Go down if it's not a last node.
- if !cur_pte.is_last(src.0.level) {
- src.0.level_down();
-
- // We have got down a level. If there's no mapped PTEs in
- // the current node, we can go back and skip to save time.
- if src.0.guards[(src.0.level - 1) as usize]
- .as_ref()
- .unwrap()
- .nr_children()
- == 0
- {
- src.0.level_up();
+ let src_va = src.0.va;
+ let mut src_entry = src.0.cur_entry();
+
+ match src_entry.to_owned() {
+ Child::PageTable(pt) => {
+ let pt = pt.lock();
+ // If there's no mapped PTEs in the next level, we can
+ // skip to save time.
+ if pt.nr_children() != 0 {
+ src.0.push_level(pt);
+ } else {
+ src.0.move_forward();
+ }
+ continue;
+ }
+ Child::None => {
src.0.move_forward();
+ continue;
}
+ Child::Untracked(_, _, _) => {
+ panic!("Copying untracked mappings");
+ }
+ Child::Page(page, mut prop) => {
+ let mapped_page_size = page.size();
- continue;
- }
-
- // Do protection.
- let mut pte_prop = cur_pte.prop();
- op(&mut pte_prop);
+ // Do protection.
+ src_entry.protect(op);
- let idx = src.0.cur_idx();
- src.cur_node_mut().protect(idx, pte_prop);
+ // Do copy.
+ op(&mut prop);
+ self.jump(src_va).unwrap();
+ let original = self.map(page, prop);
+ assert!(original.is_none());
- // Do copy.
- let child = src.cur_node_mut().child(idx, true);
- let Child::<E, C>::Page(page, prop) = child else {
- panic!("Unexpected child for source mapping: {:#?}", child);
- };
- self.jump(src.0.va).unwrap();
- let mapped_page_size = page.size();
- let original = self.map(page, prop);
- debug_assert!(original.is_none());
-
- // Only move the source cursor forward since `Self::map` will do it.
- // This assertion is to ensure that they move by the same length.
- debug_assert_eq!(mapped_page_size, page_size::<C>(src.0.level));
- src.0.move_forward();
+ // Only move the source cursor forward since `Self::map` will do it.
+ // This assertion is to ensure that they move by the same length.
+ debug_assert_eq!(mapped_page_size, page_size::<C>(src.0.level));
+ src.0.move_forward();
+ }
+ }
}
}
-
- /// Goes down a level assuming the current slot is absent.
- ///
- /// This method will create a new child page table node and go down to it.
- fn level_down_create(&mut self) {
- debug_assert!(self.0.level > 1);
- let new_node = PageTableNode::<E, C>::alloc(self.0.level - 1);
- let idx = self.0.cur_idx();
- let is_tracked = self.0.in_tracked_range();
- let old = self.cur_node_mut().replace_child(
- idx,
- Child::PageTable(new_node.clone_raw()),
- is_tracked,
- );
- debug_assert!(old.is_none());
- self.0.level -= 1;
- self.0.guards[(self.0.level - 1) as usize] = Some(new_node);
- }
-
- /// Goes down a level assuming the current slot is an untracked huge page.
- ///
- /// This method will split the huge page and go down to the next level.
- fn level_down_split(&mut self) {
- debug_assert!(self.0.level > 1);
- debug_assert!(!self.0.in_tracked_range());
-
- let idx = self.0.cur_idx();
- self.cur_node_mut().split_untracked_huge(idx);
-
- let Child::PageTable(new_node) = self.0.cur_child() else {
- unreachable!();
- };
- self.0.level -= 1;
- self.0.guards[(self.0.level - 1) as usize] = Some(new_node.lock());
- }
-
- fn cur_node_mut(&mut self) -> &mut PageTableNode<E, C> {
- self.0.guards[(self.0.level - 1) as usize].as_mut().unwrap()
- }
}
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -785,91 +777,46 @@ where
assert!(src_end <= src.0.barrier_va.end);
while self.0.va < this_end && src.0.va < src_end {
- let cur_pte = src.0.read_cur_pte();
- if !cur_pte.is_present() {
- src.0.move_forward();
- continue;
- }
-
- // Go down if it's not a last node.
- if !cur_pte.is_last(src.0.level) {
- src.0.level_down();
-
- // We have got down a level. If there's no mapped PTEs in
- // the current node, we can go back and skip to save time.
- if src.0.guards[(src.0.level - 1) as usize]
- .as_ref()
- .unwrap()
- .nr_children()
- == 0
- {
- src.0.level_up();
+ let src_va = src.0.va;
+ let mut src_entry = src.0.cur_entry();
+
+ match src_entry.to_owned() {
+ Child::PageTable(pt) => {
+ let pt = pt.lock();
+ // If there's no mapped PTEs in the next level, we can
+ // skip to save time.
+ if pt.nr_children() != 0 {
+ src.0.push_level(pt);
+ } else {
+ src.0.move_forward();
+ }
+ continue;
+ }
+ Child::None => {
src.0.move_forward();
+ continue;
}
+ Child::Untracked(_, _, _) => {
+ panic!("Copying untracked mappings");
+ }
+ Child::Page(page, mut prop) => {
+ let mapped_page_size = page.size();
- continue;
- }
-
- // Do protection.
- let mut pte_prop = cur_pte.prop();
- op(&mut pte_prop);
+ // Do protection.
+ src_entry.protect(op);
- let idx = src.0.cur_idx();
- src.cur_node_mut().protect(idx, pte_prop);
+ // Do copy.
+ op(&mut prop);
+ self.jump(src_va).unwrap();
+ let original = self.map(page, prop);
+ assert!(original.is_none());
- // Do copy.
- let child = src.cur_node_mut().child(idx, true);
- let Child::<E, C>::Page(page, prop) = child else {
- panic!("Unexpected child for source mapping: {:#?}", child);
- };
- self.jump(src.0.va).unwrap();
- let mapped_page_size = page.size();
- let original = self.map(page, prop);
- debug_assert!(original.is_none());
-
- // Only move the source cursor forward since `Self::map` will do it.
- // This assertion is to ensure that they move by the same length.
- debug_assert_eq!(mapped_page_size, page_size::<C>(src.0.level));
- src.0.move_forward();
+ // Only move the source cursor forward since `Self::map` will do it.
+ // This assertion is to ensure that they move by the same length.
+ debug_assert_eq!(mapped_page_size, page_size::<C>(src.0.level));
+ src.0.move_forward();
+ }
+ }
}
}
-
- /// Goes down a level assuming the current slot is absent.
- ///
- /// This method will create a new child page table node and go down to it.
- fn level_down_create(&mut self) {
- debug_assert!(self.0.level > 1);
- let new_node = PageTableNode::<E, C>::alloc(self.0.level - 1);
- let idx = self.0.cur_idx();
- let is_tracked = self.0.in_tracked_range();
- let old = self.cur_node_mut().replace_child(
- idx,
- Child::PageTable(new_node.clone_raw()),
- is_tracked,
- );
- debug_assert!(old.is_none());
- self.0.level -= 1;
- self.0.guards[(self.0.level - 1) as usize] = Some(new_node);
- }
-
- /// Goes down a level assuming the current slot is an untracked huge page.
- ///
- /// This method will split the huge page and go down to the next level.
- fn level_down_split(&mut self) {
- debug_assert!(self.0.level > 1);
- debug_assert!(!self.0.in_tracked_range());
-
- let idx = self.0.cur_idx();
- self.cur_node_mut().split_untracked_huge(idx);
-
- let Child::PageTable(new_node) = self.0.cur_child() else {
- unreachable!();
- };
- self.0.level -= 1;
- self.0.guards[(self.0.level - 1) as usize] = Some(new_node.lock());
- }
-
- fn cur_node_mut(&mut self) -> &mut PageTableNode<E, C> {
- self.0.guards[(self.0.level - 1) as usize].as_mut().unwrap()
- }
}
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -3,8 +3,8 @@
use core::{fmt::Debug, marker::PhantomData, ops::Range};
use super::{
- nr_subpage_per_huge, page_prop::PageProperty, page_size, Paddr, PagingConstsTrait, PagingLevel,
- Vaddr,
+ nr_subpage_per_huge, page::meta::MapTrackingStatus, page_prop::PageProperty, page_size, Paddr,
+ PagingConstsTrait, PagingLevel, Vaddr,
};
use crate::{
arch::mm::{PageTableEntry, PagingConsts},
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -3,8 +3,8 @@
use core::{fmt::Debug, marker::PhantomData, ops::Range};
use super::{
- nr_subpage_per_huge, page_prop::PageProperty, page_size, Paddr, PagingConstsTrait, PagingLevel,
- Vaddr,
+ nr_subpage_per_huge, page::meta::MapTrackingStatus, page_prop::PageProperty, page_size, Paddr,
+ PagingConstsTrait, PagingLevel, Vaddr,
};
use crate::{
arch::mm::{PageTableEntry, PagingConsts},
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -100,16 +100,17 @@ impl PageTable<KernelMode> {
/// This should be the only way to create the user page table, that is to
/// duplicate the kernel page table with all the kernel mappings shared.
pub fn create_user_page_table(&self) -> PageTable<UserMode> {
- let root_node = self.root.clone_shallow().lock();
- let mut new_node = PageTableNode::alloc(PagingConsts::NR_LEVELS);
+ let mut root_node = self.root.clone_shallow().lock();
+ let mut new_node =
+ PageTableNode::alloc(PagingConsts::NR_LEVELS, MapTrackingStatus::NotApplicable);
// Make a shallow copy of the root node in the kernel space range.
// The user space range is not copied.
const NR_PTES_PER_NODE: usize = nr_subpage_per_huge::<PagingConsts>();
for i in NR_PTES_PER_NODE / 2..NR_PTES_PER_NODE {
- let child = root_node.child(i, /* meaningless */ true);
- if !child.is_none() {
- let _ = new_node.replace_child(i, child, /* meaningless */ true);
+ let root_entry = root_node.entry(i);
+ if !root_entry.is_none() {
+ let _ = new_node.entry(i).replace(root_entry.to_owned());
}
}
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -100,16 +100,17 @@ impl PageTable<KernelMode> {
/// This should be the only way to create the user page table, that is to
/// duplicate the kernel page table with all the kernel mappings shared.
pub fn create_user_page_table(&self) -> PageTable<UserMode> {
- let root_node = self.root.clone_shallow().lock();
- let mut new_node = PageTableNode::alloc(PagingConsts::NR_LEVELS);
+ let mut root_node = self.root.clone_shallow().lock();
+ let mut new_node =
+ PageTableNode::alloc(PagingConsts::NR_LEVELS, MapTrackingStatus::NotApplicable);
// Make a shallow copy of the root node in the kernel space range.
// The user space range is not copied.
const NR_PTES_PER_NODE: usize = nr_subpage_per_huge::<PagingConsts>();
for i in NR_PTES_PER_NODE / 2..NR_PTES_PER_NODE {
- let child = root_node.child(i, /* meaningless */ true);
- if !child.is_none() {
- let _ = new_node.replace_child(i, child, /* meaningless */ true);
+ let root_entry = root_node.entry(i);
+ if !root_entry.is_none() {
+ let _ = new_node.entry(i).replace(root_entry.to_owned());
}
}
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -136,13 +137,18 @@ impl PageTable<KernelMode> {
let mut root_node = self.root.clone_shallow().lock();
for i in start..end {
- if !root_node.read_pte(i).is_present() {
- let node = PageTableNode::alloc(PagingConsts::NR_LEVELS - 1);
- let _ = root_node.replace_child(
- i,
- Child::PageTable(node.into_raw()),
- i < NR_PTES_PER_NODE * 3 / 4,
- );
+ let root_entry = root_node.entry(i);
+ if root_entry.is_none() {
+ let nxt_level = PagingConsts::NR_LEVELS - 1;
+ let is_tracked = if super::kspace::should_map_as_tracked(
+ i * page_size::<PagingConsts>(nxt_level),
+ ) {
+ MapTrackingStatus::Tracked
+ } else {
+ MapTrackingStatus::Untracked
+ };
+ let node = PageTableNode::alloc(nxt_level, is_tracked);
+ let _ = root_entry.replace(Child::PageTable(node.into_raw()));
}
}
}
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -136,13 +137,18 @@ impl PageTable<KernelMode> {
let mut root_node = self.root.clone_shallow().lock();
for i in start..end {
- if !root_node.read_pte(i).is_present() {
- let node = PageTableNode::alloc(PagingConsts::NR_LEVELS - 1);
- let _ = root_node.replace_child(
- i,
- Child::PageTable(node.into_raw()),
- i < NR_PTES_PER_NODE * 3 / 4,
- );
+ let root_entry = root_node.entry(i);
+ if root_entry.is_none() {
+ let nxt_level = PagingConsts::NR_LEVELS - 1;
+ let is_tracked = if super::kspace::should_map_as_tracked(
+ i * page_size::<PagingConsts>(nxt_level),
+ ) {
+ MapTrackingStatus::Tracked
+ } else {
+ MapTrackingStatus::Untracked
+ };
+ let node = PageTableNode::alloc(nxt_level, is_tracked);
+ let _ = root_entry.replace(Child::PageTable(node.into_raw()));
}
}
}
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -175,7 +181,8 @@ where
/// Create a new empty page table. Useful for the kernel page table and IOMMU page tables only.
pub fn empty() -> Self {
PageTable {
- root: PageTableNode::<E, C>::alloc(C::NR_LEVELS).into_raw(),
+ root: PageTableNode::<E, C>::alloc(C::NR_LEVELS, MapTrackingStatus::NotApplicable)
+ .into_raw(),
_phantom: PhantomData,
}
}
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -175,7 +181,8 @@ where
/// Create a new empty page table. Useful for the kernel page table and IOMMU page tables only.
pub fn empty() -> Self {
PageTable {
- root: PageTableNode::<E, C>::alloc(C::NR_LEVELS).into_raw(),
+ root: PageTableNode::<E, C>::alloc(C::NR_LEVELS, MapTrackingStatus::NotApplicable)
+ .into_raw(),
_phantom: PhantomData,
}
}
diff --git /dev/null b/ostd/src/mm/page_table/node/child.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/mm/page_table/node/child.rs
@@ -0,0 +1,172 @@
+// SPDX-License-Identifier: MPL-2.0
+
+//! This module specifies the type of the children of a page table node.
+
+use core::{mem::ManuallyDrop, panic};
+
+use super::{PageTableEntryTrait, RawPageTableNode};
+use crate::{
+ arch::mm::{PageTableEntry, PagingConsts},
+ mm::{
+ page::{inc_page_ref_count, meta::MapTrackingStatus, DynPage},
+ page_prop::PageProperty,
+ Paddr, PagingConstsTrait, PagingLevel,
+ },
+};
+
+/// A child of a page table node.
+///
+/// This is a owning handle to a child of a page table node. If the child is
+/// either a page table node or a page, it holds a reference count to the
+/// corresponding page.
+#[derive(Debug)]
+pub(in crate::mm) enum Child<
+ E: PageTableEntryTrait = PageTableEntry,
+ C: PagingConstsTrait = PagingConsts,
+> where
+ [(); C::NR_LEVELS as usize]:,
+{
+ PageTable(RawPageTableNode<E, C>),
+ Page(DynPage, PageProperty),
+ /// Pages not tracked by handles.
+ Untracked(Paddr, PagingLevel, PageProperty),
+ None,
+}
+
+impl<E: PageTableEntryTrait, C: PagingConstsTrait> Child<E, C>
+where
+ [(); C::NR_LEVELS as usize]:,
+{
+ /// Returns whether the child does not map to anything.
+ pub(in crate::mm) fn is_none(&self) -> bool {
+ matches!(self, Child::None)
+ }
+
+ /// Returns whether the child is compatible with the given node.
+ ///
+ /// In other words, it checks whether the child can be a child of a node
+ /// with the given level and tracking status.
+ pub(super) fn is_compatible(
+ &self,
+ node_level: PagingLevel,
+ is_tracked: MapTrackingStatus,
+ ) -> bool {
+ match self {
+ Child::PageTable(pt) => node_level == pt.level() + 1,
+ Child::Page(p, _) => {
+ node_level == p.level() && is_tracked == MapTrackingStatus::Tracked
+ }
+ Child::Untracked(_, level, _) => {
+ node_level == *level && is_tracked == MapTrackingStatus::Untracked
+ }
+ Child::None => true,
+ }
+ }
+
+ /// Converts a child into a owning PTE.
+ ///
+ /// By conversion it loses information about whether the page is tracked
+ /// or not. Also it loses the level information. However, the returned PTE
+ /// takes the ownership (reference count) of the child.
+ ///
+ /// Usually this is for recording the PTE into a page table node. When the
+ /// child is needed again by reading the PTE of a page table node, extra
+ /// information should be provided using the [`Child::from_pte`] method.
+ pub(super) fn into_pte(self) -> E {
+ match self {
+ Child::PageTable(pt) => {
+ let pt = ManuallyDrop::new(pt);
+ E::new_pt(pt.paddr())
+ }
+ Child::Page(page, prop) => {
+ let level = page.level();
+ E::new_page(page.into_raw(), level, prop)
+ }
+ Child::Untracked(pa, level, prop) => E::new_page(pa, level, prop),
+ Child::None => E::new_absent(),
+ }
+ }
+
+ /// Converts a PTE back to a child.
+ ///
+ /// # Safety
+ ///
+ /// The provided PTE must be originated from [`Child::into_pte`]. And the
+ /// provided information (level and tracking status) must be the same with
+ /// the lost information during the conversion. Strictly speaking, the
+ /// provided arguments must be compatible with the original child (
+ /// specified by [`Child::is_compatible`]).
+ ///
+ /// This method should be only used no more than once for a PTE that has
+ /// been converted from a child using the [`Child::into_pte`] method.
+ pub(super) unsafe fn from_pte(
+ pte: E,
+ level: PagingLevel,
+ is_tracked: MapTrackingStatus,
+ ) -> Self {
+ if !pte.is_present() {
+ return Child::None;
+ }
+
+ let paddr = pte.paddr();
+
+ if !pte.is_last(level) {
+ // SAFETY: The physical address points to a valid page table node
+ // at the given level.
+ return Child::PageTable(unsafe { RawPageTableNode::from_raw_parts(paddr, level - 1) });
+ }
+
+ match is_tracked {
+ MapTrackingStatus::Tracked => {
+ // SAFETY: The physical address points to a valid page.
+ let page = unsafe { DynPage::from_raw(paddr) };
+ Child::Page(page, pte.prop())
+ }
+ MapTrackingStatus::Untracked => Child::Untracked(paddr, level, pte.prop()),
+ MapTrackingStatus::NotApplicable => panic!("Invalid tracking status"),
+ }
+ }
+
+ /// Gains an extra owning reference to the child.
+ ///
+ /// # Safety
+ ///
+ /// The provided PTE must be originated from [`Child::into_pte`], which is
+ /// the same requirement as the [`Child::from_pte`] method.
+ ///
+ /// This method must not be used with a PTE that has been restored to a
+ /// child using the [`Child::from_pte`] method.
+ pub(super) unsafe fn clone_from_pte(
+ pte: &E,
+ level: PagingLevel,
+ is_tracked: MapTrackingStatus,
+ ) -> Self {
+ if !pte.is_present() {
+ return Child::None;
+ }
+
+ let paddr = pte.paddr();
+
+ if !pte.is_last(level) {
+ // SAFETY: The physical address is valid and the PTE already owns
+ // the reference to the page.
+ unsafe { inc_page_ref_count(paddr) };
+ // SAFETY: The physical address points to a valid page table node
+ // at the given level.
+ return Child::PageTable(unsafe { RawPageTableNode::from_raw_parts(paddr, level - 1) });
+ }
+
+ match is_tracked {
+ MapTrackingStatus::Tracked => {
+ // SAFETY: The physical address is valid and the PTE already owns
+ // the reference to the page.
+ unsafe { inc_page_ref_count(paddr) };
+ // SAFETY: The physical address points to a valid page.
+ let page = unsafe { DynPage::from_raw(paddr) };
+ Child::Page(page, pte.prop())
+ }
+ MapTrackingStatus::Untracked => Child::Untracked(paddr, level, pte.prop()),
+ MapTrackingStatus::NotApplicable => panic!("Invalid tracking status"),
+ }
+ }
+}
diff --git /dev/null b/ostd/src/mm/page_table/node/child.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/mm/page_table/node/child.rs
@@ -0,0 +1,172 @@
+// SPDX-License-Identifier: MPL-2.0
+
+//! This module specifies the type of the children of a page table node.
+
+use core::{mem::ManuallyDrop, panic};
+
+use super::{PageTableEntryTrait, RawPageTableNode};
+use crate::{
+ arch::mm::{PageTableEntry, PagingConsts},
+ mm::{
+ page::{inc_page_ref_count, meta::MapTrackingStatus, DynPage},
+ page_prop::PageProperty,
+ Paddr, PagingConstsTrait, PagingLevel,
+ },
+};
+
+/// A child of a page table node.
+///
+/// This is a owning handle to a child of a page table node. If the child is
+/// either a page table node or a page, it holds a reference count to the
+/// corresponding page.
+#[derive(Debug)]
+pub(in crate::mm) enum Child<
+ E: PageTableEntryTrait = PageTableEntry,
+ C: PagingConstsTrait = PagingConsts,
+> where
+ [(); C::NR_LEVELS as usize]:,
+{
+ PageTable(RawPageTableNode<E, C>),
+ Page(DynPage, PageProperty),
+ /// Pages not tracked by handles.
+ Untracked(Paddr, PagingLevel, PageProperty),
+ None,
+}
+
+impl<E: PageTableEntryTrait, C: PagingConstsTrait> Child<E, C>
+where
+ [(); C::NR_LEVELS as usize]:,
+{
+ /// Returns whether the child does not map to anything.
+ pub(in crate::mm) fn is_none(&self) -> bool {
+ matches!(self, Child::None)
+ }
+
+ /// Returns whether the child is compatible with the given node.
+ ///
+ /// In other words, it checks whether the child can be a child of a node
+ /// with the given level and tracking status.
+ pub(super) fn is_compatible(
+ &self,
+ node_level: PagingLevel,
+ is_tracked: MapTrackingStatus,
+ ) -> bool {
+ match self {
+ Child::PageTable(pt) => node_level == pt.level() + 1,
+ Child::Page(p, _) => {
+ node_level == p.level() && is_tracked == MapTrackingStatus::Tracked
+ }
+ Child::Untracked(_, level, _) => {
+ node_level == *level && is_tracked == MapTrackingStatus::Untracked
+ }
+ Child::None => true,
+ }
+ }
+
+ /// Converts a child into a owning PTE.
+ ///
+ /// By conversion it loses information about whether the page is tracked
+ /// or not. Also it loses the level information. However, the returned PTE
+ /// takes the ownership (reference count) of the child.
+ ///
+ /// Usually this is for recording the PTE into a page table node. When the
+ /// child is needed again by reading the PTE of a page table node, extra
+ /// information should be provided using the [`Child::from_pte`] method.
+ pub(super) fn into_pte(self) -> E {
+ match self {
+ Child::PageTable(pt) => {
+ let pt = ManuallyDrop::new(pt);
+ E::new_pt(pt.paddr())
+ }
+ Child::Page(page, prop) => {
+ let level = page.level();
+ E::new_page(page.into_raw(), level, prop)
+ }
+ Child::Untracked(pa, level, prop) => E::new_page(pa, level, prop),
+ Child::None => E::new_absent(),
+ }
+ }
+
+ /// Converts a PTE back to a child.
+ ///
+ /// # Safety
+ ///
+ /// The provided PTE must be originated from [`Child::into_pte`]. And the
+ /// provided information (level and tracking status) must be the same with
+ /// the lost information during the conversion. Strictly speaking, the
+ /// provided arguments must be compatible with the original child (
+ /// specified by [`Child::is_compatible`]).
+ ///
+ /// This method should be only used no more than once for a PTE that has
+ /// been converted from a child using the [`Child::into_pte`] method.
+ pub(super) unsafe fn from_pte(
+ pte: E,
+ level: PagingLevel,
+ is_tracked: MapTrackingStatus,
+ ) -> Self {
+ if !pte.is_present() {
+ return Child::None;
+ }
+
+ let paddr = pte.paddr();
+
+ if !pte.is_last(level) {
+ // SAFETY: The physical address points to a valid page table node
+ // at the given level.
+ return Child::PageTable(unsafe { RawPageTableNode::from_raw_parts(paddr, level - 1) });
+ }
+
+ match is_tracked {
+ MapTrackingStatus::Tracked => {
+ // SAFETY: The physical address points to a valid page.
+ let page = unsafe { DynPage::from_raw(paddr) };
+ Child::Page(page, pte.prop())
+ }
+ MapTrackingStatus::Untracked => Child::Untracked(paddr, level, pte.prop()),
+ MapTrackingStatus::NotApplicable => panic!("Invalid tracking status"),
+ }
+ }
+
+ /// Gains an extra owning reference to the child.
+ ///
+ /// # Safety
+ ///
+ /// The provided PTE must be originated from [`Child::into_pte`], which is
+ /// the same requirement as the [`Child::from_pte`] method.
+ ///
+ /// This method must not be used with a PTE that has been restored to a
+ /// child using the [`Child::from_pte`] method.
+ pub(super) unsafe fn clone_from_pte(
+ pte: &E,
+ level: PagingLevel,
+ is_tracked: MapTrackingStatus,
+ ) -> Self {
+ if !pte.is_present() {
+ return Child::None;
+ }
+
+ let paddr = pte.paddr();
+
+ if !pte.is_last(level) {
+ // SAFETY: The physical address is valid and the PTE already owns
+ // the reference to the page.
+ unsafe { inc_page_ref_count(paddr) };
+ // SAFETY: The physical address points to a valid page table node
+ // at the given level.
+ return Child::PageTable(unsafe { RawPageTableNode::from_raw_parts(paddr, level - 1) });
+ }
+
+ match is_tracked {
+ MapTrackingStatus::Tracked => {
+ // SAFETY: The physical address is valid and the PTE already owns
+ // the reference to the page.
+ unsafe { inc_page_ref_count(paddr) };
+ // SAFETY: The physical address points to a valid page.
+ let page = unsafe { DynPage::from_raw(paddr) };
+ Child::Page(page, pte.prop())
+ }
+ MapTrackingStatus::Untracked => Child::Untracked(paddr, level, pte.prop()),
+ MapTrackingStatus::NotApplicable => panic!("Invalid tracking status"),
+ }
+ }
+}
diff --git /dev/null b/ostd/src/mm/page_table/node/entry.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/mm/page_table/node/entry.rs
@@ -0,0 +1,161 @@
+// SPDX-License-Identifier: MPL-2.0
+
+//! This module provides accessors to the page table entries in a node.
+
+use super::{Child, PageTableEntryTrait, PageTableNode};
+use crate::mm::{
+ nr_subpage_per_huge, page::meta::MapTrackingStatus, page_prop::PageProperty, page_size,
+ PagingConstsTrait,
+};
+
+/// A view of an entry in a page table node.
+///
+/// It can be borrowed from a node using the [`PageTableNode::entry`] method.
+///
+/// This is a static reference to an entry in a node that does not account for
+/// a dynamic reference count to the child. It can be used to create a owned
+/// handle, which is a [`Child`].
+pub(in crate::mm) struct Entry<'a, E: PageTableEntryTrait, C: PagingConstsTrait>
+where
+ [(); C::NR_LEVELS as usize]:,
+{
+ /// The page table entry.
+ ///
+ /// We store the page table entry here to optimize the number of reads from
+ /// the node. We cannot hold a `&mut E` reference to the entry because that
+ /// other CPUs may modify the memory location for accessed/dirty bits. Such
+ /// accesses will violate the aliasing rules of Rust and cause undefined
+ /// behaviors.
+ pte: E,
+ /// The index of the entry in the node.
+ idx: usize,
+ /// The node that contains the entry.
+ node: &'a mut PageTableNode<E, C>,
+}
+
+impl<'a, E: PageTableEntryTrait, C: PagingConstsTrait> Entry<'a, E, C>
+where
+ [(); C::NR_LEVELS as usize]:,
+{
+ /// Returns if the entry does not map to anything.
+ pub(in crate::mm) fn is_none(&self) -> bool {
+ !self.pte.is_present()
+ }
+
+ /// Returns if the entry maps to a page table node.
+ pub(in crate::mm) fn is_node(&self) -> bool {
+ self.pte.is_present() && !self.pte.is_last(self.node.level())
+ }
+
+ /// Gets a owned handle to the child.
+ pub(in crate::mm) fn to_owned(&self) -> Child<E, C> {
+ // SAFETY: The entry structure represents an existent entry with the
+ // right node information.
+ unsafe { Child::clone_from_pte(&self.pte, self.node.level(), self.node.is_tracked()) }
+ }
+
+ /// Operates on the mapping properties of the entry.
+ ///
+ /// It only modifies the properties if the entry is present.
+ // FIXME: in x86_64, you can protect a page with neither of the RWX
+ // permissions. This would make the page not accessible and leaked. Such a
+ // behavior is memory-safe but wrong. In RISC-V there's no problem.
+ pub(in crate::mm) fn protect(&mut self, op: &mut impl FnMut(&mut PageProperty)) {
+ if !self.pte.is_present() {
+ return;
+ }
+
+ let prop = self.pte.prop();
+ let mut new_prop = prop;
+ op(&mut new_prop);
+
+ if prop == new_prop {
+ return;
+ }
+
+ self.pte.set_prop(new_prop);
+
+ // SAFETY:
+ // 1. The index is within the bounds.
+ // 2. We replace the PTE with a new one, which differs only in
+ // `PageProperty`, so it is still compatible with the current
+ // page table node.
+ unsafe { self.node.write_pte(self.idx, self.pte) };
+ }
+
+ /// Replaces the entry with a new child.
+ ///
+ /// The old child is returned.
+ ///
+ /// # Panics
+ ///
+ /// The method panics if the given child is not compatible with the node.
+ /// The compatibility is specified by the [`Child::is_compatible`].
+ pub(in crate::mm) fn replace(self, new_child: Child<E, C>) -> Child<E, C> {
+ assert!(new_child.is_compatible(self.node.level(), self.node.is_tracked()));
+
+ // SAFETY: The entry structure represents an existent entry with the
+ // right node information. The old PTE is overwritten by the new child
+ // so that it is not used anymore.
+ let old_child =
+ unsafe { Child::from_pte(self.pte, self.node.level(), self.node.is_tracked()) };
+
+ if old_child.is_none() && !new_child.is_none() {
+ *self.node.nr_children_mut() += 1;
+ } else if !old_child.is_none() && new_child.is_none() {
+ *self.node.nr_children_mut() -= 1;
+ }
+
+ // SAFETY:
+ // 1. The index is within the bounds.
+ // 2. The new PTE is compatible with the page table node, as asserted above.
+ unsafe { self.node.write_pte(self.idx, new_child.into_pte()) };
+
+ old_child
+ }
+
+ /// Splits the entry to smaller pages if it maps to a untracked huge page.
+ ///
+ /// If the entry does map to a untracked huge page, it is split into smaller
+ /// pages mapped by a child page table node. The new child page table node
+ /// is returned.
+ ///
+ /// If the entry does not map to a untracked huge page, the method returns
+ /// `None`.
+ pub(in crate::mm) fn split_if_untracked_huge(self) -> Option<PageTableNode<E, C>> {
+ let level = self.node.level();
+
+ if !(self.pte.is_last(level)
+ && level > 1
+ && self.node.is_tracked() == MapTrackingStatus::Untracked)
+ {
+ return None;
+ }
+
+ let pa = self.pte.paddr();
+ let prop = self.pte.prop();
+
+ let mut new_page = PageTableNode::<E, C>::alloc(level - 1, MapTrackingStatus::Untracked);
+ for i in 0..nr_subpage_per_huge::<C>() {
+ let small_pa = pa + i * page_size::<C>(level - 1);
+ let _ = new_page
+ .entry(i)
+ .replace(Child::Untracked(small_pa, level - 1, prop));
+ }
+
+ let _ = self.replace(Child::PageTable(new_page.clone_raw()));
+
+ Some(new_page)
+ }
+
+ /// Create a new entry at the node.
+ ///
+ /// # Safety
+ ///
+ /// The caller must ensure that the index is within the bounds of the node.
+ pub(super) unsafe fn new_at(node: &'a mut PageTableNode<E, C>, idx: usize) -> Self {
+ // SAFETY: The index is within the bound.
+ let pte = unsafe { node.read_pte(idx) };
+ Self { pte, idx, node }
+ }
+}
diff --git /dev/null b/ostd/src/mm/page_table/node/entry.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/mm/page_table/node/entry.rs
@@ -0,0 +1,161 @@
+// SPDX-License-Identifier: MPL-2.0
+
+//! This module provides accessors to the page table entries in a node.
+
+use super::{Child, PageTableEntryTrait, PageTableNode};
+use crate::mm::{
+ nr_subpage_per_huge, page::meta::MapTrackingStatus, page_prop::PageProperty, page_size,
+ PagingConstsTrait,
+};
+
+/// A view of an entry in a page table node.
+///
+/// It can be borrowed from a node using the [`PageTableNode::entry`] method.
+///
+/// This is a static reference to an entry in a node that does not account for
+/// a dynamic reference count to the child. It can be used to create a owned
+/// handle, which is a [`Child`].
+pub(in crate::mm) struct Entry<'a, E: PageTableEntryTrait, C: PagingConstsTrait>
+where
+ [(); C::NR_LEVELS as usize]:,
+{
+ /// The page table entry.
+ ///
+ /// We store the page table entry here to optimize the number of reads from
+ /// the node. We cannot hold a `&mut E` reference to the entry because that
+ /// other CPUs may modify the memory location for accessed/dirty bits. Such
+ /// accesses will violate the aliasing rules of Rust and cause undefined
+ /// behaviors.
+ pte: E,
+ /// The index of the entry in the node.
+ idx: usize,
+ /// The node that contains the entry.
+ node: &'a mut PageTableNode<E, C>,
+}
+
+impl<'a, E: PageTableEntryTrait, C: PagingConstsTrait> Entry<'a, E, C>
+where
+ [(); C::NR_LEVELS as usize]:,
+{
+ /// Returns if the entry does not map to anything.
+ pub(in crate::mm) fn is_none(&self) -> bool {
+ !self.pte.is_present()
+ }
+
+ /// Returns if the entry maps to a page table node.
+ pub(in crate::mm) fn is_node(&self) -> bool {
+ self.pte.is_present() && !self.pte.is_last(self.node.level())
+ }
+
+ /// Gets a owned handle to the child.
+ pub(in crate::mm) fn to_owned(&self) -> Child<E, C> {
+ // SAFETY: The entry structure represents an existent entry with the
+ // right node information.
+ unsafe { Child::clone_from_pte(&self.pte, self.node.level(), self.node.is_tracked()) }
+ }
+
+ /// Operates on the mapping properties of the entry.
+ ///
+ /// It only modifies the properties if the entry is present.
+ // FIXME: in x86_64, you can protect a page with neither of the RWX
+ // permissions. This would make the page not accessible and leaked. Such a
+ // behavior is memory-safe but wrong. In RISC-V there's no problem.
+ pub(in crate::mm) fn protect(&mut self, op: &mut impl FnMut(&mut PageProperty)) {
+ if !self.pte.is_present() {
+ return;
+ }
+
+ let prop = self.pte.prop();
+ let mut new_prop = prop;
+ op(&mut new_prop);
+
+ if prop == new_prop {
+ return;
+ }
+
+ self.pte.set_prop(new_prop);
+
+ // SAFETY:
+ // 1. The index is within the bounds.
+ // 2. We replace the PTE with a new one, which differs only in
+ // `PageProperty`, so it is still compatible with the current
+ // page table node.
+ unsafe { self.node.write_pte(self.idx, self.pte) };
+ }
+
+ /// Replaces the entry with a new child.
+ ///
+ /// The old child is returned.
+ ///
+ /// # Panics
+ ///
+ /// The method panics if the given child is not compatible with the node.
+ /// The compatibility is specified by the [`Child::is_compatible`].
+ pub(in crate::mm) fn replace(self, new_child: Child<E, C>) -> Child<E, C> {
+ assert!(new_child.is_compatible(self.node.level(), self.node.is_tracked()));
+
+ // SAFETY: The entry structure represents an existent entry with the
+ // right node information. The old PTE is overwritten by the new child
+ // so that it is not used anymore.
+ let old_child =
+ unsafe { Child::from_pte(self.pte, self.node.level(), self.node.is_tracked()) };
+
+ if old_child.is_none() && !new_child.is_none() {
+ *self.node.nr_children_mut() += 1;
+ } else if !old_child.is_none() && new_child.is_none() {
+ *self.node.nr_children_mut() -= 1;
+ }
+
+ // SAFETY:
+ // 1. The index is within the bounds.
+ // 2. The new PTE is compatible with the page table node, as asserted above.
+ unsafe { self.node.write_pte(self.idx, new_child.into_pte()) };
+
+ old_child
+ }
+
+ /// Splits the entry to smaller pages if it maps to a untracked huge page.
+ ///
+ /// If the entry does map to a untracked huge page, it is split into smaller
+ /// pages mapped by a child page table node. The new child page table node
+ /// is returned.
+ ///
+ /// If the entry does not map to a untracked huge page, the method returns
+ /// `None`.
+ pub(in crate::mm) fn split_if_untracked_huge(self) -> Option<PageTableNode<E, C>> {
+ let level = self.node.level();
+
+ if !(self.pte.is_last(level)
+ && level > 1
+ && self.node.is_tracked() == MapTrackingStatus::Untracked)
+ {
+ return None;
+ }
+
+ let pa = self.pte.paddr();
+ let prop = self.pte.prop();
+
+ let mut new_page = PageTableNode::<E, C>::alloc(level - 1, MapTrackingStatus::Untracked);
+ for i in 0..nr_subpage_per_huge::<C>() {
+ let small_pa = pa + i * page_size::<C>(level - 1);
+ let _ = new_page
+ .entry(i)
+ .replace(Child::Untracked(small_pa, level - 1, prop));
+ }
+
+ let _ = self.replace(Child::PageTable(new_page.clone_raw()));
+
+ Some(new_page)
+ }
+
+ /// Create a new entry at the node.
+ ///
+ /// # Safety
+ ///
+ /// The caller must ensure that the index is within the bounds of the node.
+ pub(super) unsafe fn new_at(node: &'a mut PageTableNode<E, C>, idx: usize) -> Self {
+ // SAFETY: The index is within the bound.
+ let pte = unsafe { node.read_pte(idx) };
+ Self { pte, idx, node }
+ }
+}
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node/mod.rs
@@ -25,19 +25,22 @@
//! the initialization of the entity that the PTE points to. This is taken care in this module.
//!
-use core::{fmt, marker::PhantomData, mem::ManuallyDrop, panic, sync::atomic::Ordering};
+mod child;
+mod entry;
-use super::{nr_subpage_per_huge, page_size, PageTableEntryTrait};
+use core::{marker::PhantomData, mem::ManuallyDrop, sync::atomic::Ordering};
+
+pub(in crate::mm) use self::{child::Child, entry::Entry};
+use super::{nr_subpage_per_huge, PageTableEntryTrait};
use crate::{
arch::mm::{PageTableEntry, PagingConsts},
mm::{
paddr_to_vaddr,
page::{
- self,
- meta::{PageMeta, PageTablePageMeta, PageUsage},
+ self, inc_page_ref_count,
+ meta::{MapTrackingStatus, PageMeta, PageTablePageMeta, PageUsage},
DynPage, Page,
},
- page_prop::PageProperty,
Paddr, PagingConstsTrait, PagingLevel, PAGE_SIZE,
},
};
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node/mod.rs
@@ -25,19 +25,22 @@
//! the initialization of the entity that the PTE points to. This is taken care in this module.
//!
-use core::{fmt, marker::PhantomData, mem::ManuallyDrop, panic, sync::atomic::Ordering};
+mod child;
+mod entry;
-use super::{nr_subpage_per_huge, page_size, PageTableEntryTrait};
+use core::{marker::PhantomData, mem::ManuallyDrop, sync::atomic::Ordering};
+
+pub(in crate::mm) use self::{child::Child, entry::Entry};
+use super::{nr_subpage_per_huge, PageTableEntryTrait};
use crate::{
arch::mm::{PageTableEntry, PagingConsts},
mm::{
paddr_to_vaddr,
page::{
- self,
- meta::{PageMeta, PageTablePageMeta, PageUsage},
+ self, inc_page_ref_count,
+ meta::{MapTrackingStatus, PageMeta, PageTablePageMeta, PageUsage},
DynPage, Page,
},
- page_prop::PageProperty,
Paddr, PagingConstsTrait, PagingLevel, PAGE_SIZE,
},
};
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node/mod.rs
@@ -55,7 +58,8 @@ pub(super) struct RawPageTableNode<E: PageTableEntryTrait, C: PagingConstsTrait>
where
[(); C::NR_LEVELS as usize]:,
{
- pub(super) raw: Paddr,
+ raw: Paddr,
+ level: PagingLevel,
_phantom: PhantomData<(E, C)>,
}
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node/mod.rs
@@ -55,7 +58,8 @@ pub(super) struct RawPageTableNode<E: PageTableEntryTrait, C: PagingConstsTrait>
where
[(); C::NR_LEVELS as usize]:,
{
- pub(super) raw: Paddr,
+ raw: Paddr,
+ level: PagingLevel,
_phantom: PhantomData<(E, C)>,
}
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node/mod.rs
@@ -67,15 +71,14 @@ where
self.raw
}
+ pub(super) fn level(&self) -> PagingLevel {
+ self.level
+ }
+
/// Converts a raw handle to an accessible handle by pertaining the lock.
pub(super) fn lock(self) -> PageTableNode<E, C> {
- // Prevent dropping the handle.
- let this = ManuallyDrop::new(self);
-
- // SAFETY: The physical address in the raw handle is valid and we are
- // transferring the ownership to a new handle. No increment of the reference
- // count is needed.
- let page = unsafe { Page::<PageTablePageMeta<E, C>>::from_raw(this.paddr()) };
+ let level = self.level;
+ let page: Page<PageTablePageMeta<E, C>> = self.into();
// Acquire the lock.
while page
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node/mod.rs
@@ -67,15 +71,14 @@ where
self.raw
}
+ pub(super) fn level(&self) -> PagingLevel {
+ self.level
+ }
+
/// Converts a raw handle to an accessible handle by pertaining the lock.
pub(super) fn lock(self) -> PageTableNode<E, C> {
- // Prevent dropping the handle.
- let this = ManuallyDrop::new(self);
-
- // SAFETY: The physical address in the raw handle is valid and we are
- // transferring the ownership to a new handle. No increment of the reference
- // count is needed.
- let page = unsafe { Page::<PageTablePageMeta<E, C>>::from_raw(this.paddr()) };
+ let level = self.level;
+ let page: Page<PageTablePageMeta<E, C>> = self.into();
// Acquire the lock.
while page
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node/mod.rs
@@ -87,7 +90,9 @@ where
core::hint::spin_loop();
}
- PageTableNode::<E, C> { page, _private: () }
+ debug_assert_eq!(page.meta().level, level);
+
+ PageTableNode::<E, C> { page }
}
/// Creates a copy of the handle.
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node/mod.rs
@@ -87,7 +90,9 @@ where
core::hint::spin_loop();
}
- PageTableNode::<E, C> { page, _private: () }
+ debug_assert_eq!(page.meta().level, level);
+
+ PageTableNode::<E, C> { page }
}
/// Creates a copy of the handle.
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node/mod.rs
@@ -96,6 +101,7 @@ where
Self {
raw: self.raw,
+ level: self.level,
_phantom: PhantomData,
}
}
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node/mod.rs
@@ -96,6 +101,7 @@ where
Self {
raw: self.raw,
+ level: self.level,
_phantom: PhantomData,
}
}
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node/mod.rs
@@ -112,12 +118,18 @@ where
/// The caller must ensure that the page table to be activated has
/// proper mappings for the kernel and has the correct const parameters
/// matching the current CPU.
+ ///
+ /// # Panics
+ ///
+ /// Only top-level page tables can be activated using this function.
pub(crate) unsafe fn activate(&self) {
use crate::{
arch::mm::{activate_page_table, current_page_table_paddr},
mm::CachePolicy,
};
+ assert_eq!(self.level, C::NR_LEVELS);
+
let last_activated_paddr = current_page_table_paddr();
if last_activated_paddr == self.raw {
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node/mod.rs
@@ -112,12 +118,18 @@ where
/// The caller must ensure that the page table to be activated has
/// proper mappings for the kernel and has the correct const parameters
/// matching the current CPU.
+ ///
+ /// # Panics
+ ///
+ /// Only top-level page tables can be activated using this function.
pub(crate) unsafe fn activate(&self) {
use crate::{
arch::mm::{activate_page_table, current_page_table_paddr},
mm::CachePolicy,
};
+ assert_eq!(self.level, C::NR_LEVELS);
+
let last_activated_paddr = current_page_table_paddr();
if last_activated_paddr == self.raw {
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node/mod.rs
@@ -132,6 +144,7 @@ where
// Restore and drop the last activated page table.
drop(Self {
raw: last_activated_paddr,
+ level: C::NR_LEVELS,
_phantom: PhantomData,
});
}
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node/mod.rs
@@ -132,6 +144,7 @@ where
// Restore and drop the last activated page table.
drop(Self {
raw: last_activated_paddr,
+ level: C::NR_LEVELS,
_phantom: PhantomData,
});
}
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node/mod.rs
@@ -152,11 +165,40 @@ where
// SAFETY: We have a reference count to the page and can safely increase the reference
// count by one more.
unsafe {
- Page::<PageTablePageMeta<E, C>>::inc_ref_count(self.paddr());
+ inc_page_ref_count(self.paddr());
+ }
+ }
+
+ /// Restores the handle from the physical address and level.
+ ///
+ /// # Safety
+ ///
+ /// The caller must ensure that the physical address is valid and points to
+ /// a forgotten page table node. A forgotten page table node can only be
+ /// restored once. The level must match the level of the page table node.
+ unsafe fn from_raw_parts(paddr: Paddr, level: PagingLevel) -> Self {
+ Self {
+ raw: paddr,
+ level,
+ _phantom: PhantomData,
}
}
}
+impl<E: PageTableEntryTrait, C: PagingConstsTrait> From<RawPageTableNode<E, C>>
+ for Page<PageTablePageMeta<E, C>>
+where
+ [(); C::NR_LEVELS as usize]:,
+{
+ fn from(raw: RawPageTableNode<E, C>) -> Self {
+ let raw = ManuallyDrop::new(raw);
+ // SAFETY: The physical address in the raw handle is valid and we are
+ // transferring the ownership to a new handle. No increment of the reference
+ // count is needed.
+ unsafe { Page::<PageTablePageMeta<E, C>>::from_raw(raw.paddr()) }
+ }
+}
+
impl<E: PageTableEntryTrait, C: PagingConstsTrait> Drop for RawPageTableNode<E, C>
where
[(); C::NR_LEVELS as usize]:,
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node/mod.rs
@@ -152,11 +165,40 @@ where
// SAFETY: We have a reference count to the page and can safely increase the reference
// count by one more.
unsafe {
- Page::<PageTablePageMeta<E, C>>::inc_ref_count(self.paddr());
+ inc_page_ref_count(self.paddr());
+ }
+ }
+
+ /// Restores the handle from the physical address and level.
+ ///
+ /// # Safety
+ ///
+ /// The caller must ensure that the physical address is valid and points to
+ /// a forgotten page table node. A forgotten page table node can only be
+ /// restored once. The level must match the level of the page table node.
+ unsafe fn from_raw_parts(paddr: Paddr, level: PagingLevel) -> Self {
+ Self {
+ raw: paddr,
+ level,
+ _phantom: PhantomData,
}
}
}
+impl<E: PageTableEntryTrait, C: PagingConstsTrait> From<RawPageTableNode<E, C>>
+ for Page<PageTablePageMeta<E, C>>
+where
+ [(); C::NR_LEVELS as usize]:,
+{
+ fn from(raw: RawPageTableNode<E, C>) -> Self {
+ let raw = ManuallyDrop::new(raw);
+ // SAFETY: The physical address in the raw handle is valid and we are
+ // transferring the ownership to a new handle. No increment of the reference
+ // count is needed.
+ unsafe { Page::<PageTablePageMeta<E, C>>::from_raw(raw.paddr()) }
+ }
+}
+
impl<E: PageTableEntryTrait, C: PagingConstsTrait> Drop for RawPageTableNode<E, C>
where
[(); C::NR_LEVELS as usize]:,
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node/mod.rs
@@ -175,64 +217,49 @@ where
/// of the page table. Dropping the page table node will also drop all handles if the page
/// table node has no references. You can set the page table node as a child of another
/// page table node.
+#[derive(Debug)]
pub(super) struct PageTableNode<
E: PageTableEntryTrait = PageTableEntry,
C: PagingConstsTrait = PagingConsts,
> where
[(); C::NR_LEVELS as usize]:,
{
- pub(super) page: Page<PageTablePageMeta<E, C>>,
- _private: (),
+ page: Page<PageTablePageMeta<E, C>>,
}
-// FIXME: We cannot `#[derive(Debug)]` here due to `DisabledPreemptGuard`. Should we skip
-// this field or implement the `Debug` trait also for `DisabledPreemptGuard`?
-impl<E, C> fmt::Debug for PageTableNode<E, C>
+impl<E: PageTableEntryTrait, C: PagingConstsTrait> PageTableNode<E, C>
where
- E: PageTableEntryTrait,
- C: PagingConstsTrait,
[(); C::NR_LEVELS as usize]:,
{
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("PageTableEntryTrait")
- .field("page", &self.page)
- .finish()
+ /// Borrows an entry in the node at a given index.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the index is not within the bound of
+ /// [`nr_subpage_per_huge<C>`].
+ pub(super) fn entry(&mut self, idx: usize) -> Entry<'_, E, C> {
+ assert!(idx < nr_subpage_per_huge::<C>());
+ // SAFETY: The index is within the bound.
+ unsafe { Entry::new_at(self, idx) }
}
-}
-/// A child of a page table node.
-#[derive(Debug)]
-pub(super) enum Child<E: PageTableEntryTrait = PageTableEntry, C: PagingConstsTrait = PagingConsts>
-where
- [(); C::NR_LEVELS as usize]:,
-{
- PageTable(RawPageTableNode<E, C>),
- Page(DynPage, PageProperty),
- /// Pages not tracked by handles.
- Untracked(Paddr, PageProperty),
- None,
-}
+ /// Gets the level of the page table node.
+ pub(super) fn level(&self) -> PagingLevel {
+ self.page.meta().level
+ }
-impl<E: PageTableEntryTrait, C: PagingConstsTrait> Child<E, C>
-where
- [(); C::NR_LEVELS as usize]:,
-{
- pub(super) fn is_none(&self) -> bool {
- matches!(self, Child::None)
+ /// Gets the tracking status of the page table node.
+ pub(super) fn is_tracked(&self) -> MapTrackingStatus {
+ self.page.meta().is_tracked
}
-}
-impl<E: PageTableEntryTrait, C: PagingConstsTrait> PageTableNode<E, C>
-where
- [(); C::NR_LEVELS as usize]:,
-{
/// Allocates a new empty page table node.
///
/// This function returns an owning handle. The newly created handle does not
/// set the lock bit for performance as it is exclusive and unlocking is an
/// extra unnecessary expensive operation.
- pub(super) fn alloc(level: PagingLevel) -> Self {
- let meta = PageTablePageMeta::new_locked(level);
+ pub(super) fn alloc(level: PagingLevel, is_tracked: MapTrackingStatus) -> Self {
+ let meta = PageTablePageMeta::new_locked(level, is_tracked);
let page = page::allocator::alloc_single::<PageTablePageMeta<E, C>>(meta).unwrap();
// Zero out the page table node.
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node/mod.rs
@@ -175,64 +217,49 @@ where
/// of the page table. Dropping the page table node will also drop all handles if the page
/// table node has no references. You can set the page table node as a child of another
/// page table node.
+#[derive(Debug)]
pub(super) struct PageTableNode<
E: PageTableEntryTrait = PageTableEntry,
C: PagingConstsTrait = PagingConsts,
> where
[(); C::NR_LEVELS as usize]:,
{
- pub(super) page: Page<PageTablePageMeta<E, C>>,
- _private: (),
+ page: Page<PageTablePageMeta<E, C>>,
}
-// FIXME: We cannot `#[derive(Debug)]` here due to `DisabledPreemptGuard`. Should we skip
-// this field or implement the `Debug` trait also for `DisabledPreemptGuard`?
-impl<E, C> fmt::Debug for PageTableNode<E, C>
+impl<E: PageTableEntryTrait, C: PagingConstsTrait> PageTableNode<E, C>
where
- E: PageTableEntryTrait,
- C: PagingConstsTrait,
[(); C::NR_LEVELS as usize]:,
{
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("PageTableEntryTrait")
- .field("page", &self.page)
- .finish()
+ /// Borrows an entry in the node at a given index.
+ ///
+ /// # Panics
+ ///
+ /// Panics if the index is not within the bound of
+ /// [`nr_subpage_per_huge<C>`].
+ pub(super) fn entry(&mut self, idx: usize) -> Entry<'_, E, C> {
+ assert!(idx < nr_subpage_per_huge::<C>());
+ // SAFETY: The index is within the bound.
+ unsafe { Entry::new_at(self, idx) }
}
-}
-/// A child of a page table node.
-#[derive(Debug)]
-pub(super) enum Child<E: PageTableEntryTrait = PageTableEntry, C: PagingConstsTrait = PagingConsts>
-where
- [(); C::NR_LEVELS as usize]:,
-{
- PageTable(RawPageTableNode<E, C>),
- Page(DynPage, PageProperty),
- /// Pages not tracked by handles.
- Untracked(Paddr, PageProperty),
- None,
-}
+ /// Gets the level of the page table node.
+ pub(super) fn level(&self) -> PagingLevel {
+ self.page.meta().level
+ }
-impl<E: PageTableEntryTrait, C: PagingConstsTrait> Child<E, C>
-where
- [(); C::NR_LEVELS as usize]:,
-{
- pub(super) fn is_none(&self) -> bool {
- matches!(self, Child::None)
+ /// Gets the tracking status of the page table node.
+ pub(super) fn is_tracked(&self) -> MapTrackingStatus {
+ self.page.meta().is_tracked
}
-}
-impl<E: PageTableEntryTrait, C: PagingConstsTrait> PageTableNode<E, C>
-where
- [(); C::NR_LEVELS as usize]:,
-{
/// Allocates a new empty page table node.
///
/// This function returns an owning handle. The newly created handle does not
/// set the lock bit for performance as it is exclusive and unlocking is an
/// extra unnecessary expensive operation.
- pub(super) fn alloc(level: PagingLevel) -> Self {
- let meta = PageTablePageMeta::new_locked(level);
+ pub(super) fn alloc(level: PagingLevel, is_tracked: MapTrackingStatus) -> Self {
+ let meta = PageTablePageMeta::new_locked(level, is_tracked);
let page = page::allocator::alloc_single::<PageTablePageMeta<E, C>>(meta).unwrap();
// Zero out the page table node.
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node/mod.rs
@@ -242,209 +269,76 @@ where
unsafe { core::ptr::write_bytes(ptr, 0, PAGE_SIZE) };
debug_assert!(E::new_absent().as_bytes().iter().all(|&b| b == 0));
- Self { page, _private: () }
- }
-
- pub fn level(&self) -> PagingLevel {
- self.meta().level
+ Self { page }
}
/// Converts the handle into a raw handle to be stored in a PTE or CPU.
pub(super) fn into_raw(self) -> RawPageTableNode<E, C> {
let this = ManuallyDrop::new(self);
- let raw = this.page.paddr();
-
+ // Release the lock.
this.page.meta().lock.store(0, Ordering::Release);
- RawPageTableNode {
- raw,
- _phantom: PhantomData,
- }
+ // SAFETY: The provided physical address is valid and the level is
+ // correct. The reference count is not changed.
+ unsafe { RawPageTableNode::from_raw_parts(this.page.paddr(), this.page.meta().level) }
}
/// Gets a raw handle while still preserving the original handle.
pub(super) fn clone_raw(&self) -> RawPageTableNode<E, C> {
- core::mem::forget(self.page.clone());
+ let page = ManuallyDrop::new(self.page.clone());
- RawPageTableNode {
- raw: self.page.paddr(),
- _phantom: PhantomData,
- }
+ // SAFETY: The provided physical address is valid and the level is
+ // correct. The reference count is increased by one.
+ unsafe { RawPageTableNode::from_raw_parts(page.paddr(), page.meta().level) }
}
- /// Gets an extra reference of the child at the given index.
- pub(super) fn child(&self, idx: usize, in_tracked_range: bool) -> Child<E, C> {
- debug_assert!(idx < nr_subpage_per_huge::<C>());
-
- let pte = self.read_pte(idx);
- if !pte.is_present() {
- Child::None
- } else {
- let paddr = pte.paddr();
- if !pte.is_last(self.level()) {
- // SAFETY: We have a reference count to the page and can safely increase the reference
- // count by one more.
- unsafe {
- Page::<PageTablePageMeta<E, C>>::inc_ref_count(paddr);
- }
- Child::PageTable(RawPageTableNode {
- raw: paddr,
- _phantom: PhantomData,
- })
- } else if in_tracked_range {
- // SAFETY: We have a reference count to the page and can safely
- // increase the reference count by one more.
- unsafe {
- DynPage::inc_ref_count(paddr);
- }
- // SAFETY: The physical address of the PTE points to a forgotten
- // page. It is reclaimed only once.
- Child::Page(unsafe { DynPage::from_raw(paddr) }, pte.prop())
- } else {
- Child::Untracked(paddr, pte.prop())
- }
- }
+ /// Gets the number of valid PTEs in the node.
+ pub(super) fn nr_children(&self) -> u16 {
+ // SAFETY: The lock is held so we have an exclusive access.
+ unsafe { *self.page.meta().nr_children.get() }
}
- /// Replace the child at the given index with a new child.
+ /// Reads a non-owning PTE at the given index.
///
- /// The old child is returned.
- pub(super) fn replace_child(
- &mut self,
- idx: usize,
- new_child: Child<E, C>,
- in_tracked_range: bool,
- ) -> Child<E, C> {
- debug_assert!(idx < nr_subpage_per_huge::<C>());
-
- let old_pte = self.read_pte(idx);
-
- let new_child_is_none = match new_child {
- Child::None => {
- if old_pte.is_present() {
- self.write_pte(idx, E::new_absent());
- }
- true
- }
- Child::PageTable(pt) => {
- let pt = ManuallyDrop::new(pt);
- let new_pte = E::new_pt(pt.paddr());
- self.write_pte(idx, new_pte);
- false
- }
- Child::Page(page, prop) => {
- debug_assert!(in_tracked_range);
- let new_pte = E::new_page(page.into_raw(), self.level(), prop);
- self.write_pte(idx, new_pte);
- false
- }
- Child::Untracked(pa, prop) => {
- debug_assert!(!in_tracked_range);
- let new_pte = E::new_page(pa, self.level(), prop);
- self.write_pte(idx, new_pte);
- false
- }
- };
-
- if old_pte.is_present() {
- if new_child_is_none {
- *self.nr_children_mut() -= 1;
- }
- let paddr = old_pte.paddr();
- if !old_pte.is_last(self.level()) {
- Child::PageTable(RawPageTableNode {
- raw: paddr,
- _phantom: PhantomData,
- })
- } else if in_tracked_range {
- // SAFETY: The physical address of the old PTE points to a
- // forgotten page. It is reclaimed only once.
- Child::Page(unsafe { DynPage::from_raw(paddr) }, old_pte.prop())
- } else {
- Child::Untracked(paddr, old_pte.prop())
- }
- } else {
- if !new_child_is_none {
- *self.nr_children_mut() += 1;
- }
- Child::None
- }
- }
-
- /// Splits the untracked huge page mapped at `idx` to smaller pages.
- pub(super) fn split_untracked_huge(&mut self, idx: usize) {
- // These should be ensured by the cursor.
- debug_assert!(idx < nr_subpage_per_huge::<C>());
- debug_assert!(self.level() > 1);
-
- let Child::Untracked(pa, prop) = self.child(idx, false) else {
- panic!("`split_untracked_huge` not called on an untracked huge page");
- };
-
- let mut new_page = PageTableNode::<E, C>::alloc(self.level() - 1);
- for i in 0..nr_subpage_per_huge::<C>() {
- let small_pa = pa + i * page_size::<C>(self.level() - 1);
- new_page.replace_child(i, Child::Untracked(small_pa, prop), false);
- }
-
- self.replace_child(idx, Child::PageTable(new_page.into_raw()), false);
- }
-
- /// Protects an already mapped child at a given index.
- pub(super) fn protect(&mut self, idx: usize, prop: PageProperty) {
- let mut pte = self.read_pte(idx);
- debug_assert!(pte.is_present()); // This should be ensured by the cursor.
-
- pte.set_prop(prop);
-
- // SAFETY: the index is within the bound and the PTE is valid.
- unsafe {
- (self.as_ptr() as *mut E).add(idx).write(pte);
- }
- }
-
- pub(super) fn read_pte(&self, idx: usize) -> E {
- // It should be ensured by the cursor.
+ /// A non-owning PTE means that it does not account for a reference count
+ /// of the a page if the PTE points to a page. The original PTE still owns
+ /// the child page.
+ ///
+ /// # Safety
+ ///
+ /// The caller must ensure that the index is within the bound.
+ unsafe fn read_pte(&self, idx: usize) -> E {
debug_assert!(idx < nr_subpage_per_huge::<C>());
-
- // SAFETY: the index is within the bound and PTE is plain-old-data.
- unsafe { self.as_ptr().add(idx).read() }
+ let ptr = paddr_to_vaddr(self.page.paddr()) as *const E;
+ // SAFETY: The index is within the bound and the PTE is plain-old-data.
+ unsafe { ptr.add(idx).read() }
}
/// Writes a page table entry at a given index.
///
- /// This operation will leak the old child if the PTE is present.
- fn write_pte(&mut self, idx: usize, pte: E) {
- // It should be ensured by the cursor.
+ /// This operation will leak the old child if the old PTE is present.
+ ///
+ /// The child represented by the given PTE will handover the ownership to
+ /// the node. The PTE will be rendered invalid after this operation.
+ ///
+ /// # Safety
+ ///
+ /// The caller must ensure that:
+ /// 1. The index must be within the bound;
+ /// 2. The PTE must represent a child compatible with this page table node
+ /// (see [`Child::is_compatible`]).
+ unsafe fn write_pte(&mut self, idx: usize, pte: E) {
debug_assert!(idx < nr_subpage_per_huge::<C>());
-
- // SAFETY: the index is within the bound and PTE is plain-old-data.
- unsafe { (self.as_ptr() as *mut E).add(idx).write(pte) };
- }
-
- /// The number of valid PTEs.
- pub(super) fn nr_children(&self) -> u16 {
- // SAFETY: The lock is held so there is no mutable reference to it.
- // It would be safe to read.
- unsafe { *self.meta().nr_children.get() }
+ let ptr = paddr_to_vaddr(self.page.paddr()) as *mut E;
+ // SAFETY: The index is within the bound and the PTE is plain-old-data.
+ unsafe { ptr.add(idx).write(pte) }
}
+ /// Gets the mutable reference to the number of valid PTEs in the node.
fn nr_children_mut(&mut self) -> &mut u16 {
// SAFETY: The lock is held so we have an exclusive access.
- unsafe { &mut *self.meta().nr_children.get() }
- }
-
- fn as_ptr(&self) -> *const E {
- paddr_to_vaddr(self.start_paddr()) as *const E
- }
-
- fn start_paddr(&self) -> Paddr {
- self.page.paddr()
- }
-
- fn meta(&self) -> &PageTablePageMeta<E, C> {
- self.page.meta()
+ unsafe { &mut *self.page.meta().nr_children.get() }
}
}
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node/mod.rs
@@ -242,209 +269,76 @@ where
unsafe { core::ptr::write_bytes(ptr, 0, PAGE_SIZE) };
debug_assert!(E::new_absent().as_bytes().iter().all(|&b| b == 0));
- Self { page, _private: () }
- }
-
- pub fn level(&self) -> PagingLevel {
- self.meta().level
+ Self { page }
}
/// Converts the handle into a raw handle to be stored in a PTE or CPU.
pub(super) fn into_raw(self) -> RawPageTableNode<E, C> {
let this = ManuallyDrop::new(self);
- let raw = this.page.paddr();
-
+ // Release the lock.
this.page.meta().lock.store(0, Ordering::Release);
- RawPageTableNode {
- raw,
- _phantom: PhantomData,
- }
+ // SAFETY: The provided physical address is valid and the level is
+ // correct. The reference count is not changed.
+ unsafe { RawPageTableNode::from_raw_parts(this.page.paddr(), this.page.meta().level) }
}
/// Gets a raw handle while still preserving the original handle.
pub(super) fn clone_raw(&self) -> RawPageTableNode<E, C> {
- core::mem::forget(self.page.clone());
+ let page = ManuallyDrop::new(self.page.clone());
- RawPageTableNode {
- raw: self.page.paddr(),
- _phantom: PhantomData,
- }
+ // SAFETY: The provided physical address is valid and the level is
+ // correct. The reference count is increased by one.
+ unsafe { RawPageTableNode::from_raw_parts(page.paddr(), page.meta().level) }
}
- /// Gets an extra reference of the child at the given index.
- pub(super) fn child(&self, idx: usize, in_tracked_range: bool) -> Child<E, C> {
- debug_assert!(idx < nr_subpage_per_huge::<C>());
-
- let pte = self.read_pte(idx);
- if !pte.is_present() {
- Child::None
- } else {
- let paddr = pte.paddr();
- if !pte.is_last(self.level()) {
- // SAFETY: We have a reference count to the page and can safely increase the reference
- // count by one more.
- unsafe {
- Page::<PageTablePageMeta<E, C>>::inc_ref_count(paddr);
- }
- Child::PageTable(RawPageTableNode {
- raw: paddr,
- _phantom: PhantomData,
- })
- } else if in_tracked_range {
- // SAFETY: We have a reference count to the page and can safely
- // increase the reference count by one more.
- unsafe {
- DynPage::inc_ref_count(paddr);
- }
- // SAFETY: The physical address of the PTE points to a forgotten
- // page. It is reclaimed only once.
- Child::Page(unsafe { DynPage::from_raw(paddr) }, pte.prop())
- } else {
- Child::Untracked(paddr, pte.prop())
- }
- }
+ /// Gets the number of valid PTEs in the node.
+ pub(super) fn nr_children(&self) -> u16 {
+ // SAFETY: The lock is held so we have an exclusive access.
+ unsafe { *self.page.meta().nr_children.get() }
}
- /// Replace the child at the given index with a new child.
+ /// Reads a non-owning PTE at the given index.
///
- /// The old child is returned.
- pub(super) fn replace_child(
- &mut self,
- idx: usize,
- new_child: Child<E, C>,
- in_tracked_range: bool,
- ) -> Child<E, C> {
- debug_assert!(idx < nr_subpage_per_huge::<C>());
-
- let old_pte = self.read_pte(idx);
-
- let new_child_is_none = match new_child {
- Child::None => {
- if old_pte.is_present() {
- self.write_pte(idx, E::new_absent());
- }
- true
- }
- Child::PageTable(pt) => {
- let pt = ManuallyDrop::new(pt);
- let new_pte = E::new_pt(pt.paddr());
- self.write_pte(idx, new_pte);
- false
- }
- Child::Page(page, prop) => {
- debug_assert!(in_tracked_range);
- let new_pte = E::new_page(page.into_raw(), self.level(), prop);
- self.write_pte(idx, new_pte);
- false
- }
- Child::Untracked(pa, prop) => {
- debug_assert!(!in_tracked_range);
- let new_pte = E::new_page(pa, self.level(), prop);
- self.write_pte(idx, new_pte);
- false
- }
- };
-
- if old_pte.is_present() {
- if new_child_is_none {
- *self.nr_children_mut() -= 1;
- }
- let paddr = old_pte.paddr();
- if !old_pte.is_last(self.level()) {
- Child::PageTable(RawPageTableNode {
- raw: paddr,
- _phantom: PhantomData,
- })
- } else if in_tracked_range {
- // SAFETY: The physical address of the old PTE points to a
- // forgotten page. It is reclaimed only once.
- Child::Page(unsafe { DynPage::from_raw(paddr) }, old_pte.prop())
- } else {
- Child::Untracked(paddr, old_pte.prop())
- }
- } else {
- if !new_child_is_none {
- *self.nr_children_mut() += 1;
- }
- Child::None
- }
- }
-
- /// Splits the untracked huge page mapped at `idx` to smaller pages.
- pub(super) fn split_untracked_huge(&mut self, idx: usize) {
- // These should be ensured by the cursor.
- debug_assert!(idx < nr_subpage_per_huge::<C>());
- debug_assert!(self.level() > 1);
-
- let Child::Untracked(pa, prop) = self.child(idx, false) else {
- panic!("`split_untracked_huge` not called on an untracked huge page");
- };
-
- let mut new_page = PageTableNode::<E, C>::alloc(self.level() - 1);
- for i in 0..nr_subpage_per_huge::<C>() {
- let small_pa = pa + i * page_size::<C>(self.level() - 1);
- new_page.replace_child(i, Child::Untracked(small_pa, prop), false);
- }
-
- self.replace_child(idx, Child::PageTable(new_page.into_raw()), false);
- }
-
- /// Protects an already mapped child at a given index.
- pub(super) fn protect(&mut self, idx: usize, prop: PageProperty) {
- let mut pte = self.read_pte(idx);
- debug_assert!(pte.is_present()); // This should be ensured by the cursor.
-
- pte.set_prop(prop);
-
- // SAFETY: the index is within the bound and the PTE is valid.
- unsafe {
- (self.as_ptr() as *mut E).add(idx).write(pte);
- }
- }
-
- pub(super) fn read_pte(&self, idx: usize) -> E {
- // It should be ensured by the cursor.
+ /// A non-owning PTE means that it does not account for a reference count
+ /// of the a page if the PTE points to a page. The original PTE still owns
+ /// the child page.
+ ///
+ /// # Safety
+ ///
+ /// The caller must ensure that the index is within the bound.
+ unsafe fn read_pte(&self, idx: usize) -> E {
debug_assert!(idx < nr_subpage_per_huge::<C>());
-
- // SAFETY: the index is within the bound and PTE is plain-old-data.
- unsafe { self.as_ptr().add(idx).read() }
+ let ptr = paddr_to_vaddr(self.page.paddr()) as *const E;
+ // SAFETY: The index is within the bound and the PTE is plain-old-data.
+ unsafe { ptr.add(idx).read() }
}
/// Writes a page table entry at a given index.
///
- /// This operation will leak the old child if the PTE is present.
- fn write_pte(&mut self, idx: usize, pte: E) {
- // It should be ensured by the cursor.
+ /// This operation will leak the old child if the old PTE is present.
+ ///
+ /// The child represented by the given PTE will handover the ownership to
+ /// the node. The PTE will be rendered invalid after this operation.
+ ///
+ /// # Safety
+ ///
+ /// The caller must ensure that:
+ /// 1. The index must be within the bound;
+ /// 2. The PTE must represent a child compatible with this page table node
+ /// (see [`Child::is_compatible`]).
+ unsafe fn write_pte(&mut self, idx: usize, pte: E) {
debug_assert!(idx < nr_subpage_per_huge::<C>());
-
- // SAFETY: the index is within the bound and PTE is plain-old-data.
- unsafe { (self.as_ptr() as *mut E).add(idx).write(pte) };
- }
-
- /// The number of valid PTEs.
- pub(super) fn nr_children(&self) -> u16 {
- // SAFETY: The lock is held so there is no mutable reference to it.
- // It would be safe to read.
- unsafe { *self.meta().nr_children.get() }
+ let ptr = paddr_to_vaddr(self.page.paddr()) as *mut E;
+ // SAFETY: The index is within the bound and the PTE is plain-old-data.
+ unsafe { ptr.add(idx).write(pte) }
}
+ /// Gets the mutable reference to the number of valid PTEs in the node.
fn nr_children_mut(&mut self) -> &mut u16 {
// SAFETY: The lock is held so we have an exclusive access.
- unsafe { &mut *self.meta().nr_children.get() }
- }
-
- fn as_ptr(&self) -> *const E {
- paddr_to_vaddr(self.start_paddr()) as *const E
- }
-
- fn start_paddr(&self) -> Paddr {
- self.page.paddr()
- }
-
- fn meta(&self) -> &PageTablePageMeta<E, C> {
- self.page.meta()
+ unsafe { &mut *self.page.meta().nr_children.get() }
}
}
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node/mod.rs
@@ -465,8 +359,16 @@ where
const USAGE: PageUsage = PageUsage::PageTable;
fn on_drop(page: &mut Page<Self>) {
+ // SAFETY: This is the last reference so we have an exclusive access.
+ let nr_children = unsafe { *page.meta().nr_children.get() };
+
+ if nr_children == 0 {
+ return;
+ }
+
let paddr = page.paddr();
let level = page.meta().level;
+ let is_tracked = page.meta().is_tracked;
// Drop the children.
for i in 0..nr_subpage_per_huge::<C>() {
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node/mod.rs
@@ -465,8 +359,16 @@ where
const USAGE: PageUsage = PageUsage::PageTable;
fn on_drop(page: &mut Page<Self>) {
+ // SAFETY: This is the last reference so we have an exclusive access.
+ let nr_children = unsafe { *page.meta().nr_children.get() };
+
+ if nr_children == 0 {
+ return;
+ }
+
let paddr = page.paddr();
let level = page.meta().level;
+ let is_tracked = page.meta().is_tracked;
// Drop the children.
for i in 0..nr_subpage_per_huge::<C>() {
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node/mod.rs
@@ -476,19 +378,21 @@ where
let pte_ptr = unsafe { (paddr_to_vaddr(paddr) as *const E).add(i) };
// SAFETY: The pointer is valid and the PTE is plain-old-data.
let pte = unsafe { pte_ptr.read() };
+
+ // Here if we use directly `Child::from_pte` we would experience a
+ // 50% increase in the overhead of the `drop` function. It seems that
+ // Rust is very conservative about inlining and optimizing dead code
+ // for `unsafe` code. So we manually inline the function here.
if pte.is_present() {
- // Just restore the handle and drop the handle.
+ let paddr = pte.paddr();
if !pte.is_last(level) {
- // This is a page table.
- // SAFETY: The physical address must be casted from a handle to a
- // page table node.
- drop(unsafe { Page::<Self>::from_raw(pte.paddr()) });
- } else {
- // This is a page. You cannot drop a page table node that maps to
- // untracked pages. This must be verified.
- // SAFETY: The physical address must be casted from a handle to a
- // page.
- drop(unsafe { DynPage::from_raw(pte.paddr()) });
+ // SAFETY: The PTE points to a page table node. The ownership
+ // of the child is transferred to the child then dropped.
+ drop(unsafe { Page::<Self>::from_raw(paddr) });
+ } else if is_tracked == MapTrackingStatus::Tracked {
+ // SAFETY: The PTE points to a tracked page. The ownership
+ // of the child is transferred to the child then dropped.
+ drop(unsafe { DynPage::from_raw(paddr) });
}
}
}
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node/mod.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node/mod.rs
@@ -476,19 +378,21 @@ where
let pte_ptr = unsafe { (paddr_to_vaddr(paddr) as *const E).add(i) };
// SAFETY: The pointer is valid and the PTE is plain-old-data.
let pte = unsafe { pte_ptr.read() };
+
+ // Here if we use directly `Child::from_pte` we would experience a
+ // 50% increase in the overhead of the `drop` function. It seems that
+ // Rust is very conservative about inlining and optimizing dead code
+ // for `unsafe` code. So we manually inline the function here.
if pte.is_present() {
- // Just restore the handle and drop the handle.
+ let paddr = pte.paddr();
if !pte.is_last(level) {
- // This is a page table.
- // SAFETY: The physical address must be casted from a handle to a
- // page table node.
- drop(unsafe { Page::<Self>::from_raw(pte.paddr()) });
- } else {
- // This is a page. You cannot drop a page table node that maps to
- // untracked pages. This must be verified.
- // SAFETY: The physical address must be casted from a handle to a
- // page.
- drop(unsafe { DynPage::from_raw(pte.paddr()) });
+ // SAFETY: The PTE points to a page table node. The ownership
+ // of the child is transferred to the child then dropped.
+ drop(unsafe { Page::<Self>::from_raw(paddr) });
+ } else if is_tracked == MapTrackingStatus::Tracked {
+ // SAFETY: The PTE points to a tracked page. The ownership
+ // of the child is transferred to the child then dropped.
+ drop(unsafe { DynPage::from_raw(paddr) });
}
}
}
|
I've already checked out your PR #918 addressing issues raised in this RFC, and find it convincing.
To sum up, the current inner API designs do have the 2 following major weaknesses:
- The "tracked" and "untracked" ranges are all managed by the page table, but the node is agnostic to it to some extent;
- The safety guarantee are not perfectly modeled.
I need some time carefully think about the solution. And thanks for proposing such a fix quickly.
|
2024-09-24T09:24:48Z
|
9da6af03943c15456cdfd781021820a7da78ea40
|
asterinas/asterinas
|
diff --git a/ostd/src/mm/page_table/test.rs b/ostd/src/mm/page_table/test.rs
--- a/ostd/src/mm/page_table/test.rs
+++ b/ostd/src/mm/page_table/test.rs
@@ -81,6 +81,10 @@ fn test_untracked_map_unmap() {
#[ktest]
fn test_user_copy_on_write() {
+ fn prot_op(prop: &mut PageProperty) {
+ prop.flags -= PageFlags::W;
+ }
+
let pt = PageTable::<UserMode>::empty();
let from = PAGE_SIZE..PAGE_SIZE * 2;
let page = allocator::alloc_single(FrameMeta::default()).unwrap();
diff --git a/ostd/src/mm/page_table/test.rs b/ostd/src/mm/page_table/test.rs
--- a/ostd/src/mm/page_table/test.rs
+++ b/ostd/src/mm/page_table/test.rs
@@ -96,7 +100,14 @@ fn test_user_copy_on_write() {
unsafe { pt.cursor_mut(&from).unwrap().map(page.clone().into(), prop) };
assert_eq!(pt.query(from.start + 10).unwrap().0, start_paddr + 10);
- let child_pt = pt.clone_with(pt.cursor_mut(&(0..MAX_USERSPACE_VADDR)).unwrap());
+ let child_pt = {
+ let child_pt = PageTable::<UserMode>::empty();
+ let range = 0..MAX_USERSPACE_VADDR;
+ let mut child_cursor = child_pt.cursor_mut(&range).unwrap();
+ let mut parent_cursor = pt.cursor_mut(&range).unwrap();
+ unsafe { child_cursor.copy_from(&mut parent_cursor, range.len(), &mut prot_op) };
+ child_pt
+ };
assert_eq!(pt.query(from.start + 10).unwrap().0, start_paddr + 10);
assert_eq!(child_pt.query(from.start + 10).unwrap().0, start_paddr + 10);
assert!(matches!(
diff --git a/ostd/src/mm/page_table/test.rs b/ostd/src/mm/page_table/test.rs
--- a/ostd/src/mm/page_table/test.rs
+++ b/ostd/src/mm/page_table/test.rs
@@ -106,7 +117,14 @@ fn test_user_copy_on_write() {
assert!(pt.query(from.start + 10).is_none());
assert_eq!(child_pt.query(from.start + 10).unwrap().0, start_paddr + 10);
- let sibling_pt = pt.clone_with(pt.cursor_mut(&(0..MAX_USERSPACE_VADDR)).unwrap());
+ let sibling_pt = {
+ let sibling_pt = PageTable::<UserMode>::empty();
+ let range = 0..MAX_USERSPACE_VADDR;
+ let mut sibling_cursor = sibling_pt.cursor_mut(&range).unwrap();
+ let mut parent_cursor = pt.cursor_mut(&range).unwrap();
+ unsafe { sibling_cursor.copy_from(&mut parent_cursor, range.len(), &mut prot_op) };
+ sibling_pt
+ };
assert!(sibling_pt.query(from.start + 10).is_none());
assert_eq!(child_pt.query(from.start + 10).unwrap().0, start_paddr + 10);
drop(pt);
|
[
"919"
] |
0.8
|
ae4ac384713e63232b74915593ebdef680049d31
|
[RFC] Safety model about the page tables
# Background
This issue discusses the internal APIs of the page table. More specifically, the following two sets of APIs:
- The APIs provided by `RawPageTableNode`/`PageTableNode`
- Files: [`framework/aster-frame/src/mm/page_table/node.rs`](https://github.com/asterinas/asterinas/blob/main/framework/aster-frame/src/mm/page_table/node.rs)
- The APIs provided by `PageTable`/`Cursor`/`CursorMut`
- Files: [`framework/aster-frame/src/mm/page_table/mod.rs`](https://github.com/asterinas/asterinas/blob/main/framework/aster-frame/src/mm/page_table/mod.rs) and [`framework/aster-frame/src/mm/page_table/cursor.rs`](https://github.com/asterinas/asterinas/blob/main/framework/aster-frame/src/mm/page_table/cursor.rs)
The focus is on what kind of safety guarantees they can provide.
Currently, this question is not clearly answered. For example, consider the following API in `PageTableNode`:
https://github.com/asterinas/asterinas/blob/c6aa9f9ee860bbdcb8bb3444b630aff9f0ac14af/framework/aster-frame/src/mm/page_table/node.rs#L383-L388
This method is marked as unsafe because it can create arbitrary mappings. This is not a valid reason to mark it as unsafe, as the activation of a `RawPageTableNode` is already marked as unsafe, as shown in the following code snippet:
https://github.com/asterinas/asterinas/blob/c6aa9f9ee860bbdcb8bb3444b630aff9f0ac14af/framework/aster-frame/src/mm/page_table/node.rs#L112-L124
_If_ the above reason is considered valid, then _every_ modification method of `PageTableNode` must also be marked as unsafe. This is because a `PageTableNode` does not know its exact position in the page table, so it can be at a critical position (e.g. the kernel text). In such cases, its modification will never be safe in the sense of mapping safety.
https://github.com/asterinas/asterinas/blob/c6aa9f9ee860bbdcb8bb3444b630aff9f0ac14af/framework/aster-frame/src/mm/page_table/node.rs#L372-L373
https://github.com/asterinas/asterinas/blob/c6aa9f9ee860bbdcb8bb3444b630aff9f0ac14af/framework/aster-frame/src/mm/page_table/node.rs#L356-L362
Fortunately, the unsafety of the activation method `RawPageTableNode::activate` should have already captured the mapping safety, so I argue that all other modification methods like `PageTableNode::set_child_untracked` mentioned above should not consider the mapping safety again. However, it should consider the safety of the page tables themselves.
But the safety of the page tables themselves still involves a lot of things, like the following:
- **Property 1**: If any PTE points to another page table, it must point to a valid page table.
- **Property 2**: If any PTE points to a physical page, it can point to either a tracked frame or an untracked region of memory.
- **Property 3**: If any PTE points to a physical page and the current page table node can only represent tracked mappings, the PTE must point to a tracked frame.
- **Property 4**: If any PTE points to a physical page and the current page table node can only represent untracked mappings, the PTE must point to an untracked region of memory.
- **Property 5**: If any PTE points to another page table, it must point to a page table that is on the next page level. If the next page level does not exist, the PTE cannot point to a page table.
The current design does indeed guarantee **Property 1** and **Property 2**, but the APIs need some revision to make them truly safe. However, it runs into difficulties when dropping the page tables, because the page table nodes do not know whether PTEs point to tracked frames or untracked regions of memory. The API change and the difficulties are described below as **Solution 1**.
To address the above difficulties, I think that it is possible to additionally guarantee **Property 3** and **Property 4** through safe APIs of page table nodes. I call this **Solution 2** below.
I don't think that **Property 5** needs to be guaranteed by `PageTableNode`. The reason is that it can be trivially guaranteed by the page table cursors. The page table cursors maintain a fixed-length array, where each slot can have a page table node at a certain level. It is clear enough, so there is little benefit to enforce these guarantees to the page table nodes.
# Solution 0
Do nothing.
**Pros:**
- No more work to do!
**Cons:**
- The current APIs are not as good as I would like them to be, and I think they are hard to maintain.
# Solution 1
The current design guarantees **Property 1** and **Property 2**. However, most of the `PageTableNode` APIs cannot be considered safe because they rely on the correctness of the input argument `in_untracked_range` to be memory safe:
https://github.com/asterinas/asterinas/blob/c6aa9f9ee860bbdcb8bb3444b630aff9f0ac14af/framework/aster-frame/src/mm/page_table/node.rs#L267-L268
For example, if someone passes `in_untracked_range = false` to `PageTableNode::child`, but the corresponding PTE actually points to an untracked memory range, then the untracked memory range will be cast to an tracked frame. This will cause serve memory safety issues.
To solve this problem, it is possible to create a new type called `MaybeTrackedPage`, which can be converted into a tracked frame (via the unsafe `assume_tracked` method) or an untracked region of memory (via the `assume_untracked` method) by the user:
https://github.com/asterinas/asterinas/blob/7f45a1bb29f5bf6d6ddb0d12fdb48dc1ca15852c/framework/aster-frame/src/mm/page_table/node.rs#L253-L268
Then the `PageTableNode::child` method can be made to return a wrapped type of `MaybeTrackedPage` (the `Child` wrapper handles cases where the PTE is empty or points to another page table):
https://github.com/asterinas/asterinas/blob/7f45a1bb29f5bf6d6ddb0d12fdb48dc1ca15852c/framework/aster-frame/src/mm/page_table/node.rs#L447-L448
I think this solution works well, _except_ for the annoying `Drop` implementation. Since the page table node has no way of knowing whether PTEs point to tracked frames or untracked regions of memory, it won't know how to drop them if such PTEs are encountered in the `Drop` method. So far it is assumed that only tracked frames can be dropped, as shown in the following code snippet:
https://github.com/asterinas/asterinas/blob/c6aa9f9ee860bbdcb8bb3444b630aff9f0ac14af/framework/aster-frame/src/mm/page_table/node.rs#L536-L540
But this assumption can easily be wrong. For example, a page table containing untracked regions of memory can be dropped if a huge page overwrites the PTE on a page table:
https://github.com/asterinas/asterinas/blob/c6aa9f9ee860bbdcb8bb3444b630aff9f0ac14af/framework/aster-frame/src/mm/page_table/node.rs#L474-L476
It is possible to work around this problem by adding methods such as `drop_deep_untracked` and `drop_deep_tracked`, which recursively drop all descendants of the current page table node, assuming they contain only tracked frames or untracked regions of memory. Then the `drop` method should not see any PTEs pointing to physical pages.
https://github.com/asterinas/asterinas/blob/7f45a1bb29f5bf6d6ddb0d12fdb48dc1ca15852c/framework/aster-frame/src/mm/page_table/node.rs#L303-L325
However, this solution is not very elegant.
**Pro:**
- It was implemented in #918, see commits "Implement `MaybeTracked{,Page,PageRef}`" and "Clarify the safety model in `PageTableNode`".
**Cons:**
- The dropping implementation is not ideal.
- The cursor (and its users) must be careful about whether the PTE represents tracked frames or untracked regions of memory.
# Solution 2
One possible solution to solve the problem above is to make page table nodes aware whether it contains tracked frames or untracked regions of memory.
I think it is reasonable to make an additional assumption: a page table node cannot _directly_ contain both PTEs to tracked frames and PTEs to regions of memory. This limits the power of the page table a bit, but is still reasonable. On x86-64, each page table node representing a 1GiB mapping can have either tracked frames or untracked regions of memory, but not both, as 2MiB huge pages, which still seems flexible to me.
This information can be recorded in the page metadata, marking each page table as `Tracked` (diretly containing PTEs only to tracked frames), `Untracked` (directly contains PTEs only to untracked regions of memory), or `None` (directly containing no PTEs to physical pages). Then when dropping a page table, it is clear the PTEs can be dropped without problems.
A simple way to enforce the page metadata is to add assertions at the beginning of methods like `PageTableNode::set_child_frame` and `PageTableNode::set_child_untracked`. Compilers may be smart to check once and update a number of PTEs.
Alternatively, I think a better solution is to make page table cursors that operate on tracked frames and untracked regions of memory _different modes_ (like the existing `UserMode` and `KernelMode`). This way, whether a cursor operates on tracked frames or untracked regions can be determined at compile time, instead of at runtime as it is now:
https://github.com/asterinas/asterinas/blob/c6aa9f9ee860bbdcb8bb3444b630aff9f0ac14af/framework/aster-frame/src/mm/page_table/cursor.rs#L278-L282
Then the page table cursor and page table node implementation should be much clearer:
```rust
impl TrackedNode {
fn set_child(&mut self, idx: usize, frame: Frame);
}
impl UntrackedNode {
fn set_child(&mut self, idx: usize, paddr: Paddr);
}
```
```rust
// `TrackedMode` associates with `TrackedNode`
impl<M: TrackedMode> Cursor<M> {
fn map(&mut self, frame: Frame, prop: PageProperty);
}
// `UntrackedMode` associates with `UntrackedNode`
impl<M: UntrackedMode> Cursor {
fn map(&mut self, pa: &Range<Paddr>, prop: PageProperty);
}
```
**Pros:**
- Improves clarity of cursor and node implementation.
- Addresses the above problem.
**Cons:**
- Cursor implementation requires more refactoring.
- Cursor may not be as flexible as it is now, but are there use cases where accesses to tracked frames and untracked regions of memory have be mixed in one cursor?
cc @junyang-zh
|
asterinas__asterinas-1369
| 1,369
|
diff --git a/kernel/src/vm/vmar/mod.rs b/kernel/src/vm/vmar/mod.rs
--- a/kernel/src/vm/vmar/mod.rs
+++ b/kernel/src/vm/vmar/mod.rs
@@ -16,7 +16,7 @@ use align_ext::AlignExt;
use aster_rights::Rights;
use ostd::{
cpu::CpuExceptionInfo,
- mm::{VmSpace, MAX_USERSPACE_VADDR},
+ mm::{tlb::TlbFlushOp, PageFlags, PageProperty, VmSpace, MAX_USERSPACE_VADDR},
};
use self::{
diff --git a/kernel/src/vm/vmar/mod.rs b/kernel/src/vm/vmar/mod.rs
--- a/kernel/src/vm/vmar/mod.rs
+++ b/kernel/src/vm/vmar/mod.rs
@@ -16,7 +16,7 @@ use align_ext::AlignExt;
use aster_rights::Rights;
use ostd::{
cpu::CpuExceptionInfo,
- mm::{VmSpace, MAX_USERSPACE_VADDR},
+ mm::{tlb::TlbFlushOp, PageFlags, PageProperty, VmSpace, MAX_USERSPACE_VADDR},
};
use self::{
diff --git a/kernel/src/vm/vmar/mod.rs b/kernel/src/vm/vmar/mod.rs
--- a/kernel/src/vm/vmar/mod.rs
+++ b/kernel/src/vm/vmar/mod.rs
@@ -220,13 +220,6 @@ impl Vmar_ {
}
fn new_root() -> Arc<Self> {
- fn handle_page_fault_wrapper(
- vm_space: &VmSpace,
- trap_info: &CpuExceptionInfo,
- ) -> core::result::Result<(), ()> {
- handle_page_fault_from_vm_space(vm_space, &trap_info.try_into().unwrap())
- }
-
let mut free_regions = BTreeMap::new();
let root_region = FreeRegion::new(ROOT_VMAR_LOWEST_ADDR..ROOT_VMAR_CAP_ADDR);
free_regions.insert(root_region.start(), root_region);
diff --git a/kernel/src/vm/vmar/mod.rs b/kernel/src/vm/vmar/mod.rs
--- a/kernel/src/vm/vmar/mod.rs
+++ b/kernel/src/vm/vmar/mod.rs
@@ -220,13 +220,6 @@ impl Vmar_ {
}
fn new_root() -> Arc<Self> {
- fn handle_page_fault_wrapper(
- vm_space: &VmSpace,
- trap_info: &CpuExceptionInfo,
- ) -> core::result::Result<(), ()> {
- handle_page_fault_from_vm_space(vm_space, &trap_info.try_into().unwrap())
- }
-
let mut free_regions = BTreeMap::new();
let root_region = FreeRegion::new(ROOT_VMAR_LOWEST_ADDR..ROOT_VMAR_CAP_ADDR);
free_regions.insert(root_region.start(), root_region);
diff --git a/kernel/src/vm/vmar/mod.rs b/kernel/src/vm/vmar/mod.rs
--- a/kernel/src/vm/vmar/mod.rs
+++ b/kernel/src/vm/vmar/mod.rs
@@ -236,7 +229,7 @@ impl Vmar_ {
vm_mappings: BTreeMap::new(),
free_regions,
};
- let vm_space = VmSpace::new();
+ let mut vm_space = VmSpace::new();
vm_space.register_page_fault_handler(handle_page_fault_wrapper);
Vmar_::new(vmar_inner, Arc::new(vm_space), 0, ROOT_VMAR_CAP_ADDR, None)
}
diff --git a/kernel/src/vm/vmar/mod.rs b/kernel/src/vm/vmar/mod.rs
--- a/kernel/src/vm/vmar/mod.rs
+++ b/kernel/src/vm/vmar/mod.rs
@@ -236,7 +229,7 @@ impl Vmar_ {
vm_mappings: BTreeMap::new(),
free_regions,
};
- let vm_space = VmSpace::new();
+ let mut vm_space = VmSpace::new();
vm_space.register_page_fault_handler(handle_page_fault_wrapper);
Vmar_::new(vmar_inner, Arc::new(vm_space), 0, ROOT_VMAR_CAP_ADDR, None)
}
diff --git a/kernel/src/vm/vmar/mod.rs b/kernel/src/vm/vmar/mod.rs
--- a/kernel/src/vm/vmar/mod.rs
+++ b/kernel/src/vm/vmar/mod.rs
@@ -668,17 +661,19 @@ impl Vmar_ {
let vm_space = if let Some(parent) = parent {
parent.vm_space().clone()
} else {
- Arc::new(self.vm_space().fork_copy_on_write())
+ let mut new_space = VmSpace::new();
+ new_space.register_page_fault_handler(handle_page_fault_wrapper);
+ Arc::new(new_space)
};
Vmar_::new(vmar_inner, vm_space, self.base, self.size, parent)
};
let inner = self.inner.lock();
+ let mut new_inner = new_vmar_.inner.lock();
+
// Clone free regions.
for (free_region_base, free_region) in &inner.free_regions {
- new_vmar_
- .inner
- .lock()
+ new_inner
.free_regions
.insert(*free_region_base, free_region.clone());
}
diff --git a/kernel/src/vm/vmar/mod.rs b/kernel/src/vm/vmar/mod.rs
--- a/kernel/src/vm/vmar/mod.rs
+++ b/kernel/src/vm/vmar/mod.rs
@@ -668,17 +661,19 @@ impl Vmar_ {
let vm_space = if let Some(parent) = parent {
parent.vm_space().clone()
} else {
- Arc::new(self.vm_space().fork_copy_on_write())
+ let mut new_space = VmSpace::new();
+ new_space.register_page_fault_handler(handle_page_fault_wrapper);
+ Arc::new(new_space)
};
Vmar_::new(vmar_inner, vm_space, self.base, self.size, parent)
};
let inner = self.inner.lock();
+ let mut new_inner = new_vmar_.inner.lock();
+
// Clone free regions.
for (free_region_base, free_region) in &inner.free_regions {
- new_vmar_
- .inner
- .lock()
+ new_inner
.free_regions
.insert(*free_region_base, free_region.clone());
}
diff --git a/kernel/src/vm/vmar/mod.rs b/kernel/src/vm/vmar/mod.rs
--- a/kernel/src/vm/vmar/mod.rs
+++ b/kernel/src/vm/vmar/mod.rs
@@ -686,26 +681,49 @@ impl Vmar_ {
// Clone child vmars.
for (child_vmar_base, child_vmar_) in &inner.child_vmar_s {
let new_child_vmar = child_vmar_.new_fork(Some(&new_vmar_))?;
- new_vmar_
- .inner
- .lock()
+ new_inner
.child_vmar_s
.insert(*child_vmar_base, new_child_vmar);
}
// Clone mappings.
- for (vm_mapping_base, vm_mapping) in &inner.vm_mappings {
- let new_mapping = Arc::new(vm_mapping.new_fork(&new_vmar_)?);
- new_vmar_
- .inner
- .lock()
- .vm_mappings
- .insert(*vm_mapping_base, new_mapping);
+ {
+ let new_vmspace = new_vmar_.vm_space();
+ let range = self.base..(self.base + self.size);
+ let mut new_cursor = new_vmspace.cursor_mut(&range).unwrap();
+ let cur_vmspace = self.vm_space();
+ let mut cur_cursor = cur_vmspace.cursor_mut(&range).unwrap();
+ for (vm_mapping_base, vm_mapping) in &inner.vm_mappings {
+ // Clone the `VmMapping` to the new VMAR.
+ let new_mapping = Arc::new(vm_mapping.new_fork(&new_vmar_)?);
+ new_inner.vm_mappings.insert(*vm_mapping_base, new_mapping);
+
+ // Protect the mapping and copy to the new page table for COW.
+ cur_cursor.jump(*vm_mapping_base).unwrap();
+ new_cursor.jump(*vm_mapping_base).unwrap();
+ let mut op = |page: &mut PageProperty| {
+ page.flags -= PageFlags::W;
+ };
+ new_cursor.copy_from(&mut cur_cursor, vm_mapping.map_size(), &mut op);
+ }
+ cur_cursor.flusher().issue_tlb_flush(TlbFlushOp::All);
+ cur_cursor.flusher().dispatch_tlb_flush();
}
+
+ drop(new_inner);
+
Ok(new_vmar_)
}
}
+/// This is for fallible user space write handling.
+fn handle_page_fault_wrapper(
+ vm_space: &VmSpace,
+ trap_info: &CpuExceptionInfo,
+) -> core::result::Result<(), ()> {
+ handle_page_fault_from_vm_space(vm_space, &trap_info.try_into().unwrap())
+}
+
impl<R> Vmar<R> {
/// The base address, i.e., the offset relative to the root VMAR.
///
diff --git a/kernel/src/vm/vmar/mod.rs b/kernel/src/vm/vmar/mod.rs
--- a/kernel/src/vm/vmar/mod.rs
+++ b/kernel/src/vm/vmar/mod.rs
@@ -686,26 +681,49 @@ impl Vmar_ {
// Clone child vmars.
for (child_vmar_base, child_vmar_) in &inner.child_vmar_s {
let new_child_vmar = child_vmar_.new_fork(Some(&new_vmar_))?;
- new_vmar_
- .inner
- .lock()
+ new_inner
.child_vmar_s
.insert(*child_vmar_base, new_child_vmar);
}
// Clone mappings.
- for (vm_mapping_base, vm_mapping) in &inner.vm_mappings {
- let new_mapping = Arc::new(vm_mapping.new_fork(&new_vmar_)?);
- new_vmar_
- .inner
- .lock()
- .vm_mappings
- .insert(*vm_mapping_base, new_mapping);
+ {
+ let new_vmspace = new_vmar_.vm_space();
+ let range = self.base..(self.base + self.size);
+ let mut new_cursor = new_vmspace.cursor_mut(&range).unwrap();
+ let cur_vmspace = self.vm_space();
+ let mut cur_cursor = cur_vmspace.cursor_mut(&range).unwrap();
+ for (vm_mapping_base, vm_mapping) in &inner.vm_mappings {
+ // Clone the `VmMapping` to the new VMAR.
+ let new_mapping = Arc::new(vm_mapping.new_fork(&new_vmar_)?);
+ new_inner.vm_mappings.insert(*vm_mapping_base, new_mapping);
+
+ // Protect the mapping and copy to the new page table for COW.
+ cur_cursor.jump(*vm_mapping_base).unwrap();
+ new_cursor.jump(*vm_mapping_base).unwrap();
+ let mut op = |page: &mut PageProperty| {
+ page.flags -= PageFlags::W;
+ };
+ new_cursor.copy_from(&mut cur_cursor, vm_mapping.map_size(), &mut op);
+ }
+ cur_cursor.flusher().issue_tlb_flush(TlbFlushOp::All);
+ cur_cursor.flusher().dispatch_tlb_flush();
}
+
+ drop(new_inner);
+
Ok(new_vmar_)
}
}
+/// This is for fallible user space write handling.
+fn handle_page_fault_wrapper(
+ vm_space: &VmSpace,
+ trap_info: &CpuExceptionInfo,
+) -> core::result::Result<(), ()> {
+ handle_page_fault_from_vm_space(vm_space, &trap_info.try_into().unwrap())
+}
+
impl<R> Vmar<R> {
/// The base address, i.e., the offset relative to the root VMAR.
///
diff --git a/kernel/src/vm/vmar/vm_mapping.rs b/kernel/src/vm/vmar/vm_mapping.rs
--- a/kernel/src/vm/vmar/vm_mapping.rs
+++ b/kernel/src/vm/vmar/vm_mapping.rs
@@ -11,7 +11,8 @@ use core::{
use align_ext::AlignExt;
use aster_rights::Rights;
use ostd::mm::{
- vm_space::VmItem, CachePolicy, Frame, FrameAllocOptions, PageFlags, PageProperty, VmSpace,
+ tlb::TlbFlushOp, vm_space::VmItem, CachePolicy, Frame, FrameAllocOptions, PageFlags,
+ PageProperty, VmSpace,
};
use super::{interval::Interval, is_intersected, Vmar, Vmar_};
diff --git a/kernel/src/vm/vmar/vm_mapping.rs b/kernel/src/vm/vmar/vm_mapping.rs
--- a/kernel/src/vm/vmar/vm_mapping.rs
+++ b/kernel/src/vm/vmar/vm_mapping.rs
@@ -11,7 +11,8 @@ use core::{
use align_ext::AlignExt;
use aster_rights::Rights;
use ostd::mm::{
- vm_space::VmItem, CachePolicy, Frame, FrameAllocOptions, PageFlags, PageProperty, VmSpace,
+ tlb::TlbFlushOp, vm_space::VmItem, CachePolicy, Frame, FrameAllocOptions, PageFlags,
+ PageProperty, VmSpace,
};
use super::{interval::Interval, is_intersected, Vmar, Vmar_};
diff --git a/kernel/src/vm/vmar/vm_mapping.rs b/kernel/src/vm/vmar/vm_mapping.rs
--- a/kernel/src/vm/vmar/vm_mapping.rs
+++ b/kernel/src/vm/vmar/vm_mapping.rs
@@ -224,7 +225,7 @@ impl VmMapping {
match cursor.query().unwrap() {
VmItem::Mapped {
- va: _,
+ va,
frame,
mut prop,
} if is_write => {
diff --git a/kernel/src/vm/vmar/vm_mapping.rs b/kernel/src/vm/vmar/vm_mapping.rs
--- a/kernel/src/vm/vmar/vm_mapping.rs
+++ b/kernel/src/vm/vmar/vm_mapping.rs
@@ -224,7 +225,7 @@ impl VmMapping {
match cursor.query().unwrap() {
VmItem::Mapped {
- va: _,
+ va,
frame,
mut prop,
} if is_write => {
diff --git a/kernel/src/vm/vmar/vm_mapping.rs b/kernel/src/vm/vmar/vm_mapping.rs
--- a/kernel/src/vm/vmar/vm_mapping.rs
+++ b/kernel/src/vm/vmar/vm_mapping.rs
@@ -245,7 +246,9 @@ impl VmMapping {
let new_flags = PageFlags::W | PageFlags::ACCESSED | PageFlags::DIRTY;
if self.is_shared || only_reference {
- cursor.protect(PAGE_SIZE, |p| p.flags |= new_flags);
+ cursor.protect_next(PAGE_SIZE, |p| p.flags |= new_flags);
+ cursor.flusher().issue_tlb_flush(TlbFlushOp::Address(va));
+ cursor.flusher().dispatch_tlb_flush();
} else {
let new_frame = duplicate_frame(&frame)?;
prop.flags |= new_flags;
diff --git a/kernel/src/vm/vmar/vm_mapping.rs b/kernel/src/vm/vmar/vm_mapping.rs
--- a/kernel/src/vm/vmar/vm_mapping.rs
+++ b/kernel/src/vm/vmar/vm_mapping.rs
@@ -245,7 +246,9 @@ impl VmMapping {
let new_flags = PageFlags::W | PageFlags::ACCESSED | PageFlags::DIRTY;
if self.is_shared || only_reference {
- cursor.protect(PAGE_SIZE, |p| p.flags |= new_flags);
+ cursor.protect_next(PAGE_SIZE, |p| p.flags |= new_flags);
+ cursor.flusher().issue_tlb_flush(TlbFlushOp::Address(va));
+ cursor.flusher().dispatch_tlb_flush();
} else {
let new_frame = duplicate_frame(&frame)?;
prop.flags |= new_flags;
diff --git a/kernel/src/vm/vmar/vm_mapping.rs b/kernel/src/vm/vmar/vm_mapping.rs
--- a/kernel/src/vm/vmar/vm_mapping.rs
+++ b/kernel/src/vm/vmar/vm_mapping.rs
@@ -558,7 +561,15 @@ impl VmMappingInner {
debug_assert!(range.start % PAGE_SIZE == 0);
debug_assert!(range.end % PAGE_SIZE == 0);
let mut cursor = vm_space.cursor_mut(&range).unwrap();
- cursor.protect(range.len(), |p| p.flags = perms.into());
+ let op = |p: &mut PageProperty| p.flags = perms.into();
+ while cursor.virt_addr() < range.end {
+ if let Some(va) = cursor.protect_next(range.end - cursor.virt_addr(), op) {
+ cursor.flusher().issue_tlb_flush(TlbFlushOp::Range(va));
+ } else {
+ break;
+ }
+ }
+ cursor.flusher().dispatch_tlb_flush();
Ok(())
}
diff --git a/kernel/src/vm/vmar/vm_mapping.rs b/kernel/src/vm/vmar/vm_mapping.rs
--- a/kernel/src/vm/vmar/vm_mapping.rs
+++ b/kernel/src/vm/vmar/vm_mapping.rs
@@ -558,7 +561,15 @@ impl VmMappingInner {
debug_assert!(range.start % PAGE_SIZE == 0);
debug_assert!(range.end % PAGE_SIZE == 0);
let mut cursor = vm_space.cursor_mut(&range).unwrap();
- cursor.protect(range.len(), |p| p.flags = perms.into());
+ let op = |p: &mut PageProperty| p.flags = perms.into();
+ while cursor.virt_addr() < range.end {
+ if let Some(va) = cursor.protect_next(range.end - cursor.virt_addr(), op) {
+ cursor.flusher().issue_tlb_flush(TlbFlushOp::Range(va));
+ } else {
+ break;
+ }
+ }
+ cursor.flusher().dispatch_tlb_flush();
Ok(())
}
diff --git a/ostd/src/mm/mod.rs b/ostd/src/mm/mod.rs
--- a/ostd/src/mm/mod.rs
+++ b/ostd/src/mm/mod.rs
@@ -18,6 +18,7 @@ pub(crate) mod page;
pub(crate) mod page_prop;
pub(crate) mod page_table;
pub mod stat;
+pub mod tlb;
pub mod vm_space;
use core::{fmt::Debug, ops::Range};
diff --git a/ostd/src/mm/mod.rs b/ostd/src/mm/mod.rs
--- a/ostd/src/mm/mod.rs
+++ b/ostd/src/mm/mod.rs
@@ -18,6 +18,7 @@ pub(crate) mod page;
pub(crate) mod page_prop;
pub(crate) mod page_table;
pub mod stat;
+pub mod tlb;
pub mod vm_space;
use core::{fmt::Debug, ops::Range};
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -734,26 +734,93 @@ where
None
}
- pub fn preempt_guard(&self) -> &DisabledPreemptGuard {
- &self.0.preempt_guard
- }
-
- /// Consumes itself and leak the root guard for the caller if it locked the root level.
+ /// Copies the mapping from the given cursor to the current cursor.
///
- /// It is useful when the caller wants to keep the root guard while the cursor should be dropped.
- pub(super) fn leak_root_guard(mut self) -> Option<PageTableNode<E, C>> {
- if self.0.guard_level != C::NR_LEVELS {
- return None;
- }
+ /// All the mappings in the current cursor's range must be empty. The
+ /// function allows the source cursor to operate on the mapping before
+ /// the copy happens. So it is equivalent to protect then duplicate.
+ /// Only the mapping is copied, the mapped pages are not copied.
+ ///
+ /// It can only copy tracked mappings since we consider the untracked
+ /// mappings not useful to be copied.
+ ///
+ /// After the operation, both cursors will advance by the specified length.
+ ///
+ /// # Safety
+ ///
+ /// The caller should ensure that
+ /// - the range being copied with the operation does not affect kernel's
+ /// memory safety.
+ /// - both of the cursors are in tracked mappings.
+ ///
+ /// # Panics
+ ///
+ /// This function will panic if:
+ /// - either one of the range to be copied is out of the range where any
+ /// of the cursor is required to operate;
+ /// - either one of the specified virtual address ranges only covers a
+ /// part of a page.
+ /// - the current cursor's range contains mapped pages.
+ pub unsafe fn copy_from(
+ &mut self,
+ src: &mut Self,
+ len: usize,
+ op: &mut impl FnMut(&mut PageProperty),
+ ) {
+ assert!(len % page_size::<C>(1) == 0);
+ let this_end = self.0.va + len;
+ assert!(this_end <= self.0.barrier_va.end);
+ let src_end = src.0.va + len;
+ assert!(src_end <= src.0.barrier_va.end);
- while self.0.level < C::NR_LEVELS {
- self.0.level_up();
- }
+ while self.0.va < this_end && src.0.va < src_end {
+ let cur_pte = src.0.read_cur_pte();
+ if !cur_pte.is_present() {
+ src.0.move_forward();
+ continue;
+ }
+
+ // Go down if it's not a last node.
+ if !cur_pte.is_last(src.0.level) {
+ src.0.level_down();
+
+ // We have got down a level. If there's no mapped PTEs in
+ // the current node, we can go back and skip to save time.
+ if src.0.guards[(src.0.level - 1) as usize]
+ .as_ref()
+ .unwrap()
+ .nr_children()
+ == 0
+ {
+ src.0.level_up();
+ src.0.move_forward();
+ }
+
+ continue;
+ }
- self.0.guards[(C::NR_LEVELS - 1) as usize].take()
+ // Do protection.
+ let mut pte_prop = cur_pte.prop();
+ op(&mut pte_prop);
+
+ let idx = src.0.cur_idx();
+ src.cur_node_mut().protect(idx, pte_prop);
- // Ok to drop the cursor here because we ensure not to access the page table if the current
- // level is the root level when running the dropping method.
+ // Do copy.
+ let child = src.cur_node_mut().child(idx, true);
+ let Child::<E, C>::Page(page, prop) = child else {
+ panic!("Unexpected child for source mapping: {:#?}", child);
+ };
+ self.jump(src.0.va).unwrap();
+ let mapped_page_size = page.size();
+ let original = self.map(page, prop);
+ debug_assert!(original.is_none());
+
+ // Only move the source cursor forward since `Self::map` will do it.
+ // This assertion is to ensure that they move by the same length.
+ debug_assert_eq!(mapped_page_size, page_size::<C>(src.0.level));
+ src.0.move_forward();
+ }
}
/// Goes down a level assuming the current slot is absent.
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -734,26 +734,93 @@ where
None
}
- pub fn preempt_guard(&self) -> &DisabledPreemptGuard {
- &self.0.preempt_guard
- }
-
- /// Consumes itself and leak the root guard for the caller if it locked the root level.
+ /// Copies the mapping from the given cursor to the current cursor.
///
- /// It is useful when the caller wants to keep the root guard while the cursor should be dropped.
- pub(super) fn leak_root_guard(mut self) -> Option<PageTableNode<E, C>> {
- if self.0.guard_level != C::NR_LEVELS {
- return None;
- }
+ /// All the mappings in the current cursor's range must be empty. The
+ /// function allows the source cursor to operate on the mapping before
+ /// the copy happens. So it is equivalent to protect then duplicate.
+ /// Only the mapping is copied, the mapped pages are not copied.
+ ///
+ /// It can only copy tracked mappings since we consider the untracked
+ /// mappings not useful to be copied.
+ ///
+ /// After the operation, both cursors will advance by the specified length.
+ ///
+ /// # Safety
+ ///
+ /// The caller should ensure that
+ /// - the range being copied with the operation does not affect kernel's
+ /// memory safety.
+ /// - both of the cursors are in tracked mappings.
+ ///
+ /// # Panics
+ ///
+ /// This function will panic if:
+ /// - either one of the range to be copied is out of the range where any
+ /// of the cursor is required to operate;
+ /// - either one of the specified virtual address ranges only covers a
+ /// part of a page.
+ /// - the current cursor's range contains mapped pages.
+ pub unsafe fn copy_from(
+ &mut self,
+ src: &mut Self,
+ len: usize,
+ op: &mut impl FnMut(&mut PageProperty),
+ ) {
+ assert!(len % page_size::<C>(1) == 0);
+ let this_end = self.0.va + len;
+ assert!(this_end <= self.0.barrier_va.end);
+ let src_end = src.0.va + len;
+ assert!(src_end <= src.0.barrier_va.end);
- while self.0.level < C::NR_LEVELS {
- self.0.level_up();
- }
+ while self.0.va < this_end && src.0.va < src_end {
+ let cur_pte = src.0.read_cur_pte();
+ if !cur_pte.is_present() {
+ src.0.move_forward();
+ continue;
+ }
+
+ // Go down if it's not a last node.
+ if !cur_pte.is_last(src.0.level) {
+ src.0.level_down();
+
+ // We have got down a level. If there's no mapped PTEs in
+ // the current node, we can go back and skip to save time.
+ if src.0.guards[(src.0.level - 1) as usize]
+ .as_ref()
+ .unwrap()
+ .nr_children()
+ == 0
+ {
+ src.0.level_up();
+ src.0.move_forward();
+ }
+
+ continue;
+ }
- self.0.guards[(C::NR_LEVELS - 1) as usize].take()
+ // Do protection.
+ let mut pte_prop = cur_pte.prop();
+ op(&mut pte_prop);
+
+ let idx = src.0.cur_idx();
+ src.cur_node_mut().protect(idx, pte_prop);
- // Ok to drop the cursor here because we ensure not to access the page table if the current
- // level is the root level when running the dropping method.
+ // Do copy.
+ let child = src.cur_node_mut().child(idx, true);
+ let Child::<E, C>::Page(page, prop) = child else {
+ panic!("Unexpected child for source mapping: {:#?}", child);
+ };
+ self.jump(src.0.va).unwrap();
+ let mapped_page_size = page.size();
+ let original = self.map(page, prop);
+ debug_assert!(original.is_none());
+
+ // Only move the source cursor forward since `Self::map` will do it.
+ // This assertion is to ensure that they move by the same length.
+ debug_assert_eq!(mapped_page_size, page_size::<C>(src.0.level));
+ src.0.move_forward();
+ }
}
/// Goes down a level assuming the current slot is absent.
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -92,53 +92,29 @@ impl PageTable<UserMode> {
self.root.activate();
}
}
-
- /// Create a cloned new page table.
- ///
- /// This method takes a mutable cursor to the old page table that locks the
- /// entire virtual address range. The caller may implement the copy-on-write
- /// mechanism by first protecting the old page table and then clone it using
- /// this method.
- ///
- /// TODO: We may consider making the page table itself copy-on-write.
- pub fn clone_with(
- &self,
- cursor: CursorMut<'_, UserMode, PageTableEntry, PagingConsts>,
- ) -> Self {
- let root_node = cursor.leak_root_guard().unwrap();
-
- const NR_PTES_PER_NODE: usize = nr_subpage_per_huge::<PagingConsts>();
- let new_root_node = unsafe {
- root_node.make_copy(
- 0..NR_PTES_PER_NODE / 2,
- NR_PTES_PER_NODE / 2..NR_PTES_PER_NODE,
- )
- };
-
- PageTable::<UserMode> {
- root: new_root_node.into_raw(),
- _phantom: PhantomData,
- }
- }
}
impl PageTable<KernelMode> {
/// Create a new user page table.
///
- /// This should be the only way to create the first user page table, that is
- /// to fork the kernel page table with all the kernel mappings shared.
- ///
- /// Then, one can use a user page table to call [`fork_copy_on_write`], creating
- /// other child page tables.
+ /// This should be the only way to create the user page table, that is to
+ /// duplicate the kernel page table with all the kernel mappings shared.
pub fn create_user_page_table(&self) -> PageTable<UserMode> {
let root_node = self.root.clone_shallow().lock();
+ let mut new_node = PageTableNode::alloc(PagingConsts::NR_LEVELS);
+ // Make a shallow copy of the root node in the kernel space range.
+ // The user space range is not copied.
const NR_PTES_PER_NODE: usize = nr_subpage_per_huge::<PagingConsts>();
- let new_root_node =
- unsafe { root_node.make_copy(0..0, NR_PTES_PER_NODE / 2..NR_PTES_PER_NODE) };
+ for i in NR_PTES_PER_NODE / 2..NR_PTES_PER_NODE {
+ let child = root_node.child(i, /* meaningless */ true);
+ if !child.is_none() {
+ let _ = new_node.replace_child(i, child, /* meaningless */ true);
+ }
+ }
PageTable::<UserMode> {
- root: new_root_node.into_raw(),
+ root: new_node.into_raw(),
_phantom: PhantomData,
}
}
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -92,53 +92,29 @@ impl PageTable<UserMode> {
self.root.activate();
}
}
-
- /// Create a cloned new page table.
- ///
- /// This method takes a mutable cursor to the old page table that locks the
- /// entire virtual address range. The caller may implement the copy-on-write
- /// mechanism by first protecting the old page table and then clone it using
- /// this method.
- ///
- /// TODO: We may consider making the page table itself copy-on-write.
- pub fn clone_with(
- &self,
- cursor: CursorMut<'_, UserMode, PageTableEntry, PagingConsts>,
- ) -> Self {
- let root_node = cursor.leak_root_guard().unwrap();
-
- const NR_PTES_PER_NODE: usize = nr_subpage_per_huge::<PagingConsts>();
- let new_root_node = unsafe {
- root_node.make_copy(
- 0..NR_PTES_PER_NODE / 2,
- NR_PTES_PER_NODE / 2..NR_PTES_PER_NODE,
- )
- };
-
- PageTable::<UserMode> {
- root: new_root_node.into_raw(),
- _phantom: PhantomData,
- }
- }
}
impl PageTable<KernelMode> {
/// Create a new user page table.
///
- /// This should be the only way to create the first user page table, that is
- /// to fork the kernel page table with all the kernel mappings shared.
- ///
- /// Then, one can use a user page table to call [`fork_copy_on_write`], creating
- /// other child page tables.
+ /// This should be the only way to create the user page table, that is to
+ /// duplicate the kernel page table with all the kernel mappings shared.
pub fn create_user_page_table(&self) -> PageTable<UserMode> {
let root_node = self.root.clone_shallow().lock();
+ let mut new_node = PageTableNode::alloc(PagingConsts::NR_LEVELS);
+ // Make a shallow copy of the root node in the kernel space range.
+ // The user space range is not copied.
const NR_PTES_PER_NODE: usize = nr_subpage_per_huge::<PagingConsts>();
- let new_root_node =
- unsafe { root_node.make_copy(0..0, NR_PTES_PER_NODE / 2..NR_PTES_PER_NODE) };
+ for i in NR_PTES_PER_NODE / 2..NR_PTES_PER_NODE {
+ let child = root_node.child(i, /* meaningless */ true);
+ if !child.is_none() {
+ let _ = new_node.replace_child(i, child, /* meaningless */ true);
+ }
+ }
PageTable::<UserMode> {
- root: new_root_node.into_raw(),
+ root: new_node.into_raw(),
_phantom: PhantomData,
}
}
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -25,9 +25,7 @@
//! the initialization of the entity that the PTE points to. This is taken care in this module.
//!
-use core::{
- fmt, marker::PhantomData, mem::ManuallyDrop, ops::Range, panic, sync::atomic::Ordering,
-};
+use core::{fmt, marker::PhantomData, mem::ManuallyDrop, panic, sync::atomic::Ordering};
use super::{nr_subpage_per_huge, page_size, PageTableEntryTrait};
use crate::{
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -25,9 +25,7 @@
//! the initialization of the entity that the PTE points to. This is taken care in this module.
//!
-use core::{
- fmt, marker::PhantomData, mem::ManuallyDrop, ops::Range, panic, sync::atomic::Ordering,
-};
+use core::{fmt, marker::PhantomData, mem::ManuallyDrop, panic, sync::atomic::Ordering};
use super::{nr_subpage_per_huge, page_size, PageTableEntryTrait};
use crate::{
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -374,74 +372,6 @@ where
}
}
- /// Makes a copy of the page table node.
- ///
- /// This function allows you to control about the way to copy the children.
- /// For indexes in `deep`, the children are deep copied and this function will be recursively called.
- /// For indexes in `shallow`, the children are shallow copied as new references.
- ///
- /// You cannot shallow copy a child that is mapped to a page. Deep copying a page child will not
- /// copy the mapped page but will copy the handle to the page.
- ///
- /// You cannot either deep copy or shallow copy a child that is mapped to an untracked page.
- ///
- /// The ranges must be disjoint.
- pub(super) unsafe fn make_copy(&self, deep: Range<usize>, shallow: Range<usize>) -> Self {
- debug_assert!(deep.end <= nr_subpage_per_huge::<C>());
- debug_assert!(shallow.end <= nr_subpage_per_huge::<C>());
- debug_assert!(deep.end <= shallow.start || deep.start >= shallow.end);
-
- let mut new_pt = Self::alloc(self.level());
- let mut copied_child_count = self.nr_children();
- for i in deep {
- if copied_child_count == 0 {
- return new_pt;
- }
- match self.child(i, true) {
- Child::PageTable(pt) => {
- let guard = pt.clone_shallow().lock();
- let new_child = guard.make_copy(0..nr_subpage_per_huge::<C>(), 0..0);
- let old = new_pt.replace_child(i, Child::PageTable(new_child.into_raw()), true);
- debug_assert!(old.is_none());
- copied_child_count -= 1;
- }
- Child::Page(page, prop) => {
- let old = new_pt.replace_child(i, Child::Page(page.clone(), prop), true);
- debug_assert!(old.is_none());
- copied_child_count -= 1;
- }
- Child::None => {}
- Child::Untracked(_, _) => {
- unreachable!();
- }
- }
- }
-
- for i in shallow {
- if copied_child_count == 0 {
- return new_pt;
- }
- debug_assert_eq!(self.level(), C::NR_LEVELS);
- match self.child(i, /*meaningless*/ true) {
- Child::PageTable(pt) => {
- let old = new_pt.replace_child(
- i,
- Child::PageTable(pt.clone_shallow()),
- /*meaningless*/ true,
- );
- debug_assert!(old.is_none());
- copied_child_count -= 1;
- }
- Child::None => {}
- Child::Page(_, _) | Child::Untracked(_, _) => {
- unreachable!();
- }
- }
- }
-
- new_pt
- }
-
/// Splits the untracked huge page mapped at `idx` to smaller pages.
pub(super) fn split_untracked_huge(&mut self, idx: usize) {
// These should be ensured by the cursor.
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -374,74 +372,6 @@ where
}
}
- /// Makes a copy of the page table node.
- ///
- /// This function allows you to control about the way to copy the children.
- /// For indexes in `deep`, the children are deep copied and this function will be recursively called.
- /// For indexes in `shallow`, the children are shallow copied as new references.
- ///
- /// You cannot shallow copy a child that is mapped to a page. Deep copying a page child will not
- /// copy the mapped page but will copy the handle to the page.
- ///
- /// You cannot either deep copy or shallow copy a child that is mapped to an untracked page.
- ///
- /// The ranges must be disjoint.
- pub(super) unsafe fn make_copy(&self, deep: Range<usize>, shallow: Range<usize>) -> Self {
- debug_assert!(deep.end <= nr_subpage_per_huge::<C>());
- debug_assert!(shallow.end <= nr_subpage_per_huge::<C>());
- debug_assert!(deep.end <= shallow.start || deep.start >= shallow.end);
-
- let mut new_pt = Self::alloc(self.level());
- let mut copied_child_count = self.nr_children();
- for i in deep {
- if copied_child_count == 0 {
- return new_pt;
- }
- match self.child(i, true) {
- Child::PageTable(pt) => {
- let guard = pt.clone_shallow().lock();
- let new_child = guard.make_copy(0..nr_subpage_per_huge::<C>(), 0..0);
- let old = new_pt.replace_child(i, Child::PageTable(new_child.into_raw()), true);
- debug_assert!(old.is_none());
- copied_child_count -= 1;
- }
- Child::Page(page, prop) => {
- let old = new_pt.replace_child(i, Child::Page(page.clone(), prop), true);
- debug_assert!(old.is_none());
- copied_child_count -= 1;
- }
- Child::None => {}
- Child::Untracked(_, _) => {
- unreachable!();
- }
- }
- }
-
- for i in shallow {
- if copied_child_count == 0 {
- return new_pt;
- }
- debug_assert_eq!(self.level(), C::NR_LEVELS);
- match self.child(i, /*meaningless*/ true) {
- Child::PageTable(pt) => {
- let old = new_pt.replace_child(
- i,
- Child::PageTable(pt.clone_shallow()),
- /*meaningless*/ true,
- );
- debug_assert!(old.is_none());
- copied_child_count -= 1;
- }
- Child::None => {}
- Child::Page(_, _) | Child::Untracked(_, _) => {
- unreachable!();
- }
- }
- }
-
- new_pt
- }
-
/// Splits the untracked huge page mapped at `idx` to smaller pages.
pub(super) fn split_untracked_huge(&mut self, idx: usize) {
// These should be ensured by the cursor.
diff --git a/ostd/src/mm/page_table/test.rs b/ostd/src/mm/page_table/test.rs
--- a/ostd/src/mm/page_table/test.rs
+++ b/ostd/src/mm/page_table/test.rs
@@ -81,6 +81,10 @@ fn test_untracked_map_unmap() {
#[ktest]
fn test_user_copy_on_write() {
+ fn prot_op(prop: &mut PageProperty) {
+ prop.flags -= PageFlags::W;
+ }
+
let pt = PageTable::<UserMode>::empty();
let from = PAGE_SIZE..PAGE_SIZE * 2;
let page = allocator::alloc_single(FrameMeta::default()).unwrap();
diff --git a/ostd/src/mm/page_table/test.rs b/ostd/src/mm/page_table/test.rs
--- a/ostd/src/mm/page_table/test.rs
+++ b/ostd/src/mm/page_table/test.rs
@@ -96,7 +100,14 @@ fn test_user_copy_on_write() {
unsafe { pt.cursor_mut(&from).unwrap().map(page.clone().into(), prop) };
assert_eq!(pt.query(from.start + 10).unwrap().0, start_paddr + 10);
- let child_pt = pt.clone_with(pt.cursor_mut(&(0..MAX_USERSPACE_VADDR)).unwrap());
+ let child_pt = {
+ let child_pt = PageTable::<UserMode>::empty();
+ let range = 0..MAX_USERSPACE_VADDR;
+ let mut child_cursor = child_pt.cursor_mut(&range).unwrap();
+ let mut parent_cursor = pt.cursor_mut(&range).unwrap();
+ unsafe { child_cursor.copy_from(&mut parent_cursor, range.len(), &mut prot_op) };
+ child_pt
+ };
assert_eq!(pt.query(from.start + 10).unwrap().0, start_paddr + 10);
assert_eq!(child_pt.query(from.start + 10).unwrap().0, start_paddr + 10);
assert!(matches!(
diff --git a/ostd/src/mm/page_table/test.rs b/ostd/src/mm/page_table/test.rs
--- a/ostd/src/mm/page_table/test.rs
+++ b/ostd/src/mm/page_table/test.rs
@@ -106,7 +117,14 @@ fn test_user_copy_on_write() {
assert!(pt.query(from.start + 10).is_none());
assert_eq!(child_pt.query(from.start + 10).unwrap().0, start_paddr + 10);
- let sibling_pt = pt.clone_with(pt.cursor_mut(&(0..MAX_USERSPACE_VADDR)).unwrap());
+ let sibling_pt = {
+ let sibling_pt = PageTable::<UserMode>::empty();
+ let range = 0..MAX_USERSPACE_VADDR;
+ let mut sibling_cursor = sibling_pt.cursor_mut(&range).unwrap();
+ let mut parent_cursor = pt.cursor_mut(&range).unwrap();
+ unsafe { sibling_cursor.copy_from(&mut parent_cursor, range.len(), &mut prot_op) };
+ sibling_pt
+ };
assert!(sibling_pt.query(from.start + 10).is_none());
assert_eq!(child_pt.query(from.start + 10).unwrap().0, start_paddr + 10);
drop(pt);
diff --git /dev/null b/ostd/src/mm/tlb.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/mm/tlb.rs
@@ -0,0 +1,222 @@
+// SPDX-License-Identifier: MPL-2.0
+
+//! TLB flush operations.
+
+use alloc::vec::Vec;
+use core::ops::Range;
+
+use super::{page::DynPage, Vaddr, PAGE_SIZE};
+use crate::{
+ cpu::{CpuSet, PinCurrentCpu},
+ cpu_local,
+ sync::SpinLock,
+ task::disable_preempt,
+};
+
+/// A TLB flusher that is aware of which CPUs are needed to be flushed.
+///
+/// The flusher needs to stick to the current CPU.
+pub struct TlbFlusher<G: PinCurrentCpu> {
+ target_cpus: CpuSet,
+ // Better to store them here since loading and counting them from the CPUs
+ // list brings non-trivial overhead.
+ need_remote_flush: bool,
+ need_self_flush: bool,
+ _pin_current: G,
+}
+
+impl<G: PinCurrentCpu> TlbFlusher<G> {
+ /// Creates a new TLB flusher with the specified CPUs to be flushed.
+ ///
+ /// The flusher needs to stick to the current CPU. So please provide a
+ /// guard that implements [`PinCurrentCpu`].
+ pub fn new(target_cpus: CpuSet, pin_current_guard: G) -> Self {
+ let current_cpu = pin_current_guard.current_cpu();
+
+ let mut need_self_flush = false;
+ let mut need_remote_flush = false;
+
+ for cpu in target_cpus.iter() {
+ if cpu == current_cpu {
+ need_self_flush = true;
+ } else {
+ need_remote_flush = true;
+ }
+ }
+ Self {
+ target_cpus,
+ need_remote_flush,
+ need_self_flush,
+ _pin_current: pin_current_guard,
+ }
+ }
+
+ /// Issues a pending TLB flush request.
+ ///
+ /// On SMP systems, the notification is sent to all the relevant CPUs only
+ /// when [`Self::dispatch_tlb_flush`] is called.
+ pub fn issue_tlb_flush(&self, op: TlbFlushOp) {
+ self.issue_tlb_flush_(op, None);
+ }
+
+ /// Dispatches all the pending TLB flush requests.
+ ///
+ /// The pending requests are issued by [`Self::issue_tlb_flush`].
+ pub fn dispatch_tlb_flush(&self) {
+ if !self.need_remote_flush {
+ return;
+ }
+
+ crate::smp::inter_processor_call(&self.target_cpus, do_remote_flush);
+ }
+
+ /// Issues a TLB flush request that must happen before dropping the page.
+ ///
+ /// If we need to remove a mapped page from the page table, we can only
+ /// recycle the page after all the relevant TLB entries in all CPUs are
+ /// flushed. Otherwise if the page is recycled for other purposes, the user
+ /// space program can still access the page through the TLB entries. This
+ /// method is designed to be used in such cases.
+ pub fn issue_tlb_flush_with(&self, op: TlbFlushOp, drop_after_flush: DynPage) {
+ self.issue_tlb_flush_(op, Some(drop_after_flush));
+ }
+
+ /// Whether the TLB flusher needs to flush the TLB entries on other CPUs.
+ pub fn need_remote_flush(&self) -> bool {
+ self.need_remote_flush
+ }
+
+ /// Whether the TLB flusher needs to flush the TLB entries on the current CPU.
+ pub fn need_self_flush(&self) -> bool {
+ self.need_self_flush
+ }
+
+ fn issue_tlb_flush_(&self, op: TlbFlushOp, drop_after_flush: Option<DynPage>) {
+ let op = op.optimize_for_large_range();
+
+ // Fast path for single CPU cases.
+ if !self.need_remote_flush {
+ if self.need_self_flush {
+ op.perform_on_current();
+ }
+ return;
+ }
+
+ // Slow path for multi-CPU cases.
+ for cpu in self.target_cpus.iter() {
+ let mut op_queue = FLUSH_OPS.get_on_cpu(cpu).lock();
+ if let Some(drop_after_flush) = drop_after_flush.clone() {
+ PAGE_KEEPER.get_on_cpu(cpu).lock().push(drop_after_flush);
+ }
+ op_queue.push(op.clone());
+ }
+ }
+}
+
+/// The operation to flush TLB entries.
+#[derive(Debug, Clone)]
+pub enum TlbFlushOp {
+ /// Flush all TLB entries except for the global entries.
+ All,
+ /// Flush the TLB entry for the specified virtual address.
+ Address(Vaddr),
+ /// Flush the TLB entries for the specified virtual address range.
+ Range(Range<Vaddr>),
+}
+
+impl TlbFlushOp {
+ /// Performs the TLB flush operation on the current CPU.
+ pub fn perform_on_current(&self) {
+ use crate::arch::mm::{
+ tlb_flush_addr, tlb_flush_addr_range, tlb_flush_all_excluding_global,
+ };
+ match self {
+ TlbFlushOp::All => tlb_flush_all_excluding_global(),
+ TlbFlushOp::Address(addr) => tlb_flush_addr(*addr),
+ TlbFlushOp::Range(range) => tlb_flush_addr_range(range),
+ }
+ }
+
+ fn optimize_for_large_range(self) -> Self {
+ match self {
+ TlbFlushOp::Range(range) => {
+ if range.len() > FLUSH_ALL_RANGE_THRESHOLD {
+ TlbFlushOp::All
+ } else {
+ TlbFlushOp::Range(range)
+ }
+ }
+ _ => self,
+ }
+ }
+}
+
+// The queues of pending requests on each CPU.
+//
+// Lock ordering: lock FLUSH_OPS before PAGE_KEEPER.
+cpu_local! {
+ static FLUSH_OPS: SpinLock<OpsStack> = SpinLock::new(OpsStack::new());
+ static PAGE_KEEPER: SpinLock<Vec<DynPage>> = SpinLock::new(Vec::new());
+}
+
+fn do_remote_flush() {
+ let preempt_guard = disable_preempt();
+ let current_cpu = preempt_guard.current_cpu();
+
+ let mut op_queue = FLUSH_OPS.get_on_cpu(current_cpu).lock();
+ op_queue.flush_all();
+ PAGE_KEEPER.get_on_cpu(current_cpu).lock().clear();
+}
+
+/// If a TLB flushing request exceeds this threshold, we flush all.
+pub(crate) const FLUSH_ALL_RANGE_THRESHOLD: usize = 32 * PAGE_SIZE;
+
+/// If the number of pending requests exceeds this threshold, we flush all the
+/// TLB entries instead of flushing them one by one.
+const FLUSH_ALL_OPS_THRESHOLD: usize = 32;
+
+struct OpsStack {
+ ops: [Option<TlbFlushOp>; FLUSH_ALL_OPS_THRESHOLD],
+ need_flush_all: bool,
+ size: usize,
+}
+
+impl OpsStack {
+ const fn new() -> Self {
+ const ARRAY_REPEAT_VALUE: Option<TlbFlushOp> = None;
+ Self {
+ ops: [ARRAY_REPEAT_VALUE; FLUSH_ALL_OPS_THRESHOLD],
+ need_flush_all: false,
+ size: 0,
+ }
+ }
+
+ fn push(&mut self, op: TlbFlushOp) {
+ if self.need_flush_all {
+ return;
+ }
+
+ if self.size < FLUSH_ALL_OPS_THRESHOLD {
+ self.ops[self.size] = Some(op);
+ self.size += 1;
+ } else {
+ self.need_flush_all = true;
+ self.size = 0;
+ }
+ }
+
+ fn flush_all(&mut self) {
+ if self.need_flush_all {
+ crate::arch::mm::tlb_flush_all_excluding_global();
+ self.need_flush_all = false;
+ } else {
+ for i in 0..self.size {
+ if let Some(op) = &self.ops[i] {
+ op.perform_on_current();
+ }
+ }
+ }
+
+ self.size = 0;
+ }
+}
diff --git /dev/null b/ostd/src/mm/tlb.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/mm/tlb.rs
@@ -0,0 +1,222 @@
+// SPDX-License-Identifier: MPL-2.0
+
+//! TLB flush operations.
+
+use alloc::vec::Vec;
+use core::ops::Range;
+
+use super::{page::DynPage, Vaddr, PAGE_SIZE};
+use crate::{
+ cpu::{CpuSet, PinCurrentCpu},
+ cpu_local,
+ sync::SpinLock,
+ task::disable_preempt,
+};
+
+/// A TLB flusher that is aware of which CPUs are needed to be flushed.
+///
+/// The flusher needs to stick to the current CPU.
+pub struct TlbFlusher<G: PinCurrentCpu> {
+ target_cpus: CpuSet,
+ // Better to store them here since loading and counting them from the CPUs
+ // list brings non-trivial overhead.
+ need_remote_flush: bool,
+ need_self_flush: bool,
+ _pin_current: G,
+}
+
+impl<G: PinCurrentCpu> TlbFlusher<G> {
+ /// Creates a new TLB flusher with the specified CPUs to be flushed.
+ ///
+ /// The flusher needs to stick to the current CPU. So please provide a
+ /// guard that implements [`PinCurrentCpu`].
+ pub fn new(target_cpus: CpuSet, pin_current_guard: G) -> Self {
+ let current_cpu = pin_current_guard.current_cpu();
+
+ let mut need_self_flush = false;
+ let mut need_remote_flush = false;
+
+ for cpu in target_cpus.iter() {
+ if cpu == current_cpu {
+ need_self_flush = true;
+ } else {
+ need_remote_flush = true;
+ }
+ }
+ Self {
+ target_cpus,
+ need_remote_flush,
+ need_self_flush,
+ _pin_current: pin_current_guard,
+ }
+ }
+
+ /// Issues a pending TLB flush request.
+ ///
+ /// On SMP systems, the notification is sent to all the relevant CPUs only
+ /// when [`Self::dispatch_tlb_flush`] is called.
+ pub fn issue_tlb_flush(&self, op: TlbFlushOp) {
+ self.issue_tlb_flush_(op, None);
+ }
+
+ /// Dispatches all the pending TLB flush requests.
+ ///
+ /// The pending requests are issued by [`Self::issue_tlb_flush`].
+ pub fn dispatch_tlb_flush(&self) {
+ if !self.need_remote_flush {
+ return;
+ }
+
+ crate::smp::inter_processor_call(&self.target_cpus, do_remote_flush);
+ }
+
+ /// Issues a TLB flush request that must happen before dropping the page.
+ ///
+ /// If we need to remove a mapped page from the page table, we can only
+ /// recycle the page after all the relevant TLB entries in all CPUs are
+ /// flushed. Otherwise if the page is recycled for other purposes, the user
+ /// space program can still access the page through the TLB entries. This
+ /// method is designed to be used in such cases.
+ pub fn issue_tlb_flush_with(&self, op: TlbFlushOp, drop_after_flush: DynPage) {
+ self.issue_tlb_flush_(op, Some(drop_after_flush));
+ }
+
+ /// Whether the TLB flusher needs to flush the TLB entries on other CPUs.
+ pub fn need_remote_flush(&self) -> bool {
+ self.need_remote_flush
+ }
+
+ /// Whether the TLB flusher needs to flush the TLB entries on the current CPU.
+ pub fn need_self_flush(&self) -> bool {
+ self.need_self_flush
+ }
+
+ fn issue_tlb_flush_(&self, op: TlbFlushOp, drop_after_flush: Option<DynPage>) {
+ let op = op.optimize_for_large_range();
+
+ // Fast path for single CPU cases.
+ if !self.need_remote_flush {
+ if self.need_self_flush {
+ op.perform_on_current();
+ }
+ return;
+ }
+
+ // Slow path for multi-CPU cases.
+ for cpu in self.target_cpus.iter() {
+ let mut op_queue = FLUSH_OPS.get_on_cpu(cpu).lock();
+ if let Some(drop_after_flush) = drop_after_flush.clone() {
+ PAGE_KEEPER.get_on_cpu(cpu).lock().push(drop_after_flush);
+ }
+ op_queue.push(op.clone());
+ }
+ }
+}
+
+/// The operation to flush TLB entries.
+#[derive(Debug, Clone)]
+pub enum TlbFlushOp {
+ /// Flush all TLB entries except for the global entries.
+ All,
+ /// Flush the TLB entry for the specified virtual address.
+ Address(Vaddr),
+ /// Flush the TLB entries for the specified virtual address range.
+ Range(Range<Vaddr>),
+}
+
+impl TlbFlushOp {
+ /// Performs the TLB flush operation on the current CPU.
+ pub fn perform_on_current(&self) {
+ use crate::arch::mm::{
+ tlb_flush_addr, tlb_flush_addr_range, tlb_flush_all_excluding_global,
+ };
+ match self {
+ TlbFlushOp::All => tlb_flush_all_excluding_global(),
+ TlbFlushOp::Address(addr) => tlb_flush_addr(*addr),
+ TlbFlushOp::Range(range) => tlb_flush_addr_range(range),
+ }
+ }
+
+ fn optimize_for_large_range(self) -> Self {
+ match self {
+ TlbFlushOp::Range(range) => {
+ if range.len() > FLUSH_ALL_RANGE_THRESHOLD {
+ TlbFlushOp::All
+ } else {
+ TlbFlushOp::Range(range)
+ }
+ }
+ _ => self,
+ }
+ }
+}
+
+// The queues of pending requests on each CPU.
+//
+// Lock ordering: lock FLUSH_OPS before PAGE_KEEPER.
+cpu_local! {
+ static FLUSH_OPS: SpinLock<OpsStack> = SpinLock::new(OpsStack::new());
+ static PAGE_KEEPER: SpinLock<Vec<DynPage>> = SpinLock::new(Vec::new());
+}
+
+fn do_remote_flush() {
+ let preempt_guard = disable_preempt();
+ let current_cpu = preempt_guard.current_cpu();
+
+ let mut op_queue = FLUSH_OPS.get_on_cpu(current_cpu).lock();
+ op_queue.flush_all();
+ PAGE_KEEPER.get_on_cpu(current_cpu).lock().clear();
+}
+
+/// If a TLB flushing request exceeds this threshold, we flush all.
+pub(crate) const FLUSH_ALL_RANGE_THRESHOLD: usize = 32 * PAGE_SIZE;
+
+/// If the number of pending requests exceeds this threshold, we flush all the
+/// TLB entries instead of flushing them one by one.
+const FLUSH_ALL_OPS_THRESHOLD: usize = 32;
+
+struct OpsStack {
+ ops: [Option<TlbFlushOp>; FLUSH_ALL_OPS_THRESHOLD],
+ need_flush_all: bool,
+ size: usize,
+}
+
+impl OpsStack {
+ const fn new() -> Self {
+ const ARRAY_REPEAT_VALUE: Option<TlbFlushOp> = None;
+ Self {
+ ops: [ARRAY_REPEAT_VALUE; FLUSH_ALL_OPS_THRESHOLD],
+ need_flush_all: false,
+ size: 0,
+ }
+ }
+
+ fn push(&mut self, op: TlbFlushOp) {
+ if self.need_flush_all {
+ return;
+ }
+
+ if self.size < FLUSH_ALL_OPS_THRESHOLD {
+ self.ops[self.size] = Some(op);
+ self.size += 1;
+ } else {
+ self.need_flush_all = true;
+ self.size = 0;
+ }
+ }
+
+ fn flush_all(&mut self) {
+ if self.need_flush_all {
+ crate::arch::mm::tlb_flush_all_excluding_global();
+ self.need_flush_all = false;
+ } else {
+ for i in 0..self.size {
+ if let Some(op) = &self.ops[i] {
+ op.perform_on_current();
+ }
+ }
+ }
+
+ self.size = 0;
+ }
+}
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -9,32 +9,25 @@
//! powerful concurrent accesses to the page table, and suffers from the same
//! validity concerns as described in [`super::page_table::cursor`].
-use alloc::collections::vec_deque::VecDeque;
use core::{
ops::Range,
sync::atomic::{AtomicPtr, Ordering},
};
-use spin::Once;
-
-use super::{
- io::Fallible,
- kspace::KERNEL_PAGE_TABLE,
- page::DynPage,
- page_table::{PageTable, UserMode},
- PageFlags, PageProperty, VmReader, VmWriter, PAGE_SIZE,
-};
use crate::{
arch::mm::{current_page_table_paddr, PageTableEntry, PagingConsts},
cpu::{num_cpus, CpuExceptionInfo, CpuSet, PinCurrentCpu},
cpu_local,
mm::{
- page_table::{self, PageTableItem},
- Frame, MAX_USERSPACE_VADDR,
+ io::Fallible,
+ kspace::KERNEL_PAGE_TABLE,
+ page_table::{self, PageTable, PageTableItem, UserMode},
+ tlb::{TlbFlushOp, TlbFlusher, FLUSH_ALL_RANGE_THRESHOLD},
+ Frame, PageProperty, VmReader, VmWriter, MAX_USERSPACE_VADDR,
},
prelude::*,
- sync::{RwLock, RwLockReadGuard, SpinLock},
- task::disable_preempt,
+ sync::{RwLock, RwLockReadGuard},
+ task::{disable_preempt, DisabledPreemptGuard},
Error,
};
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -9,32 +9,25 @@
//! powerful concurrent accesses to the page table, and suffers from the same
//! validity concerns as described in [`super::page_table::cursor`].
-use alloc::collections::vec_deque::VecDeque;
use core::{
ops::Range,
sync::atomic::{AtomicPtr, Ordering},
};
-use spin::Once;
-
-use super::{
- io::Fallible,
- kspace::KERNEL_PAGE_TABLE,
- page::DynPage,
- page_table::{PageTable, UserMode},
- PageFlags, PageProperty, VmReader, VmWriter, PAGE_SIZE,
-};
use crate::{
arch::mm::{current_page_table_paddr, PageTableEntry, PagingConsts},
cpu::{num_cpus, CpuExceptionInfo, CpuSet, PinCurrentCpu},
cpu_local,
mm::{
- page_table::{self, PageTableItem},
- Frame, MAX_USERSPACE_VADDR,
+ io::Fallible,
+ kspace::KERNEL_PAGE_TABLE,
+ page_table::{self, PageTable, PageTableItem, UserMode},
+ tlb::{TlbFlushOp, TlbFlusher, FLUSH_ALL_RANGE_THRESHOLD},
+ Frame, PageProperty, VmReader, VmWriter, MAX_USERSPACE_VADDR,
},
prelude::*,
- sync::{RwLock, RwLockReadGuard, SpinLock},
- task::disable_preempt,
+ sync::{RwLock, RwLockReadGuard},
+ task::{disable_preempt, DisabledPreemptGuard},
Error,
};
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -56,7 +49,7 @@ use crate::{
#[derive(Debug)]
pub struct VmSpace {
pt: PageTable<UserMode>,
- page_fault_handler: Once<fn(&VmSpace, &CpuExceptionInfo) -> core::result::Result<(), ()>>,
+ page_fault_handler: Option<fn(&VmSpace, &CpuExceptionInfo) -> core::result::Result<(), ()>>,
/// A CPU can only activate a `VmSpace` when no mutable cursors are alive.
/// Cursors hold read locks and activation require a write lock.
activation_lock: RwLock<()>,
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -56,7 +49,7 @@ use crate::{
#[derive(Debug)]
pub struct VmSpace {
pt: PageTable<UserMode>,
- page_fault_handler: Once<fn(&VmSpace, &CpuExceptionInfo) -> core::result::Result<(), ()>>,
+ page_fault_handler: Option<fn(&VmSpace, &CpuExceptionInfo) -> core::result::Result<(), ()>>,
/// A CPU can only activate a `VmSpace` when no mutable cursors are alive.
/// Cursors hold read locks and activation require a write lock.
activation_lock: RwLock<()>,
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -67,7 +60,7 @@ impl VmSpace {
pub fn new() -> Self {
Self {
pt: KERNEL_PAGE_TABLE.get().unwrap().create_user_page_table(),
- page_fault_handler: Once::new(),
+ page_fault_handler: None,
activation_lock: RwLock::new(()),
}
}
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -67,7 +60,7 @@ impl VmSpace {
pub fn new() -> Self {
Self {
pt: KERNEL_PAGE_TABLE.get().unwrap().create_user_page_table(),
- page_fault_handler: Once::new(),
+ page_fault_handler: None,
activation_lock: RwLock::new(()),
}
}
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -98,11 +91,7 @@ impl VmSpace {
Ok(self.pt.cursor_mut(va).map(|pt_cursor| {
let activation_lock = self.activation_lock.read();
- let cur_cpu = pt_cursor.preempt_guard().current_cpu();
-
let mut activated_cpus = CpuSet::new_empty();
- let mut need_self_flush = false;
- let mut need_remote_flush = false;
for cpu in 0..num_cpus() {
// The activation lock is held; other CPUs cannot activate this `VmSpace`.
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -98,11 +91,7 @@ impl VmSpace {
Ok(self.pt.cursor_mut(va).map(|pt_cursor| {
let activation_lock = self.activation_lock.read();
- let cur_cpu = pt_cursor.preempt_guard().current_cpu();
-
let mut activated_cpus = CpuSet::new_empty();
- let mut need_self_flush = false;
- let mut need_remote_flush = false;
for cpu in 0..num_cpus() {
// The activation lock is held; other CPUs cannot activate this `VmSpace`.
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -110,20 +99,13 @@ impl VmSpace {
ACTIVATED_VM_SPACE.get_on_cpu(cpu).load(Ordering::Relaxed) as *const VmSpace;
if ptr == self as *const VmSpace {
activated_cpus.add(cpu);
- if cpu == cur_cpu {
- need_self_flush = true;
- } else {
- need_remote_flush = true;
- }
}
}
CursorMut {
pt_cursor,
activation_lock,
- activated_cpus,
- need_remote_flush,
- need_self_flush,
+ flusher: TlbFlusher::new(activated_cpus, disable_preempt()),
}
})?)
}
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -110,20 +99,13 @@ impl VmSpace {
ACTIVATED_VM_SPACE.get_on_cpu(cpu).load(Ordering::Relaxed) as *const VmSpace;
if ptr == self as *const VmSpace {
activated_cpus.add(cpu);
- if cpu == cur_cpu {
- need_self_flush = true;
- } else {
- need_remote_flush = true;
- }
}
}
CursorMut {
pt_cursor,
activation_lock,
- activated_cpus,
- need_remote_flush,
- need_self_flush,
+ flusher: TlbFlusher::new(activated_cpus, disable_preempt()),
}
})?)
}
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -156,63 +138,18 @@ impl VmSpace {
&self,
info: &CpuExceptionInfo,
) -> core::result::Result<(), ()> {
- if let Some(func) = self.page_fault_handler.get() {
+ if let Some(func) = self.page_fault_handler {
return func(self, info);
}
Err(())
}
/// Registers the page fault handler in this `VmSpace`.
- ///
- /// The page fault handler of a `VmSpace` can only be initialized once.
- /// If it has been initialized before, calling this method will have no effect.
pub fn register_page_fault_handler(
- &self,
+ &mut self,
func: fn(&VmSpace, &CpuExceptionInfo) -> core::result::Result<(), ()>,
) {
- self.page_fault_handler.call_once(|| func);
- }
-
- /// Forks a new VM space with copy-on-write semantics.
- ///
- /// Both the parent and the newly forked VM space will be marked as
- /// read-only. And both the VM space will take handles to the same
- /// physical memory pages.
- pub fn fork_copy_on_write(&self) -> Self {
- // Protect the parent VM space as read-only.
- let end = MAX_USERSPACE_VADDR;
- let mut cursor = self.cursor_mut(&(0..end)).unwrap();
- let mut op = |prop: &mut PageProperty| {
- prop.flags -= PageFlags::W;
- };
-
- cursor.protect(end, &mut op);
-
- let page_fault_handler = {
- let new_handler = Once::new();
- if let Some(handler) = self.page_fault_handler.get() {
- new_handler.call_once(|| *handler);
- }
- new_handler
- };
-
- let CursorMut {
- pt_cursor,
- activation_lock,
- ..
- } = cursor;
-
- let new_pt = self.pt.clone_with(pt_cursor);
-
- // Release the activation lock after the page table is cloned to
- // prevent modification to the parent page table while cloning.
- drop(activation_lock);
-
- Self {
- pt: new_pt,
- page_fault_handler,
- activation_lock: RwLock::new(()),
- }
+ self.page_fault_handler = Some(func);
}
/// Creates a reader to read data from the user space of the current task.
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -156,63 +138,18 @@ impl VmSpace {
&self,
info: &CpuExceptionInfo,
) -> core::result::Result<(), ()> {
- if let Some(func) = self.page_fault_handler.get() {
+ if let Some(func) = self.page_fault_handler {
return func(self, info);
}
Err(())
}
/// Registers the page fault handler in this `VmSpace`.
- ///
- /// The page fault handler of a `VmSpace` can only be initialized once.
- /// If it has been initialized before, calling this method will have no effect.
pub fn register_page_fault_handler(
- &self,
+ &mut self,
func: fn(&VmSpace, &CpuExceptionInfo) -> core::result::Result<(), ()>,
) {
- self.page_fault_handler.call_once(|| func);
- }
-
- /// Forks a new VM space with copy-on-write semantics.
- ///
- /// Both the parent and the newly forked VM space will be marked as
- /// read-only. And both the VM space will take handles to the same
- /// physical memory pages.
- pub fn fork_copy_on_write(&self) -> Self {
- // Protect the parent VM space as read-only.
- let end = MAX_USERSPACE_VADDR;
- let mut cursor = self.cursor_mut(&(0..end)).unwrap();
- let mut op = |prop: &mut PageProperty| {
- prop.flags -= PageFlags::W;
- };
-
- cursor.protect(end, &mut op);
-
- let page_fault_handler = {
- let new_handler = Once::new();
- if let Some(handler) = self.page_fault_handler.get() {
- new_handler.call_once(|| *handler);
- }
- new_handler
- };
-
- let CursorMut {
- pt_cursor,
- activation_lock,
- ..
- } = cursor;
-
- let new_pt = self.pt.clone_with(pt_cursor);
-
- // Release the activation lock after the page table is cloned to
- // prevent modification to the parent page table while cloning.
- drop(activation_lock);
-
- Self {
- pt: new_pt,
- page_fault_handler,
- activation_lock: RwLock::new(()),
- }
+ self.page_fault_handler = Some(func);
}
/// Creates a reader to read data from the user space of the current task.
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -311,12 +248,9 @@ pub struct CursorMut<'a, 'b> {
pt_cursor: page_table::CursorMut<'a, UserMode, PageTableEntry, PagingConsts>,
#[allow(dead_code)]
activation_lock: RwLockReadGuard<'b, ()>,
- // Better to store them here since loading and counting them from the CPUs
- // list brings non-trivial overhead. We have a read lock so the stored set
- // is always a superset of actual activated CPUs.
- activated_cpus: CpuSet,
- need_remote_flush: bool,
- need_self_flush: bool,
+ // We have a read lock so the CPU set in the flusher is always a superset
+ // of actual activated CPUs.
+ flusher: TlbFlusher<DisabledPreemptGuard>,
}
impl CursorMut<'_, '_> {
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -311,12 +248,9 @@ pub struct CursorMut<'a, 'b> {
pt_cursor: page_table::CursorMut<'a, UserMode, PageTableEntry, PagingConsts>,
#[allow(dead_code)]
activation_lock: RwLockReadGuard<'b, ()>,
- // Better to store them here since loading and counting them from the CPUs
- // list brings non-trivial overhead. We have a read lock so the stored set
- // is always a superset of actual activated CPUs.
- activated_cpus: CpuSet,
- need_remote_flush: bool,
- need_self_flush: bool,
+ // We have a read lock so the CPU set in the flusher is always a superset
+ // of actual activated CPUs.
+ flusher: TlbFlusher<DisabledPreemptGuard>,
}
impl CursorMut<'_, '_> {
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -345,6 +279,11 @@ impl CursorMut<'_, '_> {
self.pt_cursor.virt_addr()
}
+ /// Get the dedicated TLB flusher for this cursor.
+ pub fn flusher(&self) -> &TlbFlusher<DisabledPreemptGuard> {
+ &self.flusher
+ }
+
/// Map a frame into the current slot.
///
/// This method will bring the cursor to the next slot after the modification.
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -345,6 +279,11 @@ impl CursorMut<'_, '_> {
self.pt_cursor.virt_addr()
}
+ /// Get the dedicated TLB flusher for this cursor.
+ pub fn flusher(&self) -> &TlbFlusher<DisabledPreemptGuard> {
+ &self.flusher
+ }
+
/// Map a frame into the current slot.
///
/// This method will bring the cursor to the next slot after the modification.
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -353,9 +292,10 @@ impl CursorMut<'_, '_> {
// SAFETY: It is safe to map untyped memory into the userspace.
let old = unsafe { self.pt_cursor.map(frame.into(), prop) };
- if old.is_some() {
- self.issue_tlb_flush(TlbFlushOp::Address(start_va), old);
- self.dispatch_tlb_flush();
+ if let Some(old) = old {
+ self.flusher
+ .issue_tlb_flush_with(TlbFlushOp::Address(start_va), old);
+ self.flusher.dispatch_tlb_flush();
}
}
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -353,9 +292,10 @@ impl CursorMut<'_, '_> {
// SAFETY: It is safe to map untyped memory into the userspace.
let old = unsafe { self.pt_cursor.map(frame.into(), prop) };
- if old.is_some() {
- self.issue_tlb_flush(TlbFlushOp::Address(start_va), old);
- self.dispatch_tlb_flush();
+ if let Some(old) = old {
+ self.flusher
+ .issue_tlb_flush_with(TlbFlushOp::Address(start_va), old);
+ self.flusher.dispatch_tlb_flush();
}
}
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -367,25 +307,31 @@ impl CursorMut<'_, '_> {
/// Already-absent mappings encountered by the cursor will be skipped. It
/// is valid to unmap a range that is not mapped.
///
+ /// It must issue and dispatch a TLB flush after the operation. Otherwise,
+ /// the memory safety will be compromised. Please call this function less
+ /// to avoid the overhead of TLB flush. Using a large `len` is wiser than
+ /// splitting the operation into multiple small ones.
+ ///
/// # Panics
///
/// This method will panic if `len` is not page-aligned.
pub fn unmap(&mut self, len: usize) {
assert!(len % super::PAGE_SIZE == 0);
let end_va = self.virt_addr() + len;
- let tlb_prefer_flush_all = len > TLB_FLUSH_ALL_THRESHOLD * PAGE_SIZE;
+ let tlb_prefer_flush_all = len > FLUSH_ALL_RANGE_THRESHOLD;
loop {
// SAFETY: It is safe to un-map memory in the userspace.
let result = unsafe { self.pt_cursor.take_next(end_va - self.virt_addr()) };
match result {
PageTableItem::Mapped { va, page, .. } => {
- if !self.need_remote_flush && tlb_prefer_flush_all {
+ if !self.flusher.need_remote_flush() && tlb_prefer_flush_all {
// Only on single-CPU cases we can drop the page immediately before flushing.
drop(page);
continue;
}
- self.issue_tlb_flush(TlbFlushOp::Address(va), Some(page));
+ self.flusher
+ .issue_tlb_flush_with(TlbFlushOp::Address(va), page);
}
PageTableItem::NotMapped { .. } => {
break;
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -367,25 +307,31 @@ impl CursorMut<'_, '_> {
/// Already-absent mappings encountered by the cursor will be skipped. It
/// is valid to unmap a range that is not mapped.
///
+ /// It must issue and dispatch a TLB flush after the operation. Otherwise,
+ /// the memory safety will be compromised. Please call this function less
+ /// to avoid the overhead of TLB flush. Using a large `len` is wiser than
+ /// splitting the operation into multiple small ones.
+ ///
/// # Panics
///
/// This method will panic if `len` is not page-aligned.
pub fn unmap(&mut self, len: usize) {
assert!(len % super::PAGE_SIZE == 0);
let end_va = self.virt_addr() + len;
- let tlb_prefer_flush_all = len > TLB_FLUSH_ALL_THRESHOLD * PAGE_SIZE;
+ let tlb_prefer_flush_all = len > FLUSH_ALL_RANGE_THRESHOLD;
loop {
// SAFETY: It is safe to un-map memory in the userspace.
let result = unsafe { self.pt_cursor.take_next(end_va - self.virt_addr()) };
match result {
PageTableItem::Mapped { va, page, .. } => {
- if !self.need_remote_flush && tlb_prefer_flush_all {
+ if !self.flusher.need_remote_flush() && tlb_prefer_flush_all {
// Only on single-CPU cases we can drop the page immediately before flushing.
drop(page);
continue;
}
- self.issue_tlb_flush(TlbFlushOp::Address(va), Some(page));
+ self.flusher
+ .issue_tlb_flush_with(TlbFlushOp::Address(va), page);
}
PageTableItem::NotMapped { .. } => {
break;
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -396,103 +342,79 @@ impl CursorMut<'_, '_> {
}
}
- if !self.need_remote_flush && tlb_prefer_flush_all {
- self.issue_tlb_flush(TlbFlushOp::All, None);
+ if !self.flusher.need_remote_flush() && tlb_prefer_flush_all {
+ self.flusher.issue_tlb_flush(TlbFlushOp::All);
}
- self.dispatch_tlb_flush();
+ self.flusher.dispatch_tlb_flush();
}
- /// Change the mapping property starting from the current slot.
+ /// Applies the operation to the next slot of mapping within the range.
///
- /// This method will bring the cursor forward by `len` bytes in the virtual
- /// address space after the modification.
+ /// The range to be found in is the current virtual address with the
+ /// provided length.
+ ///
+ /// The function stops and yields the actually protected range if it has
+ /// actually protected a page, no matter if the following pages are also
+ /// required to be protected.
+ ///
+ /// It also makes the cursor moves forward to the next page after the
+ /// protected one. If no mapped pages exist in the following range, the
+ /// cursor will stop at the end of the range and return [`None`].
///
- /// The way to change the property is specified by the closure `op`.
+ /// Note that it will **NOT** flush the TLB after the operation. Please
+ /// make the decision yourself on when and how to flush the TLB using
+ /// [`Self::flusher`].
///
/// # Panics
///
- /// This method will panic if `len` is not page-aligned.
- pub fn protect(&mut self, len: usize, mut op: impl FnMut(&mut PageProperty)) {
- assert!(len % super::PAGE_SIZE == 0);
- let end = self.virt_addr() + len;
- let tlb_prefer_flush_all = len > TLB_FLUSH_ALL_THRESHOLD * PAGE_SIZE;
-
+ /// This function will panic if:
+ /// - the range to be protected is out of the range where the cursor
+ /// is required to operate;
+ /// - the specified virtual address range only covers a part of a page.
+ pub fn protect_next(
+ &mut self,
+ len: usize,
+ mut op: impl FnMut(&mut PageProperty),
+ ) -> Option<Range<Vaddr>> {
// SAFETY: It is safe to protect memory in the userspace.
- while let Some(range) =
- unsafe { self.pt_cursor.protect_next(end - self.virt_addr(), &mut op) }
- {
- if !tlb_prefer_flush_all {
- self.issue_tlb_flush(TlbFlushOp::Range(range), None);
- }
- }
-
- if tlb_prefer_flush_all {
- self.issue_tlb_flush(TlbFlushOp::All, None);
- }
- self.dispatch_tlb_flush();
+ unsafe { self.pt_cursor.protect_next(len, &mut op) }
}
- fn issue_tlb_flush(&self, op: TlbFlushOp, drop_after_flush: Option<DynPage>) {
- let request = TlbFlushRequest {
- op,
- drop_after_flush,
- };
-
- // Fast path for single CPU cases.
- if !self.need_remote_flush {
- if self.need_self_flush {
- request.do_flush();
- }
- return;
- }
-
- // Slow path for multi-CPU cases.
- for cpu in self.activated_cpus.iter() {
- let mut queue = TLB_FLUSH_REQUESTS.get_on_cpu(cpu).lock();
- queue.push_back(request.clone());
- }
- }
-
- fn dispatch_tlb_flush(&self) {
- if !self.need_remote_flush {
- return;
- }
-
- fn do_remote_flush() {
- let preempt_guard = disable_preempt();
- let mut requests = TLB_FLUSH_REQUESTS
- .get_on_cpu(preempt_guard.current_cpu())
- .lock();
- if requests.len() > TLB_FLUSH_ALL_THRESHOLD {
- // TODO: in most cases, we need only to flush all the TLB entries
- // for an ASID if it is enabled.
- crate::arch::mm::tlb_flush_all_excluding_global();
- requests.clear();
- } else {
- while let Some(request) = requests.pop_front() {
- request.do_flush();
- if matches!(request.op, TlbFlushOp::All) {
- requests.clear();
- break;
- }
- }
- }
- }
-
- crate::smp::inter_processor_call(&self.activated_cpus.clone(), do_remote_flush);
+ /// Copies the mapping from the given cursor to the current cursor.
+ ///
+ /// All the mappings in the current cursor's range must be empty. The
+ /// function allows the source cursor to operate on the mapping before
+ /// the copy happens. So it is equivalent to protect then duplicate.
+ /// Only the mapping is copied, the mapped pages are not copied.
+ ///
+ /// After the operation, both cursors will advance by the specified length.
+ ///
+ /// Note that it will **NOT** flush the TLB after the operation. Please
+ /// make the decision yourself on when and how to flush the TLB using
+ /// the source's [`CursorMut::flusher`].
+ ///
+ /// # Panics
+ ///
+ /// This function will panic if:
+ /// - either one of the range to be copied is out of the range where any
+ /// of the cursor is required to operate;
+ /// - either one of the specified virtual address ranges only covers a
+ /// part of a page.
+ /// - the current cursor's range contains mapped pages.
+ pub fn copy_from(
+ &mut self,
+ src: &mut Self,
+ len: usize,
+ op: &mut impl FnMut(&mut PageProperty),
+ ) {
+ // SAFETY: Operations on user memory spaces are safe if it doesn't
+ // involve dropping any pages.
+ unsafe { self.pt_cursor.copy_from(&mut src.pt_cursor, len, op) }
}
}
-/// The threshold used to determine whether we need to flush all TLB entries
-/// when handling a bunch of TLB flush requests. If the number of requests
-/// exceeds this threshold, the overhead incurred by flushing pages
-/// individually would surpass the overhead of flushing all entries at once.
-const TLB_FLUSH_ALL_THRESHOLD: usize = 32;
-
cpu_local! {
- /// The queue of pending requests.
- static TLB_FLUSH_REQUESTS: SpinLock<VecDeque<TlbFlushRequest>> = SpinLock::new(VecDeque::new());
/// The `Arc` pointer to the activated VM space on this CPU. If the pointer
/// is NULL, it means that the activated page table is merely the kernel
/// page table.
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -396,103 +342,79 @@ impl CursorMut<'_, '_> {
}
}
- if !self.need_remote_flush && tlb_prefer_flush_all {
- self.issue_tlb_flush(TlbFlushOp::All, None);
+ if !self.flusher.need_remote_flush() && tlb_prefer_flush_all {
+ self.flusher.issue_tlb_flush(TlbFlushOp::All);
}
- self.dispatch_tlb_flush();
+ self.flusher.dispatch_tlb_flush();
}
- /// Change the mapping property starting from the current slot.
+ /// Applies the operation to the next slot of mapping within the range.
///
- /// This method will bring the cursor forward by `len` bytes in the virtual
- /// address space after the modification.
+ /// The range to be found in is the current virtual address with the
+ /// provided length.
+ ///
+ /// The function stops and yields the actually protected range if it has
+ /// actually protected a page, no matter if the following pages are also
+ /// required to be protected.
+ ///
+ /// It also makes the cursor moves forward to the next page after the
+ /// protected one. If no mapped pages exist in the following range, the
+ /// cursor will stop at the end of the range and return [`None`].
///
- /// The way to change the property is specified by the closure `op`.
+ /// Note that it will **NOT** flush the TLB after the operation. Please
+ /// make the decision yourself on when and how to flush the TLB using
+ /// [`Self::flusher`].
///
/// # Panics
///
- /// This method will panic if `len` is not page-aligned.
- pub fn protect(&mut self, len: usize, mut op: impl FnMut(&mut PageProperty)) {
- assert!(len % super::PAGE_SIZE == 0);
- let end = self.virt_addr() + len;
- let tlb_prefer_flush_all = len > TLB_FLUSH_ALL_THRESHOLD * PAGE_SIZE;
-
+ /// This function will panic if:
+ /// - the range to be protected is out of the range where the cursor
+ /// is required to operate;
+ /// - the specified virtual address range only covers a part of a page.
+ pub fn protect_next(
+ &mut self,
+ len: usize,
+ mut op: impl FnMut(&mut PageProperty),
+ ) -> Option<Range<Vaddr>> {
// SAFETY: It is safe to protect memory in the userspace.
- while let Some(range) =
- unsafe { self.pt_cursor.protect_next(end - self.virt_addr(), &mut op) }
- {
- if !tlb_prefer_flush_all {
- self.issue_tlb_flush(TlbFlushOp::Range(range), None);
- }
- }
-
- if tlb_prefer_flush_all {
- self.issue_tlb_flush(TlbFlushOp::All, None);
- }
- self.dispatch_tlb_flush();
+ unsafe { self.pt_cursor.protect_next(len, &mut op) }
}
- fn issue_tlb_flush(&self, op: TlbFlushOp, drop_after_flush: Option<DynPage>) {
- let request = TlbFlushRequest {
- op,
- drop_after_flush,
- };
-
- // Fast path for single CPU cases.
- if !self.need_remote_flush {
- if self.need_self_flush {
- request.do_flush();
- }
- return;
- }
-
- // Slow path for multi-CPU cases.
- for cpu in self.activated_cpus.iter() {
- let mut queue = TLB_FLUSH_REQUESTS.get_on_cpu(cpu).lock();
- queue.push_back(request.clone());
- }
- }
-
- fn dispatch_tlb_flush(&self) {
- if !self.need_remote_flush {
- return;
- }
-
- fn do_remote_flush() {
- let preempt_guard = disable_preempt();
- let mut requests = TLB_FLUSH_REQUESTS
- .get_on_cpu(preempt_guard.current_cpu())
- .lock();
- if requests.len() > TLB_FLUSH_ALL_THRESHOLD {
- // TODO: in most cases, we need only to flush all the TLB entries
- // for an ASID if it is enabled.
- crate::arch::mm::tlb_flush_all_excluding_global();
- requests.clear();
- } else {
- while let Some(request) = requests.pop_front() {
- request.do_flush();
- if matches!(request.op, TlbFlushOp::All) {
- requests.clear();
- break;
- }
- }
- }
- }
-
- crate::smp::inter_processor_call(&self.activated_cpus.clone(), do_remote_flush);
+ /// Copies the mapping from the given cursor to the current cursor.
+ ///
+ /// All the mappings in the current cursor's range must be empty. The
+ /// function allows the source cursor to operate on the mapping before
+ /// the copy happens. So it is equivalent to protect then duplicate.
+ /// Only the mapping is copied, the mapped pages are not copied.
+ ///
+ /// After the operation, both cursors will advance by the specified length.
+ ///
+ /// Note that it will **NOT** flush the TLB after the operation. Please
+ /// make the decision yourself on when and how to flush the TLB using
+ /// the source's [`CursorMut::flusher`].
+ ///
+ /// # Panics
+ ///
+ /// This function will panic if:
+ /// - either one of the range to be copied is out of the range where any
+ /// of the cursor is required to operate;
+ /// - either one of the specified virtual address ranges only covers a
+ /// part of a page.
+ /// - the current cursor's range contains mapped pages.
+ pub fn copy_from(
+ &mut self,
+ src: &mut Self,
+ len: usize,
+ op: &mut impl FnMut(&mut PageProperty),
+ ) {
+ // SAFETY: Operations on user memory spaces are safe if it doesn't
+ // involve dropping any pages.
+ unsafe { self.pt_cursor.copy_from(&mut src.pt_cursor, len, op) }
}
}
-/// The threshold used to determine whether we need to flush all TLB entries
-/// when handling a bunch of TLB flush requests. If the number of requests
-/// exceeds this threshold, the overhead incurred by flushing pages
-/// individually would surpass the overhead of flushing all entries at once.
-const TLB_FLUSH_ALL_THRESHOLD: usize = 32;
-
cpu_local! {
- /// The queue of pending requests.
- static TLB_FLUSH_REQUESTS: SpinLock<VecDeque<TlbFlushRequest>> = SpinLock::new(VecDeque::new());
/// The `Arc` pointer to the activated VM space on this CPU. If the pointer
/// is NULL, it means that the activated page table is merely the kernel
/// page table.
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -502,38 +424,6 @@ cpu_local! {
static ACTIVATED_VM_SPACE: AtomicPtr<VmSpace> = AtomicPtr::new(core::ptr::null_mut());
}
-#[derive(Debug, Clone)]
-struct TlbFlushRequest {
- op: TlbFlushOp,
- // If we need to remove a mapped page from the page table, we can only
- // recycle the page after all the relevant TLB entries in all CPUs are
- // flushed. Otherwise if the page is recycled for other purposes, the user
- // space program can still access the page through the TLB entries.
- #[allow(dead_code)]
- drop_after_flush: Option<DynPage>,
-}
-
-#[derive(Debug, Clone)]
-enum TlbFlushOp {
- All,
- Address(Vaddr),
- Range(Range<Vaddr>),
-}
-
-impl TlbFlushRequest {
- /// Perform the TLB flush operation on the current CPU.
- fn do_flush(&self) {
- use crate::arch::mm::{
- tlb_flush_addr, tlb_flush_addr_range, tlb_flush_all_excluding_global,
- };
- match &self.op {
- TlbFlushOp::All => tlb_flush_all_excluding_global(),
- TlbFlushOp::Address(addr) => tlb_flush_addr(*addr),
- TlbFlushOp::Range(range) => tlb_flush_addr_range(range),
- }
- }
-}
-
/// The result of a query over the VM space.
#[derive(Debug)]
pub enum VmItem {
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -502,38 +424,6 @@ cpu_local! {
static ACTIVATED_VM_SPACE: AtomicPtr<VmSpace> = AtomicPtr::new(core::ptr::null_mut());
}
-#[derive(Debug, Clone)]
-struct TlbFlushRequest {
- op: TlbFlushOp,
- // If we need to remove a mapped page from the page table, we can only
- // recycle the page after all the relevant TLB entries in all CPUs are
- // flushed. Otherwise if the page is recycled for other purposes, the user
- // space program can still access the page through the TLB entries.
- #[allow(dead_code)]
- drop_after_flush: Option<DynPage>,
-}
-
-#[derive(Debug, Clone)]
-enum TlbFlushOp {
- All,
- Address(Vaddr),
- Range(Range<Vaddr>),
-}
-
-impl TlbFlushRequest {
- /// Perform the TLB flush operation on the current CPU.
- fn do_flush(&self) {
- use crate::arch::mm::{
- tlb_flush_addr, tlb_flush_addr_range, tlb_flush_all_excluding_global,
- };
- match &self.op {
- TlbFlushOp::All => tlb_flush_all_excluding_global(),
- TlbFlushOp::Address(addr) => tlb_flush_addr(*addr),
- TlbFlushOp::Range(range) => tlb_flush_addr_range(range),
- }
- }
-}
-
/// The result of a query over the VM space.
#[derive(Debug)]
pub enum VmItem {
|
I've already checked out your PR #918 addressing issues raised in this RFC, and find it convincing.
To sum up, the current inner API designs do have the 2 following major weaknesses:
- The "tracked" and "untracked" ranges are all managed by the page table, but the node is agnostic to it to some extent;
- The safety guarantee are not perfectly modeled.
I need some time carefully think about the solution. And thanks for proposing such a fix quickly.
|
2024-09-23T14:17:42Z
|
ae4ac384713e63232b74915593ebdef680049d31
|
asterinas/asterinas
|
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -16,7 +17,14 @@ LOG_LEVEL ?= error
SCHEME ?= ""
SMP ?= 1
OSTD_TASK_STACK_SIZE_IN_PAGES ?= 64
-# End of global options.
+# End of global build options.
+
+# GDB debugging and profiling options.
+GDB_TCP_PORT ?= 1234
+GDB_PROFILE_FORMAT ?= flame-graph
+GDB_PROFILE_COUNT ?= 200
+GDB_PROFILE_INTERVAL ?= 0.1
+# End of GDB options.
# The Makefile provides a way to run arbitrary tests in the kernel
# mode using the kernel command line.
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -26,6 +34,8 @@ EXTRA_BLOCKLISTS_DIRS ?= ""
SYSCALL_TEST_DIR ?= /tmp
# End of auto test features.
+# ========================= End of Makefile options. ==========================
+
CARGO_OSDK := ~/.cargo/bin/cargo-osdk
CARGO_OSDK_ARGS := --target-arch=$(ARCH) --kcmd-args="ostd.log_level=$(LOG_LEVEL)"
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -189,11 +199,20 @@ endif
.PHONY: gdb_server
gdb_server: initramfs $(CARGO_OSDK)
- @cargo osdk run $(CARGO_OSDK_ARGS) -G --vsc --gdb-server-addr :$(GDB_TCP_PORT)
+ @cargo osdk run $(CARGO_OSDK_ARGS) --gdb-server wait-client,vscode,addr=:$(GDB_TCP_PORT)
.PHONY: gdb_client
gdb_client: $(CARGO_OSDK)
- @cd kernel && cargo osdk debug $(CARGO_OSDK_ARGS) --remote :$(GDB_TCP_PORT)
+ @cargo osdk debug $(CARGO_OSDK_ARGS) --remote :$(GDB_TCP_PORT)
+
+.PHONY: profile_server
+profile_server: initramfs $(CARGO_OSDK)
+ @cargo osdk run $(CARGO_OSDK_ARGS) --gdb-server addr=:$(GDB_TCP_PORT)
+
+.PHONY: profile_client
+profile_client: $(CARGO_OSDK)
+ @cargo osdk profile $(CARGO_OSDK_ARGS) --remote :$(GDB_TCP_PORT) \
+ --samples $(GDB_PROFILE_COUNT) --interval $(GDB_PROFILE_INTERVAL) --format $(GDB_PROFILE_FORMAT)
.PHONY: test
test:
diff --git a/docs/src/osdk/reference/commands/README.md b/docs/src/osdk/reference/commands/README.md
--- a/docs/src/osdk/reference/commands/README.md
+++ b/docs/src/osdk/reference/commands/README.md
@@ -11,6 +11,7 @@ Currently, OSDK supports the following subcommands:
- **run**: Run the kernel with a VMM
- **test**: Execute kernel mode unit test by starting a VMM
- **debug**: Debug a remote target via GDB
+- **profile**: Profile a remote GDB debug target to collect stack traces
- **check**: Analyze the current package and report errors
- **clippy**: Check the current package and catch common mistakes
diff --git a/osdk/src/cli.rs b/osdk/src/cli.rs
--- a/osdk/src/cli.rs
+++ b/osdk/src/cli.rs
@@ -2,13 +2,13 @@
use std::path::PathBuf;
-use clap::{crate_version, Args, Parser};
+use clap::{crate_version, Args, Parser, ValueEnum};
use crate::{
arch::Arch,
commands::{
execute_build_command, execute_debug_command, execute_forwarded_command,
- execute_new_command, execute_run_command, execute_test_command,
+ execute_new_command, execute_profile_command, execute_run_command, execute_test_command,
},
config::{
manifest::{ProjectType, TomlManifest},
diff --git a/osdk/src/cli.rs b/osdk/src/cli.rs
--- a/osdk/src/cli.rs
+++ b/osdk/src/cli.rs
@@ -46,6 +46,12 @@ pub fn main() {
debug_args,
);
}
+ OsdkSubcommand::Profile(profile_args) => {
+ execute_profile_command(
+ &load_config(&profile_args.common_args).run.build.profile,
+ profile_args,
+ );
+ }
OsdkSubcommand::Test(test_args) => {
execute_test_command(&load_config(&test_args.common_args), test_args);
}
diff --git a/osdk/src/cli.rs b/osdk/src/cli.rs
--- a/osdk/src/cli.rs
+++ b/osdk/src/cli.rs
@@ -79,6 +85,8 @@ pub enum OsdkSubcommand {
Run(RunArgs),
#[command(about = "Debug a remote target via GDB")]
Debug(DebugArgs),
+ #[command(about = "Profile a remote GDB debug target to collect stack traces for flame graph")]
+ Profile(ProfileArgs),
#[command(about = "Execute kernel mode unit test by starting a VMM")]
Test(TestArgs),
#[command(about = "Check a local package and all of its dependencies for errors")]
diff --git a/osdk/src/commands/mod.rs b/osdk/src/commands/mod.rs
--- a/osdk/src/commands/mod.rs
+++ b/osdk/src/commands/mod.rs
@@ -5,13 +5,14 @@
mod build;
mod debug;
mod new;
+mod profile;
mod run;
mod test;
mod util;
pub use self::{
build::execute_build_command, debug::execute_debug_command, new::execute_new_command,
- run::execute_run_command, test::execute_test_command,
+ profile::execute_profile_command, run::execute_run_command, test::execute_test_command,
};
use crate::arch::get_default_arch;
diff --git /dev/null b/osdk/src/commands/profile.rs
new file mode 100644
--- /dev/null
+++ b/osdk/src/commands/profile.rs
@@ -0,0 +1,383 @@
+// SPDX-License-Identifier: MPL-2.0
+
+//! OSDK profile command implementation.
+//!
+//! The profile command is used to collect stack traces when running the target
+//! kernel in QEMU. It attaches to the GDB server initiated with [`super::run`]
+//! and collects the stack trace periodically. The collected data can be
+//! further analyzed using tools like
+//! [flame graph](https://github.com/brendangregg/FlameGraph).
+
+use inferno::flamegraph;
+
+use crate::{
+ cli::{ProfileArgs, ProfileFormat},
+ commands::util::bin_file_name,
+ util::{get_current_crate_info, get_target_directory},
+};
+use regex::Regex;
+use std::{collections::HashMap, fs::File, io::Write, path::PathBuf, process::Command};
+
+pub fn execute_profile_command(_profile: &str, args: &ProfileArgs) {
+ if let Some(parse_input) = &args.parse {
+ do_parse_stack_traces(parse_input, args);
+ } else {
+ do_collect_stack_traces(args);
+ }
+}
+
+fn do_parse_stack_traces(target_file: &PathBuf, args: &ProfileArgs) {
+ let out_args = &args.out_args;
+ let in_file = File::open(target_file).expect("Failed to open input file");
+ let profile: Profile =
+ serde_json::from_reader(in_file).expect("Failed to parse the input JSON file");
+ let out_file = File::create(out_args.output_path(Some(target_file)))
+ .expect("Failed to create output file");
+
+ let out_format = out_args.format();
+ if matches!(out_format, ProfileFormat::Json) {
+ println!("Warning: parsing JSON profile to the same format.");
+ return;
+ }
+ profile.serialize_to(out_format, out_args.cpu_mask, out_file);
+}
+
+fn do_collect_stack_traces(args: &ProfileArgs) {
+ let file_path = get_target_directory()
+ .join("osdk")
+ .join(get_current_crate_info().name)
+ .join(bin_file_name());
+
+ let remote = &args.remote;
+ let samples = &args.samples;
+ let interval = &args.interval;
+
+ let mut profile_buffer = ProfileBuffer::new();
+
+ println!("Profiling \"{}\" at \"{}\".", file_path.display(), remote);
+ use indicatif::{ProgressIterator, ProgressStyle};
+ let style = ProgressStyle::default_bar().progress_chars("#>-");
+ for _ in (0..*samples).progress_with_style(style) {
+ // Use GDB to halt the remote, get stack traces, and resume
+ let output = Command::new("gdb")
+ .args([
+ "-batch",
+ "-ex",
+ "set pagination 0",
+ "-ex",
+ &format!("file {}", file_path.display()),
+ "-ex",
+ &format!("target remote {}", remote),
+ "-ex",
+ "thread apply all bt -frame-arguments presence -frame-info short-location",
+ ])
+ .output()
+ .expect("Failed to execute gdb");
+
+ for line in String::from_utf8_lossy(&output.stdout).lines() {
+ profile_buffer.append_raw_line(line);
+ }
+
+ // Sleep between samples
+ std::thread::sleep(std::time::Duration::from_secs_f64(*interval));
+ }
+
+ let out_args = &args.out_args;
+ let out_path = out_args.output_path(None);
+ println!(
+ "Profile data collected. Writing the output to \"{}\".",
+ out_path.display()
+ );
+
+ let out_file = File::create(out_path).expect("Failed to create output file");
+ profile_buffer
+ .cur_profile
+ .serialize_to(out_args.format(), out_args.cpu_mask, out_file);
+}
+
+#[derive(Debug, Default, Serialize, Deserialize)]
+struct Profile {
+ // Index 0: capture; Index 1: CPU ID; Index 2: stack frame
+ stack_traces: Vec<HashMap<u32, Vec<String>>>,
+}
+
+impl Profile {
+ fn serialize_to<W: Write>(&self, format: ProfileFormat, cpu_mask: u128, mut target: W) {
+ match format {
+ ProfileFormat::Folded => {
+ let folded = self.fold(cpu_mask);
+
+ // Write the folded traces to the target text writer.
+ for (key, count) in folded {
+ writeln!(&mut target, "{} {}", key, count)
+ .expect("Failed to write folded output");
+ }
+ }
+ ProfileFormat::Json => {
+ let filtered = self.filter_cpu(cpu_mask);
+
+ serde_json::to_writer(target, &filtered).expect("Failed to write JSON output");
+ }
+ ProfileFormat::FlameGraph => {
+ let folded = self.fold(cpu_mask);
+
+ // Generate the flame graph folded text lines.
+ let lines = folded
+ .iter()
+ .map(|(key, count)| format!("{} {}", key, count))
+ .collect::<Vec<_>>();
+
+ // Generate the flame graph to the target SVG writer.
+ let mut opt = flamegraph::Options::default();
+ flamegraph::from_lines(&mut opt, lines.iter().map(|s| s.as_str()), target).unwrap();
+ }
+ }
+ }
+
+ fn filter_cpu(&self, cpu_mask: u128) -> Profile {
+ let filtered_traces = self
+ .stack_traces
+ .iter()
+ .map(|capture| {
+ capture
+ .iter()
+ .filter(|(cpu_id, _)| **cpu_id < 128 && cpu_mask & (1u128 << **cpu_id) != 0)
+ .map(|(cpu_id, stack)| (*cpu_id, stack.clone()))
+ .collect::<HashMap<_, _>>()
+ })
+ .collect::<Vec<_>>();
+
+ Self {
+ stack_traces: filtered_traces,
+ }
+ }
+
+ fn fold(&self, cpu_mask: u128) -> HashMap<String, u32> {
+ let mut folded = HashMap::new();
+
+ for capture in &self.stack_traces {
+ for (cpu_id, stack) in capture {
+ if *cpu_id >= 128 || cpu_mask & (1u128 << *cpu_id) == 0 {
+ continue;
+ }
+
+ let folded_key = stack.iter().rev().cloned().collect::<Vec<_>>().join(";");
+ *folded.entry(folded_key).or_insert(0) += 1;
+ }
+ }
+
+ folded
+ }
+}
+
+#[derive(Debug)]
+struct ProfileBuffer {
+ cur_profile: Profile,
+ // Pre-compile regex patterns for cleaning the input.
+ hex_in_pattern: Regex,
+ impl_pattern: Regex,
+ // The state
+ cur_cpu: Option<u32>,
+}
+
+impl ProfileBuffer {
+ fn new() -> Self {
+ Self {
+ cur_profile: Profile::default(),
+ hex_in_pattern: Regex::new(r"0x[0-9a-f]+ in").unwrap(),
+ impl_pattern: Regex::new(r"::\{.*?\}").unwrap(),
+ cur_cpu: None,
+ }
+ }
+
+ fn append_raw_line(&mut self, line: &str) {
+ // Lines starting with '#' are stack frames
+ if !line.starts_with('#') {
+ // Otherwise it may initiate a new capture or a new CPU stack trace
+
+ // Check if this is a new CPU trace (starts with `Thread` and contains `CPU#N`)
+ if line.starts_with("Thread") {
+ let cpu_id_idx = line.find("CPU#").unwrap();
+ let cpu_id = line[cpu_id_idx + 4..]
+ .split_whitespace()
+ .next()
+ .unwrap()
+ .parse::<u32>()
+ .unwrap();
+ self.cur_cpu = Some(cpu_id);
+
+ // if the new CPU id is already in the stack traces, start a new capture
+ match self.cur_profile.stack_traces.last() {
+ Some(capture) => {
+ if capture.contains_key(&cpu_id) {
+ self.cur_profile.stack_traces.push(HashMap::new());
+ }
+ }
+ None => {
+ self.cur_profile.stack_traces.push(HashMap::new());
+ }
+ }
+ }
+
+ return;
+ }
+
+ // Clean the input line
+ let mut processed = line.trim().to_string();
+
+ // Remove everything between angle brackets '<...>'
+ processed = Self::remove_generics(&processed);
+
+ // Remove "::impl{}" and hex addresses
+ processed = self.impl_pattern.replace_all(&processed, "").to_string();
+ processed = self.hex_in_pattern.replace_all(&processed, "").to_string();
+
+ // Remove unnecessary parts like "()" and "(...)"
+ processed = processed.replace("(...)", "");
+ processed = processed.replace("()", "");
+
+ // Split the line by spaces and expect the second part to be the function name
+ let parts: Vec<&str> = processed.split_whitespace().collect();
+ if parts.len() > 1 {
+ let func_name = parts[1].to_string();
+
+ // Append the function name to the latest stack trace
+ let current_capture = self.cur_profile.stack_traces.last_mut().unwrap();
+ let cur_cpu = self.cur_cpu.unwrap();
+ current_capture.entry(cur_cpu).or_default().push(func_name);
+ }
+ }
+
+ fn remove_generics(line: &str) -> String {
+ let mut result = String::new();
+ let mut bracket_depth = 0;
+
+ for c in line.chars() {
+ match c {
+ '<' => bracket_depth += 1,
+ '>' => {
+ if bracket_depth > 0 {
+ bracket_depth -= 1;
+ }
+ }
+ _ => {
+ if bracket_depth == 0 {
+ result.push(c);
+ }
+ }
+ }
+ }
+
+ result
+ }
+}
+
+#[cfg(test)]
+#[test]
+fn test_profile_parse_raw() {
+ let test_case = r#"
+0xffffffff880b0f6f in aster_nix::sched::priority_scheduler::{impl#4}::pick_next_current<ostd::task::Task> (self=0xffffffff88489808 <_ZN4ostd2mm14heap_allocator10HEAP_SPACE17h85a5340e6564f69dE.llvm.15305379556759765072+992480>) at src/sched/priority_scheduler.rs:156
+156 let next_entity = if !self.real_time_entities.is_empty() {
+
+Thread 2 (Thread 1.2 (CPU#1 [running])):
+#0 ostd::sync::spin::SpinLock<aster_nix::sched::priority_scheduler::PreemptRunQueue<ostd::task::Task>, ostd::sync::spin::PreemptDisabled>::acquire_lock<aster_nix::sched::priority_scheduler::PreemptRunQueue<ostd::task::Task>, ostd::sync::spin::PreemptDisabled> (...)
+#1 ostd::sync::spin::SpinLock<aster_nix::sched::priority_scheduler::PreemptRunQueue<ostd::task::Task>, ostd::sync::spin::PreemptDisabled>::lock<aster_nix::sched::priority_scheduler::PreemptRunQueue<ostd::task::Task>, ostd::sync::spin::PreemptDisabled> (...)
+#2 aster_nix::sched::priority_scheduler::{impl#1}::local_mut_rq_with<ostd::task::Task> (...)
+#3 0xffffffff8826b205 in ostd::task::scheduler::reschedule<ostd::task::scheduler::yield_now::{closure_env#0}> (...)
+#4 ostd::task::scheduler::yield_now ()
+#5 0xffffffff880a92c5 in ostd::task::Task::yield_now ()
+#6 aster_nix::thread::Thread::yield_now ()
+#7 aster_nix::ap_init::ap_idle_thread ()
+#8 core::ops::function::Fn::call<fn(), ()> ()
+#9 0xffffffff880b341e in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (...)
+#10 aster_nix::thread::kernel_thread::create_new_kernel_task::{closure#0} ()
+#11 0xffffffff882a3ea8 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (...)
+#12 ostd::task::{impl#2}::build::kernel_task_entry ()
+#13 0x0000000000000000 in ?? ()
+
+Thread 1 (Thread 1.1 (CPU#0 [running])):
+#0 aster_nix::sched::priority_scheduler::{impl#1}::local_mut_rq_with<ostd::task::Task> (...)
+#1 0xffffffff8826b205 in ostd::task::scheduler::reschedule<ostd::task::scheduler::yield_now::{closure_env#0}> (...)
+#2 ostd::task::scheduler::yield_now ()
+#3 0xffffffff880a92c5 in ostd::task::Task::yield_now ()
+#4 aster_nix::thread::Thread::yield_now ()
+#5 aster_nix::ap_init::ap_idle_thread ()
+#6 core::ops::function::Fn::call<fn(), ()> ()
+#7 0xffffffff880b341e in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (...)
+#8 aster_nix::thread::kernel_thread::create_new_kernel_task::{closure#0} ()
+#9 0xffffffff882a3ea8 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (...)
+#10 ostd::task::{impl#2}::build::kernel_task_entry ()
+#11 0x0000000000000000 in ?? ()
+[Inferior 1 (process 1) detached]
+0xffffffff880b0f6f in aster_nix::sched::priority_scheduler::{impl#4}::pick_next_current<ostd::task::Task> (self=0xffffffff88489808 <_ZN4ostd2mm14heap_allocator10HEAP_SPACE17h85a5340e6564f69dE.llvm.15305379556759765072+992480>) at src/sched/priority_scheduler.rs:156
+156 let next_entity = if !self.real_time_entities.is_empty() {
+
+Thread 2 (Thread 1.2 (CPU#1 [running])):
+#0 0xffffffff880b0f6f in aster_nix::sched::priority_scheduler::{impl#4}::pick_next_current<ostd::task::Task> (...)
+#1 0xffffffff8826b3e0 in ostd::task::scheduler::yield_now::{closure#0} (...)
+#2 ostd::task::scheduler::reschedule::{closure#0}<ostd::task::scheduler::yield_now::{closure_env#0}> (...)
+#3 0xffffffff880b0cff in aster_nix::sched::priority_scheduler::{impl#1}::local_mut_rq_with<ostd::task::Task> (...)
+#4 0xffffffff8826b205 in ostd::task::scheduler::reschedule<ostd::task::scheduler::yield_now::{closure_env#0}> (...)
+#5 ostd::task::scheduler::yield_now ()
+#6 0xffffffff880a92c5 in ostd::task::Task::yield_now ()
+#7 aster_nix::thread::Thread::yield_now ()
+#8 aster_nix::ap_init::ap_idle_thread ()
+#9 core::ops::function::Fn::call<fn(), ()> ()
+#10 0xffffffff880b341e in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (...)
+#11 aster_nix::thread::kernel_thread::create_new_kernel_task::{closure#0} ()
+#12 0xffffffff882a3ea8 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (...)
+#13 ostd::task::{impl#2}::build::kernel_task_entry ()
+#14 0x0000000000000000 in ?? ()
+
+Thread 1 (Thread 1.1 (CPU#0 [running])):
+#0 ostd::arch::x86::interrupts_ack (...)
+#1 0xffffffff8828d704 in ostd::trap::handler::call_irq_callback_functions (...)
+#2 0xffffffff88268e48 in ostd::arch::x86::trap::trap_handler (...)
+#3 0xffffffff88274db6 in __from_kernel ()
+#4 0x0000000000000001 in ?? ()
+#5 0x0000000000000001 in ?? ()
+#6 0x00000000000001c4 in ?? ()
+#7 0xffffffff882c8580 in ?? ()
+#8 0x0000000000000002 in ?? ()
+#9 0xffffffff88489808 in _ZN4ostd2mm14heap_allocator10HEAP_SPACE17h85a5340e6564f69dE.llvm.15305379556759765072 ()
+#10 0x0000000000000000 in ?? ()
+[Inferior 1 (process 1) detached]
+"#;
+
+ let mut buffer = ProfileBuffer::new();
+ for line in test_case.lines() {
+ buffer.append_raw_line(line);
+ }
+
+ let profile = &buffer.cur_profile;
+ assert_eq!(profile.stack_traces.len(), 2);
+ assert_eq!(profile.stack_traces[0].len(), 2);
+ assert_eq!(profile.stack_traces[1].len(), 2);
+
+ let stack00 = profile.stack_traces[0].get(&0).unwrap();
+ assert_eq!(stack00.len(), 12);
+ assert_eq!(
+ stack00[0],
+ "aster_nix::sched::priority_scheduler::local_mut_rq_with"
+ );
+ assert_eq!(stack00[11], "??");
+
+ let stack01 = profile.stack_traces[0].get(&1).unwrap();
+ assert_eq!(stack01.len(), 14);
+ assert_eq!(stack01[9], "alloc::boxed::call");
+
+ let stack10 = profile.stack_traces[1].get(&0).unwrap();
+ assert_eq!(stack10.len(), 11);
+ assert_eq!(
+ stack10[9],
+ "_ZN4ostd2mm14heap_allocator10HEAP_SPACE17h85a5340e6564f69dE.llvm.15305379556759765072"
+ );
+
+ let stack11 = profile.stack_traces[1].get(&1).unwrap();
+ assert_eq!(stack11.len(), 15);
+ assert_eq!(
+ stack11[0],
+ "aster_nix::sched::priority_scheduler::pick_next_current"
+ );
+ assert_eq!(stack11[14], "??");
+}
diff --git a/osdk/tests/commands/run.rs b/osdk/tests/commands/run.rs
--- a/osdk/tests/commands/run.rs
+++ b/osdk/tests/commands/run.rs
@@ -79,7 +79,11 @@ mod qemu_gdb_feature {
path.to_string_lossy().to_string()
};
- let mut instance = cargo_osdk(["run", "-G", "--gdb-server-addr", unix_socket.as_str()]);
+ let mut instance = cargo_osdk([
+ "run",
+ "--gdb-server",
+ format!("addr={},wait-client", unix_socket.as_str()).as_str(),
+ ]);
instance.current_dir(&workspace.os_dir());
let sock = unix_socket.clone();
diff --git a/osdk/tests/commands/run.rs b/osdk/tests/commands/run.rs
--- a/osdk/tests/commands/run.rs
+++ b/osdk/tests/commands/run.rs
@@ -106,8 +110,8 @@ mod qemu_gdb_feature {
let mut gdb = Command::new("gdb");
gdb.args(["-ex", format!("target remote {}", addr).as_str()]);
gdb.write_stdin("\n")
- .write_stdin("c\n")
- .write_stdin("quit\n");
+ .write_stdin("quit\n")
+ .write_stdin("y\n");
gdb.assert().success();
}
mod vsc {
diff --git a/osdk/tests/commands/run.rs b/osdk/tests/commands/run.rs
--- a/osdk/tests/commands/run.rs
+++ b/osdk/tests/commands/run.rs
@@ -123,14 +127,18 @@ mod qemu_gdb_feature {
let workspace = workspace::WorkSpace::new(WORKSPACE, kernel_name);
let addr = ":50001";
- let mut instance = cargo_osdk(["run", "-G", "--vsc", "--gdb-server-addr", addr]);
+ let mut instance = cargo_osdk([
+ "run",
+ "--gdb-server",
+ format!("wait-client,vscode,addr={}", addr).as_str(),
+ ]);
instance.current_dir(&workspace.os_dir());
let dir = workspace.os_dir();
let bin_file_path = Path::new(&workspace.os_dir())
.join("target")
- .join("x86_64-unknown-none")
- .join("debug")
+ .join("osdk")
+ .join(kernel_name)
.join(format!("{}-osdk-bin", kernel_name));
let _gdb = std::thread::spawn(move || {
while !bin_file_path.exists() {
|
[
"964"
] |
0.8
|
f7932595125a0bba8230b5f8d3b110c687d6f3b2
|
[Perf Guide] Flame graph scripts on Asterinas
[Flame graph](https://github.com/brendangregg/FlameGraph) is a well known and powerful tool for performance (bottoleneck) analysis. It's based on sampling. If you inspect the call stack 100 times per second, the function that appears more often, would like to consume more time. The flame graph helps you to visualize it.
Here's my experience about how to capture a flame graph for Asterinas.
Just like what's proposed in #691, the first step is to launch a GDB server (`make gdb_server RELEASE=1`), attach to it (`make gdb_client`) and quit to leave the kernel running.
Then, use the following script to sample call stacks using GDB:
<details><summary>script to sample</summary>
<p>
```bash
#!/bin/bash
# Number of samples
nsamples=100
# Sleep time between samples (in seconds)
sleeptime=0.1
# Hostname or IP address of the machine running QEMU with GDB server
remote_host="localhost"
# Port number where QEMU GDB server is listening
remote_port="1234"
sleep 0.1
for x in $(seq 1 $nsamples)
do
gdb -batch \
-ex "set pagination 0" \
-ex "file target/osdk/aster-nix/aster-nix-osdk-bin" \
-ex "target remote $remote_host:$remote_port" \
-ex "bt -frame-arguments presence -frame-info short-location" >> gdb_perf.log
sleep $sleeptime
done
```
</p>
</details>
After that, the text log is dumped to `gdb_perf.log`. Use a python script to generate folded stack traces for the flame graph:
<details><summary>Details</summary>
<p>
```python
import re
def process_stack_trace(file_path):
with open(file_path, 'r') as file:
lines = file.readlines()
captures = []
current_capture = []
for line in lines:
if not line.startswith('#'):
continue
if line.startswith('#0'):
if current_capture:
captures.append(current_capture)
current_capture = []
processed = line.strip()
# remove all things between < and >, use bracket matching
cut_generic = ''
cnt = 0
for c in processed:
if c == '<':
cnt += 1
if cnt == 0:
cut_generic += c
if c == '>':
cnt -= 1
processed = cut_generic
# remove all things like "::{impl#70}"
processed = re.sub(r'::\{.*?\}', '', processed)
# remove all "(...)"
processed = processed.replace('(...)', '')
# remove all "()"
processed = processed.replace('()', '')
# remove all things like "0xffffffff8819d0fb in"
processed = re.sub(r'0x[0-9a-f]+ in', '', processed)
# split by spaces, the first is number and the second is function name
parts = [s for s in processed.split(' ') if s != '']
current_capture.append(parts[1])
if current_capture:
captures.append(current_capture)
folded = {} # { bt: value }
for capture in captures:
bt_from_butt = []
for frame in reversed(capture):
bt_from_butt.append(frame)
folded_key = ';'.join(bt_from_butt)
if folded_key in folded:
folded[folded_key] += 1
else:
folded[folded_key] = 1
with open('out.folded', 'w') as out_file:
for key, v in folded.items():
out_file.write(f"{key} {v}\n")
if __name__ == "__main__":
process_stack_trace('gdb_perf.log')
```
</p>
</details>
This script generates a file `out.folded`. Then the file is ready to be processed using [Flame graph](https://github.com/brendangregg/FlameGraph). Follow the guide to have an SVG.
TLDR:
```shell
./FlameGraph/flamegraph.pl ./asterinas/out.folded > kernel.svg
```
Here's an example on the unixbench spawn benchmark (on [c75a373](https://github.com/asterinas/asterinas/commit/c75a3732b9a6a7f0dbf11a839affaf2c126ecdc5)):

([An interactive one](https://github.com/asterinas/asterinas/assets/30975570/0ea5b99b-c769-4342-b17f-0d17e100ef8d))
Here's also another example using #895 to optimize it:

([An interactive one](https://github.com/asterinas/asterinas/assets/30975570/6e960bd7-ed26-49d0-91a5-1289673b6215))
You can clearly see that when the bottleneck `read_val_from_user` is optimized, the performance boosts significantly and the bottleneck becomes the `ProcessBuilder`.
|
asterinas__asterinas-1362
| 1,362
|
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -1,13 +1,14 @@
# SPDX-License-Identifier: MPL-2.0
-# Global options.
+# =========================== Makefile options. ===============================
+
+# Global build options.
ARCH ?= x86_64
BENCHMARK ?= none
BOOT_METHOD ?= grub-rescue-iso
BOOT_PROTOCOL ?= multiboot2
BUILD_SYSCALL_TEST ?= 0
ENABLE_KVM ?= 1
-GDB_TCP_PORT ?= 1234
INTEL_TDX ?= 0
MEM ?= 8G
RELEASE ?= 0
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -1,13 +1,14 @@
# SPDX-License-Identifier: MPL-2.0
-# Global options.
+# =========================== Makefile options. ===============================
+
+# Global build options.
ARCH ?= x86_64
BENCHMARK ?= none
BOOT_METHOD ?= grub-rescue-iso
BOOT_PROTOCOL ?= multiboot2
BUILD_SYSCALL_TEST ?= 0
ENABLE_KVM ?= 1
-GDB_TCP_PORT ?= 1234
INTEL_TDX ?= 0
MEM ?= 8G
RELEASE ?= 0
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -16,7 +17,14 @@ LOG_LEVEL ?= error
SCHEME ?= ""
SMP ?= 1
OSTD_TASK_STACK_SIZE_IN_PAGES ?= 64
-# End of global options.
+# End of global build options.
+
+# GDB debugging and profiling options.
+GDB_TCP_PORT ?= 1234
+GDB_PROFILE_FORMAT ?= flame-graph
+GDB_PROFILE_COUNT ?= 200
+GDB_PROFILE_INTERVAL ?= 0.1
+# End of GDB options.
# The Makefile provides a way to run arbitrary tests in the kernel
# mode using the kernel command line.
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -26,6 +34,8 @@ EXTRA_BLOCKLISTS_DIRS ?= ""
SYSCALL_TEST_DIR ?= /tmp
# End of auto test features.
+# ========================= End of Makefile options. ==========================
+
CARGO_OSDK := ~/.cargo/bin/cargo-osdk
CARGO_OSDK_ARGS := --target-arch=$(ARCH) --kcmd-args="ostd.log_level=$(LOG_LEVEL)"
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -189,11 +199,20 @@ endif
.PHONY: gdb_server
gdb_server: initramfs $(CARGO_OSDK)
- @cargo osdk run $(CARGO_OSDK_ARGS) -G --vsc --gdb-server-addr :$(GDB_TCP_PORT)
+ @cargo osdk run $(CARGO_OSDK_ARGS) --gdb-server wait-client,vscode,addr=:$(GDB_TCP_PORT)
.PHONY: gdb_client
gdb_client: $(CARGO_OSDK)
- @cd kernel && cargo osdk debug $(CARGO_OSDK_ARGS) --remote :$(GDB_TCP_PORT)
+ @cargo osdk debug $(CARGO_OSDK_ARGS) --remote :$(GDB_TCP_PORT)
+
+.PHONY: profile_server
+profile_server: initramfs $(CARGO_OSDK)
+ @cargo osdk run $(CARGO_OSDK_ARGS) --gdb-server addr=:$(GDB_TCP_PORT)
+
+.PHONY: profile_client
+profile_client: $(CARGO_OSDK)
+ @cargo osdk profile $(CARGO_OSDK_ARGS) --remote :$(GDB_TCP_PORT) \
+ --samples $(GDB_PROFILE_COUNT) --interval $(GDB_PROFILE_INTERVAL) --format $(GDB_PROFILE_FORMAT)
.PHONY: test
test:
diff --git a/docs/src/osdk/reference/commands/README.md b/docs/src/osdk/reference/commands/README.md
--- a/docs/src/osdk/reference/commands/README.md
+++ b/docs/src/osdk/reference/commands/README.md
@@ -11,6 +11,7 @@ Currently, OSDK supports the following subcommands:
- **run**: Run the kernel with a VMM
- **test**: Execute kernel mode unit test by starting a VMM
- **debug**: Debug a remote target via GDB
+- **profile**: Profile a remote GDB debug target to collect stack traces
- **check**: Analyze the current package and report errors
- **clippy**: Check the current package and catch common mistakes
diff --git a/docs/src/osdk/reference/commands/debug.md b/docs/src/osdk/reference/commands/debug.md
--- a/docs/src/osdk/reference/commands/debug.md
+++ b/docs/src/osdk/reference/commands/debug.md
@@ -2,29 +2,39 @@
## Overview
-`cargo osdk debug` is used to debug a remote target via GDB.
-The usage is as follows:
+`cargo osdk debug` is used to debug a remote target via GDB. You need to start
+a running server to debug with. This is accomplished by the `run` subcommand
+with `--gdb-server`. Then you can use the following command to attach to the
+server and do debugging.
```bash
cargo osdk debug [OPTIONS]
```
+Note that when KVM is enabled, hardware-assisted break points (`hbreak`) are
+needed instead of the normal break points (`break`/`b`) in GDB.
+
## Options
`--remote <REMOTE>`:
-Specify the address of the remote target [default: .aster-gdb-socket].
+Specify the address of the remote target [default: .osdk-gdb-socket].
The address can be either a path for the UNIX domain socket
or a TCP port on an IP address.
## Examples
-- To debug a remote target via a
-[QEMU GDB stub](https://www.qemu.org/docs/master/system/gdb.html),
- - connect to an unix socket, e.g., `./debug`;
- ```bash
- cargo osdk debug --remote ./debug
- ```
- - connect to a TCP port (`[IP]:PORT`), e.g., `localhost:1234`.
- ```bash
- cargo osdk debug --remote localhost:1234
- ```
+To debug a remote target started with
+[QEMU GDB stub](https://www.qemu.org/docs/master/system/gdb.html) or the `run`
+subcommand, use the following commands.
+
+Connect to an unix socket, e.g., `./debug`:
+
+```bash
+cargo osdk debug --remote ./debug
+```
+
+Connect to a TCP port (`[IP]:PORT`), e.g., `localhost:1234`:
+
+```bash
+cargo osdk debug --remote localhost:1234
+```
diff --git a/docs/src/osdk/reference/commands/debug.md b/docs/src/osdk/reference/commands/debug.md
--- a/docs/src/osdk/reference/commands/debug.md
+++ b/docs/src/osdk/reference/commands/debug.md
@@ -2,29 +2,39 @@
## Overview
-`cargo osdk debug` is used to debug a remote target via GDB.
-The usage is as follows:
+`cargo osdk debug` is used to debug a remote target via GDB. You need to start
+a running server to debug with. This is accomplished by the `run` subcommand
+with `--gdb-server`. Then you can use the following command to attach to the
+server and do debugging.
```bash
cargo osdk debug [OPTIONS]
```
+Note that when KVM is enabled, hardware-assisted break points (`hbreak`) are
+needed instead of the normal break points (`break`/`b`) in GDB.
+
## Options
`--remote <REMOTE>`:
-Specify the address of the remote target [default: .aster-gdb-socket].
+Specify the address of the remote target [default: .osdk-gdb-socket].
The address can be either a path for the UNIX domain socket
or a TCP port on an IP address.
## Examples
-- To debug a remote target via a
-[QEMU GDB stub](https://www.qemu.org/docs/master/system/gdb.html),
- - connect to an unix socket, e.g., `./debug`;
- ```bash
- cargo osdk debug --remote ./debug
- ```
- - connect to a TCP port (`[IP]:PORT`), e.g., `localhost:1234`.
- ```bash
- cargo osdk debug --remote localhost:1234
- ```
+To debug a remote target started with
+[QEMU GDB stub](https://www.qemu.org/docs/master/system/gdb.html) or the `run`
+subcommand, use the following commands.
+
+Connect to an unix socket, e.g., `./debug`:
+
+```bash
+cargo osdk debug --remote ./debug
+```
+
+Connect to a TCP port (`[IP]:PORT`), e.g., `localhost:1234`:
+
+```bash
+cargo osdk debug --remote localhost:1234
+```
diff --git /dev/null b/docs/src/osdk/reference/commands/profile.md
new file mode 100644
--- /dev/null
+++ b/docs/src/osdk/reference/commands/profile.md
@@ -0,0 +1,75 @@
+# cargo osdk profile
+
+## Overview
+
+The profile command is used to collect stack traces when running the target
+kernel in QEMU. It attaches to the GDB server initiated with the run subcommand
+and collects the stack trace periodically. The collected information can be
+used to directly generate a flame graph, or be stored for later analysis using
+[the original flame graph tool](https://github.com/brendangregg/FlameGraph).
+
+## Options
+
+`--remote <REMOTE>`:
+
+Specify the address of the remote target.
+By default this is `.osdk-gdb-socket`
+
+`--samples <SAMPLES>`:
+
+The number of samples to collect (default 200).
+It is recommended to go beyond 100 for performance analysis.
+
+`--interval <INTERVAL>`:
+
+The interval between samples in seconds (default 0.1).
+
+`--parse <PATH>`:
+
+Parse a collected JSON profile file into other formats.
+
+`--format <FORMAT>`:
+
+Possible values:
+ - `json`: The parsed stack trace log from GDB in JSON.
+ - `folded`: The folded stack trace for flame graph.
+ - `flame-graph`: A SVG flame graph.
+
+If the user does not specify the format, it will be inferred from the
+output file extension. If the output file does not have an extension,
+the default format is flame graph.
+
+`--cpu-mask <CPU_MASK>`:
+
+The mask of the CPU to generate traces for in the output profile data
+(default first 128 cores). This mask is presented as an integer.
+
+`--output <PATH>`:
+
+The path to the output profile data file.
+
+If the user does not specify the output path, it will be generated from
+the crate name, current time stamp and the format.
+
+## Examples
+
+To profile a remote QEMU GDB server running some workload for flame graph, do:
+
+```bash
+cargo osdk profile --remote :1234 \
+ --samples 100 --interval 0.01
+```
+
+If wanted a detailed analysis, do:
+
+```bash
+cargo osdk profile --remote :1234 \
+ --samples 100 --interval 0.01 --output trace.json
+```
+
+When you get the above detailed analysis, you can also use the JSON file
+to generate the folded format for flame graph.
+
+```bash
+cargo osdk profile --parse trace.json --output trace.folded
+```
diff --git /dev/null b/docs/src/osdk/reference/commands/profile.md
new file mode 100644
--- /dev/null
+++ b/docs/src/osdk/reference/commands/profile.md
@@ -0,0 +1,75 @@
+# cargo osdk profile
+
+## Overview
+
+The profile command is used to collect stack traces when running the target
+kernel in QEMU. It attaches to the GDB server initiated with the run subcommand
+and collects the stack trace periodically. The collected information can be
+used to directly generate a flame graph, or be stored for later analysis using
+[the original flame graph tool](https://github.com/brendangregg/FlameGraph).
+
+## Options
+
+`--remote <REMOTE>`:
+
+Specify the address of the remote target.
+By default this is `.osdk-gdb-socket`
+
+`--samples <SAMPLES>`:
+
+The number of samples to collect (default 200).
+It is recommended to go beyond 100 for performance analysis.
+
+`--interval <INTERVAL>`:
+
+The interval between samples in seconds (default 0.1).
+
+`--parse <PATH>`:
+
+Parse a collected JSON profile file into other formats.
+
+`--format <FORMAT>`:
+
+Possible values:
+ - `json`: The parsed stack trace log from GDB in JSON.
+ - `folded`: The folded stack trace for flame graph.
+ - `flame-graph`: A SVG flame graph.
+
+If the user does not specify the format, it will be inferred from the
+output file extension. If the output file does not have an extension,
+the default format is flame graph.
+
+`--cpu-mask <CPU_MASK>`:
+
+The mask of the CPU to generate traces for in the output profile data
+(default first 128 cores). This mask is presented as an integer.
+
+`--output <PATH>`:
+
+The path to the output profile data file.
+
+If the user does not specify the output path, it will be generated from
+the crate name, current time stamp and the format.
+
+## Examples
+
+To profile a remote QEMU GDB server running some workload for flame graph, do:
+
+```bash
+cargo osdk profile --remote :1234 \
+ --samples 100 --interval 0.01
+```
+
+If wanted a detailed analysis, do:
+
+```bash
+cargo osdk profile --remote :1234 \
+ --samples 100 --interval 0.01 --output trace.json
+```
+
+When you get the above detailed analysis, you can also use the JSON file
+to generate the folded format for flame graph.
+
+```bash
+cargo osdk profile --parse trace.json --output trace.folded
+```
diff --git a/docs/src/osdk/reference/commands/run.md b/docs/src/osdk/reference/commands/run.md
--- a/docs/src/osdk/reference/commands/run.md
+++ b/docs/src/osdk/reference/commands/run.md
@@ -15,34 +15,34 @@ Most options are the same as those of `cargo osdk build`.
Refer to the [documentation](build.md) of `cargo osdk build`
for more details.
-Options related with debugging:
+Additionally, when running the kernel using QEMU, we can setup the QEMU as a
+debug server using option `--gdb-server`. This option supports an additional
+comma separated configuration list:
-- `-G, --enable-gdb`: Enable QEMU GDB server for debugging.
-- `--vsc`: Generate a '.vscode/launch.json' for debugging kernel with Visual Studio Code
-(only works when QEMU GDB server is enabled, i.e., `--enable-gdb`).
-Requires [CodeLLDB](https://marketplace.visualstudio.com/items?itemName=vadimcn.vscode-lldb).
-- `--gdb-server-addr <ADDR>`: The network address on which the GDB server listens,
-it can be either a path for the UNIX domain socket or a TCP port on an IP address.
-[default: `.aster-gdb-socket`(a local UNIX socket)]
+ - `addr=ADDR`: the network or unix socket address on which the GDB server listens
+ (default: `.osdk-gdb-socket`, a local UNIX socket);
+ - `wait-client`: let the GDB server wait for the GDB client before execution;
+ - `vscode`: generate a '.vscode/launch.json' for debugging with Visual Studio Code
+ (Requires [CodeLLDB](https://marketplace.visualstudio.com/items?itemName=vadimcn.vscode-lldb)).
See [Debug Command](debug.md) to interact with the GDB server in terminal.
## Examples
-- Launch a debug server via QEMU with an unix socket stub, e.g. `.debug`:
+Launch a debug server via QEMU with an unix socket stub, e.g. `.debug`:
```bash
-cargo osdk run --enable-gdb --gdb-server-addr .debug
+cargo osdk run --gdb-server addr=.debug
```
-- Launch a debug server via QEMU with a TCP stub, e.g., `localhost:1234`:
+Launch a debug server via QEMU with a TCP stub, e.g., `localhost:1234`:
```bash
-cargo osdk run --enable-gdb --gdb-server-addr :1234
+cargo osdk run --gdb-server addr=:1234
```
-- Launch a debug server via QEMU and use VSCode to interact:
+Launch a debug server via QEMU and use VSCode to interact with:
```bash
-cargo osdk run --enable-gdb --vsc --gdb-server-addr :1234
+cargo osdk run --gdb-server wait-client,vscode,addr=:1234
```
diff --git a/docs/src/osdk/reference/commands/run.md b/docs/src/osdk/reference/commands/run.md
--- a/docs/src/osdk/reference/commands/run.md
+++ b/docs/src/osdk/reference/commands/run.md
@@ -15,34 +15,34 @@ Most options are the same as those of `cargo osdk build`.
Refer to the [documentation](build.md) of `cargo osdk build`
for more details.
-Options related with debugging:
+Additionally, when running the kernel using QEMU, we can setup the QEMU as a
+debug server using option `--gdb-server`. This option supports an additional
+comma separated configuration list:
-- `-G, --enable-gdb`: Enable QEMU GDB server for debugging.
-- `--vsc`: Generate a '.vscode/launch.json' for debugging kernel with Visual Studio Code
-(only works when QEMU GDB server is enabled, i.e., `--enable-gdb`).
-Requires [CodeLLDB](https://marketplace.visualstudio.com/items?itemName=vadimcn.vscode-lldb).
-- `--gdb-server-addr <ADDR>`: The network address on which the GDB server listens,
-it can be either a path for the UNIX domain socket or a TCP port on an IP address.
-[default: `.aster-gdb-socket`(a local UNIX socket)]
+ - `addr=ADDR`: the network or unix socket address on which the GDB server listens
+ (default: `.osdk-gdb-socket`, a local UNIX socket);
+ - `wait-client`: let the GDB server wait for the GDB client before execution;
+ - `vscode`: generate a '.vscode/launch.json' for debugging with Visual Studio Code
+ (Requires [CodeLLDB](https://marketplace.visualstudio.com/items?itemName=vadimcn.vscode-lldb)).
See [Debug Command](debug.md) to interact with the GDB server in terminal.
## Examples
-- Launch a debug server via QEMU with an unix socket stub, e.g. `.debug`:
+Launch a debug server via QEMU with an unix socket stub, e.g. `.debug`:
```bash
-cargo osdk run --enable-gdb --gdb-server-addr .debug
+cargo osdk run --gdb-server addr=.debug
```
-- Launch a debug server via QEMU with a TCP stub, e.g., `localhost:1234`:
+Launch a debug server via QEMU with a TCP stub, e.g., `localhost:1234`:
```bash
-cargo osdk run --enable-gdb --gdb-server-addr :1234
+cargo osdk run --gdb-server addr=:1234
```
-- Launch a debug server via QEMU and use VSCode to interact:
+Launch a debug server via QEMU and use VSCode to interact with:
```bash
-cargo osdk run --enable-gdb --vsc --gdb-server-addr :1234
+cargo osdk run --gdb-server wait-client,vscode,addr=:1234
```
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -15,6 +15,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011"
dependencies = [
"cfg-if",
+ "getrandom",
"once_cell",
"version_check",
"zerocopy",
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -15,6 +15,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011"
dependencies = [
"cfg-if",
+ "getrandom",
"once_cell",
"version_check",
"zerocopy",
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -35,6 +36,21 @@ version = "0.2.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f"
+[[package]]
+name = "android-tzdata"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0"
+
+[[package]]
+name = "android_system_properties"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "anstream"
version = "0.6.12"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -35,6 +36,21 @@ version = "0.2.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f"
+[[package]]
+name = "android-tzdata"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0"
+
+[[package]]
+name = "android_system_properties"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "anstream"
version = "0.6.12"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -83,6 +99,12 @@ dependencies = [
"windows-sys",
]
+[[package]]
+name = "arrayvec"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
+
[[package]]
name = "assert_cmd"
version = "2.0.14"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -83,6 +99,12 @@ dependencies = [
"windows-sys",
]
+[[package]]
+name = "arrayvec"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
+
[[package]]
name = "assert_cmd"
version = "2.0.14"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -98,12 +120,24 @@ dependencies = [
"wait-timeout",
]
+[[package]]
+name = "autocfg"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0"
+
[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
+[[package]]
+name = "bitflags"
+version = "2.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de"
+
[[package]]
name = "block-buffer"
version = "0.10.4"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -98,12 +120,24 @@ dependencies = [
"wait-timeout",
]
+[[package]]
+name = "autocfg"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0"
+
[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
+[[package]]
+name = "bitflags"
+version = "2.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de"
+
[[package]]
name = "block-buffer"
version = "0.10.4"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -124,6 +158,12 @@ dependencies = [
"serde",
]
+[[package]]
+name = "bumpalo"
+version = "3.16.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c"
+
[[package]]
name = "bytemuck"
version = "1.17.0"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -124,6 +158,12 @@ dependencies = [
"serde",
]
+[[package]]
+name = "bumpalo"
+version = "3.16.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c"
+
[[package]]
name = "bytemuck"
version = "1.17.0"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -149,9 +189,12 @@ name = "cargo-osdk"
version = "0.8.3"
dependencies = [
"assert_cmd",
+ "chrono",
"clap",
"env_logger",
"indexmap",
+ "indicatif",
+ "inferno",
"lazy_static",
"linux-bzimage-builder",
"log",
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -149,9 +189,12 @@ name = "cargo-osdk"
version = "0.8.3"
dependencies = [
"assert_cmd",
+ "chrono",
"clap",
"env_logger",
"indexmap",
+ "indicatif",
+ "inferno",
"lazy_static",
"linux-bzimage-builder",
"log",
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -166,12 +209,35 @@ dependencies = [
"toml",
]
+[[package]]
+name = "cc"
+version = "1.1.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "07b1695e2c7e8fc85310cde85aeaab7e3097f593c91d209d3f9df76c928100f0"
+dependencies = [
+ "shlex",
+]
+
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
+[[package]]
+name = "chrono"
+version = "0.4.38"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401"
+dependencies = [
+ "android-tzdata",
+ "iana-time-zone",
+ "js-sys",
+ "num-traits",
+ "wasm-bindgen",
+ "windows-targets",
+]
+
[[package]]
name = "clap"
version = "4.5.1"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -166,12 +209,35 @@ dependencies = [
"toml",
]
+[[package]]
+name = "cc"
+version = "1.1.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "07b1695e2c7e8fc85310cde85aeaab7e3097f593c91d209d3f9df76c928100f0"
+dependencies = [
+ "shlex",
+]
+
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
+[[package]]
+name = "chrono"
+version = "0.4.38"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401"
+dependencies = [
+ "android-tzdata",
+ "iana-time-zone",
+ "js-sys",
+ "num-traits",
+ "wasm-bindgen",
+ "windows-targets",
+]
+
[[package]]
name = "clap"
version = "4.5.1"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -218,6 +284,25 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7"
+[[package]]
+name = "console"
+version = "0.15.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0e1f83fc076bd6dd27517eacdf25fef6c4dfe5f1d7448bafaaf3a26f13b5e4eb"
+dependencies = [
+ "encode_unicode",
+ "lazy_static",
+ "libc",
+ "unicode-width",
+ "windows-sys",
+]
+
+[[package]]
+name = "core-foundation-sys"
+version = "0.8.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
+
[[package]]
name = "core2"
version = "0.4.0"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -218,6 +284,25 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7"
+[[package]]
+name = "console"
+version = "0.15.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0e1f83fc076bd6dd27517eacdf25fef6c4dfe5f1d7448bafaaf3a26f13b5e4eb"
+dependencies = [
+ "encode_unicode",
+ "lazy_static",
+ "libc",
+ "unicode-width",
+ "windows-sys",
+]
+
+[[package]]
+name = "core-foundation-sys"
+version = "0.8.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
+
[[package]]
name = "core2"
version = "0.4.0"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -245,6 +330,21 @@ dependencies = [
"cfg-if",
]
+[[package]]
+name = "crossbeam-channel"
+version = "0.5.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "33480d6946193aa8033910124896ca395333cae7e2d1113d1fef6c3272217df2"
+dependencies = [
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-utils"
+version = "0.8.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80"
+
[[package]]
name = "crypto-common"
version = "0.1.6"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -245,6 +330,21 @@ dependencies = [
"cfg-if",
]
+[[package]]
+name = "crossbeam-channel"
+version = "0.5.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "33480d6946193aa8033910124896ca395333cae7e2d1113d1fef6c3272217df2"
+dependencies = [
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-utils"
+version = "0.8.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80"
+
[[package]]
name = "crypto-common"
version = "0.1.6"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -261,6 +361,20 @@ version = "0.3.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7762d17f1241643615821a8455a0b2c3e803784b058693d990b11f2dce25a0ca"
+[[package]]
+name = "dashmap"
+version = "6.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5041cc499144891f3790297212f32a74fb938e5136a14943f338ef9e0ae276cf"
+dependencies = [
+ "cfg-if",
+ "crossbeam-utils",
+ "hashbrown",
+ "lock_api",
+ "once_cell",
+ "parking_lot_core",
+]
+
[[package]]
name = "difflib"
version = "0.4.0"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -261,6 +361,20 @@ version = "0.3.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7762d17f1241643615821a8455a0b2c3e803784b058693d990b11f2dce25a0ca"
+[[package]]
+name = "dashmap"
+version = "6.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5041cc499144891f3790297212f32a74fb938e5136a14943f338ef9e0ae276cf"
+dependencies = [
+ "cfg-if",
+ "crossbeam-utils",
+ "hashbrown",
+ "lock_api",
+ "once_cell",
+ "parking_lot_core",
+]
+
[[package]]
name = "difflib"
version = "0.4.0"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -283,6 +397,12 @@ version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fea41bba32d969b513997752735605054bc0dfa92b4c56bf1189f2e174be7a10"
+[[package]]
+name = "encode_unicode"
+version = "0.3.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f"
+
[[package]]
name = "env_filter"
version = "0.1.0"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -283,6 +397,12 @@ version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fea41bba32d969b513997752735605054bc0dfa92b4c56bf1189f2e174be7a10"
+[[package]]
+name = "encode_unicode"
+version = "0.3.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f"
+
[[package]]
name = "env_filter"
version = "0.1.0"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -322,6 +442,17 @@ dependencies = [
"version_check",
]
+[[package]]
+name = "getrandom"
+version = "0.2.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "wasi",
+]
+
[[package]]
name = "hashbrown"
version = "0.14.3"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -322,6 +442,17 @@ dependencies = [
"version_check",
]
+[[package]]
+name = "getrandom"
+version = "0.2.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "wasi",
+]
+
[[package]]
name = "hashbrown"
version = "0.14.3"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -338,12 +469,41 @@ version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
+[[package]]
+name = "hermit-abi"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fbf6a919d6cf397374f7dfeeea91d974c7c0a7221d0d0f4f20d859d329e53fcc"
+
[[package]]
name = "humantime"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"
+[[package]]
+name = "iana-time-zone"
+version = "0.1.61"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "235e081f3925a06703c2d0117ea8b91f042756fd6e7a6e5d901e8ca1a996b220"
+dependencies = [
+ "android_system_properties",
+ "core-foundation-sys",
+ "iana-time-zone-haiku",
+ "js-sys",
+ "wasm-bindgen",
+ "windows-core",
+]
+
+[[package]]
+name = "iana-time-zone-haiku"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
+dependencies = [
+ "cc",
+]
+
[[package]]
name = "indexmap"
version = "2.2.3"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -338,12 +469,41 @@ version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
+[[package]]
+name = "hermit-abi"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fbf6a919d6cf397374f7dfeeea91d974c7c0a7221d0d0f4f20d859d329e53fcc"
+
[[package]]
name = "humantime"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"
+[[package]]
+name = "iana-time-zone"
+version = "0.1.61"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "235e081f3925a06703c2d0117ea8b91f042756fd6e7a6e5d901e8ca1a996b220"
+dependencies = [
+ "android_system_properties",
+ "core-foundation-sys",
+ "iana-time-zone-haiku",
+ "js-sys",
+ "wasm-bindgen",
+ "windows-core",
+]
+
+[[package]]
+name = "iana-time-zone-haiku"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
+dependencies = [
+ "cc",
+]
+
[[package]]
name = "indexmap"
version = "2.2.3"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -354,12 +514,77 @@ dependencies = [
"hashbrown",
]
+[[package]]
+name = "indicatif"
+version = "0.17.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "763a5a8f45087d6bcea4222e7b72c291a054edf80e4ef6efd2a4979878c7bea3"
+dependencies = [
+ "console",
+ "instant",
+ "number_prefix",
+ "portable-atomic",
+ "unicode-width",
+]
+
+[[package]]
+name = "inferno"
+version = "0.11.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "232929e1d75fe899576a3d5c7416ad0d88dbfbb3c3d6aa00873a7408a50ddb88"
+dependencies = [
+ "ahash",
+ "clap",
+ "crossbeam-channel",
+ "crossbeam-utils",
+ "dashmap",
+ "env_logger",
+ "indexmap",
+ "is-terminal",
+ "itoa",
+ "log",
+ "num-format",
+ "once_cell",
+ "quick-xml",
+ "rgb",
+ "str_stack",
+]
+
+[[package]]
+name = "instant"
+version = "0.1.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "is-terminal"
+version = "0.4.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "261f68e344040fbd0edea105bef17c66edf46f984ddb1115b775ce31be948f4b"
+dependencies = [
+ "hermit-abi",
+ "libc",
+ "windows-sys",
+]
+
[[package]]
name = "itoa"
version = "1.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c"
+[[package]]
+name = "js-sys"
+version = "0.3.70"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1868808506b929d7b0cfa8f75951347aa71bb21144b7791bae35d9bccfcfe37a"
+dependencies = [
+ "wasm-bindgen",
+]
+
[[package]]
name = "lazy_static"
version = "1.4.0"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -354,12 +514,77 @@ dependencies = [
"hashbrown",
]
+[[package]]
+name = "indicatif"
+version = "0.17.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "763a5a8f45087d6bcea4222e7b72c291a054edf80e4ef6efd2a4979878c7bea3"
+dependencies = [
+ "console",
+ "instant",
+ "number_prefix",
+ "portable-atomic",
+ "unicode-width",
+]
+
+[[package]]
+name = "inferno"
+version = "0.11.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "232929e1d75fe899576a3d5c7416ad0d88dbfbb3c3d6aa00873a7408a50ddb88"
+dependencies = [
+ "ahash",
+ "clap",
+ "crossbeam-channel",
+ "crossbeam-utils",
+ "dashmap",
+ "env_logger",
+ "indexmap",
+ "is-terminal",
+ "itoa",
+ "log",
+ "num-format",
+ "once_cell",
+ "quick-xml",
+ "rgb",
+ "str_stack",
+]
+
+[[package]]
+name = "instant"
+version = "0.1.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "is-terminal"
+version = "0.4.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "261f68e344040fbd0edea105bef17c66edf46f984ddb1115b775ce31be948f4b"
+dependencies = [
+ "hermit-abi",
+ "libc",
+ "windows-sys",
+]
+
[[package]]
name = "itoa"
version = "1.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c"
+[[package]]
+name = "js-sys"
+version = "0.3.70"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1868808506b929d7b0cfa8f75951347aa71bb21144b7791bae35d9bccfcfe37a"
+dependencies = [
+ "wasm-bindgen",
+]
+
[[package]]
name = "lazy_static"
version = "1.4.0"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -368,9 +593,9 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "libc"
-version = "0.2.153"
+version = "0.2.159"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd"
+checksum = "561d97a539a36e26a9a5fad1ea11a3039a67714694aaa379433e580854bc3dc5"
[[package]]
name = "libflate"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -368,9 +593,9 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "libc"
-version = "0.2.153"
+version = "0.2.159"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd"
+checksum = "561d97a539a36e26a9a5fad1ea11a3039a67714694aaa379433e580854bc3dc5"
[[package]]
name = "libflate"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -400,13 +625,23 @@ dependencies = [
name = "linux-bzimage-builder"
version = "0.2.0"
dependencies = [
- "bitflags",
+ "bitflags 1.3.2",
"bytemuck",
"libflate",
"serde",
"xmas-elf",
]
+[[package]]
+name = "lock_api"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17"
+dependencies = [
+ "autocfg",
+ "scopeguard",
+]
+
[[package]]
name = "log"
version = "0.4.20"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -400,13 +625,23 @@ dependencies = [
name = "linux-bzimage-builder"
version = "0.2.0"
dependencies = [
- "bitflags",
+ "bitflags 1.3.2",
"bytemuck",
"libflate",
"serde",
"xmas-elf",
]
+[[package]]
+name = "lock_api"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17"
+dependencies = [
+ "autocfg",
+ "scopeguard",
+]
+
[[package]]
name = "log"
version = "0.4.20"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -419,12 +654,56 @@ version = "2.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "523dc4f511e55ab87b694dc30d0f820d60906ef06413f93d4d7a1385599cc149"
+[[package]]
+name = "num-format"
+version = "0.4.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a652d9771a63711fd3c3deb670acfbe5c30a4072e664d7a3bf5a9e1056ac72c3"
+dependencies = [
+ "arrayvec",
+ "itoa",
+]
+
+[[package]]
+name = "num-traits"
+version = "0.2.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "number_prefix"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3"
+
[[package]]
name = "once_cell"
version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92"
+[[package]]
+name = "parking_lot_core"
+version = "0.9.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "redox_syscall",
+ "smallvec",
+ "windows-targets",
+]
+
+[[package]]
+name = "portable-atomic"
+version = "1.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d30538d42559de6b034bc76fd6dd4c38961b1ee5c6c56e3808c50128fdbc22ce"
+
[[package]]
name = "predicates"
version = "3.1.0"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -419,12 +654,56 @@ version = "2.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "523dc4f511e55ab87b694dc30d0f820d60906ef06413f93d4d7a1385599cc149"
+[[package]]
+name = "num-format"
+version = "0.4.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a652d9771a63711fd3c3deb670acfbe5c30a4072e664d7a3bf5a9e1056ac72c3"
+dependencies = [
+ "arrayvec",
+ "itoa",
+]
+
+[[package]]
+name = "num-traits"
+version = "0.2.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "number_prefix"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3"
+
[[package]]
name = "once_cell"
version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92"
+[[package]]
+name = "parking_lot_core"
+version = "0.9.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "redox_syscall",
+ "smallvec",
+ "windows-targets",
+]
+
+[[package]]
+name = "portable-atomic"
+version = "1.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d30538d42559de6b034bc76fd6dd4c38961b1ee5c6c56e3808c50128fdbc22ce"
+
[[package]]
name = "predicates"
version = "3.1.0"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -461,6 +740,15 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "quick-xml"
+version = "0.26.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f50b1c63b38611e7d4d7f68b82d3ad0cc71a2ad2e7f61fc10f1328d917c93cd"
+dependencies = [
+ "memchr",
+]
+
[[package]]
name = "quote"
version = "1.0.35"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -461,6 +740,15 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "quick-xml"
+version = "0.26.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f50b1c63b38611e7d4d7f68b82d3ad0cc71a2ad2e7f61fc10f1328d917c93cd"
+dependencies = [
+ "memchr",
+]
+
[[package]]
name = "quote"
version = "1.0.35"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -470,6 +758,15 @@ dependencies = [
"proc-macro2",
]
+[[package]]
+name = "redox_syscall"
+version = "0.5.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "355ae415ccd3a04315d3f8246e86d67689ea74d88d915576e1589a351062a13b"
+dependencies = [
+ "bitflags 2.6.0",
+]
+
[[package]]
name = "regex"
version = "1.10.4"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -470,6 +758,15 @@ dependencies = [
"proc-macro2",
]
+[[package]]
+name = "redox_syscall"
+version = "0.5.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "355ae415ccd3a04315d3f8246e86d67689ea74d88d915576e1589a351062a13b"
+dependencies = [
+ "bitflags 2.6.0",
+]
+
[[package]]
name = "regex"
version = "1.10.4"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -508,6 +805,15 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "rgb"
+version = "0.8.50"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "57397d16646700483b67d2dd6511d79318f9d057fdbd21a4066aeac8b41d310a"
+dependencies = [
+ "bytemuck",
+]
+
[[package]]
name = "rle-decode-fast"
version = "1.0.3"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -508,6 +805,15 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "rgb"
+version = "0.8.50"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "57397d16646700483b67d2dd6511d79318f9d057fdbd21a4066aeac8b41d310a"
+dependencies = [
+ "bytemuck",
+]
+
[[package]]
name = "rle-decode-fast"
version = "1.0.3"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -520,6 +826,12 @@ version = "1.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e86697c916019a8588c99b5fac3cead74ec0b4b819707a682fd4d23fa0ce1ba1"
+[[package]]
+name = "scopeguard"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+
[[package]]
name = "serde"
version = "1.0.197"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -520,6 +826,12 @@ version = "1.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e86697c916019a8588c99b5fac3cead74ec0b4b819707a682fd4d23fa0ce1ba1"
+[[package]]
+name = "scopeguard"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+
[[package]]
name = "serde"
version = "1.0.197"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -577,6 +889,18 @@ version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
+[[package]]
+name = "smallvec"
+version = "1.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
+
+[[package]]
+name = "str_stack"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9091b6114800a5f2141aee1d1b9d6ca3592ac062dc5decb3764ec5895a47b4eb"
+
[[package]]
name = "strsim"
version = "0.11.0"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -577,6 +889,18 @@ version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
+[[package]]
+name = "smallvec"
+version = "1.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
+
+[[package]]
+name = "str_stack"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9091b6114800a5f2141aee1d1b9d6ca3592ac062dc5decb3764ec5895a47b4eb"
+
[[package]]
name = "strsim"
version = "0.11.0"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -647,6 +971,12 @@ version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
+[[package]]
+name = "unicode-width"
+version = "0.1.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"
+
[[package]]
name = "utf8parse"
version = "0.2.1"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -647,6 +971,12 @@ version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
+[[package]]
+name = "unicode-width"
+version = "0.1.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"
+
[[package]]
name = "utf8parse"
version = "0.2.1"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -668,6 +998,76 @@ dependencies = [
"libc",
]
+[[package]]
+name = "wasi"
+version = "0.11.0+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
+
+[[package]]
+name = "wasm-bindgen"
+version = "0.2.93"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a82edfc16a6c469f5f44dc7b571814045d60404b55a0ee849f9bcfa2e63dd9b5"
+dependencies = [
+ "cfg-if",
+ "once_cell",
+ "wasm-bindgen-macro",
+]
+
+[[package]]
+name = "wasm-bindgen-backend"
+version = "0.2.93"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9de396da306523044d3302746f1208fa71d7532227f15e347e2d93e4145dd77b"
+dependencies = [
+ "bumpalo",
+ "log",
+ "once_cell",
+ "proc-macro2",
+ "quote",
+ "syn",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-macro"
+version = "0.2.93"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "585c4c91a46b072c92e908d99cb1dcdf95c5218eeb6f3bf1efa991ee7a68cccf"
+dependencies = [
+ "quote",
+ "wasm-bindgen-macro-support",
+]
+
+[[package]]
+name = "wasm-bindgen-macro-support"
+version = "0.2.93"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "afc340c74d9005395cf9dd098506f7f44e38f2b4a21c6aaacf9a105ea5e1e836"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "wasm-bindgen-backend",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-shared"
+version = "0.2.93"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c62a0a307cb4a311d3a07867860911ca130c3494e8c2719593806c08bc5d0484"
+
+[[package]]
+name = "windows-core"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9"
+dependencies = [
+ "windows-targets",
+]
+
[[package]]
name = "windows-sys"
version = "0.52.0"
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -668,6 +998,76 @@ dependencies = [
"libc",
]
+[[package]]
+name = "wasi"
+version = "0.11.0+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
+
+[[package]]
+name = "wasm-bindgen"
+version = "0.2.93"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a82edfc16a6c469f5f44dc7b571814045d60404b55a0ee849f9bcfa2e63dd9b5"
+dependencies = [
+ "cfg-if",
+ "once_cell",
+ "wasm-bindgen-macro",
+]
+
+[[package]]
+name = "wasm-bindgen-backend"
+version = "0.2.93"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9de396da306523044d3302746f1208fa71d7532227f15e347e2d93e4145dd77b"
+dependencies = [
+ "bumpalo",
+ "log",
+ "once_cell",
+ "proc-macro2",
+ "quote",
+ "syn",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-macro"
+version = "0.2.93"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "585c4c91a46b072c92e908d99cb1dcdf95c5218eeb6f3bf1efa991ee7a68cccf"
+dependencies = [
+ "quote",
+ "wasm-bindgen-macro-support",
+]
+
+[[package]]
+name = "wasm-bindgen-macro-support"
+version = "0.2.93"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "afc340c74d9005395cf9dd098506f7f44e38f2b4a21c6aaacf9a105ea5e1e836"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "wasm-bindgen-backend",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-shared"
+version = "0.2.93"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c62a0a307cb4a311d3a07867860911ca130c3494e8c2719593806c08bc5d0484"
+
+[[package]]
+name = "windows-core"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9"
+dependencies = [
+ "windows-targets",
+]
+
[[package]]
name = "windows-sys"
version = "0.52.0"
diff --git a/osdk/Cargo.toml b/osdk/Cargo.toml
--- a/osdk/Cargo.toml
+++ b/osdk/Cargo.toml
@@ -19,8 +19,11 @@ version = "0.2.0"
[dependencies]
clap = { version = "4.4.17", features = ["cargo", "derive"] }
+chrono = "0.4.38"
env_logger = "0.11.0"
+inferno = "0.11.21"
indexmap = "2.2.1"
+indicatif = "0.17.8" # For a commandline progress bar
lazy_static = "1.4.0"
log = "0.4.20"
quote = "1.0.35"
diff --git a/osdk/Cargo.toml b/osdk/Cargo.toml
--- a/osdk/Cargo.toml
+++ b/osdk/Cargo.toml
@@ -19,8 +19,11 @@ version = "0.2.0"
[dependencies]
clap = { version = "4.4.17", features = ["cargo", "derive"] }
+chrono = "0.4.38"
env_logger = "0.11.0"
+inferno = "0.11.21"
indexmap = "2.2.1"
+indicatif = "0.17.8" # For a commandline progress bar
lazy_static = "1.4.0"
log = "0.4.20"
quote = "1.0.35"
diff --git a/osdk/src/cli.rs b/osdk/src/cli.rs
--- a/osdk/src/cli.rs
+++ b/osdk/src/cli.rs
@@ -2,13 +2,13 @@
use std::path::PathBuf;
-use clap::{crate_version, Args, Parser};
+use clap::{crate_version, Args, Parser, ValueEnum};
use crate::{
arch::Arch,
commands::{
execute_build_command, execute_debug_command, execute_forwarded_command,
- execute_new_command, execute_run_command, execute_test_command,
+ execute_new_command, execute_profile_command, execute_run_command, execute_test_command,
},
config::{
manifest::{ProjectType, TomlManifest},
diff --git a/osdk/src/cli.rs b/osdk/src/cli.rs
--- a/osdk/src/cli.rs
+++ b/osdk/src/cli.rs
@@ -37,7 +37,7 @@ pub fn main() {
OsdkSubcommand::Run(run_args) => {
execute_run_command(
&load_config(&run_args.common_args),
- &run_args.gdb_server_args,
+ run_args.gdb_server.as_deref(),
);
}
OsdkSubcommand::Debug(debug_args) => {
diff --git a/osdk/src/cli.rs b/osdk/src/cli.rs
--- a/osdk/src/cli.rs
+++ b/osdk/src/cli.rs
@@ -37,7 +37,7 @@ pub fn main() {
OsdkSubcommand::Run(run_args) => {
execute_run_command(
&load_config(&run_args.common_args),
- &run_args.gdb_server_args,
+ run_args.gdb_server.as_deref(),
);
}
OsdkSubcommand::Debug(debug_args) => {
diff --git a/osdk/src/cli.rs b/osdk/src/cli.rs
--- a/osdk/src/cli.rs
+++ b/osdk/src/cli.rs
@@ -46,6 +46,12 @@ pub fn main() {
debug_args,
);
}
+ OsdkSubcommand::Profile(profile_args) => {
+ execute_profile_command(
+ &load_config(&profile_args.common_args).run.build.profile,
+ profile_args,
+ );
+ }
OsdkSubcommand::Test(test_args) => {
execute_test_command(&load_config(&test_args.common_args), test_args);
}
diff --git a/osdk/src/cli.rs b/osdk/src/cli.rs
--- a/osdk/src/cli.rs
+++ b/osdk/src/cli.rs
@@ -79,6 +85,8 @@ pub enum OsdkSubcommand {
Run(RunArgs),
#[command(about = "Debug a remote target via GDB")]
Debug(DebugArgs),
+ #[command(about = "Profile a remote GDB debug target to collect stack traces for flame graph")]
+ Profile(ProfileArgs),
#[command(about = "Execute kernel mode unit test by starting a VMM")]
Test(TestArgs),
#[command(about = "Check a local package and all of its dependencies for errors")]
diff --git a/osdk/src/cli.rs b/osdk/src/cli.rs
--- a/osdk/src/cli.rs
+++ b/osdk/src/cli.rs
@@ -160,49 +168,150 @@ pub struct BuildArgs {
#[derive(Debug, Parser)]
pub struct RunArgs {
+ #[arg(
+ long = "gdb-server",
+ help = "Enable the QEMU GDB server for debugging\n\
+ This option supports an additional comma separated configuration list:\n\t \
+ addr=ADDR: the network or unix socket address on which the GDB server listens, \
+ `.osdk-gdb-socket` by default;\n\t \
+ wait-client: let the GDB server wait for the GDB client before execution;\n\t \
+ vscode: generate a '.vscode/launch.json' for debugging with Visual Studio Code.",
+ value_name = "[addr=ADDR][,wait-client][,vscode]",
+ default_missing_value = ""
+ )]
+ pub gdb_server: Option<String>,
#[command(flatten)]
- pub gdb_server_args: GdbServerArgs,
+ pub common_args: CommonArgs,
+}
+
+#[derive(Debug, Parser)]
+pub struct DebugArgs {
+ #[arg(
+ long,
+ help = "Specify the address of the remote target",
+ default_value = ".osdk-gdb-socket"
+ )]
+ pub remote: String,
#[command(flatten)]
pub common_args: CommonArgs,
}
-#[derive(Debug, Args, Clone, Default)]
-pub struct GdbServerArgs {
- /// Whether to enable QEMU GDB server for debugging
+#[derive(Debug, Parser)]
+pub struct ProfileArgs {
#[arg(
- long = "enable-gdb",
- short = 'G',
- help = "Enable QEMU GDB server for debugging",
- default_value_t
+ long,
+ help = "Specify the address of the remote target",
+ default_value = ".osdk-gdb-socket"
)]
- pub is_gdb_enabled: bool,
+ pub remote: String,
+ #[arg(long, help = "The number of samples to collect", default_value = "200")]
+ pub samples: usize,
#[arg(
- long = "vsc",
- help = "Generate a '.vscode/launch.json' for debugging with Visual Studio Code \
- (only works when '--enable-gdb' is enabled)",
- default_value_t
+ long,
+ help = "The interval between samples in seconds",
+ default_value = "0.1"
)]
- pub vsc_launch_file: bool,
+ pub interval: f64,
#[arg(
- long = "gdb-server-addr",
- help = "The network address on which the GDB server listens, \
- it can be either a path for the UNIX domain socket or a TCP port on an IP address.",
- value_name = "ADDR",
- default_value = ".aster-gdb-socket"
+ long,
+ help = "Parse a collected JSON profile file into other formats",
+ value_name = "PATH",
+ conflicts_with = "samples",
+ conflicts_with = "interval"
)]
- pub gdb_server_addr: String,
+ pub parse: Option<PathBuf>,
+ #[command(flatten)]
+ pub out_args: DebugProfileOutArgs,
+ #[command(flatten)]
+ pub common_args: CommonArgs,
+}
+
+#[derive(Clone, Copy, Debug, ValueEnum)]
+pub enum ProfileFormat {
+ /// The raw stack trace log parsed from GDB in JSON
+ Json,
+ /// The folded stack trace for generating a flame graph later using
+ /// [the original tool](https://github.com/brendangregg/FlameGraph)
+ Folded,
+ /// A SVG flame graph
+ FlameGraph,
+}
+
+impl ProfileFormat {
+ pub fn file_extension(&self) -> &'static str {
+ match self {
+ ProfileFormat::Json => "json",
+ ProfileFormat::Folded => "folded",
+ ProfileFormat::FlameGraph => "svg",
+ }
+ }
}
#[derive(Debug, Parser)]
-pub struct DebugArgs {
+pub struct DebugProfileOutArgs {
+ #[arg(long, help = "The output format for the profile data")]
+ format: Option<ProfileFormat>,
#[arg(
long,
- help = "Specify the address of the remote target",
- default_value = ".aster-gdb-socket"
+ help = "The mask of the CPU to generate traces for in the output profile data",
+ default_value_t = u128::MAX
)]
- pub remote: String,
- #[command(flatten)]
- pub common_args: CommonArgs,
+ pub cpu_mask: u128,
+ #[arg(
+ long,
+ help = "The path to the output profile data file",
+ value_name = "PATH"
+ )]
+ output: Option<PathBuf>,
+}
+
+impl DebugProfileOutArgs {
+ /// Get the output format for the profile data.
+ ///
+ /// If the user does not specify the format, it will be inferred from the
+ /// output file extension. If the output file does not have an extension,
+ /// the default format is flame graph.
+ pub fn format(&self) -> ProfileFormat {
+ self.format.unwrap_or_else(|| {
+ if self.output.is_some() {
+ match self.output.as_ref().unwrap().extension() {
+ Some(ext) if ext == "folded" => ProfileFormat::Folded,
+ Some(ext) if ext == "json" => ProfileFormat::Json,
+ Some(ext) if ext == "svg" => ProfileFormat::FlameGraph,
+ _ => ProfileFormat::FlameGraph,
+ }
+ } else {
+ ProfileFormat::FlameGraph
+ }
+ })
+ }
+
+ /// Get the output path for the profile data.
+ ///
+ /// If the user does not specify the output path, it will be generated from
+ /// the current time stamp and the format. The caller can provide a hint
+ /// output path to the file to override the file name.
+ pub fn output_path(&self, hint: Option<&PathBuf>) -> PathBuf {
+ self.output.clone().unwrap_or_else(|| {
+ use chrono::{offset::Local, DateTime};
+ let file_stem = if let Some(hint) = hint {
+ format!(
+ "{}",
+ hint.parent()
+ .unwrap()
+ .join(hint.file_stem().unwrap())
+ .display()
+ )
+ } else {
+ let crate_name = crate::util::get_current_crate_info().name;
+ let time_stamp = std::time::SystemTime::now();
+ let time_stamp: DateTime<Local> = time_stamp.into();
+ let time_stamp = time_stamp.format("%H%M%S");
+ format!("{}-profile-{}", crate_name, time_stamp)
+ };
+ PathBuf::from(format!("{}.{}", file_stem, self.format().file_extension()))
+ })
+ }
}
#[derive(Debug, Parser)]
diff --git a/osdk/src/cli.rs b/osdk/src/cli.rs
--- a/osdk/src/cli.rs
+++ b/osdk/src/cli.rs
@@ -160,49 +168,150 @@ pub struct BuildArgs {
#[derive(Debug, Parser)]
pub struct RunArgs {
+ #[arg(
+ long = "gdb-server",
+ help = "Enable the QEMU GDB server for debugging\n\
+ This option supports an additional comma separated configuration list:\n\t \
+ addr=ADDR: the network or unix socket address on which the GDB server listens, \
+ `.osdk-gdb-socket` by default;\n\t \
+ wait-client: let the GDB server wait for the GDB client before execution;\n\t \
+ vscode: generate a '.vscode/launch.json' for debugging with Visual Studio Code.",
+ value_name = "[addr=ADDR][,wait-client][,vscode]",
+ default_missing_value = ""
+ )]
+ pub gdb_server: Option<String>,
#[command(flatten)]
- pub gdb_server_args: GdbServerArgs,
+ pub common_args: CommonArgs,
+}
+
+#[derive(Debug, Parser)]
+pub struct DebugArgs {
+ #[arg(
+ long,
+ help = "Specify the address of the remote target",
+ default_value = ".osdk-gdb-socket"
+ )]
+ pub remote: String,
#[command(flatten)]
pub common_args: CommonArgs,
}
-#[derive(Debug, Args, Clone, Default)]
-pub struct GdbServerArgs {
- /// Whether to enable QEMU GDB server for debugging
+#[derive(Debug, Parser)]
+pub struct ProfileArgs {
#[arg(
- long = "enable-gdb",
- short = 'G',
- help = "Enable QEMU GDB server for debugging",
- default_value_t
+ long,
+ help = "Specify the address of the remote target",
+ default_value = ".osdk-gdb-socket"
)]
- pub is_gdb_enabled: bool,
+ pub remote: String,
+ #[arg(long, help = "The number of samples to collect", default_value = "200")]
+ pub samples: usize,
#[arg(
- long = "vsc",
- help = "Generate a '.vscode/launch.json' for debugging with Visual Studio Code \
- (only works when '--enable-gdb' is enabled)",
- default_value_t
+ long,
+ help = "The interval between samples in seconds",
+ default_value = "0.1"
)]
- pub vsc_launch_file: bool,
+ pub interval: f64,
#[arg(
- long = "gdb-server-addr",
- help = "The network address on which the GDB server listens, \
- it can be either a path for the UNIX domain socket or a TCP port on an IP address.",
- value_name = "ADDR",
- default_value = ".aster-gdb-socket"
+ long,
+ help = "Parse a collected JSON profile file into other formats",
+ value_name = "PATH",
+ conflicts_with = "samples",
+ conflicts_with = "interval"
)]
- pub gdb_server_addr: String,
+ pub parse: Option<PathBuf>,
+ #[command(flatten)]
+ pub out_args: DebugProfileOutArgs,
+ #[command(flatten)]
+ pub common_args: CommonArgs,
+}
+
+#[derive(Clone, Copy, Debug, ValueEnum)]
+pub enum ProfileFormat {
+ /// The raw stack trace log parsed from GDB in JSON
+ Json,
+ /// The folded stack trace for generating a flame graph later using
+ /// [the original tool](https://github.com/brendangregg/FlameGraph)
+ Folded,
+ /// A SVG flame graph
+ FlameGraph,
+}
+
+impl ProfileFormat {
+ pub fn file_extension(&self) -> &'static str {
+ match self {
+ ProfileFormat::Json => "json",
+ ProfileFormat::Folded => "folded",
+ ProfileFormat::FlameGraph => "svg",
+ }
+ }
}
#[derive(Debug, Parser)]
-pub struct DebugArgs {
+pub struct DebugProfileOutArgs {
+ #[arg(long, help = "The output format for the profile data")]
+ format: Option<ProfileFormat>,
#[arg(
long,
- help = "Specify the address of the remote target",
- default_value = ".aster-gdb-socket"
+ help = "The mask of the CPU to generate traces for in the output profile data",
+ default_value_t = u128::MAX
)]
- pub remote: String,
- #[command(flatten)]
- pub common_args: CommonArgs,
+ pub cpu_mask: u128,
+ #[arg(
+ long,
+ help = "The path to the output profile data file",
+ value_name = "PATH"
+ )]
+ output: Option<PathBuf>,
+}
+
+impl DebugProfileOutArgs {
+ /// Get the output format for the profile data.
+ ///
+ /// If the user does not specify the format, it will be inferred from the
+ /// output file extension. If the output file does not have an extension,
+ /// the default format is flame graph.
+ pub fn format(&self) -> ProfileFormat {
+ self.format.unwrap_or_else(|| {
+ if self.output.is_some() {
+ match self.output.as_ref().unwrap().extension() {
+ Some(ext) if ext == "folded" => ProfileFormat::Folded,
+ Some(ext) if ext == "json" => ProfileFormat::Json,
+ Some(ext) if ext == "svg" => ProfileFormat::FlameGraph,
+ _ => ProfileFormat::FlameGraph,
+ }
+ } else {
+ ProfileFormat::FlameGraph
+ }
+ })
+ }
+
+ /// Get the output path for the profile data.
+ ///
+ /// If the user does not specify the output path, it will be generated from
+ /// the current time stamp and the format. The caller can provide a hint
+ /// output path to the file to override the file name.
+ pub fn output_path(&self, hint: Option<&PathBuf>) -> PathBuf {
+ self.output.clone().unwrap_or_else(|| {
+ use chrono::{offset::Local, DateTime};
+ let file_stem = if let Some(hint) = hint {
+ format!(
+ "{}",
+ hint.parent()
+ .unwrap()
+ .join(hint.file_stem().unwrap())
+ .display()
+ )
+ } else {
+ let crate_name = crate::util::get_current_crate_info().name;
+ let time_stamp = std::time::SystemTime::now();
+ let time_stamp: DateTime<Local> = time_stamp.into();
+ let time_stamp = time_stamp.format("%H%M%S");
+ format!("{}-profile-{}", crate_name, time_stamp)
+ };
+ PathBuf::from(format!("{}.{}", file_stem, self.format().file_extension()))
+ })
+ }
}
#[derive(Debug, Parser)]
diff --git a/osdk/src/commands/debug.rs b/osdk/src/commands/debug.rs
--- a/osdk/src/commands/debug.rs
+++ b/osdk/src/commands/debug.rs
@@ -18,10 +18,9 @@ pub fn execute_debug_command(_profile: &str, args: &DebugArgs) {
let mut gdb = Command::new("gdb");
gdb.args([
+ format!("{}", file_path.display()).as_str(),
"-ex",
format!("target remote {}", remote).as_str(),
- "-ex",
- format!("file {}", file_path.display()).as_str(),
]);
gdb.status().unwrap();
}
diff --git a/osdk/src/commands/debug.rs b/osdk/src/commands/debug.rs
--- a/osdk/src/commands/debug.rs
+++ b/osdk/src/commands/debug.rs
@@ -18,10 +18,9 @@ pub fn execute_debug_command(_profile: &str, args: &DebugArgs) {
let mut gdb = Command::new("gdb");
gdb.args([
+ format!("{}", file_path.display()).as_str(),
"-ex",
format!("target remote {}", remote).as_str(),
- "-ex",
- format!("file {}", file_path.display()).as_str(),
]);
gdb.status().unwrap();
}
diff --git a/osdk/src/commands/mod.rs b/osdk/src/commands/mod.rs
--- a/osdk/src/commands/mod.rs
+++ b/osdk/src/commands/mod.rs
@@ -5,13 +5,14 @@
mod build;
mod debug;
mod new;
+mod profile;
mod run;
mod test;
mod util;
pub use self::{
build::execute_build_command, debug::execute_debug_command, new::execute_new_command,
- run::execute_run_command, test::execute_test_command,
+ profile::execute_profile_command, run::execute_run_command, test::execute_test_command,
};
use crate::arch::get_default_arch;
diff --git /dev/null b/osdk/src/commands/profile.rs
new file mode 100644
--- /dev/null
+++ b/osdk/src/commands/profile.rs
@@ -0,0 +1,383 @@
+// SPDX-License-Identifier: MPL-2.0
+
+//! OSDK profile command implementation.
+//!
+//! The profile command is used to collect stack traces when running the target
+//! kernel in QEMU. It attaches to the GDB server initiated with [`super::run`]
+//! and collects the stack trace periodically. The collected data can be
+//! further analyzed using tools like
+//! [flame graph](https://github.com/brendangregg/FlameGraph).
+
+use inferno::flamegraph;
+
+use crate::{
+ cli::{ProfileArgs, ProfileFormat},
+ commands::util::bin_file_name,
+ util::{get_current_crate_info, get_target_directory},
+};
+use regex::Regex;
+use std::{collections::HashMap, fs::File, io::Write, path::PathBuf, process::Command};
+
+pub fn execute_profile_command(_profile: &str, args: &ProfileArgs) {
+ if let Some(parse_input) = &args.parse {
+ do_parse_stack_traces(parse_input, args);
+ } else {
+ do_collect_stack_traces(args);
+ }
+}
+
+fn do_parse_stack_traces(target_file: &PathBuf, args: &ProfileArgs) {
+ let out_args = &args.out_args;
+ let in_file = File::open(target_file).expect("Failed to open input file");
+ let profile: Profile =
+ serde_json::from_reader(in_file).expect("Failed to parse the input JSON file");
+ let out_file = File::create(out_args.output_path(Some(target_file)))
+ .expect("Failed to create output file");
+
+ let out_format = out_args.format();
+ if matches!(out_format, ProfileFormat::Json) {
+ println!("Warning: parsing JSON profile to the same format.");
+ return;
+ }
+ profile.serialize_to(out_format, out_args.cpu_mask, out_file);
+}
+
+fn do_collect_stack_traces(args: &ProfileArgs) {
+ let file_path = get_target_directory()
+ .join("osdk")
+ .join(get_current_crate_info().name)
+ .join(bin_file_name());
+
+ let remote = &args.remote;
+ let samples = &args.samples;
+ let interval = &args.interval;
+
+ let mut profile_buffer = ProfileBuffer::new();
+
+ println!("Profiling \"{}\" at \"{}\".", file_path.display(), remote);
+ use indicatif::{ProgressIterator, ProgressStyle};
+ let style = ProgressStyle::default_bar().progress_chars("#>-");
+ for _ in (0..*samples).progress_with_style(style) {
+ // Use GDB to halt the remote, get stack traces, and resume
+ let output = Command::new("gdb")
+ .args([
+ "-batch",
+ "-ex",
+ "set pagination 0",
+ "-ex",
+ &format!("file {}", file_path.display()),
+ "-ex",
+ &format!("target remote {}", remote),
+ "-ex",
+ "thread apply all bt -frame-arguments presence -frame-info short-location",
+ ])
+ .output()
+ .expect("Failed to execute gdb");
+
+ for line in String::from_utf8_lossy(&output.stdout).lines() {
+ profile_buffer.append_raw_line(line);
+ }
+
+ // Sleep between samples
+ std::thread::sleep(std::time::Duration::from_secs_f64(*interval));
+ }
+
+ let out_args = &args.out_args;
+ let out_path = out_args.output_path(None);
+ println!(
+ "Profile data collected. Writing the output to \"{}\".",
+ out_path.display()
+ );
+
+ let out_file = File::create(out_path).expect("Failed to create output file");
+ profile_buffer
+ .cur_profile
+ .serialize_to(out_args.format(), out_args.cpu_mask, out_file);
+}
+
+#[derive(Debug, Default, Serialize, Deserialize)]
+struct Profile {
+ // Index 0: capture; Index 1: CPU ID; Index 2: stack frame
+ stack_traces: Vec<HashMap<u32, Vec<String>>>,
+}
+
+impl Profile {
+ fn serialize_to<W: Write>(&self, format: ProfileFormat, cpu_mask: u128, mut target: W) {
+ match format {
+ ProfileFormat::Folded => {
+ let folded = self.fold(cpu_mask);
+
+ // Write the folded traces to the target text writer.
+ for (key, count) in folded {
+ writeln!(&mut target, "{} {}", key, count)
+ .expect("Failed to write folded output");
+ }
+ }
+ ProfileFormat::Json => {
+ let filtered = self.filter_cpu(cpu_mask);
+
+ serde_json::to_writer(target, &filtered).expect("Failed to write JSON output");
+ }
+ ProfileFormat::FlameGraph => {
+ let folded = self.fold(cpu_mask);
+
+ // Generate the flame graph folded text lines.
+ let lines = folded
+ .iter()
+ .map(|(key, count)| format!("{} {}", key, count))
+ .collect::<Vec<_>>();
+
+ // Generate the flame graph to the target SVG writer.
+ let mut opt = flamegraph::Options::default();
+ flamegraph::from_lines(&mut opt, lines.iter().map(|s| s.as_str()), target).unwrap();
+ }
+ }
+ }
+
+ fn filter_cpu(&self, cpu_mask: u128) -> Profile {
+ let filtered_traces = self
+ .stack_traces
+ .iter()
+ .map(|capture| {
+ capture
+ .iter()
+ .filter(|(cpu_id, _)| **cpu_id < 128 && cpu_mask & (1u128 << **cpu_id) != 0)
+ .map(|(cpu_id, stack)| (*cpu_id, stack.clone()))
+ .collect::<HashMap<_, _>>()
+ })
+ .collect::<Vec<_>>();
+
+ Self {
+ stack_traces: filtered_traces,
+ }
+ }
+
+ fn fold(&self, cpu_mask: u128) -> HashMap<String, u32> {
+ let mut folded = HashMap::new();
+
+ for capture in &self.stack_traces {
+ for (cpu_id, stack) in capture {
+ if *cpu_id >= 128 || cpu_mask & (1u128 << *cpu_id) == 0 {
+ continue;
+ }
+
+ let folded_key = stack.iter().rev().cloned().collect::<Vec<_>>().join(";");
+ *folded.entry(folded_key).or_insert(0) += 1;
+ }
+ }
+
+ folded
+ }
+}
+
+#[derive(Debug)]
+struct ProfileBuffer {
+ cur_profile: Profile,
+ // Pre-compile regex patterns for cleaning the input.
+ hex_in_pattern: Regex,
+ impl_pattern: Regex,
+ // The state
+ cur_cpu: Option<u32>,
+}
+
+impl ProfileBuffer {
+ fn new() -> Self {
+ Self {
+ cur_profile: Profile::default(),
+ hex_in_pattern: Regex::new(r"0x[0-9a-f]+ in").unwrap(),
+ impl_pattern: Regex::new(r"::\{.*?\}").unwrap(),
+ cur_cpu: None,
+ }
+ }
+
+ fn append_raw_line(&mut self, line: &str) {
+ // Lines starting with '#' are stack frames
+ if !line.starts_with('#') {
+ // Otherwise it may initiate a new capture or a new CPU stack trace
+
+ // Check if this is a new CPU trace (starts with `Thread` and contains `CPU#N`)
+ if line.starts_with("Thread") {
+ let cpu_id_idx = line.find("CPU#").unwrap();
+ let cpu_id = line[cpu_id_idx + 4..]
+ .split_whitespace()
+ .next()
+ .unwrap()
+ .parse::<u32>()
+ .unwrap();
+ self.cur_cpu = Some(cpu_id);
+
+ // if the new CPU id is already in the stack traces, start a new capture
+ match self.cur_profile.stack_traces.last() {
+ Some(capture) => {
+ if capture.contains_key(&cpu_id) {
+ self.cur_profile.stack_traces.push(HashMap::new());
+ }
+ }
+ None => {
+ self.cur_profile.stack_traces.push(HashMap::new());
+ }
+ }
+ }
+
+ return;
+ }
+
+ // Clean the input line
+ let mut processed = line.trim().to_string();
+
+ // Remove everything between angle brackets '<...>'
+ processed = Self::remove_generics(&processed);
+
+ // Remove "::impl{}" and hex addresses
+ processed = self.impl_pattern.replace_all(&processed, "").to_string();
+ processed = self.hex_in_pattern.replace_all(&processed, "").to_string();
+
+ // Remove unnecessary parts like "()" and "(...)"
+ processed = processed.replace("(...)", "");
+ processed = processed.replace("()", "");
+
+ // Split the line by spaces and expect the second part to be the function name
+ let parts: Vec<&str> = processed.split_whitespace().collect();
+ if parts.len() > 1 {
+ let func_name = parts[1].to_string();
+
+ // Append the function name to the latest stack trace
+ let current_capture = self.cur_profile.stack_traces.last_mut().unwrap();
+ let cur_cpu = self.cur_cpu.unwrap();
+ current_capture.entry(cur_cpu).or_default().push(func_name);
+ }
+ }
+
+ fn remove_generics(line: &str) -> String {
+ let mut result = String::new();
+ let mut bracket_depth = 0;
+
+ for c in line.chars() {
+ match c {
+ '<' => bracket_depth += 1,
+ '>' => {
+ if bracket_depth > 0 {
+ bracket_depth -= 1;
+ }
+ }
+ _ => {
+ if bracket_depth == 0 {
+ result.push(c);
+ }
+ }
+ }
+ }
+
+ result
+ }
+}
+
+#[cfg(test)]
+#[test]
+fn test_profile_parse_raw() {
+ let test_case = r#"
+0xffffffff880b0f6f in aster_nix::sched::priority_scheduler::{impl#4}::pick_next_current<ostd::task::Task> (self=0xffffffff88489808 <_ZN4ostd2mm14heap_allocator10HEAP_SPACE17h85a5340e6564f69dE.llvm.15305379556759765072+992480>) at src/sched/priority_scheduler.rs:156
+156 let next_entity = if !self.real_time_entities.is_empty() {
+
+Thread 2 (Thread 1.2 (CPU#1 [running])):
+#0 ostd::sync::spin::SpinLock<aster_nix::sched::priority_scheduler::PreemptRunQueue<ostd::task::Task>, ostd::sync::spin::PreemptDisabled>::acquire_lock<aster_nix::sched::priority_scheduler::PreemptRunQueue<ostd::task::Task>, ostd::sync::spin::PreemptDisabled> (...)
+#1 ostd::sync::spin::SpinLock<aster_nix::sched::priority_scheduler::PreemptRunQueue<ostd::task::Task>, ostd::sync::spin::PreemptDisabled>::lock<aster_nix::sched::priority_scheduler::PreemptRunQueue<ostd::task::Task>, ostd::sync::spin::PreemptDisabled> (...)
+#2 aster_nix::sched::priority_scheduler::{impl#1}::local_mut_rq_with<ostd::task::Task> (...)
+#3 0xffffffff8826b205 in ostd::task::scheduler::reschedule<ostd::task::scheduler::yield_now::{closure_env#0}> (...)
+#4 ostd::task::scheduler::yield_now ()
+#5 0xffffffff880a92c5 in ostd::task::Task::yield_now ()
+#6 aster_nix::thread::Thread::yield_now ()
+#7 aster_nix::ap_init::ap_idle_thread ()
+#8 core::ops::function::Fn::call<fn(), ()> ()
+#9 0xffffffff880b341e in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (...)
+#10 aster_nix::thread::kernel_thread::create_new_kernel_task::{closure#0} ()
+#11 0xffffffff882a3ea8 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (...)
+#12 ostd::task::{impl#2}::build::kernel_task_entry ()
+#13 0x0000000000000000 in ?? ()
+
+Thread 1 (Thread 1.1 (CPU#0 [running])):
+#0 aster_nix::sched::priority_scheduler::{impl#1}::local_mut_rq_with<ostd::task::Task> (...)
+#1 0xffffffff8826b205 in ostd::task::scheduler::reschedule<ostd::task::scheduler::yield_now::{closure_env#0}> (...)
+#2 ostd::task::scheduler::yield_now ()
+#3 0xffffffff880a92c5 in ostd::task::Task::yield_now ()
+#4 aster_nix::thread::Thread::yield_now ()
+#5 aster_nix::ap_init::ap_idle_thread ()
+#6 core::ops::function::Fn::call<fn(), ()> ()
+#7 0xffffffff880b341e in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (...)
+#8 aster_nix::thread::kernel_thread::create_new_kernel_task::{closure#0} ()
+#9 0xffffffff882a3ea8 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (...)
+#10 ostd::task::{impl#2}::build::kernel_task_entry ()
+#11 0x0000000000000000 in ?? ()
+[Inferior 1 (process 1) detached]
+0xffffffff880b0f6f in aster_nix::sched::priority_scheduler::{impl#4}::pick_next_current<ostd::task::Task> (self=0xffffffff88489808 <_ZN4ostd2mm14heap_allocator10HEAP_SPACE17h85a5340e6564f69dE.llvm.15305379556759765072+992480>) at src/sched/priority_scheduler.rs:156
+156 let next_entity = if !self.real_time_entities.is_empty() {
+
+Thread 2 (Thread 1.2 (CPU#1 [running])):
+#0 0xffffffff880b0f6f in aster_nix::sched::priority_scheduler::{impl#4}::pick_next_current<ostd::task::Task> (...)
+#1 0xffffffff8826b3e0 in ostd::task::scheduler::yield_now::{closure#0} (...)
+#2 ostd::task::scheduler::reschedule::{closure#0}<ostd::task::scheduler::yield_now::{closure_env#0}> (...)
+#3 0xffffffff880b0cff in aster_nix::sched::priority_scheduler::{impl#1}::local_mut_rq_with<ostd::task::Task> (...)
+#4 0xffffffff8826b205 in ostd::task::scheduler::reschedule<ostd::task::scheduler::yield_now::{closure_env#0}> (...)
+#5 ostd::task::scheduler::yield_now ()
+#6 0xffffffff880a92c5 in ostd::task::Task::yield_now ()
+#7 aster_nix::thread::Thread::yield_now ()
+#8 aster_nix::ap_init::ap_idle_thread ()
+#9 core::ops::function::Fn::call<fn(), ()> ()
+#10 0xffffffff880b341e in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (...)
+#11 aster_nix::thread::kernel_thread::create_new_kernel_task::{closure#0} ()
+#12 0xffffffff882a3ea8 in alloc::boxed::{impl#50}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (...)
+#13 ostd::task::{impl#2}::build::kernel_task_entry ()
+#14 0x0000000000000000 in ?? ()
+
+Thread 1 (Thread 1.1 (CPU#0 [running])):
+#0 ostd::arch::x86::interrupts_ack (...)
+#1 0xffffffff8828d704 in ostd::trap::handler::call_irq_callback_functions (...)
+#2 0xffffffff88268e48 in ostd::arch::x86::trap::trap_handler (...)
+#3 0xffffffff88274db6 in __from_kernel ()
+#4 0x0000000000000001 in ?? ()
+#5 0x0000000000000001 in ?? ()
+#6 0x00000000000001c4 in ?? ()
+#7 0xffffffff882c8580 in ?? ()
+#8 0x0000000000000002 in ?? ()
+#9 0xffffffff88489808 in _ZN4ostd2mm14heap_allocator10HEAP_SPACE17h85a5340e6564f69dE.llvm.15305379556759765072 ()
+#10 0x0000000000000000 in ?? ()
+[Inferior 1 (process 1) detached]
+"#;
+
+ let mut buffer = ProfileBuffer::new();
+ for line in test_case.lines() {
+ buffer.append_raw_line(line);
+ }
+
+ let profile = &buffer.cur_profile;
+ assert_eq!(profile.stack_traces.len(), 2);
+ assert_eq!(profile.stack_traces[0].len(), 2);
+ assert_eq!(profile.stack_traces[1].len(), 2);
+
+ let stack00 = profile.stack_traces[0].get(&0).unwrap();
+ assert_eq!(stack00.len(), 12);
+ assert_eq!(
+ stack00[0],
+ "aster_nix::sched::priority_scheduler::local_mut_rq_with"
+ );
+ assert_eq!(stack00[11], "??");
+
+ let stack01 = profile.stack_traces[0].get(&1).unwrap();
+ assert_eq!(stack01.len(), 14);
+ assert_eq!(stack01[9], "alloc::boxed::call");
+
+ let stack10 = profile.stack_traces[1].get(&0).unwrap();
+ assert_eq!(stack10.len(), 11);
+ assert_eq!(
+ stack10[9],
+ "_ZN4ostd2mm14heap_allocator10HEAP_SPACE17h85a5340e6564f69dE.llvm.15305379556759765072"
+ );
+
+ let stack11 = profile.stack_traces[1].get(&1).unwrap();
+ assert_eq!(stack11.len(), 15);
+ assert_eq!(
+ stack11[0],
+ "aster_nix::sched::priority_scheduler::pick_next_current"
+ );
+ assert_eq!(stack11[14], "??");
+}
diff --git a/osdk/src/commands/run.rs b/osdk/src/commands/run.rs
--- a/osdk/src/commands/run.rs
+++ b/osdk/src/commands/run.rs
@@ -1,60 +1,29 @@
// SPDX-License-Identifier: MPL-2.0
+use std::process::exit;
+
+use vsc::VscLaunchConfig;
+
use super::{build::create_base_and_cached_build, util::DEFAULT_TARGET_RELPATH};
use crate::{
- cli::GdbServerArgs,
config::{scheme::ActionChoice, Config},
+ error::Errno,
+ error_msg,
util::{get_current_crate_info, get_target_directory},
};
-pub fn execute_run_command(config: &Config, gdb_server_args: &GdbServerArgs) {
- if gdb_server_args.is_gdb_enabled {
- use std::env;
- env::set_var(
- "RUSTFLAGS",
- env::var("RUSTFLAGS").unwrap_or_default() + " -g",
- );
- }
-
+pub fn execute_run_command(config: &Config, gdb_server_args: Option<&str>) {
let cargo_target_directory = get_target_directory();
let osdk_output_directory = cargo_target_directory.join(DEFAULT_TARGET_RELPATH);
let target_name = get_current_crate_info().name;
let mut config = config.clone();
- if gdb_server_args.is_gdb_enabled {
- let qemu_gdb_args = {
- let gdb_stub_addr = gdb_server_args.gdb_server_addr.as_str();
- match gdb::stub_type_of(gdb_stub_addr) {
- gdb::StubAddrType::Unix => {
- format!(
- " -chardev socket,path={},server=on,wait=off,id=gdb0 -gdb chardev:gdb0 -S",
- gdb_stub_addr
- )
- }
- gdb::StubAddrType::Tcp => {
- format!(
- " -gdb tcp:{} -S",
- gdb::tcp_addr_util::format_tcp_addr(gdb_stub_addr)
- )
- }
- }
- };
- config.run.qemu.args += &qemu_gdb_args;
-
- // Ensure debug info added when debugging in the release profile.
- if config.run.build.profile.contains("release") {
- config
- .run
- .build
- .override_configs
- .push(format!("profile.{}.debug=true", config.run.build.profile));
- }
- }
- let _vsc_launch_file = gdb_server_args.vsc_launch_file.then(|| {
- vsc::check_gdb_config(gdb_server_args);
- let profile = super::util::profile_name_adapter(&config.run.build.profile);
- vsc::VscLaunchConfig::new(profile, &gdb_server_args.gdb_server_addr)
- });
+
+ let _vsc_launch_file = if let Some(gdb_server_str) = gdb_server_args {
+ adapt_for_gdb_server(&mut config, gdb_server_str)
+ } else {
+ None
+ };
let default_bundle_directory = osdk_output_directory.join(target_name);
let bundle = create_base_and_cached_build(
diff --git a/osdk/src/commands/run.rs b/osdk/src/commands/run.rs
--- a/osdk/src/commands/run.rs
+++ b/osdk/src/commands/run.rs
@@ -1,60 +1,29 @@
// SPDX-License-Identifier: MPL-2.0
+use std::process::exit;
+
+use vsc::VscLaunchConfig;
+
use super::{build::create_base_and_cached_build, util::DEFAULT_TARGET_RELPATH};
use crate::{
- cli::GdbServerArgs,
config::{scheme::ActionChoice, Config},
+ error::Errno,
+ error_msg,
util::{get_current_crate_info, get_target_directory},
};
-pub fn execute_run_command(config: &Config, gdb_server_args: &GdbServerArgs) {
- if gdb_server_args.is_gdb_enabled {
- use std::env;
- env::set_var(
- "RUSTFLAGS",
- env::var("RUSTFLAGS").unwrap_or_default() + " -g",
- );
- }
-
+pub fn execute_run_command(config: &Config, gdb_server_args: Option<&str>) {
let cargo_target_directory = get_target_directory();
let osdk_output_directory = cargo_target_directory.join(DEFAULT_TARGET_RELPATH);
let target_name = get_current_crate_info().name;
let mut config = config.clone();
- if gdb_server_args.is_gdb_enabled {
- let qemu_gdb_args = {
- let gdb_stub_addr = gdb_server_args.gdb_server_addr.as_str();
- match gdb::stub_type_of(gdb_stub_addr) {
- gdb::StubAddrType::Unix => {
- format!(
- " -chardev socket,path={},server=on,wait=off,id=gdb0 -gdb chardev:gdb0 -S",
- gdb_stub_addr
- )
- }
- gdb::StubAddrType::Tcp => {
- format!(
- " -gdb tcp:{} -S",
- gdb::tcp_addr_util::format_tcp_addr(gdb_stub_addr)
- )
- }
- }
- };
- config.run.qemu.args += &qemu_gdb_args;
-
- // Ensure debug info added when debugging in the release profile.
- if config.run.build.profile.contains("release") {
- config
- .run
- .build
- .override_configs
- .push(format!("profile.{}.debug=true", config.run.build.profile));
- }
- }
- let _vsc_launch_file = gdb_server_args.vsc_launch_file.then(|| {
- vsc::check_gdb_config(gdb_server_args);
- let profile = super::util::profile_name_adapter(&config.run.build.profile);
- vsc::VscLaunchConfig::new(profile, &gdb_server_args.gdb_server_addr)
- });
+
+ let _vsc_launch_file = if let Some(gdb_server_str) = gdb_server_args {
+ adapt_for_gdb_server(&mut config, gdb_server_str)
+ } else {
+ None
+ };
let default_bundle_directory = osdk_output_directory.join(target_name);
let bundle = create_base_and_cached_build(
diff --git a/osdk/src/commands/run.rs b/osdk/src/commands/run.rs
--- a/osdk/src/commands/run.rs
+++ b/osdk/src/commands/run.rs
@@ -69,6 +38,82 @@ pub fn execute_run_command(config: &Config, gdb_server_args: &GdbServerArgs) {
bundle.run(&config, ActionChoice::Run);
}
+fn adapt_for_gdb_server(config: &mut Config, gdb_server_str: &str) -> Option<VscLaunchConfig> {
+ let gdb_server_args = GdbServerArgs::from_str(gdb_server_str);
+
+ // Add GDB server arguments to QEMU.
+ let qemu_gdb_args = {
+ let gdb_stub_addr = gdb_server_args.host_addr.as_str();
+ match gdb::stub_type_of(gdb_stub_addr) {
+ gdb::StubAddrType::Unix => {
+ format!(
+ " -chardev socket,path={},server=on,wait=off,id=gdb0 -gdb chardev:gdb0",
+ gdb_stub_addr
+ )
+ }
+ gdb::StubAddrType::Tcp => {
+ format!(
+ " -gdb tcp:{}",
+ gdb::tcp_addr_util::format_tcp_addr(gdb_stub_addr)
+ )
+ }
+ }
+ };
+ config.run.qemu.args += &qemu_gdb_args;
+
+ if gdb_server_args.wait_client {
+ config.run.qemu.args += " -S";
+ }
+
+ // Ensure debug info added when debugging in the release profile.
+ if config.run.build.profile.contains("release") {
+ config
+ .run
+ .build
+ .override_configs
+ .push(format!("profile.{}.debug=true", config.run.build.profile));
+ }
+
+ gdb_server_args.vsc_launch_file.then(|| {
+ vsc::check_gdb_config(&gdb_server_args);
+ let profile = super::util::profile_name_adapter(&config.run.build.profile);
+ vsc::VscLaunchConfig::new(profile, &gdb_server_args.host_addr)
+ })
+}
+
+struct GdbServerArgs {
+ host_addr: String,
+ wait_client: bool,
+ vsc_launch_file: bool,
+}
+
+impl GdbServerArgs {
+ fn from_str(args: &str) -> Self {
+ let mut host_addr = ".osdk-gdb-socket".to_string();
+ let mut wait_client = false;
+ let mut vsc_launch_file = false;
+
+ for arg in args.split(",") {
+ let kv = arg.split('=').collect::<Vec<_>>();
+ match kv.as_slice() {
+ ["addr", addr] => host_addr = addr.to_string(),
+ ["wait-client"] => wait_client = true,
+ ["vscode"] => vsc_launch_file = true,
+ _ => {
+ error_msg!("Invalid GDB server argument: {}", arg);
+ exit(Errno::Cli as _);
+ }
+ }
+ }
+
+ GdbServerArgs {
+ host_addr,
+ wait_client,
+ vsc_launch_file,
+ }
+ }
+}
+
mod gdb {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StubAddrType {
diff --git a/osdk/src/commands/run.rs b/osdk/src/commands/run.rs
--- a/osdk/src/commands/run.rs
+++ b/osdk/src/commands/run.rs
@@ -69,6 +38,82 @@ pub fn execute_run_command(config: &Config, gdb_server_args: &GdbServerArgs) {
bundle.run(&config, ActionChoice::Run);
}
+fn adapt_for_gdb_server(config: &mut Config, gdb_server_str: &str) -> Option<VscLaunchConfig> {
+ let gdb_server_args = GdbServerArgs::from_str(gdb_server_str);
+
+ // Add GDB server arguments to QEMU.
+ let qemu_gdb_args = {
+ let gdb_stub_addr = gdb_server_args.host_addr.as_str();
+ match gdb::stub_type_of(gdb_stub_addr) {
+ gdb::StubAddrType::Unix => {
+ format!(
+ " -chardev socket,path={},server=on,wait=off,id=gdb0 -gdb chardev:gdb0",
+ gdb_stub_addr
+ )
+ }
+ gdb::StubAddrType::Tcp => {
+ format!(
+ " -gdb tcp:{}",
+ gdb::tcp_addr_util::format_tcp_addr(gdb_stub_addr)
+ )
+ }
+ }
+ };
+ config.run.qemu.args += &qemu_gdb_args;
+
+ if gdb_server_args.wait_client {
+ config.run.qemu.args += " -S";
+ }
+
+ // Ensure debug info added when debugging in the release profile.
+ if config.run.build.profile.contains("release") {
+ config
+ .run
+ .build
+ .override_configs
+ .push(format!("profile.{}.debug=true", config.run.build.profile));
+ }
+
+ gdb_server_args.vsc_launch_file.then(|| {
+ vsc::check_gdb_config(&gdb_server_args);
+ let profile = super::util::profile_name_adapter(&config.run.build.profile);
+ vsc::VscLaunchConfig::new(profile, &gdb_server_args.host_addr)
+ })
+}
+
+struct GdbServerArgs {
+ host_addr: String,
+ wait_client: bool,
+ vsc_launch_file: bool,
+}
+
+impl GdbServerArgs {
+ fn from_str(args: &str) -> Self {
+ let mut host_addr = ".osdk-gdb-socket".to_string();
+ let mut wait_client = false;
+ let mut vsc_launch_file = false;
+
+ for arg in args.split(",") {
+ let kv = arg.split('=').collect::<Vec<_>>();
+ match kv.as_slice() {
+ ["addr", addr] => host_addr = addr.to_string(),
+ ["wait-client"] => wait_client = true,
+ ["vscode"] => vsc_launch_file = true,
+ _ => {
+ error_msg!("Invalid GDB server argument: {}", arg);
+ exit(Errno::Cli as _);
+ }
+ }
+ }
+
+ GdbServerArgs {
+ host_addr,
+ wait_client,
+ vsc_launch_file,
+ }
+ }
+}
+
mod gdb {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StubAddrType {
diff --git a/osdk/src/commands/run.rs b/osdk/src/commands/run.rs
--- a/osdk/src/commands/run.rs
+++ b/osdk/src/commands/run.rs
@@ -111,7 +156,6 @@ mod gdb {
mod vsc {
use crate::{
- cli::GdbServerArgs,
commands::util::bin_file_name,
util::{get_cargo_metadata, get_current_crate_info},
};
diff --git a/osdk/src/commands/run.rs b/osdk/src/commands/run.rs
--- a/osdk/src/commands/run.rs
+++ b/osdk/src/commands/run.rs
@@ -111,7 +156,6 @@ mod gdb {
mod vsc {
use crate::{
- cli::GdbServerArgs,
commands::util::bin_file_name,
util::{get_cargo_metadata, get_current_crate_info},
};
diff --git a/osdk/src/commands/run.rs b/osdk/src/commands/run.rs
--- a/osdk/src/commands/run.rs
+++ b/osdk/src/commands/run.rs
@@ -121,7 +165,7 @@ mod vsc {
path::Path,
};
- use super::gdb;
+ use super::{gdb, GdbServerArgs};
const VSC_DIR: &str = ".vscode";
diff --git a/osdk/src/commands/run.rs b/osdk/src/commands/run.rs
--- a/osdk/src/commands/run.rs
+++ b/osdk/src/commands/run.rs
@@ -121,7 +165,7 @@ mod vsc {
path::Path,
};
- use super::gdb;
+ use super::{gdb, GdbServerArgs};
const VSC_DIR: &str = ".vscode";
diff --git a/osdk/src/commands/run.rs b/osdk/src/commands/run.rs
--- a/osdk/src/commands/run.rs
+++ b/osdk/src/commands/run.rs
@@ -170,6 +214,7 @@ mod vsc {
}
}
}
+
impl Drop for VscLaunchConfig {
fn drop(&mut self) {
// remove generated files
diff --git a/osdk/src/commands/run.rs b/osdk/src/commands/run.rs
--- a/osdk/src/commands/run.rs
+++ b/osdk/src/commands/run.rs
@@ -170,6 +214,7 @@ mod vsc {
}
}
}
+
impl Drop for VscLaunchConfig {
fn drop(&mut self) {
// remove generated files
diff --git a/osdk/src/commands/run.rs b/osdk/src/commands/run.rs
--- a/osdk/src/commands/run.rs
+++ b/osdk/src/commands/run.rs
@@ -205,22 +250,16 @@ mod vsc {
use crate::{error::Errno, error_msg};
use std::process::exit;
- if !args.is_gdb_enabled {
- error_msg!(
- "No need for a VSCode launch file without launching GDB server,\
- pass '-h' for help"
- );
- exit(Errno::ParseMetadata as _);
- }
-
// check GDB server address
- let gdb_stub_addr = args.gdb_server_addr.as_str();
+ let gdb_stub_addr = args.host_addr.as_str();
if gdb_stub_addr.is_empty() {
error_msg!("GDB server address is required to generate a VSCode launch file");
exit(Errno::ParseMetadata as _);
}
if gdb::stub_type_of(gdb_stub_addr) != gdb::StubAddrType::Tcp {
- error_msg!("Non-TCP GDB server address is not supported under '--vsc' currently");
+ error_msg!(
+ "Non-TCP GDB server address is not supported under '--gdb-server vscode' currently"
+ );
exit(Errno::ParseMetadata as _);
}
}
diff --git a/osdk/src/commands/run.rs b/osdk/src/commands/run.rs
--- a/osdk/src/commands/run.rs
+++ b/osdk/src/commands/run.rs
@@ -205,22 +250,16 @@ mod vsc {
use crate::{error::Errno, error_msg};
use std::process::exit;
- if !args.is_gdb_enabled {
- error_msg!(
- "No need for a VSCode launch file without launching GDB server,\
- pass '-h' for help"
- );
- exit(Errno::ParseMetadata as _);
- }
-
// check GDB server address
- let gdb_stub_addr = args.gdb_server_addr.as_str();
+ let gdb_stub_addr = args.host_addr.as_str();
if gdb_stub_addr.is_empty() {
error_msg!("GDB server address is required to generate a VSCode launch file");
exit(Errno::ParseMetadata as _);
}
if gdb::stub_type_of(gdb_stub_addr) != gdb::StubAddrType::Tcp {
- error_msg!("Non-TCP GDB server address is not supported under '--vsc' currently");
+ error_msg!(
+ "Non-TCP GDB server address is not supported under '--gdb-server vscode' currently"
+ );
exit(Errno::ParseMetadata as _);
}
}
diff --git a/osdk/src/error.rs b/osdk/src/error.rs
--- a/osdk/src/error.rs
+++ b/osdk/src/error.rs
@@ -3,14 +3,15 @@
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Errno {
- CreateCrate = 1,
- GetMetadata = 2,
- AddRustToolchain = 3,
- ParseMetadata = 4,
- ExecuteCommand = 5,
- BuildCrate = 6,
- RunBundle = 7,
- BadCrateName = 8,
+ Cli = 1,
+ CreateCrate = 2,
+ GetMetadata = 3,
+ AddRustToolchain = 4,
+ ParseMetadata = 5,
+ ExecuteCommand = 6,
+ BuildCrate = 7,
+ RunBundle = 8,
+ BadCrateName = 9,
}
/// Print error message to console
diff --git a/osdk/src/error.rs b/osdk/src/error.rs
--- a/osdk/src/error.rs
+++ b/osdk/src/error.rs
@@ -3,14 +3,15 @@
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Errno {
- CreateCrate = 1,
- GetMetadata = 2,
- AddRustToolchain = 3,
- ParseMetadata = 4,
- ExecuteCommand = 5,
- BuildCrate = 6,
- RunBundle = 7,
- BadCrateName = 8,
+ Cli = 1,
+ CreateCrate = 2,
+ GetMetadata = 3,
+ AddRustToolchain = 4,
+ ParseMetadata = 5,
+ ExecuteCommand = 6,
+ BuildCrate = 7,
+ RunBundle = 8,
+ BadCrateName = 9,
}
/// Print error message to console
diff --git a/osdk/tests/commands/run.rs b/osdk/tests/commands/run.rs
--- a/osdk/tests/commands/run.rs
+++ b/osdk/tests/commands/run.rs
@@ -79,7 +79,11 @@ mod qemu_gdb_feature {
path.to_string_lossy().to_string()
};
- let mut instance = cargo_osdk(["run", "-G", "--gdb-server-addr", unix_socket.as_str()]);
+ let mut instance = cargo_osdk([
+ "run",
+ "--gdb-server",
+ format!("addr={},wait-client", unix_socket.as_str()).as_str(),
+ ]);
instance.current_dir(&workspace.os_dir());
let sock = unix_socket.clone();
diff --git a/osdk/tests/commands/run.rs b/osdk/tests/commands/run.rs
--- a/osdk/tests/commands/run.rs
+++ b/osdk/tests/commands/run.rs
@@ -106,8 +110,8 @@ mod qemu_gdb_feature {
let mut gdb = Command::new("gdb");
gdb.args(["-ex", format!("target remote {}", addr).as_str()]);
gdb.write_stdin("\n")
- .write_stdin("c\n")
- .write_stdin("quit\n");
+ .write_stdin("quit\n")
+ .write_stdin("y\n");
gdb.assert().success();
}
mod vsc {
diff --git a/osdk/tests/commands/run.rs b/osdk/tests/commands/run.rs
--- a/osdk/tests/commands/run.rs
+++ b/osdk/tests/commands/run.rs
@@ -123,14 +127,18 @@ mod qemu_gdb_feature {
let workspace = workspace::WorkSpace::new(WORKSPACE, kernel_name);
let addr = ":50001";
- let mut instance = cargo_osdk(["run", "-G", "--vsc", "--gdb-server-addr", addr]);
+ let mut instance = cargo_osdk([
+ "run",
+ "--gdb-server",
+ format!("wait-client,vscode,addr={}", addr).as_str(),
+ ]);
instance.current_dir(&workspace.os_dir());
let dir = workspace.os_dir();
let bin_file_path = Path::new(&workspace.os_dir())
.join("target")
- .join("x86_64-unknown-none")
- .join("debug")
+ .join("osdk")
+ .join(kernel_name)
.join(format!("{}-osdk-bin", kernel_name));
let _gdb = std::thread::spawn(move || {
while !bin_file_path.exists() {
|
2024-09-21T13:48:03Z
|
ae4ac384713e63232b74915593ebdef680049d31
|
|
asterinas/asterinas
|
diff --git a/kernel/src/lib.rs b/kernel/src/lib.rs
--- a/kernel/src/lib.rs
+++ b/kernel/src/lib.rs
@@ -146,15 +143,8 @@ fn init_thread() {
// driver::pci::virtio::block::block_device_test();
let thread = Thread::spawn_kernel_thread(ThreadOptions::new(|| {
println!("[kernel] Hello world from kernel!");
- let current = current_thread!();
- let tid = current.tid();
- debug!("current tid = {}", tid);
}));
thread.join();
- info!(
- "[aster-nix/lib.rs] spawn kernel thread, tid = {}",
- thread.tid()
- );
print_banner();
diff --git a/kernel/src/process/process/mod.rs b/kernel/src/process/process/mod.rs
--- a/kernel/src/process/process/mod.rs
+++ b/kernel/src/process/process/mod.rs
@@ -710,7 +718,7 @@ mod test {
fn new_process(parent: Option<Arc<Process>>) -> Arc<Process> {
crate::util::random::init();
crate::fs::rootfs::init_root_mount();
- let pid = allocate_tid();
+ let pid = allocate_posix_tid();
let parent = if let Some(parent) = parent {
Arc::downgrade(&parent)
} else {
diff --git a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
--- a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
+++ b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
@@ -102,11 +102,13 @@ fn create_user_task(user_space: Arc<UserSpace>) -> Arc<Task> {
// Kernel tasks are managed by the Framework,
// while scheduling algorithms for them can be
// determined by the users of the Framework.
- TaskOptions::new(user_task)
- .user_space(Some(user_space))
- .data(0)
- .build()
- .unwrap()
+ Arc::new(
+ TaskOptions::new(user_task)
+ .user_space(Some(user_space))
+ .data(0)
+ .build()
+ .unwrap(),
+ )
}
fn handle_syscall(user_context: &mut UserContext, user_space: &UserSpace) {
diff --git a/ostd/src/task/mod.rs b/ostd/src/task/mod.rs
--- a/ostd/src/task/mod.rs
+++ b/ostd/src/task/mod.rs
@@ -237,11 +237,13 @@ mod test {
let task = || {
assert_eq!(1, 1);
};
- let task_option = crate::task::TaskOptions::new(task)
- .data(())
- .build()
- .unwrap();
- task_option.run();
+ let task = Arc::new(
+ crate::task::TaskOptions::new(task)
+ .data(())
+ .build()
+ .unwrap(),
+ );
+ task.run();
}
#[ktest]
|
[
"1244"
] |
0.8
|
42e28763c59202486af4298d5305e5c5e5ab9b54
|
Reachable unwrap panic in `read_clock()`
### Describe the bug
There is a reachable unwrap panic in `read_clock()` at kernel/src/syscall/clock_gettime.rs:141 when make a `clock_gettime` syscall with specific argument.
https://github.com/asterinas/asterinas/blob/aa77747f94c4b1cb1237ba52414642827a6efc25/kernel/src/syscall/clock_gettime.rs#L141
### To Reproduce
1. Compile a program which calls `clock_gettime`:
```C
#include <errno.h>
#include <stdio.h>
#include <sys/syscall.h>
#include <time.h>
#include <unistd.h>
int main() {
clock_gettime(-10, 0x1);
perror("clock_gettime");
return 0;
}
```
2. Run the compiled program in Asterinas.
### Expected behavior
Asterinas reports panic and is terminated.
### Environment
- Official docker asterinas/asterinas:0.8.0
- 11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz
- Asterinas version: main aa77747f
### Logs
```
~ # /root/clock_gettime.c
panicked at /root/asterinas/kernel/src/syscall/clock_gettime.rs:141:61:
called `Option::unwrap()` on a `None` value
Printing stack trace:
1: fn 0xffffffff8880e1c0 - pc 0xffffffff8880e1d8 / registers:
rax 0x12; rdx 0xffffffff88a3a1a0; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff80007f6297c0;
2: fn 0xffffffff8880dfa0 - pc 0xffffffff8880e118 / registers:
rax 0x12; rdx 0xffffffff88a3a1a0; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff80007f6297d0;
3: fn 0xffffffff88049000 - pc 0xffffffff8804900a / registers:
rax 0x12; rdx 0xffffffff88a3a1a0; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff80007f629950;
4: fn 0xffffffff889b0fb0 - pc 0xffffffff889b1032 / registers:
rax 0x12; rdx 0xffffffff88a3a1a0; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff80007f629960;
5: fn 0xffffffff889b1150 - pc 0xffffffff889b1190 / registers:
rax 0x12; rdx 0xffffffff88a3a1a0; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff80007f6299f0;
6: fn 0xffffffff8899a710 - pc 0xffffffff8899a725 / registers:
rax 0x12; rdx 0xffffffff88a3a1a0; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff80007f629a60;
7: fn 0xffffffff884f2290 - pc 0xffffffff884f289f / registers:
rax 0x12; rdx 0xffffffff88a3a1a0; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff80007f629a70;
8: fn 0xffffffff884f1d20 - pc 0xffffffff884f1d81 / registers:
rax 0x12; rdx 0xffffffff88a3a1a0; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff80007f629d30;
9: fn 0xffffffff88161a50 - pc 0xffffffff8818d4ab / registers:
rax 0x12; rdx 0xffffffff88a3a1a0; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff80007f629f30;
10: fn 0xffffffff88152f60 - pc 0xffffffff88152fee / registers:
rax 0x12; rdx 0xffffffff88a3a1a0; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff80007f6403d0;
11: fn 0xffffffff88110380 - pc 0xffffffff88110eff / registers:
rax 0x12; rdx 0xffffffff88a3a1a0; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff80007f640570;
12: fn 0xffffffff8845cb70 - pc 0xffffffff8845cb7e / registers:
rax 0x12; rdx 0xffffffff88a3a1a0; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff80007f640f90;
13: fn 0xffffffff887cdc50 - pc 0xffffffff887cdc66 / registers:
rax 0x12; rdx 0xffffffff88a3a1a0; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff80007f640fb0;
14: fn 0xffffffff887b0280 - pc 0xffffffff887b02e9 / registers:
rax 0x12; rdx 0xffffffff88a3a1a0; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff80007f640fd0;
rax 0x12; rdx 0xffffffff88a3a1a0; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff80007f641000;
[OSDK] The kernel seems panicked. Parsing stack trace for source lines:
( 1) /root/asterinas/ostd/src/panicking.rs:106
( 2) /root/asterinas/ostd/src/panicking.rs:59
( 3) 89yvfinwjerz0clyodmhm6lzz:?
( 4) ??:?
( 5) /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/panicking.rs:220
( 6) ??:?
( 7) /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/option.rs:961
( 8) /root/asterinas/kernel/src/syscall/clock_gettime.rs:29
( 9) /root/asterinas/kernel/src/syscall/mod.rs:164
( 10) /root/asterinas/kernel/src/syscall/mod.rs:328
( 11) /root/asterinas/kernel/src/thread/task.rs:69
( 12) /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:79
( 13) /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2077
( 14) /root/asterinas/ostd/src/task/task/mod.rs:341
make: *** [Makefile:167: run] Error 1
```
|
asterinas__asterinas-1328
| 1,328
|
diff --git a/kernel/src/lib.rs b/kernel/src/lib.rs
--- a/kernel/src/lib.rs
+++ b/kernel/src/lib.rs
@@ -133,10 +133,7 @@ fn ap_init() -> ! {
}
fn init_thread() {
- println!(
- "[kernel] Spawn init thread, tid = {}",
- current_thread!().tid()
- );
+ println!("[kernel] Spawn init thread");
// Work queue should be initialized before interrupt is enabled,
// in case any irq handler uses work queue as bottom half
thread::work_queue::init();
diff --git a/kernel/src/lib.rs b/kernel/src/lib.rs
--- a/kernel/src/lib.rs
+++ b/kernel/src/lib.rs
@@ -133,10 +133,7 @@ fn ap_init() -> ! {
}
fn init_thread() {
- println!(
- "[kernel] Spawn init thread, tid = {}",
- current_thread!().tid()
- );
+ println!("[kernel] Spawn init thread");
// Work queue should be initialized before interrupt is enabled,
// in case any irq handler uses work queue as bottom half
thread::work_queue::init();
diff --git a/kernel/src/lib.rs b/kernel/src/lib.rs
--- a/kernel/src/lib.rs
+++ b/kernel/src/lib.rs
@@ -146,15 +143,8 @@ fn init_thread() {
// driver::pci::virtio::block::block_device_test();
let thread = Thread::spawn_kernel_thread(ThreadOptions::new(|| {
println!("[kernel] Hello world from kernel!");
- let current = current_thread!();
- let tid = current.tid();
- debug!("current tid = {}", tid);
}));
thread.join();
- info!(
- "[aster-nix/lib.rs] spawn kernel thread, tid = {}",
- thread.tid()
- );
print_banner();
diff --git a/kernel/src/process/clone.rs b/kernel/src/process/clone.rs
--- a/kernel/src/process/clone.rs
+++ b/kernel/src/process/clone.rs
@@ -4,11 +4,12 @@ use core::sync::atomic::Ordering;
use ostd::{
cpu::UserContext,
+ task::Task,
user::{UserContextApi, UserSpace},
};
use super::{
- posix_thread::{PosixThread, PosixThreadBuilder, PosixThreadExt, ThreadName},
+ posix_thread::{thread_table, PosixThread, PosixThreadBuilder, PosixThreadExt, ThreadName},
process_table,
process_vm::ProcessVm,
signal::sig_disposition::SigDispositions,
diff --git a/kernel/src/process/clone.rs b/kernel/src/process/clone.rs
--- a/kernel/src/process/clone.rs
+++ b/kernel/src/process/clone.rs
@@ -4,11 +4,12 @@ use core::sync::atomic::Ordering;
use ostd::{
cpu::UserContext,
+ task::Task,
user::{UserContextApi, UserSpace},
};
use super::{
- posix_thread::{PosixThread, PosixThreadBuilder, PosixThreadExt, ThreadName},
+ posix_thread::{thread_table, PosixThread, PosixThreadBuilder, PosixThreadExt, ThreadName},
process_table,
process_vm::ProcessVm,
signal::sig_disposition::SigDispositions,
diff --git a/kernel/src/process/clone.rs b/kernel/src/process/clone.rs
--- a/kernel/src/process/clone.rs
+++ b/kernel/src/process/clone.rs
@@ -18,7 +19,8 @@ use crate::{
cpu::LinuxAbi,
fs::{file_table::FileTable, fs_resolver::FsResolver, utils::FileCreationMask},
prelude::*,
- thread::{allocate_tid, thread_table, Thread, Tid},
+ process::posix_thread::allocate_posix_tid,
+ thread::{Thread, Tid},
};
bitflags! {
diff --git a/kernel/src/process/clone.rs b/kernel/src/process/clone.rs
--- a/kernel/src/process/clone.rs
+++ b/kernel/src/process/clone.rs
@@ -18,7 +19,8 @@ use crate::{
cpu::LinuxAbi,
fs::{file_table::FileTable, fs_resolver::FsResolver, utils::FileCreationMask},
prelude::*,
- thread::{allocate_tid, thread_table, Thread, Tid},
+ process::posix_thread::allocate_posix_tid,
+ thread::{Thread, Tid},
};
bitflags! {
diff --git a/kernel/src/process/clone.rs b/kernel/src/process/clone.rs
--- a/kernel/src/process/clone.rs
+++ b/kernel/src/process/clone.rs
@@ -132,7 +134,8 @@ pub fn clone_child(
) -> Result<Tid> {
clone_args.clone_flags.check_unsupported_flags()?;
if clone_args.clone_flags.contains(CloneFlags::CLONE_THREAD) {
- let child_thread = clone_child_thread(ctx, parent_context, clone_args)?;
+ let child_task = clone_child_task(ctx, parent_context, clone_args)?;
+ let child_thread = Thread::borrow_from_task(&child_task);
child_thread.run();
let child_tid = child_thread.tid();
diff --git a/kernel/src/process/clone.rs b/kernel/src/process/clone.rs
--- a/kernel/src/process/clone.rs
+++ b/kernel/src/process/clone.rs
@@ -132,7 +134,8 @@ pub fn clone_child(
) -> Result<Tid> {
clone_args.clone_flags.check_unsupported_flags()?;
if clone_args.clone_flags.contains(CloneFlags::CLONE_THREAD) {
- let child_thread = clone_child_thread(ctx, parent_context, clone_args)?;
+ let child_task = clone_child_task(ctx, parent_context, clone_args)?;
+ let child_thread = Thread::borrow_from_task(&child_task);
child_thread.run();
let child_tid = child_thread.tid();
diff --git a/kernel/src/process/clone.rs b/kernel/src/process/clone.rs
--- a/kernel/src/process/clone.rs
+++ b/kernel/src/process/clone.rs
@@ -146,11 +149,11 @@ pub fn clone_child(
}
}
-fn clone_child_thread(
+fn clone_child_task(
ctx: &Context,
parent_context: &UserContext,
clone_args: CloneArgs,
-) -> Result<Arc<Thread>> {
+) -> Result<Arc<Task>> {
let Context {
process,
posix_thread,
diff --git a/kernel/src/process/clone.rs b/kernel/src/process/clone.rs
--- a/kernel/src/process/clone.rs
+++ b/kernel/src/process/clone.rs
@@ -146,11 +149,11 @@ pub fn clone_child(
}
}
-fn clone_child_thread(
+fn clone_child_task(
ctx: &Context,
parent_context: &UserContext,
clone_args: CloneArgs,
-) -> Result<Arc<Thread>> {
+) -> Result<Arc<Task>> {
let Context {
process,
posix_thread,
diff --git a/kernel/src/process/clone.rs b/kernel/src/process/clone.rs
--- a/kernel/src/process/clone.rs
+++ b/kernel/src/process/clone.rs
@@ -180,8 +183,8 @@ fn clone_child_thread(
// Inherit sigmask from current thread
let sig_mask = posix_thread.sig_mask().load(Ordering::Relaxed).into();
- let child_tid = allocate_tid();
- let child_thread = {
+ let child_tid = allocate_posix_tid();
+ let child_task = {
let credentials = {
let credentials = ctx.posix_thread.credentials();
Credentials::new_from(&credentials)
diff --git a/kernel/src/process/clone.rs b/kernel/src/process/clone.rs
--- a/kernel/src/process/clone.rs
+++ b/kernel/src/process/clone.rs
@@ -180,8 +183,8 @@ fn clone_child_thread(
// Inherit sigmask from current thread
let sig_mask = posix_thread.sig_mask().load(Ordering::Relaxed).into();
- let child_tid = allocate_tid();
- let child_thread = {
+ let child_tid = allocate_posix_tid();
+ let child_task = {
let credentials = {
let credentials = ctx.posix_thread.credentials();
Credentials::new_from(&credentials)
diff --git a/kernel/src/process/clone.rs b/kernel/src/process/clone.rs
--- a/kernel/src/process/clone.rs
+++ b/kernel/src/process/clone.rs
@@ -193,13 +196,13 @@ fn clone_child_thread(
thread_builder.build()
};
- process.threads().lock().push(child_thread.clone());
+ process.tasks().lock().push(child_task.clone());
- let child_posix_thread = child_thread.as_posix_thread().unwrap();
+ let child_posix_thread = child_task.as_posix_thread().unwrap();
clone_parent_settid(child_tid, clone_args.parent_tidptr, clone_flags)?;
clone_child_cleartid(child_posix_thread, clone_args.child_tidptr, clone_flags)?;
clone_child_settid(child_posix_thread, clone_args.child_tidptr, clone_flags)?;
- Ok(child_thread)
+ Ok(child_task)
}
fn clone_child_process(
diff --git a/kernel/src/process/clone.rs b/kernel/src/process/clone.rs
--- a/kernel/src/process/clone.rs
+++ b/kernel/src/process/clone.rs
@@ -193,13 +196,13 @@ fn clone_child_thread(
thread_builder.build()
};
- process.threads().lock().push(child_thread.clone());
+ process.tasks().lock().push(child_task.clone());
- let child_posix_thread = child_thread.as_posix_thread().unwrap();
+ let child_posix_thread = child_task.as_posix_thread().unwrap();
clone_parent_settid(child_tid, clone_args.parent_tidptr, clone_flags)?;
clone_child_cleartid(child_posix_thread, clone_args.child_tidptr, clone_flags)?;
clone_child_settid(child_posix_thread, clone_args.child_tidptr, clone_flags)?;
- Ok(child_thread)
+ Ok(child_task)
}
fn clone_child_process(
diff --git a/kernel/src/process/clone.rs b/kernel/src/process/clone.rs
--- a/kernel/src/process/clone.rs
+++ b/kernel/src/process/clone.rs
@@ -262,7 +265,7 @@ fn clone_child_process(
// inherit parent's nice value
let child_nice = process.nice().load(Ordering::Relaxed);
- let child_tid = allocate_tid();
+ let child_tid = allocate_posix_tid();
let child = {
let child_elf_path = process.executable_path();
diff --git a/kernel/src/process/clone.rs b/kernel/src/process/clone.rs
--- a/kernel/src/process/clone.rs
+++ b/kernel/src/process/clone.rs
@@ -262,7 +265,7 @@ fn clone_child_process(
// inherit parent's nice value
let child_nice = process.nice().load(Ordering::Relaxed);
- let child_tid = allocate_tid();
+ let child_tid = allocate_posix_tid();
let child = {
let child_elf_path = process.executable_path();
diff --git a/kernel/src/process/exit.rs b/kernel/src/process/exit.rs
--- a/kernel/src/process/exit.rs
+++ b/kernel/src/process/exit.rs
@@ -4,9 +4,10 @@ use super::{process_table, Pid, Process, TermStatus};
use crate::{
prelude::*,
process::{
- posix_thread::do_exit,
+ posix_thread::{do_exit, PosixThreadExt},
signal::{constants::SIGCHLD, signals::kernel::KernelSignal},
},
+ thread::Thread,
};
pub fn do_exit_group(term_status: TermStatus) {
diff --git a/kernel/src/process/exit.rs b/kernel/src/process/exit.rs
--- a/kernel/src/process/exit.rs
+++ b/kernel/src/process/exit.rs
@@ -4,9 +4,10 @@ use super::{process_table, Pid, Process, TermStatus};
use crate::{
prelude::*,
process::{
- posix_thread::do_exit,
+ posix_thread::{do_exit, PosixThreadExt},
signal::{constants::SIGCHLD, signals::kernel::KernelSignal},
},
+ thread::Thread,
};
pub fn do_exit_group(term_status: TermStatus) {
diff --git a/kernel/src/process/exit.rs b/kernel/src/process/exit.rs
--- a/kernel/src/process/exit.rs
+++ b/kernel/src/process/exit.rs
@@ -18,9 +19,11 @@ pub fn do_exit_group(term_status: TermStatus) {
current.set_zombie(term_status);
// Exit all threads
- let threads = current.threads().lock().clone();
- for thread in threads {
- if let Err(e) = do_exit(thread, term_status) {
+ let tasks = current.tasks().lock().clone();
+ for task in tasks {
+ let thread = Thread::borrow_from_task(&task);
+ let posix_thread = thread.as_posix_thread().unwrap();
+ if let Err(e) = do_exit(thread, posix_thread, term_status) {
debug!("Ignore error when call exit: {:?}", e);
}
}
diff --git a/kernel/src/process/exit.rs b/kernel/src/process/exit.rs
--- a/kernel/src/process/exit.rs
+++ b/kernel/src/process/exit.rs
@@ -18,9 +19,11 @@ pub fn do_exit_group(term_status: TermStatus) {
current.set_zombie(term_status);
// Exit all threads
- let threads = current.threads().lock().clone();
- for thread in threads {
- if let Err(e) = do_exit(thread, term_status) {
+ let tasks = current.tasks().lock().clone();
+ for task in tasks {
+ let thread = Thread::borrow_from_task(&task);
+ let posix_thread = thread.as_posix_thread().unwrap();
+ if let Err(e) = do_exit(thread, posix_thread, term_status) {
debug!("Ignore error when call exit: {:?}", e);
}
}
diff --git a/kernel/src/process/kill.rs b/kernel/src/process/kill.rs
--- a/kernel/src/process/kill.rs
+++ b/kernel/src/process/kill.rs
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: MPL-2.0
use super::{
- posix_thread::PosixThreadExt,
+ posix_thread::{thread_table, PosixThreadExt},
process_table,
signal::{
constants::SIGCONT,
diff --git a/kernel/src/process/kill.rs b/kernel/src/process/kill.rs
--- a/kernel/src/process/kill.rs
+++ b/kernel/src/process/kill.rs
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: MPL-2.0
use super::{
- posix_thread::PosixThreadExt,
+ posix_thread::{thread_table, PosixThreadExt},
process_table,
signal::{
constants::SIGCONT,
diff --git a/kernel/src/process/kill.rs b/kernel/src/process/kill.rs
--- a/kernel/src/process/kill.rs
+++ b/kernel/src/process/kill.rs
@@ -10,10 +10,7 @@ use super::{
},
Pgid, Pid, Process, Sid, Uid,
};
-use crate::{
- prelude::*,
- thread::{thread_table, Tid},
-};
+use crate::{prelude::*, thread::Tid};
/// Sends a signal to a process, using the current process as the sender.
///
diff --git a/kernel/src/process/kill.rs b/kernel/src/process/kill.rs
--- a/kernel/src/process/kill.rs
+++ b/kernel/src/process/kill.rs
@@ -10,10 +10,7 @@ use super::{
},
Pgid, Pid, Process, Sid, Uid,
};
-use crate::{
- prelude::*,
- thread::{thread_table, Tid},
-};
+use crate::{prelude::*, thread::Tid};
/// Sends a signal to a process, using the current process as the sender.
///
diff --git a/kernel/src/process/kill.rs b/kernel/src/process/kill.rs
--- a/kernel/src/process/kill.rs
+++ b/kernel/src/process/kill.rs
@@ -120,14 +117,14 @@ pub fn kill_all(signal: Option<UserSignal>, ctx: &Context) -> Result<()> {
}
fn kill_process(process: &Process, signal: Option<UserSignal>, ctx: &Context) -> Result<()> {
- let threads = process.threads().lock();
+ let tasks = process.tasks().lock();
let signum = signal.map(|signal| signal.num());
let sender_ids = current_thread_sender_ids(signum.as_ref(), ctx);
let mut permitted_thread = None;
- for thread in threads.iter() {
- let posix_thread = thread.as_posix_thread().unwrap();
+ for task in tasks.iter() {
+ let posix_thread = task.as_posix_thread().unwrap();
// First check permission
if posix_thread
diff --git a/kernel/src/process/kill.rs b/kernel/src/process/kill.rs
--- a/kernel/src/process/kill.rs
+++ b/kernel/src/process/kill.rs
@@ -120,14 +117,14 @@ pub fn kill_all(signal: Option<UserSignal>, ctx: &Context) -> Result<()> {
}
fn kill_process(process: &Process, signal: Option<UserSignal>, ctx: &Context) -> Result<()> {
- let threads = process.threads().lock();
+ let tasks = process.tasks().lock();
let signum = signal.map(|signal| signal.num());
let sender_ids = current_thread_sender_ids(signum.as_ref(), ctx);
let mut permitted_thread = None;
- for thread in threads.iter() {
- let posix_thread = thread.as_posix_thread().unwrap();
+ for task in tasks.iter() {
+ let posix_thread = task.as_posix_thread().unwrap();
// First check permission
if posix_thread
diff --git a/kernel/src/process/posix_thread/builder.rs b/kernel/src/process/posix_thread/builder.rs
--- a/kernel/src/process/posix_thread/builder.rs
+++ b/kernel/src/process/posix_thread/builder.rs
@@ -2,9 +2,9 @@
#![allow(dead_code)]
-use ostd::user::UserSpace;
+use ostd::{task::Task, user::UserSpace};
-use super::PosixThread;
+use super::{thread_table, PosixThread};
use crate::{
prelude::*,
process::{
diff --git a/kernel/src/process/posix_thread/builder.rs b/kernel/src/process/posix_thread/builder.rs
--- a/kernel/src/process/posix_thread/builder.rs
+++ b/kernel/src/process/posix_thread/builder.rs
@@ -2,9 +2,9 @@
#![allow(dead_code)]
-use ostd::user::UserSpace;
+use ostd::{task::Task, user::UserSpace};
-use super::PosixThread;
+use super::{thread_table, PosixThread};
use crate::{
prelude::*,
process::{
diff --git a/kernel/src/process/posix_thread/builder.rs b/kernel/src/process/posix_thread/builder.rs
--- a/kernel/src/process/posix_thread/builder.rs
+++ b/kernel/src/process/posix_thread/builder.rs
@@ -12,7 +12,7 @@ use crate::{
signal::{sig_mask::AtomicSigMask, sig_queues::SigQueues},
Credentials, Process,
},
- thread::{status::ThreadStatus, task, thread_table, Thread, Tid},
+ thread::{status::ThreadStatus, task, Thread, Tid},
time::{clocks::ProfClock, TimerManager},
};
diff --git a/kernel/src/process/posix_thread/builder.rs b/kernel/src/process/posix_thread/builder.rs
--- a/kernel/src/process/posix_thread/builder.rs
+++ b/kernel/src/process/posix_thread/builder.rs
@@ -12,7 +12,7 @@ use crate::{
signal::{sig_mask::AtomicSigMask, sig_queues::SigQueues},
Credentials, Process,
},
- thread::{status::ThreadStatus, task, thread_table, Thread, Tid},
+ thread::{status::ThreadStatus, task, Thread, Tid},
time::{clocks::ProfClock, TimerManager},
};
diff --git a/kernel/src/process/posix_thread/builder.rs b/kernel/src/process/posix_thread/builder.rs
--- a/kernel/src/process/posix_thread/builder.rs
+++ b/kernel/src/process/posix_thread/builder.rs
@@ -72,7 +72,7 @@ impl PosixThreadBuilder {
self
}
- pub fn build(self) -> Arc<Thread> {
+ pub fn build(self) -> Arc<Task> {
let Self {
tid,
user_space,
diff --git a/kernel/src/process/posix_thread/builder.rs b/kernel/src/process/posix_thread/builder.rs
--- a/kernel/src/process/posix_thread/builder.rs
+++ b/kernel/src/process/posix_thread/builder.rs
@@ -72,7 +72,7 @@ impl PosixThreadBuilder {
self
}
- pub fn build(self) -> Arc<Thread> {
+ pub fn build(self) -> Arc<Task> {
let Self {
tid,
user_space,
diff --git a/kernel/src/process/posix_thread/builder.rs b/kernel/src/process/posix_thread/builder.rs
--- a/kernel/src/process/posix_thread/builder.rs
+++ b/kernel/src/process/posix_thread/builder.rs
@@ -85,34 +85,36 @@ impl PosixThreadBuilder {
sig_queues,
} = self;
- let thread = Arc::new_cyclic(|thread_ref| {
- let task = task::create_new_user_task(user_space, thread_ref.clone());
- let status = ThreadStatus::Init;
-
- let prof_clock = ProfClock::new();
- let virtual_timer_manager = TimerManager::new(prof_clock.user_clock().clone());
- let prof_timer_manager = TimerManager::new(prof_clock.clone());
-
- let posix_thread = PosixThread {
- process,
- name: Mutex::new(thread_name),
- set_child_tid: Mutex::new(set_child_tid),
- clear_child_tid: Mutex::new(clear_child_tid),
- credentials,
- sig_mask,
- sig_queues,
- sig_context: Mutex::new(None),
- sig_stack: Mutex::new(None),
- signalled_waker: SpinLock::new(None),
- robust_list: Mutex::new(None),
- prof_clock,
- virtual_timer_manager,
- prof_timer_manager,
+ Arc::new_cyclic(|weak_task| {
+ let posix_thread = {
+ let prof_clock = ProfClock::new();
+ let virtual_timer_manager = TimerManager::new(prof_clock.user_clock().clone());
+ let prof_timer_manager = TimerManager::new(prof_clock.clone());
+
+ PosixThread {
+ process,
+ tid,
+ name: Mutex::new(thread_name),
+ set_child_tid: Mutex::new(set_child_tid),
+ clear_child_tid: Mutex::new(clear_child_tid),
+ credentials,
+ sig_mask,
+ sig_queues,
+ sig_context: Mutex::new(None),
+ sig_stack: Mutex::new(None),
+ signalled_waker: SpinLock::new(None),
+ robust_list: Mutex::new(None),
+ prof_clock,
+ virtual_timer_manager,
+ prof_timer_manager,
+ }
};
- Thread::new(tid, task, posix_thread, status)
- });
- thread_table::add_thread(thread.clone());
- thread
+ let status = ThreadStatus::Init;
+ let thread = Arc::new(Thread::new(weak_task.clone(), posix_thread, status));
+
+ thread_table::add_thread(tid, thread.clone());
+ task::create_new_user_task(user_space, thread)
+ })
}
}
diff --git a/kernel/src/process/posix_thread/builder.rs b/kernel/src/process/posix_thread/builder.rs
--- a/kernel/src/process/posix_thread/builder.rs
+++ b/kernel/src/process/posix_thread/builder.rs
@@ -85,34 +85,36 @@ impl PosixThreadBuilder {
sig_queues,
} = self;
- let thread = Arc::new_cyclic(|thread_ref| {
- let task = task::create_new_user_task(user_space, thread_ref.clone());
- let status = ThreadStatus::Init;
-
- let prof_clock = ProfClock::new();
- let virtual_timer_manager = TimerManager::new(prof_clock.user_clock().clone());
- let prof_timer_manager = TimerManager::new(prof_clock.clone());
-
- let posix_thread = PosixThread {
- process,
- name: Mutex::new(thread_name),
- set_child_tid: Mutex::new(set_child_tid),
- clear_child_tid: Mutex::new(clear_child_tid),
- credentials,
- sig_mask,
- sig_queues,
- sig_context: Mutex::new(None),
- sig_stack: Mutex::new(None),
- signalled_waker: SpinLock::new(None),
- robust_list: Mutex::new(None),
- prof_clock,
- virtual_timer_manager,
- prof_timer_manager,
+ Arc::new_cyclic(|weak_task| {
+ let posix_thread = {
+ let prof_clock = ProfClock::new();
+ let virtual_timer_manager = TimerManager::new(prof_clock.user_clock().clone());
+ let prof_timer_manager = TimerManager::new(prof_clock.clone());
+
+ PosixThread {
+ process,
+ tid,
+ name: Mutex::new(thread_name),
+ set_child_tid: Mutex::new(set_child_tid),
+ clear_child_tid: Mutex::new(clear_child_tid),
+ credentials,
+ sig_mask,
+ sig_queues,
+ sig_context: Mutex::new(None),
+ sig_stack: Mutex::new(None),
+ signalled_waker: SpinLock::new(None),
+ robust_list: Mutex::new(None),
+ prof_clock,
+ virtual_timer_manager,
+ prof_timer_manager,
+ }
};
- Thread::new(tid, task, posix_thread, status)
- });
- thread_table::add_thread(thread.clone());
- thread
+ let status = ThreadStatus::Init;
+ let thread = Arc::new(Thread::new(weak_task.clone(), posix_thread, status));
+
+ thread_table::add_thread(tid, thread.clone());
+ task::create_new_user_task(user_space, thread)
+ })
}
}
diff --git a/kernel/src/process/posix_thread/exit.rs b/kernel/src/process/posix_thread/exit.rs
--- a/kernel/src/process/posix_thread/exit.rs
+++ b/kernel/src/process/posix_thread/exit.rs
@@ -1,10 +1,10 @@
// SPDX-License-Identifier: MPL-2.0
-use super::{futex::futex_wake, robust_list::wake_robust_futex, PosixThread, PosixThreadExt};
+use super::{futex::futex_wake, robust_list::wake_robust_futex, thread_table, PosixThread};
use crate::{
prelude::*,
process::{do_exit_group, TermStatus},
- thread::{thread_table, Thread, Tid},
+ thread::{Thread, Tid},
};
/// Exits the thread if the thread is a POSIX thread.
diff --git a/kernel/src/process/posix_thread/exit.rs b/kernel/src/process/posix_thread/exit.rs
--- a/kernel/src/process/posix_thread/exit.rs
+++ b/kernel/src/process/posix_thread/exit.rs
@@ -1,10 +1,10 @@
// SPDX-License-Identifier: MPL-2.0
-use super::{futex::futex_wake, robust_list::wake_robust_futex, PosixThread, PosixThreadExt};
+use super::{futex::futex_wake, robust_list::wake_robust_futex, thread_table, PosixThread};
use crate::{
prelude::*,
process::{do_exit_group, TermStatus},
- thread::{thread_table, Thread, Tid},
+ thread::{Thread, Tid},
};
/// Exits the thread if the thread is a POSIX thread.
diff --git a/kernel/src/process/posix_thread/exit.rs b/kernel/src/process/posix_thread/exit.rs
--- a/kernel/src/process/posix_thread/exit.rs
+++ b/kernel/src/process/posix_thread/exit.rs
@@ -12,15 +12,13 @@ use crate::{
/// # Panics
///
/// If the thread is not a POSIX thread, this method will panic.
-pub fn do_exit(thread: Arc<Thread>, term_status: TermStatus) -> Result<()> {
+pub fn do_exit(thread: &Thread, posix_thread: &PosixThread, term_status: TermStatus) -> Result<()> {
if thread.status().is_exited() {
return Ok(());
}
thread.exit();
- let tid = thread.tid();
-
- let posix_thread = thread.as_posix_thread().unwrap();
+ let tid = posix_thread.tid;
let mut clear_ctid = posix_thread.clear_child_tid().lock();
// If clear_ctid !=0 ,do a futex wake and write zero to the clear_ctid addr.
diff --git a/kernel/src/process/posix_thread/exit.rs b/kernel/src/process/posix_thread/exit.rs
--- a/kernel/src/process/posix_thread/exit.rs
+++ b/kernel/src/process/posix_thread/exit.rs
@@ -12,15 +12,13 @@ use crate::{
/// # Panics
///
/// If the thread is not a POSIX thread, this method will panic.
-pub fn do_exit(thread: Arc<Thread>, term_status: TermStatus) -> Result<()> {
+pub fn do_exit(thread: &Thread, posix_thread: &PosixThread, term_status: TermStatus) -> Result<()> {
if thread.status().is_exited() {
return Ok(());
}
thread.exit();
- let tid = thread.tid();
-
- let posix_thread = thread.as_posix_thread().unwrap();
+ let tid = posix_thread.tid;
let mut clear_ctid = posix_thread.clear_child_tid().lock();
// If clear_ctid !=0 ,do a futex wake and write zero to the clear_ctid addr.
diff --git a/kernel/src/process/posix_thread/mod.rs b/kernel/src/process/posix_thread/mod.rs
--- a/kernel/src/process/posix_thread/mod.rs
+++ b/kernel/src/process/posix_thread/mod.rs
@@ -2,7 +2,7 @@
#![allow(dead_code)]
-use core::sync::atomic::Ordering;
+use core::sync::atomic::{AtomicU32, Ordering};
use aster_rights::{ReadOp, WriteOp};
use ostd::sync::Waker;
diff --git a/kernel/src/process/posix_thread/mod.rs b/kernel/src/process/posix_thread/mod.rs
--- a/kernel/src/process/posix_thread/mod.rs
+++ b/kernel/src/process/posix_thread/mod.rs
@@ -2,7 +2,7 @@
#![allow(dead_code)]
-use core::sync::atomic::Ordering;
+use core::sync::atomic::{AtomicU32, Ordering};
use aster_rights::{ReadOp, WriteOp};
use ostd::sync::Waker;
diff --git a/kernel/src/process/posix_thread/mod.rs b/kernel/src/process/posix_thread/mod.rs
--- a/kernel/src/process/posix_thread/mod.rs
+++ b/kernel/src/process/posix_thread/mod.rs
@@ -22,7 +22,7 @@ use crate::{
events::Observer,
prelude::*,
process::signal::constants::SIGCONT,
- thread::Tid,
+ thread::{Thread, Tid},
time::{clocks::ProfClock, Timer, TimerManager},
};
diff --git a/kernel/src/process/posix_thread/mod.rs b/kernel/src/process/posix_thread/mod.rs
--- a/kernel/src/process/posix_thread/mod.rs
+++ b/kernel/src/process/posix_thread/mod.rs
@@ -22,7 +22,7 @@ use crate::{
events::Observer,
prelude::*,
process::signal::constants::SIGCONT,
- thread::Tid,
+ thread::{Thread, Tid},
time::{clocks::ProfClock, Timer, TimerManager},
};
diff --git a/kernel/src/process/posix_thread/mod.rs b/kernel/src/process/posix_thread/mod.rs
--- a/kernel/src/process/posix_thread/mod.rs
+++ b/kernel/src/process/posix_thread/mod.rs
@@ -32,16 +32,19 @@ pub mod futex;
mod name;
mod posix_thread_ext;
mod robust_list;
+pub mod thread_table;
pub use builder::PosixThreadBuilder;
pub use exit::do_exit;
pub use name::{ThreadName, MAX_THREAD_NAME_LEN};
-pub use posix_thread_ext::PosixThreadExt;
+pub use posix_thread_ext::{create_posix_task_from_executable, PosixThreadExt};
pub use robust_list::RobustListHead;
pub struct PosixThread {
// Immutable part
process: Weak<Process>,
+ tid: Tid,
+
// Mutable part
name: Mutex<Option<ThreadName>>,
diff --git a/kernel/src/process/posix_thread/mod.rs b/kernel/src/process/posix_thread/mod.rs
--- a/kernel/src/process/posix_thread/mod.rs
+++ b/kernel/src/process/posix_thread/mod.rs
@@ -32,16 +32,19 @@ pub mod futex;
mod name;
mod posix_thread_ext;
mod robust_list;
+pub mod thread_table;
pub use builder::PosixThreadBuilder;
pub use exit::do_exit;
pub use name::{ThreadName, MAX_THREAD_NAME_LEN};
-pub use posix_thread_ext::PosixThreadExt;
+pub use posix_thread_ext::{create_posix_task_from_executable, PosixThreadExt};
pub use robust_list::RobustListHead;
pub struct PosixThread {
// Immutable part
process: Weak<Process>,
+ tid: Tid,
+
// Mutable part
name: Mutex<Option<ThreadName>>,
diff --git a/kernel/src/process/posix_thread/mod.rs b/kernel/src/process/posix_thread/mod.rs
--- a/kernel/src/process/posix_thread/mod.rs
+++ b/kernel/src/process/posix_thread/mod.rs
@@ -87,6 +90,11 @@ impl PosixThread {
Weak::clone(&self.process)
}
+ /// Returns the thread id
+ pub fn tid(&self) -> Tid {
+ self.tid
+ }
+
pub fn thread_name(&self) -> &Mutex<Option<ThreadName>> {
&self.name
}
diff --git a/kernel/src/process/posix_thread/mod.rs b/kernel/src/process/posix_thread/mod.rs
--- a/kernel/src/process/posix_thread/mod.rs
+++ b/kernel/src/process/posix_thread/mod.rs
@@ -87,6 +90,11 @@ impl PosixThread {
Weak::clone(&self.process)
}
+ /// Returns the thread id
+ pub fn tid(&self) -> Tid {
+ self.tid
+ }
+
pub fn thread_name(&self) -> &Mutex<Option<ThreadName>> {
&self.name
}
diff --git a/kernel/src/process/posix_thread/mod.rs b/kernel/src/process/posix_thread/mod.rs
--- a/kernel/src/process/posix_thread/mod.rs
+++ b/kernel/src/process/posix_thread/mod.rs
@@ -266,12 +274,10 @@ impl PosixThread {
fn is_last_thread(&self) -> bool {
let process = self.process.upgrade().unwrap();
- let threads = process.threads().lock();
- threads
+ let tasks = process.tasks().lock();
+ tasks
.iter()
- .filter(|thread| !thread.status().is_exited())
- .count()
- == 0
+ .any(|task| !Thread::borrow_from_task(task).status().is_exited())
}
/// Gets the read-only credentials of the thread.
diff --git a/kernel/src/process/posix_thread/mod.rs b/kernel/src/process/posix_thread/mod.rs
--- a/kernel/src/process/posix_thread/mod.rs
+++ b/kernel/src/process/posix_thread/mod.rs
@@ -266,12 +274,10 @@ impl PosixThread {
fn is_last_thread(&self) -> bool {
let process = self.process.upgrade().unwrap();
- let threads = process.threads().lock();
- threads
+ let tasks = process.tasks().lock();
+ tasks
.iter()
- .filter(|thread| !thread.status().is_exited())
- .count()
- == 0
+ .any(|task| !Thread::borrow_from_task(task).status().is_exited())
}
/// Gets the read-only credentials of the thread.
diff --git a/kernel/src/process/posix_thread/mod.rs b/kernel/src/process/posix_thread/mod.rs
--- a/kernel/src/process/posix_thread/mod.rs
+++ b/kernel/src/process/posix_thread/mod.rs
@@ -292,3 +298,10 @@ impl PosixThread {
self.credentials.dup().restrict()
}
}
+
+static POSIX_TID_ALLOCATOR: AtomicU32 = AtomicU32::new(0);
+
+/// Allocates a new tid for the new posix thread
+pub fn allocate_posix_tid() -> Tid {
+ POSIX_TID_ALLOCATOR.fetch_add(1, Ordering::SeqCst)
+}
diff --git a/kernel/src/process/posix_thread/mod.rs b/kernel/src/process/posix_thread/mod.rs
--- a/kernel/src/process/posix_thread/mod.rs
+++ b/kernel/src/process/posix_thread/mod.rs
@@ -292,3 +298,10 @@ impl PosixThread {
self.credentials.dup().restrict()
}
}
+
+static POSIX_TID_ALLOCATOR: AtomicU32 = AtomicU32::new(0);
+
+/// Allocates a new tid for the new posix thread
+pub fn allocate_posix_tid() -> Tid {
+ POSIX_TID_ALLOCATOR.fetch_add(1, Ordering::SeqCst)
+}
diff --git a/kernel/src/process/posix_thread/posix_thread_ext.rs b/kernel/src/process/posix_thread/posix_thread_ext.rs
--- a/kernel/src/process/posix_thread/posix_thread_ext.rs
+++ b/kernel/src/process/posix_thread/posix_thread_ext.rs
@@ -2,6 +2,7 @@
use ostd::{
cpu::UserContext,
+ task::Task,
user::{UserContextApi, UserSpace},
};
diff --git a/kernel/src/process/posix_thread/posix_thread_ext.rs b/kernel/src/process/posix_thread/posix_thread_ext.rs
--- a/kernel/src/process/posix_thread/posix_thread_ext.rs
+++ b/kernel/src/process/posix_thread/posix_thread_ext.rs
@@ -2,6 +2,7 @@
use ostd::{
cpu::UserContext,
+ task::Task,
user::{UserContextApi, UserSpace},
};
diff --git a/kernel/src/process/posix_thread/posix_thread_ext.rs b/kernel/src/process/posix_thread/posix_thread_ext.rs
--- a/kernel/src/process/posix_thread/posix_thread_ext.rs
+++ b/kernel/src/process/posix_thread/posix_thread_ext.rs
@@ -13,52 +14,57 @@ use crate::{
thread::{Thread, Tid},
};
pub trait PosixThreadExt {
+ /// Returns the thread id.
+ ///
+ /// # Panics
+ ///
+ /// If the thread is not posix thread, this method will panic.
+ fn tid(&self) -> Tid {
+ self.as_posix_thread().unwrap().tid()
+ }
fn as_posix_thread(&self) -> Option<&PosixThread>;
- #[allow(clippy::too_many_arguments)]
- fn new_posix_thread_from_executable(
- tid: Tid,
- credentials: Credentials,
- process_vm: &ProcessVm,
- fs_resolver: &FsResolver,
- executable_path: &str,
- process: Weak<Process>,
- argv: Vec<CString>,
- envp: Vec<CString>,
- ) -> Result<Arc<Self>>;
}
impl PosixThreadExt for Thread {
- /// This function should only be called when launch shell()
- fn new_posix_thread_from_executable(
- tid: Tid,
- credentials: Credentials,
- process_vm: &ProcessVm,
- fs_resolver: &FsResolver,
- executable_path: &str,
- process: Weak<Process>,
- argv: Vec<CString>,
- envp: Vec<CString>,
- ) -> Result<Arc<Self>> {
- let elf_file = {
- let fs_path = FsPath::new(AT_FDCWD, executable_path)?;
- fs_resolver.lookup(&fs_path)?
- };
- let (_, elf_load_info) =
- load_program_to_vm(process_vm, elf_file, argv, envp, fs_resolver, 1)?;
-
- let vm_space = process_vm.root_vmar().vm_space().clone();
- let mut cpu_ctx = UserContext::default();
- cpu_ctx.set_instruction_pointer(elf_load_info.entry_point() as _);
- cpu_ctx.set_stack_pointer(elf_load_info.user_stack_top() as _);
- let user_space = Arc::new(UserSpace::new(vm_space, cpu_ctx));
- let thread_name = Some(ThreadName::new_from_executable_path(executable_path)?);
- let thread_builder = PosixThreadBuilder::new(tid, user_space, credentials)
- .thread_name(thread_name)
- .process(process);
- Ok(thread_builder.build())
+ fn as_posix_thread(&self) -> Option<&PosixThread> {
+ self.data().downcast_ref::<PosixThread>()
}
+}
+impl PosixThreadExt for Arc<Task> {
fn as_posix_thread(&self) -> Option<&PosixThread> {
- self.data().downcast_ref::<PosixThread>()
+ Thread::borrow_from_task(self).as_posix_thread()
}
}
+
+/// Creates a task for running an executable file.
+///
+/// This function should _only_ be used to create the init user task.
+#[allow(clippy::too_many_arguments)]
+pub fn create_posix_task_from_executable(
+ tid: Tid,
+ credentials: Credentials,
+ process_vm: &ProcessVm,
+ fs_resolver: &FsResolver,
+ executable_path: &str,
+ process: Weak<Process>,
+ argv: Vec<CString>,
+ envp: Vec<CString>,
+) -> Result<Arc<Task>> {
+ let elf_file = {
+ let fs_path = FsPath::new(AT_FDCWD, executable_path)?;
+ fs_resolver.lookup(&fs_path)?
+ };
+ let (_, elf_load_info) = load_program_to_vm(process_vm, elf_file, argv, envp, fs_resolver, 1)?;
+
+ let vm_space = process_vm.root_vmar().vm_space().clone();
+ let mut cpu_ctx = UserContext::default();
+ cpu_ctx.set_instruction_pointer(elf_load_info.entry_point() as _);
+ cpu_ctx.set_stack_pointer(elf_load_info.user_stack_top() as _);
+ let user_space = Arc::new(UserSpace::new(vm_space, cpu_ctx));
+ let thread_name = Some(ThreadName::new_from_executable_path(executable_path)?);
+ let thread_builder = PosixThreadBuilder::new(tid, user_space, credentials)
+ .thread_name(thread_name)
+ .process(process);
+ Ok(thread_builder.build())
+}
diff --git a/kernel/src/process/posix_thread/posix_thread_ext.rs b/kernel/src/process/posix_thread/posix_thread_ext.rs
--- a/kernel/src/process/posix_thread/posix_thread_ext.rs
+++ b/kernel/src/process/posix_thread/posix_thread_ext.rs
@@ -13,52 +14,57 @@ use crate::{
thread::{Thread, Tid},
};
pub trait PosixThreadExt {
+ /// Returns the thread id.
+ ///
+ /// # Panics
+ ///
+ /// If the thread is not posix thread, this method will panic.
+ fn tid(&self) -> Tid {
+ self.as_posix_thread().unwrap().tid()
+ }
fn as_posix_thread(&self) -> Option<&PosixThread>;
- #[allow(clippy::too_many_arguments)]
- fn new_posix_thread_from_executable(
- tid: Tid,
- credentials: Credentials,
- process_vm: &ProcessVm,
- fs_resolver: &FsResolver,
- executable_path: &str,
- process: Weak<Process>,
- argv: Vec<CString>,
- envp: Vec<CString>,
- ) -> Result<Arc<Self>>;
}
impl PosixThreadExt for Thread {
- /// This function should only be called when launch shell()
- fn new_posix_thread_from_executable(
- tid: Tid,
- credentials: Credentials,
- process_vm: &ProcessVm,
- fs_resolver: &FsResolver,
- executable_path: &str,
- process: Weak<Process>,
- argv: Vec<CString>,
- envp: Vec<CString>,
- ) -> Result<Arc<Self>> {
- let elf_file = {
- let fs_path = FsPath::new(AT_FDCWD, executable_path)?;
- fs_resolver.lookup(&fs_path)?
- };
- let (_, elf_load_info) =
- load_program_to_vm(process_vm, elf_file, argv, envp, fs_resolver, 1)?;
-
- let vm_space = process_vm.root_vmar().vm_space().clone();
- let mut cpu_ctx = UserContext::default();
- cpu_ctx.set_instruction_pointer(elf_load_info.entry_point() as _);
- cpu_ctx.set_stack_pointer(elf_load_info.user_stack_top() as _);
- let user_space = Arc::new(UserSpace::new(vm_space, cpu_ctx));
- let thread_name = Some(ThreadName::new_from_executable_path(executable_path)?);
- let thread_builder = PosixThreadBuilder::new(tid, user_space, credentials)
- .thread_name(thread_name)
- .process(process);
- Ok(thread_builder.build())
+ fn as_posix_thread(&self) -> Option<&PosixThread> {
+ self.data().downcast_ref::<PosixThread>()
}
+}
+impl PosixThreadExt for Arc<Task> {
fn as_posix_thread(&self) -> Option<&PosixThread> {
- self.data().downcast_ref::<PosixThread>()
+ Thread::borrow_from_task(self).as_posix_thread()
}
}
+
+/// Creates a task for running an executable file.
+///
+/// This function should _only_ be used to create the init user task.
+#[allow(clippy::too_many_arguments)]
+pub fn create_posix_task_from_executable(
+ tid: Tid,
+ credentials: Credentials,
+ process_vm: &ProcessVm,
+ fs_resolver: &FsResolver,
+ executable_path: &str,
+ process: Weak<Process>,
+ argv: Vec<CString>,
+ envp: Vec<CString>,
+) -> Result<Arc<Task>> {
+ let elf_file = {
+ let fs_path = FsPath::new(AT_FDCWD, executable_path)?;
+ fs_resolver.lookup(&fs_path)?
+ };
+ let (_, elf_load_info) = load_program_to_vm(process_vm, elf_file, argv, envp, fs_resolver, 1)?;
+
+ let vm_space = process_vm.root_vmar().vm_space().clone();
+ let mut cpu_ctx = UserContext::default();
+ cpu_ctx.set_instruction_pointer(elf_load_info.entry_point() as _);
+ cpu_ctx.set_stack_pointer(elf_load_info.user_stack_top() as _);
+ let user_space = Arc::new(UserSpace::new(vm_space, cpu_ctx));
+ let thread_name = Some(ThreadName::new_from_executable_path(executable_path)?);
+ let thread_builder = PosixThreadBuilder::new(tid, user_space, credentials)
+ .thread_name(thread_name)
+ .process(process);
+ Ok(thread_builder.build())
+}
diff --git /dev/null b/kernel/src/process/posix_thread/thread_table.rs
new file mode 100644
--- /dev/null
+++ b/kernel/src/process/posix_thread/thread_table.rs
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: MPL-2.0
+
+use super::{Thread, Tid};
+use crate::{prelude::*, process::posix_thread::PosixThreadExt};
+
+static THREAD_TABLE: SpinLock<BTreeMap<Tid, Arc<Thread>>> = SpinLock::new(BTreeMap::new());
+
+/// Adds a posix thread to global thread table
+pub fn add_thread(tid: Tid, thread: Arc<Thread>) {
+ debug_assert_eq!(tid, thread.tid());
+ THREAD_TABLE.lock().insert(tid, thread);
+}
+
+/// Removes a posix thread to global thread table
+pub fn remove_thread(tid: Tid) {
+ THREAD_TABLE.lock().remove(&tid);
+}
+
+/// Gets a posix thread from the global thread table
+pub fn get_thread(tid: Tid) -> Option<Arc<Thread>> {
+ THREAD_TABLE.lock().get(&tid).cloned()
+}
diff --git /dev/null b/kernel/src/process/posix_thread/thread_table.rs
new file mode 100644
--- /dev/null
+++ b/kernel/src/process/posix_thread/thread_table.rs
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: MPL-2.0
+
+use super::{Thread, Tid};
+use crate::{prelude::*, process::posix_thread::PosixThreadExt};
+
+static THREAD_TABLE: SpinLock<BTreeMap<Tid, Arc<Thread>>> = SpinLock::new(BTreeMap::new());
+
+/// Adds a posix thread to global thread table
+pub fn add_thread(tid: Tid, thread: Arc<Thread>) {
+ debug_assert_eq!(tid, thread.tid());
+ THREAD_TABLE.lock().insert(tid, thread);
+}
+
+/// Removes a posix thread to global thread table
+pub fn remove_thread(tid: Tid) {
+ THREAD_TABLE.lock().remove(&tid);
+}
+
+/// Gets a posix thread from the global thread table
+pub fn get_thread(tid: Tid) -> Option<Arc<Thread>> {
+ THREAD_TABLE.lock().get(&tid).cloned()
+}
diff --git a/kernel/src/process/process/builder.rs b/kernel/src/process/process/builder.rs
--- a/kernel/src/process/process/builder.rs
+++ b/kernel/src/process/process/builder.rs
@@ -7,14 +7,13 @@ use crate::{
fs::{file_table::FileTable, fs_resolver::FsResolver, utils::FileCreationMask},
prelude::*,
process::{
- posix_thread::{PosixThreadBuilder, PosixThreadExt},
+ posix_thread::{create_posix_task_from_executable, PosixThreadBuilder},
process_vm::ProcessVm,
rlimit::ResourceLimits,
signal::sig_disposition::SigDispositions,
Credentials,
},
sched::nice::Nice,
- thread::Thread,
};
pub struct ProcessBuilder<'a> {
diff --git a/kernel/src/process/process/builder.rs b/kernel/src/process/process/builder.rs
--- a/kernel/src/process/process/builder.rs
+++ b/kernel/src/process/process/builder.rs
@@ -7,14 +7,13 @@ use crate::{
fs::{file_table::FileTable, fs_resolver::FsResolver, utils::FileCreationMask},
prelude::*,
process::{
- posix_thread::{PosixThreadBuilder, PosixThreadExt},
+ posix_thread::{create_posix_task_from_executable, PosixThreadBuilder},
process_vm::ProcessVm,
rlimit::ResourceLimits,
signal::sig_disposition::SigDispositions,
Credentials,
},
sched::nice::Nice,
- thread::Thread,
};
pub struct ProcessBuilder<'a> {
diff --git a/kernel/src/process/process/builder.rs b/kernel/src/process/process/builder.rs
--- a/kernel/src/process/process/builder.rs
+++ b/kernel/src/process/process/builder.rs
@@ -190,11 +189,11 @@ impl<'a> ProcessBuilder<'a> {
)
};
- let thread = if let Some(thread_builder) = main_thread_builder {
+ let task = if let Some(thread_builder) = main_thread_builder {
let builder = thread_builder.process(Arc::downgrade(&process));
builder.build()
} else {
- Thread::new_posix_thread_from_executable(
+ create_posix_task_from_executable(
pid,
credentials.unwrap(),
process.vm(),
diff --git a/kernel/src/process/process/builder.rs b/kernel/src/process/process/builder.rs
--- a/kernel/src/process/process/builder.rs
+++ b/kernel/src/process/process/builder.rs
@@ -190,11 +189,11 @@ impl<'a> ProcessBuilder<'a> {
)
};
- let thread = if let Some(thread_builder) = main_thread_builder {
+ let task = if let Some(thread_builder) = main_thread_builder {
let builder = thread_builder.process(Arc::downgrade(&process));
builder.build()
} else {
- Thread::new_posix_thread_from_executable(
+ create_posix_task_from_executable(
pid,
credentials.unwrap(),
process.vm(),
diff --git a/kernel/src/process/process/builder.rs b/kernel/src/process/process/builder.rs
--- a/kernel/src/process/process/builder.rs
+++ b/kernel/src/process/process/builder.rs
@@ -206,7 +205,7 @@ impl<'a> ProcessBuilder<'a> {
)?
};
- process.threads().lock().push(thread);
+ process.tasks().lock().push(task);
process.set_runnable();
diff --git a/kernel/src/process/process/builder.rs b/kernel/src/process/process/builder.rs
--- a/kernel/src/process/process/builder.rs
+++ b/kernel/src/process/process/builder.rs
@@ -206,7 +205,7 @@ impl<'a> ProcessBuilder<'a> {
)?
};
- process.threads().lock().push(thread);
+ process.tasks().lock().push(task);
process.set_runnable();
diff --git a/kernel/src/process/process/mod.rs b/kernel/src/process/process/mod.rs
--- a/kernel/src/process/process/mod.rs
+++ b/kernel/src/process/process/mod.rs
@@ -4,7 +4,7 @@ use core::sync::atomic::Ordering;
use self::timer_manager::PosixTimerManager;
use super::{
- posix_thread::PosixThreadExt,
+ posix_thread::{allocate_posix_tid, PosixThreadExt},
process_table,
process_vm::{Heap, InitStackReader, ProcessVm},
rlimit::ResourceLimits,
diff --git a/kernel/src/process/process/mod.rs b/kernel/src/process/process/mod.rs
--- a/kernel/src/process/process/mod.rs
+++ b/kernel/src/process/process/mod.rs
@@ -4,7 +4,7 @@ use core::sync::atomic::Ordering;
use self::timer_manager::PosixTimerManager;
use super::{
- posix_thread::PosixThreadExt,
+ posix_thread::{allocate_posix_tid, PosixThreadExt},
process_table,
process_vm::{Heap, InitStackReader, ProcessVm},
rlimit::ResourceLimits,
diff --git a/kernel/src/process/process/mod.rs b/kernel/src/process/process/mod.rs
--- a/kernel/src/process/process/mod.rs
+++ b/kernel/src/process/process/mod.rs
@@ -21,7 +21,7 @@ use crate::{
fs::{file_table::FileTable, fs_resolver::FsResolver, utils::FileCreationMask},
prelude::*,
sched::nice::Nice,
- thread::{allocate_tid, Thread},
+ thread::Thread,
time::clocks::ProfClock,
vm::vmar::Vmar,
};
diff --git a/kernel/src/process/process/mod.rs b/kernel/src/process/process/mod.rs
--- a/kernel/src/process/process/mod.rs
+++ b/kernel/src/process/process/mod.rs
@@ -21,7 +21,7 @@ use crate::{
fs::{file_table::FileTable, fs_resolver::FsResolver, utils::FileCreationMask},
prelude::*,
sched::nice::Nice,
- thread::{allocate_tid, Thread},
+ thread::Thread,
time::clocks::ProfClock,
vm::vmar::Vmar,
};
diff --git a/kernel/src/process/process/mod.rs b/kernel/src/process/process/mod.rs
--- a/kernel/src/process/process/mod.rs
+++ b/kernel/src/process/process/mod.rs
@@ -37,7 +37,7 @@ use aster_rights::Full;
use atomic::Atomic;
pub use builder::ProcessBuilder;
pub use job_control::JobControl;
-use ostd::sync::WaitQueue;
+use ostd::{sync::WaitQueue, task::Task};
pub use process_group::ProcessGroup;
pub use session::Session;
pub use terminal::Terminal;
diff --git a/kernel/src/process/process/mod.rs b/kernel/src/process/process/mod.rs
--- a/kernel/src/process/process/mod.rs
+++ b/kernel/src/process/process/mod.rs
@@ -37,7 +37,7 @@ use aster_rights::Full;
use atomic::Atomic;
pub use builder::ProcessBuilder;
pub use job_control::JobControl;
-use ostd::sync::WaitQueue;
+use ostd::{sync::WaitQueue, task::Task};
pub use process_group::ProcessGroup;
pub use session::Session;
pub use terminal::Terminal;
diff --git a/kernel/src/process/process/mod.rs b/kernel/src/process/process/mod.rs
--- a/kernel/src/process/process/mod.rs
+++ b/kernel/src/process/process/mod.rs
@@ -68,7 +68,7 @@ pub struct Process {
/// The executable path.
executable_path: RwLock<String>,
/// The threads
- threads: Mutex<Vec<Arc<Thread>>>,
+ tasks: Mutex<Vec<Arc<Task>>>,
/// Process status
status: ProcessStatus,
/// Parent process
diff --git a/kernel/src/process/process/mod.rs b/kernel/src/process/process/mod.rs
--- a/kernel/src/process/process/mod.rs
+++ b/kernel/src/process/process/mod.rs
@@ -68,7 +68,7 @@ pub struct Process {
/// The executable path.
executable_path: RwLock<String>,
/// The threads
- threads: Mutex<Vec<Arc<Thread>>>,
+ tasks: Mutex<Vec<Arc<Task>>>,
/// Process status
status: ProcessStatus,
/// Parent process
diff --git a/kernel/src/process/process/mod.rs b/kernel/src/process/process/mod.rs
--- a/kernel/src/process/process/mod.rs
+++ b/kernel/src/process/process/mod.rs
@@ -167,14 +167,20 @@ impl Process {
/// - the function is called in the bootstrap context;
/// - or if the current task is not associated with a process.
pub fn current() -> Option<Arc<Process>> {
- Some(Thread::current()?.as_posix_thread()?.process())
+ Some(
+ Task::current()?
+ .data()
+ .downcast_ref::<Arc<Thread>>()?
+ .as_posix_thread()?
+ .process(),
+ )
}
#[allow(clippy::too_many_arguments)]
fn new(
pid: Pid,
parent: Weak<Process>,
- threads: Vec<Arc<Thread>>,
+ tasks: Vec<Arc<Task>>,
executable_path: String,
process_vm: ProcessVm,
diff --git a/kernel/src/process/process/mod.rs b/kernel/src/process/process/mod.rs
--- a/kernel/src/process/process/mod.rs
+++ b/kernel/src/process/process/mod.rs
@@ -167,14 +167,20 @@ impl Process {
/// - the function is called in the bootstrap context;
/// - or if the current task is not associated with a process.
pub fn current() -> Option<Arc<Process>> {
- Some(Thread::current()?.as_posix_thread()?.process())
+ Some(
+ Task::current()?
+ .data()
+ .downcast_ref::<Arc<Thread>>()?
+ .as_posix_thread()?
+ .process(),
+ )
}
#[allow(clippy::too_many_arguments)]
fn new(
pid: Pid,
parent: Weak<Process>,
- threads: Vec<Arc<Thread>>,
+ tasks: Vec<Arc<Task>>,
executable_path: String,
process_vm: ProcessVm,
diff --git a/kernel/src/process/process/mod.rs b/kernel/src/process/process/mod.rs
--- a/kernel/src/process/process/mod.rs
+++ b/kernel/src/process/process/mod.rs
@@ -194,7 +200,7 @@ impl Process {
Arc::new_cyclic(|process_ref: &Weak<Process>| Self {
pid,
- threads: Mutex::new(threads),
+ tasks: Mutex::new(tasks),
executable_path: RwLock::new(executable_path),
process_vm,
children_wait_queue,
diff --git a/kernel/src/process/process/mod.rs b/kernel/src/process/process/mod.rs
--- a/kernel/src/process/process/mod.rs
+++ b/kernel/src/process/process/mod.rs
@@ -194,7 +200,7 @@ impl Process {
Arc::new_cyclic(|process_ref: &Weak<Process>| Self {
pid,
- threads: Mutex::new(threads),
+ tasks: Mutex::new(tasks),
executable_path: RwLock::new(executable_path),
process_vm,
children_wait_queue,
diff --git a/kernel/src/process/process/mod.rs b/kernel/src/process/process/mod.rs
--- a/kernel/src/process/process/mod.rs
+++ b/kernel/src/process/process/mod.rs
@@ -236,7 +242,7 @@ impl Process {
envp: Vec<CString>,
) -> Result<Arc<Self>> {
let process_builder = {
- let pid = allocate_tid();
+ let pid = allocate_posix_tid();
let parent = Weak::new();
let credentials = Credentials::new_root();
diff --git a/kernel/src/process/process/mod.rs b/kernel/src/process/process/mod.rs
--- a/kernel/src/process/process/mod.rs
+++ b/kernel/src/process/process/mod.rs
@@ -236,7 +242,7 @@ impl Process {
envp: Vec<CString>,
) -> Result<Arc<Self>> {
let process_builder = {
- let pid = allocate_tid();
+ let pid = allocate_posix_tid();
let parent = Weak::new();
let credentials = Credentials::new_root();
diff --git a/kernel/src/process/process/mod.rs b/kernel/src/process/process/mod.rs
--- a/kernel/src/process/process/mod.rs
+++ b/kernel/src/process/process/mod.rs
@@ -271,13 +277,14 @@ impl Process {
/// start to run current process
pub fn run(&self) {
- let threads = self.threads.lock();
+ let tasks = self.tasks.lock();
// when run the process, the process should has only one thread
- debug_assert!(threads.len() == 1);
+ debug_assert!(tasks.len() == 1);
debug_assert!(self.is_runnable());
- let thread = threads[0].clone();
+ let task = tasks[0].clone();
// should not hold the lock when run thread
- drop(threads);
+ drop(tasks);
+ let thread = Thread::borrow_from_task(&task);
thread.run();
}
diff --git a/kernel/src/process/process/mod.rs b/kernel/src/process/process/mod.rs
--- a/kernel/src/process/process/mod.rs
+++ b/kernel/src/process/process/mod.rs
@@ -271,13 +277,14 @@ impl Process {
/// start to run current process
pub fn run(&self) {
- let threads = self.threads.lock();
+ let tasks = self.tasks.lock();
// when run the process, the process should has only one thread
- debug_assert!(threads.len() == 1);
+ debug_assert!(tasks.len() == 1);
debug_assert!(self.is_runnable());
- let thread = threads[0].clone();
+ let task = tasks[0].clone();
// should not hold the lock when run thread
- drop(threads);
+ drop(tasks);
+ let thread = Thread::borrow_from_task(&task);
thread.run();
}
diff --git a/kernel/src/process/process/mod.rs b/kernel/src/process/process/mod.rs
--- a/kernel/src/process/process/mod.rs
+++ b/kernel/src/process/process/mod.rs
@@ -297,8 +304,8 @@ impl Process {
&self.timer_manager
}
- pub fn threads(&self) -> &Mutex<Vec<Arc<Thread>>> {
- &self.threads
+ pub fn tasks(&self) -> &Mutex<Vec<Arc<Task>>> {
+ &self.tasks
}
pub fn executable_path(&self) -> String {
diff --git a/kernel/src/process/process/mod.rs b/kernel/src/process/process/mod.rs
--- a/kernel/src/process/process/mod.rs
+++ b/kernel/src/process/process/mod.rs
@@ -297,8 +304,8 @@ impl Process {
&self.timer_manager
}
- pub fn threads(&self) -> &Mutex<Vec<Arc<Thread>>> {
- &self.threads
+ pub fn tasks(&self) -> &Mutex<Vec<Arc<Task>>> {
+ &self.tasks
}
pub fn executable_path(&self) -> String {
diff --git a/kernel/src/process/process/mod.rs b/kernel/src/process/process/mod.rs
--- a/kernel/src/process/process/mod.rs
+++ b/kernel/src/process/process/mod.rs
@@ -318,10 +325,11 @@ impl Process {
}
pub fn main_thread(&self) -> Option<Arc<Thread>> {
- self.threads
+ self.tasks
.lock()
.iter()
- .find(|thread| thread.tid() == self.pid)
+ .find(|task| task.tid() == self.pid)
+ .map(Thread::borrow_from_task)
.cloned()
}
diff --git a/kernel/src/process/process/mod.rs b/kernel/src/process/process/mod.rs
--- a/kernel/src/process/process/mod.rs
+++ b/kernel/src/process/process/mod.rs
@@ -318,10 +325,11 @@ impl Process {
}
pub fn main_thread(&self) -> Option<Arc<Thread>> {
- self.threads
+ self.tasks
.lock()
.iter()
- .find(|thread| thread.tid() == self.pid)
+ .find(|task| task.tid() == self.pid)
+ .map(Thread::borrow_from_task)
.cloned()
}
diff --git a/kernel/src/process/process/mod.rs b/kernel/src/process/process/mod.rs
--- a/kernel/src/process/process/mod.rs
+++ b/kernel/src/process/process/mod.rs
@@ -644,7 +652,7 @@ impl Process {
// TODO: check that the signal is not user signal
// Enqueue signal to the first thread that does not block the signal
- let threads = self.threads.lock();
+ let threads = self.tasks.lock();
for thread in threads.iter() {
let posix_thread = thread.as_posix_thread().unwrap();
if !posix_thread.has_signal_blocked(signal.num()) {
diff --git a/kernel/src/process/process/mod.rs b/kernel/src/process/process/mod.rs
--- a/kernel/src/process/process/mod.rs
+++ b/kernel/src/process/process/mod.rs
@@ -644,7 +652,7 @@ impl Process {
// TODO: check that the signal is not user signal
// Enqueue signal to the first thread that does not block the signal
- let threads = self.threads.lock();
+ let threads = self.tasks.lock();
for thread in threads.iter() {
let posix_thread = thread.as_posix_thread().unwrap();
if !posix_thread.has_signal_blocked(signal.num()) {
diff --git a/kernel/src/process/process/mod.rs b/kernel/src/process/process/mod.rs
--- a/kernel/src/process/process/mod.rs
+++ b/kernel/src/process/process/mod.rs
@@ -710,7 +718,7 @@ mod test {
fn new_process(parent: Option<Arc<Process>>) -> Arc<Process> {
crate::util::random::init();
crate::fs::rootfs::init_root_mount();
- let pid = allocate_tid();
+ let pid = allocate_posix_tid();
let parent = if let Some(parent) = parent {
Arc::downgrade(&parent)
} else {
diff --git a/kernel/src/process/signal/pause.rs b/kernel/src/process/signal/pause.rs
--- a/kernel/src/process/signal/pause.rs
+++ b/kernel/src/process/signal/pause.rs
@@ -86,16 +86,9 @@ impl Pause for Waiter {
return Ok(res);
}
- let current_thread = self
- .task()
- .data()
- .downcast_ref::<Weak<Thread>>()
- .and_then(|thread| thread.upgrade());
-
- let Some(posix_thread) = current_thread
- .as_ref()
- .and_then(|thread| thread.as_posix_thread())
- else {
+ let current_thread = self.task().data().downcast_ref::<Arc<Thread>>();
+
+ let Some(posix_thread) = current_thread.and_then(|thread| thread.as_posix_thread()) else {
if let Some(timeout) = timeout {
return self.wait_until_or_timeout(cond, timeout);
} else {
diff --git a/kernel/src/process/signal/pause.rs b/kernel/src/process/signal/pause.rs
--- a/kernel/src/process/signal/pause.rs
+++ b/kernel/src/process/signal/pause.rs
@@ -86,16 +86,9 @@ impl Pause for Waiter {
return Ok(res);
}
- let current_thread = self
- .task()
- .data()
- .downcast_ref::<Weak<Thread>>()
- .and_then(|thread| thread.upgrade());
-
- let Some(posix_thread) = current_thread
- .as_ref()
- .and_then(|thread| thread.as_posix_thread())
- else {
+ let current_thread = self.task().data().downcast_ref::<Arc<Thread>>();
+
+ let Some(posix_thread) = current_thread.and_then(|thread| thread.as_posix_thread()) else {
if let Some(timeout) = timeout {
return self.wait_until_or_timeout(cond, timeout);
} else {
diff --git a/kernel/src/process/wait.rs b/kernel/src/process/wait.rs
--- a/kernel/src/process/wait.rs
+++ b/kernel/src/process/wait.rs
@@ -2,12 +2,15 @@
#![allow(dead_code)]
-use super::{
- process_filter::ProcessFilter,
- signal::{constants::SIGCHLD, with_signal_blocked},
- ExitCode, Pid, Process,
+use super::{process_filter::ProcessFilter, signal::constants::SIGCHLD, ExitCode, Pid, Process};
+use crate::{
+ prelude::*,
+ process::{
+ posix_thread::{thread_table, PosixThreadExt},
+ process_table,
+ signal::with_signal_blocked,
+ },
};
-use crate::{prelude::*, process::process_table, thread::thread_table};
// The definition of WaitOptions is from Occlum
bitflags! {
diff --git a/kernel/src/process/wait.rs b/kernel/src/process/wait.rs
--- a/kernel/src/process/wait.rs
+++ b/kernel/src/process/wait.rs
@@ -2,12 +2,15 @@
#![allow(dead_code)]
-use super::{
- process_filter::ProcessFilter,
- signal::{constants::SIGCHLD, with_signal_blocked},
- ExitCode, Pid, Process,
+use super::{process_filter::ProcessFilter, signal::constants::SIGCHLD, ExitCode, Pid, Process};
+use crate::{
+ prelude::*,
+ process::{
+ posix_thread::{thread_table, PosixThreadExt},
+ process_table,
+ signal::with_signal_blocked,
+ },
};
-use crate::{prelude::*, process::process_table, thread::thread_table};
// The definition of WaitOptions is from Occlum
bitflags! {
diff --git a/kernel/src/process/wait.rs b/kernel/src/process/wait.rs
--- a/kernel/src/process/wait.rs
+++ b/kernel/src/process/wait.rs
@@ -85,8 +88,8 @@ pub fn wait_child_exit(
fn reap_zombie_child(process: &Process, pid: Pid) -> ExitCode {
let child_process = process.children().lock().remove(&pid).unwrap();
assert!(child_process.is_zombie());
- for thread in &*child_process.threads().lock() {
- thread_table::remove_thread(thread.tid());
+ for task in &*child_process.tasks().lock() {
+ thread_table::remove_thread(task.tid());
}
// Lock order: session table -> group table -> process table -> group of process
diff --git a/kernel/src/process/wait.rs b/kernel/src/process/wait.rs
--- a/kernel/src/process/wait.rs
+++ b/kernel/src/process/wait.rs
@@ -85,8 +88,8 @@ pub fn wait_child_exit(
fn reap_zombie_child(process: &Process, pid: Pid) -> ExitCode {
let child_process = process.children().lock().remove(&pid).unwrap();
assert!(child_process.is_zombie());
- for thread in &*child_process.threads().lock() {
- thread_table::remove_thread(thread.tid());
+ for task in &*child_process.tasks().lock() {
+ thread_table::remove_thread(task.tid());
}
// Lock order: session table -> group table -> process table -> group of process
diff --git a/kernel/src/syscall/clock_gettime.rs b/kernel/src/syscall/clock_gettime.rs
--- a/kernel/src/syscall/clock_gettime.rs
+++ b/kernel/src/syscall/clock_gettime.rs
@@ -7,8 +7,10 @@ use int_to_c_enum::TryFromInt;
use super::SyscallReturn;
use crate::{
prelude::*,
- process::{posix_thread::PosixThreadExt, process_table},
- thread::thread_table,
+ process::{
+ posix_thread::{thread_table, PosixThreadExt},
+ process_table,
+ },
time::{
clockid_t,
clocks::{
diff --git a/kernel/src/syscall/clock_gettime.rs b/kernel/src/syscall/clock_gettime.rs
--- a/kernel/src/syscall/clock_gettime.rs
+++ b/kernel/src/syscall/clock_gettime.rs
@@ -7,8 +7,10 @@ use int_to_c_enum::TryFromInt;
use super::SyscallReturn;
use crate::{
prelude::*,
- process::{posix_thread::PosixThreadExt, process_table},
- thread::thread_table,
+ process::{
+ posix_thread::{thread_table, PosixThreadExt},
+ process_table,
+ },
time::{
clockid_t,
clocks::{
diff --git a/kernel/src/syscall/exit.rs b/kernel/src/syscall/exit.rs
--- a/kernel/src/syscall/exit.rs
+++ b/kernel/src/syscall/exit.rs
@@ -6,12 +6,11 @@ use crate::{
syscall::SyscallReturn,
};
-pub fn sys_exit(exit_code: i32, _ctx: &Context) -> Result<SyscallReturn> {
+pub fn sys_exit(exit_code: i32, ctx: &Context) -> Result<SyscallReturn> {
debug!("exid code = {}", exit_code);
- let current_thread = current_thread!();
let term_status = TermStatus::Exited(exit_code as _);
- do_exit(current_thread, term_status)?;
+ do_exit(ctx.thread, ctx.posix_thread, term_status)?;
Ok(SyscallReturn::Return(0))
}
diff --git a/kernel/src/syscall/exit.rs b/kernel/src/syscall/exit.rs
--- a/kernel/src/syscall/exit.rs
+++ b/kernel/src/syscall/exit.rs
@@ -6,12 +6,11 @@ use crate::{
syscall::SyscallReturn,
};
-pub fn sys_exit(exit_code: i32, _ctx: &Context) -> Result<SyscallReturn> {
+pub fn sys_exit(exit_code: i32, ctx: &Context) -> Result<SyscallReturn> {
debug!("exid code = {}", exit_code);
- let current_thread = current_thread!();
let term_status = TermStatus::Exited(exit_code as _);
- do_exit(current_thread, term_status)?;
+ do_exit(ctx.thread, ctx.posix_thread, term_status)?;
Ok(SyscallReturn::Return(0))
}
diff --git a/kernel/src/syscall/futex.rs b/kernel/src/syscall/futex.rs
--- a/kernel/src/syscall/futex.rs
+++ b/kernel/src/syscall/futex.rs
@@ -71,6 +71,6 @@ pub fn sys_futex(
_ => panic!("Unsupported futex operations"),
}?;
- debug!("futex returns, tid= {} ", ctx.thread.tid());
+ debug!("futex returns, tid= {} ", ctx.posix_thread.tid());
Ok(SyscallReturn::Return(res as _))
}
diff --git a/kernel/src/syscall/futex.rs b/kernel/src/syscall/futex.rs
--- a/kernel/src/syscall/futex.rs
+++ b/kernel/src/syscall/futex.rs
@@ -71,6 +71,6 @@ pub fn sys_futex(
_ => panic!("Unsupported futex operations"),
}?;
- debug!("futex returns, tid= {} ", ctx.thread.tid());
+ debug!("futex returns, tid= {} ", ctx.posix_thread.tid());
Ok(SyscallReturn::Return(res as _))
}
diff --git a/kernel/src/syscall/gettid.rs b/kernel/src/syscall/gettid.rs
--- a/kernel/src/syscall/gettid.rs
+++ b/kernel/src/syscall/gettid.rs
@@ -4,6 +4,6 @@ use super::SyscallReturn;
use crate::prelude::*;
pub fn sys_gettid(ctx: &Context) -> Result<SyscallReturn> {
- let tid = ctx.thread.tid();
+ let tid = ctx.posix_thread.tid();
Ok(SyscallReturn::Return(tid as _))
}
diff --git a/kernel/src/syscall/gettid.rs b/kernel/src/syscall/gettid.rs
--- a/kernel/src/syscall/gettid.rs
+++ b/kernel/src/syscall/gettid.rs
@@ -4,6 +4,6 @@ use super::SyscallReturn;
use crate::prelude::*;
pub fn sys_gettid(ctx: &Context) -> Result<SyscallReturn> {
- let tid = ctx.thread.tid();
+ let tid = ctx.posix_thread.tid();
Ok(SyscallReturn::Return(tid as _))
}
diff --git a/kernel/src/syscall/mod.rs b/kernel/src/syscall/mod.rs
--- a/kernel/src/syscall/mod.rs
+++ b/kernel/src/syscall/mod.rs
@@ -345,7 +345,10 @@ macro_rules! log_syscall_entry {
if log::log_enabled!(log::Level::Info) {
let syscall_name_str = stringify!($syscall_name);
let pid = $crate::current!().pid();
- let tid = $crate::current_thread!().tid();
+ let tid = {
+ use $crate::process::posix_thread::PosixThreadExt;
+ $crate::current_thread!().tid()
+ };
log::info!(
"[pid={}][tid={}][id={}][{}]",
pid,
diff --git a/kernel/src/syscall/mod.rs b/kernel/src/syscall/mod.rs
--- a/kernel/src/syscall/mod.rs
+++ b/kernel/src/syscall/mod.rs
@@ -345,7 +345,10 @@ macro_rules! log_syscall_entry {
if log::log_enabled!(log::Level::Info) {
let syscall_name_str = stringify!($syscall_name);
let pid = $crate::current!().pid();
- let tid = $crate::current_thread!().tid();
+ let tid = {
+ use $crate::process::posix_thread::PosixThreadExt;
+ $crate::current_thread!().tid()
+ };
log::info!(
"[pid={}][tid={}][id={}][{}]",
pid,
diff --git a/kernel/src/syscall/set_tid_address.rs b/kernel/src/syscall/set_tid_address.rs
--- a/kernel/src/syscall/set_tid_address.rs
+++ b/kernel/src/syscall/set_tid_address.rs
@@ -13,6 +13,6 @@ pub fn sys_set_tid_address(tidptr: Vaddr, ctx: &Context) -> Result<SyscallReturn
} else {
*clear_child_tid = tidptr;
}
- let tid = ctx.thread.tid();
+ let tid = ctx.posix_thread.tid();
Ok(SyscallReturn::Return(tid as _))
}
diff --git a/kernel/src/syscall/set_tid_address.rs b/kernel/src/syscall/set_tid_address.rs
--- a/kernel/src/syscall/set_tid_address.rs
+++ b/kernel/src/syscall/set_tid_address.rs
@@ -13,6 +13,6 @@ pub fn sys_set_tid_address(tidptr: Vaddr, ctx: &Context) -> Result<SyscallReturn
} else {
*clear_child_tid = tidptr;
}
- let tid = ctx.thread.tid();
+ let tid = ctx.posix_thread.tid();
Ok(SyscallReturn::Return(tid as _))
}
diff --git a/kernel/src/syscall/timer_create.rs b/kernel/src/syscall/timer_create.rs
--- a/kernel/src/syscall/timer_create.rs
+++ b/kernel/src/syscall/timer_create.rs
@@ -7,7 +7,7 @@ use super::{
use crate::{
prelude::*,
process::{
- posix_thread::PosixThreadExt,
+ posix_thread::{thread_table, PosixThreadExt},
process_table,
signal::{
c_types::{sigevent_t, SigNotify},
diff --git a/kernel/src/syscall/timer_create.rs b/kernel/src/syscall/timer_create.rs
--- a/kernel/src/syscall/timer_create.rs
+++ b/kernel/src/syscall/timer_create.rs
@@ -7,7 +7,7 @@ use super::{
use crate::{
prelude::*,
process::{
- posix_thread::PosixThreadExt,
+ posix_thread::{thread_table, PosixThreadExt},
process_table,
signal::{
c_types::{sigevent_t, SigNotify},
diff --git a/kernel/src/syscall/timer_create.rs b/kernel/src/syscall/timer_create.rs
--- a/kernel/src/syscall/timer_create.rs
+++ b/kernel/src/syscall/timer_create.rs
@@ -17,10 +17,7 @@ use crate::{
},
},
syscall::ClockId,
- thread::{
- thread_table,
- work_queue::{submit_work_item, work_item::WorkItem},
- },
+ thread::work_queue::{submit_work_item, work_item::WorkItem},
time::{
clockid_t,
clocks::{BootTimeClock, MonotonicClock, RealTimeClock},
diff --git a/kernel/src/syscall/timer_create.rs b/kernel/src/syscall/timer_create.rs
--- a/kernel/src/syscall/timer_create.rs
+++ b/kernel/src/syscall/timer_create.rs
@@ -17,10 +17,7 @@ use crate::{
},
},
syscall::ClockId,
- thread::{
- thread_table,
- work_queue::{submit_work_item, work_item::WorkItem},
- },
+ thread::work_queue::{submit_work_item, work_item::WorkItem},
time::{
clockid_t,
clocks::{BootTimeClock, MonotonicClock, RealTimeClock},
diff --git a/kernel/src/thread/kernel_thread.rs b/kernel/src/thread/kernel_thread.rs
--- a/kernel/src/thread/kernel_thread.rs
+++ b/kernel/src/thread/kernel_thread.rs
@@ -2,23 +2,22 @@
use ostd::{
cpu::CpuSet,
- task::{Priority, TaskOptions},
+ task::{Priority, Task, TaskOptions},
};
-use super::{allocate_tid, status::ThreadStatus, thread_table, Thread};
+use super::{status::ThreadStatus, Thread};
use crate::prelude::*;
/// The inner data of a kernel thread
pub struct KernelThread;
pub trait KernelThreadExt {
- /// get the kernel_thread structure
+ /// Gets the kernel_thread structure
fn as_kernel_thread(&self) -> Option<&KernelThread>;
- /// create a new kernel thread structure, **NOT** run the thread.
- fn new_kernel_thread(thread_options: ThreadOptions) -> Arc<Thread>;
- /// create a new kernel thread structure, and then run the thread.
+ /// Creates a new kernel thread, and then run the thread.
fn spawn_kernel_thread(thread_options: ThreadOptions) -> Arc<Thread> {
- let thread = Self::new_kernel_thread(thread_options);
+ let task = create_new_kernel_task(thread_options);
+ let thread = Thread::borrow_from_task(&task).clone();
thread.run();
thread
}
diff --git a/kernel/src/thread/kernel_thread.rs b/kernel/src/thread/kernel_thread.rs
--- a/kernel/src/thread/kernel_thread.rs
+++ b/kernel/src/thread/kernel_thread.rs
@@ -2,23 +2,22 @@
use ostd::{
cpu::CpuSet,
- task::{Priority, TaskOptions},
+ task::{Priority, Task, TaskOptions},
};
-use super::{allocate_tid, status::ThreadStatus, thread_table, Thread};
+use super::{status::ThreadStatus, Thread};
use crate::prelude::*;
/// The inner data of a kernel thread
pub struct KernelThread;
pub trait KernelThreadExt {
- /// get the kernel_thread structure
+ /// Gets the kernel_thread structure
fn as_kernel_thread(&self) -> Option<&KernelThread>;
- /// create a new kernel thread structure, **NOT** run the thread.
- fn new_kernel_thread(thread_options: ThreadOptions) -> Arc<Thread>;
- /// create a new kernel thread structure, and then run the thread.
+ /// Creates a new kernel thread, and then run the thread.
fn spawn_kernel_thread(thread_options: ThreadOptions) -> Arc<Thread> {
- let thread = Self::new_kernel_thread(thread_options);
+ let task = create_new_kernel_task(thread_options);
+ let thread = Thread::borrow_from_task(&task).clone();
thread.run();
thread
}
diff --git a/kernel/src/thread/kernel_thread.rs b/kernel/src/thread/kernel_thread.rs
--- a/kernel/src/thread/kernel_thread.rs
+++ b/kernel/src/thread/kernel_thread.rs
@@ -31,31 +30,6 @@ impl KernelThreadExt for Thread {
self.data().downcast_ref::<KernelThread>()
}
- fn new_kernel_thread(mut thread_options: ThreadOptions) -> Arc<Self> {
- let task_fn = thread_options.take_func();
- let thread_fn = move || {
- task_fn();
- let current_thread = current_thread!();
- // ensure the thread is exit
- current_thread.exit();
- };
- let tid = allocate_tid();
- let thread = Arc::new_cyclic(|thread_ref| {
- let weal_thread = thread_ref.clone();
- let task = TaskOptions::new(thread_fn)
- .data(weal_thread)
- .priority(thread_options.priority)
- .cpu_affinity(thread_options.cpu_affinity)
- .build()
- .unwrap();
- let status = ThreadStatus::Init;
- let kernel_thread = KernelThread;
- Thread::new(tid, task, kernel_thread, status)
- });
- thread_table::add_thread(thread.clone());
- thread
- }
-
fn join(&self) {
loop {
if self.status().is_exited() {
diff --git a/kernel/src/thread/kernel_thread.rs b/kernel/src/thread/kernel_thread.rs
--- a/kernel/src/thread/kernel_thread.rs
+++ b/kernel/src/thread/kernel_thread.rs
@@ -31,31 +30,6 @@ impl KernelThreadExt for Thread {
self.data().downcast_ref::<KernelThread>()
}
- fn new_kernel_thread(mut thread_options: ThreadOptions) -> Arc<Self> {
- let task_fn = thread_options.take_func();
- let thread_fn = move || {
- task_fn();
- let current_thread = current_thread!();
- // ensure the thread is exit
- current_thread.exit();
- };
- let tid = allocate_tid();
- let thread = Arc::new_cyclic(|thread_ref| {
- let weal_thread = thread_ref.clone();
- let task = TaskOptions::new(thread_fn)
- .data(weal_thread)
- .priority(thread_options.priority)
- .cpu_affinity(thread_options.cpu_affinity)
- .build()
- .unwrap();
- let status = ThreadStatus::Init;
- let kernel_thread = KernelThread;
- Thread::new(tid, task, kernel_thread, status)
- });
- thread_table::add_thread(thread.clone());
- thread
- }
-
fn join(&self) {
loop {
if self.status().is_exited() {
diff --git a/kernel/src/thread/kernel_thread.rs b/kernel/src/thread/kernel_thread.rs
--- a/kernel/src/thread/kernel_thread.rs
+++ b/kernel/src/thread/kernel_thread.rs
@@ -67,6 +41,31 @@ impl KernelThreadExt for Thread {
}
}
+/// Creates a new task of kernel thread, **NOT** run the thread.
+pub fn create_new_kernel_task(mut thread_options: ThreadOptions) -> Arc<Task> {
+ let task_fn = thread_options.take_func();
+ let thread_fn = move || {
+ task_fn();
+ // Ensures the thread is exit
+ current_thread!().exit();
+ };
+
+ Arc::new_cyclic(|weak_task| {
+ let thread = {
+ let kernel_thread = KernelThread;
+ let status = ThreadStatus::Init;
+ Arc::new(Thread::new(weak_task.clone(), kernel_thread, status))
+ };
+
+ TaskOptions::new(thread_fn)
+ .data(thread)
+ .priority(thread_options.priority)
+ .cpu_affinity(thread_options.cpu_affinity)
+ .build()
+ .unwrap()
+ })
+}
+
/// Options to create or spawn a new thread.
pub struct ThreadOptions {
func: Option<Box<dyn Fn() + Send + Sync>>,
diff --git a/kernel/src/thread/kernel_thread.rs b/kernel/src/thread/kernel_thread.rs
--- a/kernel/src/thread/kernel_thread.rs
+++ b/kernel/src/thread/kernel_thread.rs
@@ -67,6 +41,31 @@ impl KernelThreadExt for Thread {
}
}
+/// Creates a new task of kernel thread, **NOT** run the thread.
+pub fn create_new_kernel_task(mut thread_options: ThreadOptions) -> Arc<Task> {
+ let task_fn = thread_options.take_func();
+ let thread_fn = move || {
+ task_fn();
+ // Ensures the thread is exit
+ current_thread!().exit();
+ };
+
+ Arc::new_cyclic(|weak_task| {
+ let thread = {
+ let kernel_thread = KernelThread;
+ let status = ThreadStatus::Init;
+ Arc::new(Thread::new(weak_task.clone(), kernel_thread, status))
+ };
+
+ TaskOptions::new(thread_fn)
+ .data(thread)
+ .priority(thread_options.priority)
+ .cpu_affinity(thread_options.cpu_affinity)
+ .build()
+ .unwrap()
+ })
+}
+
/// Options to create or spawn a new thread.
pub struct ThreadOptions {
func: Option<Box<dyn Fn() + Send + Sync>>,
diff --git a/kernel/src/thread/mod.rs b/kernel/src/thread/mod.rs
--- a/kernel/src/thread/mod.rs
+++ b/kernel/src/thread/mod.rs
@@ -2,7 +2,7 @@
//! Posix thread implementation
-use core::sync::atomic::{AtomicU32, Ordering};
+use core::sync::atomic::Ordering;
use ostd::task::Task;
diff --git a/kernel/src/thread/mod.rs b/kernel/src/thread/mod.rs
--- a/kernel/src/thread/mod.rs
+++ b/kernel/src/thread/mod.rs
@@ -2,7 +2,7 @@
//! Posix thread implementation
-use core::sync::atomic::{AtomicU32, Ordering};
+use core::sync::atomic::Ordering;
use ostd::task::Task;
diff --git a/kernel/src/thread/mod.rs b/kernel/src/thread/mod.rs
--- a/kernel/src/thread/mod.rs
+++ b/kernel/src/thread/mod.rs
@@ -13,20 +13,15 @@ pub mod exception;
pub mod kernel_thread;
pub mod status;
pub mod task;
-pub mod thread_table;
pub mod work_queue;
pub type Tid = u32;
-static TID_ALLOCATOR: AtomicU32 = AtomicU32::new(0);
-
/// A thread is a wrapper on top of task.
pub struct Thread {
// immutable part
- /// Thread id
- tid: Tid,
/// Low-level info
- task: Arc<Task>,
+ task: Weak<Task>,
/// Data: Posix thread info/Kernel thread Info
data: Box<dyn Send + Sync + Any>,
diff --git a/kernel/src/thread/mod.rs b/kernel/src/thread/mod.rs
--- a/kernel/src/thread/mod.rs
+++ b/kernel/src/thread/mod.rs
@@ -13,20 +13,15 @@ pub mod exception;
pub mod kernel_thread;
pub mod status;
pub mod task;
-pub mod thread_table;
pub mod work_queue;
pub type Tid = u32;
-static TID_ALLOCATOR: AtomicU32 = AtomicU32::new(0);
-
/// A thread is a wrapper on top of task.
pub struct Thread {
// immutable part
- /// Thread id
- tid: Tid,
/// Low-level info
- task: Arc<Task>,
+ task: Weak<Task>,
/// Data: Posix thread info/Kernel thread Info
data: Box<dyn Send + Sync + Any>,
diff --git a/kernel/src/thread/mod.rs b/kernel/src/thread/mod.rs
--- a/kernel/src/thread/mod.rs
+++ b/kernel/src/thread/mod.rs
@@ -36,14 +31,8 @@ pub struct Thread {
impl Thread {
/// Never call these function directly
- pub fn new(
- tid: Tid,
- task: Arc<Task>,
- data: impl Send + Sync + Any,
- status: ThreadStatus,
- ) -> Self {
+ pub fn new(task: Weak<Task>, data: impl Send + Sync + Any, status: ThreadStatus) -> Self {
Thread {
- tid,
task,
data: Box::new(data),
status: AtomicThreadStatus::new(status),
diff --git a/kernel/src/thread/mod.rs b/kernel/src/thread/mod.rs
--- a/kernel/src/thread/mod.rs
+++ b/kernel/src/thread/mod.rs
@@ -36,14 +31,8 @@ pub struct Thread {
impl Thread {
/// Never call these function directly
- pub fn new(
- tid: Tid,
- task: Arc<Task>,
- data: impl Send + Sync + Any,
- status: ThreadStatus,
- ) -> Self {
+ pub fn new(task: Weak<Task>, data: impl Send + Sync + Any, status: ThreadStatus) -> Self {
Thread {
- tid,
task,
data: Box::new(data),
status: AtomicThreadStatus::new(status),
diff --git a/kernel/src/thread/mod.rs b/kernel/src/thread/mod.rs
--- a/kernel/src/thread/mod.rs
+++ b/kernel/src/thread/mod.rs
@@ -57,18 +46,23 @@ impl Thread {
pub fn current() -> Option<Arc<Self>> {
Task::current()?
.data()
- .downcast_ref::<Weak<Thread>>()?
- .upgrade()
+ .downcast_ref::<Arc<Thread>>()
+ .cloned()
}
- pub(in crate::thread) fn task(&self) -> &Arc<Task> {
- &self.task
+ /// Gets the Thread from task's data.
+ ///
+ /// # Panics
+ ///
+ /// This method panics if the task is not a thread.
+ pub fn borrow_from_task(task: &Arc<Task>) -> &Arc<Self> {
+ task.data().downcast_ref::<Arc<Thread>>().unwrap()
}
/// Runs this thread at once.
pub fn run(&self) {
self.set_status(ThreadStatus::Running);
- self.task.run();
+ self.task.upgrade().unwrap().run();
}
pub(super) fn exit(&self) {
diff --git a/kernel/src/thread/mod.rs b/kernel/src/thread/mod.rs
--- a/kernel/src/thread/mod.rs
+++ b/kernel/src/thread/mod.rs
@@ -57,18 +46,23 @@ impl Thread {
pub fn current() -> Option<Arc<Self>> {
Task::current()?
.data()
- .downcast_ref::<Weak<Thread>>()?
- .upgrade()
+ .downcast_ref::<Arc<Thread>>()
+ .cloned()
}
- pub(in crate::thread) fn task(&self) -> &Arc<Task> {
- &self.task
+ /// Gets the Thread from task's data.
+ ///
+ /// # Panics
+ ///
+ /// This method panics if the task is not a thread.
+ pub fn borrow_from_task(task: &Arc<Task>) -> &Arc<Self> {
+ task.data().downcast_ref::<Arc<Thread>>().unwrap()
}
/// Runs this thread at once.
pub fn run(&self) {
self.set_status(ThreadStatus::Running);
- self.task.run();
+ self.task.upgrade().unwrap().run();
}
pub(super) fn exit(&self) {
diff --git a/kernel/src/thread/mod.rs b/kernel/src/thread/mod.rs
--- a/kernel/src/thread/mod.rs
+++ b/kernel/src/thread/mod.rs
@@ -94,10 +88,6 @@ impl Thread {
Task::yield_now()
}
- pub fn tid(&self) -> Tid {
- self.tid
- }
-
/// Returns the associated data.
///
/// The return type must be borrowed box, otherwise the `downcast_ref` will fail.
diff --git a/kernel/src/thread/mod.rs b/kernel/src/thread/mod.rs
--- a/kernel/src/thread/mod.rs
+++ b/kernel/src/thread/mod.rs
@@ -94,10 +88,6 @@ impl Thread {
Task::yield_now()
}
- pub fn tid(&self) -> Tid {
- self.tid
- }
-
/// Returns the associated data.
///
/// The return type must be borrowed box, otherwise the `downcast_ref` will fail.
diff --git a/kernel/src/thread/mod.rs b/kernel/src/thread/mod.rs
--- a/kernel/src/thread/mod.rs
+++ b/kernel/src/thread/mod.rs
@@ -106,8 +96,3 @@ impl Thread {
&self.data
}
}
-
-/// Allocates a new tid for the new thread
-pub fn allocate_tid() -> Tid {
- TID_ALLOCATOR.fetch_add(1, Ordering::SeqCst)
-}
diff --git a/kernel/src/thread/mod.rs b/kernel/src/thread/mod.rs
--- a/kernel/src/thread/mod.rs
+++ b/kernel/src/thread/mod.rs
@@ -106,8 +96,3 @@ impl Thread {
&self.data
}
}
-
-/// Allocates a new tid for the new thread
-pub fn allocate_tid() -> Tid {
- TID_ALLOCATOR.fetch_add(1, Ordering::SeqCst)
-}
diff --git a/kernel/src/thread/task.rs b/kernel/src/thread/task.rs
--- a/kernel/src/thread/task.rs
+++ b/kernel/src/thread/task.rs
@@ -16,12 +16,12 @@ use crate::{
};
/// create new task with userspace and parent process
-pub fn create_new_user_task(user_space: Arc<UserSpace>, thread_ref: Weak<Thread>) -> Arc<Task> {
+pub fn create_new_user_task(user_space: Arc<UserSpace>, thread_ref: Arc<Thread>) -> Task {
fn user_task_entry() {
let current_thread = current_thread!();
let current_posix_thread = current_thread.as_posix_thread().unwrap();
let current_process = current_posix_thread.process();
- let current_task = current_thread.task();
+ let current_task = Task::current().unwrap();
let user_space = current_task
.user_space()
diff --git a/kernel/src/thread/task.rs b/kernel/src/thread/task.rs
--- a/kernel/src/thread/task.rs
+++ b/kernel/src/thread/task.rs
@@ -16,12 +16,12 @@ use crate::{
};
/// create new task with userspace and parent process
-pub fn create_new_user_task(user_space: Arc<UserSpace>, thread_ref: Weak<Thread>) -> Arc<Task> {
+pub fn create_new_user_task(user_space: Arc<UserSpace>, thread_ref: Arc<Thread>) -> Task {
fn user_task_entry() {
let current_thread = current_thread!();
let current_posix_thread = current_thread.as_posix_thread().unwrap();
let current_process = current_posix_thread.process();
- let current_task = current_thread.task();
+ let current_task = Task::current().unwrap();
let user_space = current_task
.user_space()
diff --git a/kernel/src/thread/task.rs b/kernel/src/thread/task.rs
--- a/kernel/src/thread/task.rs
+++ b/kernel/src/thread/task.rs
@@ -47,7 +47,7 @@ pub fn create_new_user_task(user_space: Arc<UserSpace>, thread_ref: Weak<Thread>
// in the child process.
if is_userspace_vaddr(child_tid_ptr) {
CurrentUserSpace::get()
- .write_val(child_tid_ptr, ¤t_thread.tid())
+ .write_val(child_tid_ptr, ¤t_posix_thread.tid())
.unwrap();
}
diff --git a/kernel/src/thread/task.rs b/kernel/src/thread/task.rs
--- a/kernel/src/thread/task.rs
+++ b/kernel/src/thread/task.rs
@@ -47,7 +47,7 @@ pub fn create_new_user_task(user_space: Arc<UserSpace>, thread_ref: Weak<Thread>
// in the child process.
if is_userspace_vaddr(child_tid_ptr) {
CurrentUserSpace::get()
- .write_val(child_tid_ptr, ¤t_thread.tid())
+ .write_val(child_tid_ptr, ¤t_posix_thread.tid())
.unwrap();
}
diff --git a/kernel/src/thread/task.rs b/kernel/src/thread/task.rs
--- a/kernel/src/thread/task.rs
+++ b/kernel/src/thread/task.rs
@@ -77,7 +77,7 @@ pub fn create_new_user_task(user_space: Arc<UserSpace>, thread_ref: Weak<Thread>
// If current is suspended, wait for a signal to wake up self
while current_thread.status().is_stopped() {
Thread::yield_now();
- debug!("{} is suspended.", current_thread.tid());
+ debug!("{} is suspended.", current_posix_thread.tid());
handle_pending_signal(user_ctx, ¤t_thread).unwrap();
}
if current_thread.status().is_exited() {
diff --git a/kernel/src/thread/task.rs b/kernel/src/thread/task.rs
--- a/kernel/src/thread/task.rs
+++ b/kernel/src/thread/task.rs
@@ -77,7 +77,7 @@ pub fn create_new_user_task(user_space: Arc<UserSpace>, thread_ref: Weak<Thread>
// If current is suspended, wait for a signal to wake up self
while current_thread.status().is_stopped() {
Thread::yield_now();
- debug!("{} is suspended.", current_thread.tid());
+ debug!("{} is suspended.", current_posix_thread.tid());
handle_pending_signal(user_ctx, ¤t_thread).unwrap();
}
if current_thread.status().is_exited() {
diff --git a/kernel/src/thread/thread_table.rs /dev/null
--- a/kernel/src/thread/thread_table.rs
+++ /dev/null
@@ -1,21 +0,0 @@
-// SPDX-License-Identifier: MPL-2.0
-
-use super::{Thread, Tid};
-use crate::prelude::*;
-
-lazy_static! {
- static ref THREAD_TABLE: SpinLock<BTreeMap<Tid, Arc<Thread>>> = SpinLock::new(BTreeMap::new());
-}
-
-pub fn add_thread(thread: Arc<Thread>) {
- let tid = thread.tid();
- THREAD_TABLE.lock().insert(tid, thread);
-}
-
-pub fn remove_thread(tid: Tid) {
- THREAD_TABLE.lock().remove(&tid);
-}
-
-pub fn get_thread(tid: Tid) -> Option<Arc<Thread>> {
- THREAD_TABLE.lock().get(&tid).cloned()
-}
diff --git a/kernel/src/thread/thread_table.rs /dev/null
--- a/kernel/src/thread/thread_table.rs
+++ /dev/null
@@ -1,21 +0,0 @@
-// SPDX-License-Identifier: MPL-2.0
-
-use super::{Thread, Tid};
-use crate::prelude::*;
-
-lazy_static! {
- static ref THREAD_TABLE: SpinLock<BTreeMap<Tid, Arc<Thread>>> = SpinLock::new(BTreeMap::new());
-}
-
-pub fn add_thread(thread: Arc<Thread>) {
- let tid = thread.tid();
- THREAD_TABLE.lock().insert(tid, thread);
-}
-
-pub fn remove_thread(tid: Tid) {
- THREAD_TABLE.lock().remove(&tid);
-}
-
-pub fn get_thread(tid: Tid) -> Option<Arc<Thread>> {
- THREAD_TABLE.lock().get(&tid).cloned()
-}
diff --git a/kernel/src/thread/work_queue/worker.rs b/kernel/src/thread/work_queue/worker.rs
--- a/kernel/src/thread/work_queue/worker.rs
+++ b/kernel/src/thread/work_queue/worker.rs
@@ -2,12 +2,15 @@
#![allow(dead_code)]
-use ostd::{cpu::CpuSet, task::Priority};
+use ostd::{
+ cpu::CpuSet,
+ task::{Priority, Task},
+};
use super::worker_pool::WorkerPool;
use crate::{
prelude::*,
- thread::kernel_thread::{KernelThreadExt, ThreadOptions},
+ thread::kernel_thread::{create_new_kernel_task, ThreadOptions},
Thread,
};
diff --git a/kernel/src/thread/work_queue/worker.rs b/kernel/src/thread/work_queue/worker.rs
--- a/kernel/src/thread/work_queue/worker.rs
+++ b/kernel/src/thread/work_queue/worker.rs
@@ -2,12 +2,15 @@
#![allow(dead_code)]
-use ostd::{cpu::CpuSet, task::Priority};
+use ostd::{
+ cpu::CpuSet,
+ task::{Priority, Task},
+};
use super::worker_pool::WorkerPool;
use crate::{
prelude::*,
- thread::kernel_thread::{KernelThreadExt, ThreadOptions},
+ thread::kernel_thread::{create_new_kernel_task, ThreadOptions},
Thread,
};
diff --git a/kernel/src/thread/work_queue/worker.rs b/kernel/src/thread/work_queue/worker.rs
--- a/kernel/src/thread/work_queue/worker.rs
+++ b/kernel/src/thread/work_queue/worker.rs
@@ -17,7 +20,7 @@ use crate::{
/// added to the `WorkerPool`.
pub(super) struct Worker {
worker_pool: Weak<WorkerPool>,
- bound_thread: Arc<Thread>,
+ bound_task: Arc<Task>,
bound_cpu: u32,
inner: SpinLock<WorkerInner>,
}
diff --git a/kernel/src/thread/work_queue/worker.rs b/kernel/src/thread/work_queue/worker.rs
--- a/kernel/src/thread/work_queue/worker.rs
+++ b/kernel/src/thread/work_queue/worker.rs
@@ -17,7 +20,7 @@ use crate::{
/// added to the `WorkerPool`.
pub(super) struct Worker {
worker_pool: Weak<WorkerPool>,
- bound_thread: Arc<Thread>,
+ bound_task: Arc<Task>,
bound_cpu: u32,
inner: SpinLock<WorkerInner>,
}
diff --git a/kernel/src/thread/work_queue/worker.rs b/kernel/src/thread/work_queue/worker.rs
--- a/kernel/src/thread/work_queue/worker.rs
+++ b/kernel/src/thread/work_queue/worker.rs
@@ -51,14 +54,14 @@ impl Worker {
if worker_pool.upgrade().unwrap().is_high_priority() {
priority = Priority::high();
}
- let bound_thread = Thread::new_kernel_thread(
+ let bound_task = create_new_kernel_task(
ThreadOptions::new(task_fn)
.cpu_affinity(cpu_affinity)
.priority(priority),
);
Self {
worker_pool,
- bound_thread,
+ bound_task,
bound_cpu,
inner: SpinLock::new(WorkerInner {
worker_status: WorkerStatus::Running,
diff --git a/kernel/src/thread/work_queue/worker.rs b/kernel/src/thread/work_queue/worker.rs
--- a/kernel/src/thread/work_queue/worker.rs
+++ b/kernel/src/thread/work_queue/worker.rs
@@ -51,14 +54,14 @@ impl Worker {
if worker_pool.upgrade().unwrap().is_high_priority() {
priority = Priority::high();
}
- let bound_thread = Thread::new_kernel_thread(
+ let bound_task = create_new_kernel_task(
ThreadOptions::new(task_fn)
.cpu_affinity(cpu_affinity)
.priority(priority),
);
Self {
worker_pool,
- bound_thread,
+ bound_task,
bound_cpu,
inner: SpinLock::new(WorkerInner {
worker_status: WorkerStatus::Running,
diff --git a/kernel/src/thread/work_queue/worker.rs b/kernel/src/thread/work_queue/worker.rs
--- a/kernel/src/thread/work_queue/worker.rs
+++ b/kernel/src/thread/work_queue/worker.rs
@@ -68,7 +71,8 @@ impl Worker {
}
pub(super) fn run(&self) {
- self.bound_thread.run();
+ let thread = Thread::borrow_from_task(&self.bound_task);
+ thread.run();
}
/// The thread function bound to normal workers.
diff --git a/kernel/src/thread/work_queue/worker.rs b/kernel/src/thread/work_queue/worker.rs
--- a/kernel/src/thread/work_queue/worker.rs
+++ b/kernel/src/thread/work_queue/worker.rs
@@ -68,7 +71,8 @@ impl Worker {
}
pub(super) fn run(&self) {
- self.bound_thread.run();
+ let thread = Thread::borrow_from_task(&self.bound_task);
+ thread.run();
}
/// The thread function bound to normal workers.
diff --git a/kernel/src/thread/work_queue/worker.rs b/kernel/src/thread/work_queue/worker.rs
--- a/kernel/src/thread/work_queue/worker.rs
+++ b/kernel/src/thread/work_queue/worker.rs
@@ -97,8 +101,8 @@ impl Worker {
self.exit();
}
- pub(super) fn bound_thread(&self) -> &Arc<Thread> {
- &self.bound_thread
+ pub(super) fn bound_task(&self) -> &Arc<Task> {
+ &self.bound_task
}
pub(super) fn is_idle(&self) -> bool {
diff --git a/kernel/src/thread/work_queue/worker.rs b/kernel/src/thread/work_queue/worker.rs
--- a/kernel/src/thread/work_queue/worker.rs
+++ b/kernel/src/thread/work_queue/worker.rs
@@ -97,8 +101,8 @@ impl Worker {
self.exit();
}
- pub(super) fn bound_thread(&self) -> &Arc<Thread> {
- &self.bound_thread
+ pub(super) fn bound_task(&self) -> &Arc<Task> {
+ &self.bound_task
}
pub(super) fn is_idle(&self) -> bool {
diff --git a/kernel/src/thread/work_queue/worker_pool.rs b/kernel/src/thread/work_queue/worker_pool.rs
--- a/kernel/src/thread/work_queue/worker_pool.rs
+++ b/kernel/src/thread/work_queue/worker_pool.rs
@@ -7,12 +7,16 @@ use core::{
time::Duration,
};
-use ostd::{cpu::CpuSet, sync::WaitQueue, task::Priority};
+use ostd::{
+ cpu::CpuSet,
+ sync::WaitQueue,
+ task::{Priority, Task},
+};
use super::{simple_scheduler::SimpleScheduler, worker::Worker, WorkItem, WorkPriority, WorkQueue};
use crate::{
prelude::*,
- thread::kernel_thread::{KernelThreadExt, ThreadOptions},
+ thread::kernel_thread::{create_new_kernel_task, ThreadOptions},
Thread,
};
diff --git a/kernel/src/thread/work_queue/worker_pool.rs b/kernel/src/thread/work_queue/worker_pool.rs
--- a/kernel/src/thread/work_queue/worker_pool.rs
+++ b/kernel/src/thread/work_queue/worker_pool.rs
@@ -7,12 +7,16 @@ use core::{
time::Duration,
};
-use ostd::{cpu::CpuSet, sync::WaitQueue, task::Priority};
+use ostd::{
+ cpu::CpuSet,
+ sync::WaitQueue,
+ task::{Priority, Task},
+};
use super::{simple_scheduler::SimpleScheduler, worker::Worker, WorkItem, WorkPriority, WorkQueue};
use crate::{
prelude::*,
- thread::kernel_thread::{KernelThreadExt, ThreadOptions},
+ thread::kernel_thread::{create_new_kernel_task, ThreadOptions},
Thread,
};
diff --git a/kernel/src/thread/work_queue/worker_pool.rs b/kernel/src/thread/work_queue/worker_pool.rs
--- a/kernel/src/thread/work_queue/worker_pool.rs
+++ b/kernel/src/thread/work_queue/worker_pool.rs
@@ -60,7 +64,7 @@ pub trait WorkerScheduler: Sync + Send {
/// are found processing in the pool.
pub struct Monitor {
worker_pool: Weak<WorkerPool>,
- bound_thread: Arc<Thread>,
+ bound_task: Arc<Task>,
}
impl LocalWorkerPool {
diff --git a/kernel/src/thread/work_queue/worker_pool.rs b/kernel/src/thread/work_queue/worker_pool.rs
--- a/kernel/src/thread/work_queue/worker_pool.rs
+++ b/kernel/src/thread/work_queue/worker_pool.rs
@@ -60,7 +64,7 @@ pub trait WorkerScheduler: Sync + Send {
/// are found processing in the pool.
pub struct Monitor {
worker_pool: Weak<WorkerPool>,
- bound_thread: Arc<Thread>,
+ bound_task: Arc<Task>,
}
impl LocalWorkerPool {
diff --git a/kernel/src/thread/work_queue/worker_pool.rs b/kernel/src/thread/work_queue/worker_pool.rs
--- a/kernel/src/thread/work_queue/worker_pool.rs
+++ b/kernel/src/thread/work_queue/worker_pool.rs
@@ -77,7 +81,7 @@ impl LocalWorkerPool {
fn add_worker(&self) {
let worker = Worker::new(self.parent.clone(), self.cpu_id);
self.workers.disable_irq().lock().push_back(worker.clone());
- worker.bound_thread().run();
+ Thread::borrow_from_task(worker.bound_task()).run();
}
fn remove_worker(&self) {
diff --git a/kernel/src/thread/work_queue/worker_pool.rs b/kernel/src/thread/work_queue/worker_pool.rs
--- a/kernel/src/thread/work_queue/worker_pool.rs
+++ b/kernel/src/thread/work_queue/worker_pool.rs
@@ -77,7 +81,7 @@ impl LocalWorkerPool {
fn add_worker(&self) {
let worker = Worker::new(self.parent.clone(), self.cpu_id);
self.workers.disable_irq().lock().push_back(worker.clone());
- worker.bound_thread().run();
+ Thread::borrow_from_task(worker.bound_task()).run();
}
fn remove_worker(&self) {
diff --git a/kernel/src/thread/work_queue/worker_pool.rs b/kernel/src/thread/work_queue/worker_pool.rs
--- a/kernel/src/thread/work_queue/worker_pool.rs
+++ b/kernel/src/thread/work_queue/worker_pool.rs
@@ -236,20 +240,20 @@ impl Monitor {
WorkPriority::High => Priority::high(),
WorkPriority::Normal => Priority::normal(),
};
- let bound_thread = Thread::new_kernel_thread(
+ let bound_task = create_new_kernel_task(
ThreadOptions::new(task_fn)
.cpu_affinity(cpu_affinity)
.priority(priority),
);
Self {
worker_pool,
- bound_thread,
+ bound_task,
}
})
}
pub fn run(&self) {
- self.bound_thread.run();
+ Thread::borrow_from_task(&self.bound_task).run()
}
fn run_monitor_loop(self: &Arc<Self>) {
diff --git a/kernel/src/thread/work_queue/worker_pool.rs b/kernel/src/thread/work_queue/worker_pool.rs
--- a/kernel/src/thread/work_queue/worker_pool.rs
+++ b/kernel/src/thread/work_queue/worker_pool.rs
@@ -236,20 +240,20 @@ impl Monitor {
WorkPriority::High => Priority::high(),
WorkPriority::Normal => Priority::normal(),
};
- let bound_thread = Thread::new_kernel_thread(
+ let bound_task = create_new_kernel_task(
ThreadOptions::new(task_fn)
.cpu_affinity(cpu_affinity)
.priority(priority),
);
Self {
worker_pool,
- bound_thread,
+ bound_task,
}
})
}
pub fn run(&self) {
- self.bound_thread.run();
+ Thread::borrow_from_task(&self.bound_task).run()
}
fn run_monitor_loop(self: &Arc<Self>) {
diff --git a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
--- a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
+++ b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
@@ -102,11 +102,13 @@ fn create_user_task(user_space: Arc<UserSpace>) -> Arc<Task> {
// Kernel tasks are managed by the Framework,
// while scheduling algorithms for them can be
// determined by the users of the Framework.
- TaskOptions::new(user_task)
- .user_space(Some(user_space))
- .data(0)
- .build()
- .unwrap()
+ Arc::new(
+ TaskOptions::new(user_task)
+ .user_space(Some(user_space))
+ .data(0)
+ .build()
+ .unwrap(),
+ )
}
fn handle_syscall(user_context: &mut UserContext, user_space: &UserSpace) {
diff --git a/ostd/src/task/mod.rs b/ostd/src/task/mod.rs
--- a/ostd/src/task/mod.rs
+++ b/ostd/src/task/mod.rs
@@ -166,7 +166,7 @@ impl TaskOptions {
}
/// Builds a new task without running it immediately.
- pub fn build(self) -> Result<Arc<Task>> {
+ pub fn build(self) -> Result<Task> {
/// all task will entering this function
/// this function is mean to executing the task_fn in Task
extern "C" fn kernel_task_entry() {
diff --git a/ostd/src/task/mod.rs b/ostd/src/task/mod.rs
--- a/ostd/src/task/mod.rs
+++ b/ostd/src/task/mod.rs
@@ -166,7 +166,7 @@ impl TaskOptions {
}
/// Builds a new task without running it immediately.
- pub fn build(self) -> Result<Arc<Task>> {
+ pub fn build(self) -> Result<Task> {
/// all task will entering this function
/// this function is mean to executing the task_fn in Task
extern "C" fn kernel_task_entry() {
diff --git a/ostd/src/task/mod.rs b/ostd/src/task/mod.rs
--- a/ostd/src/task/mod.rs
+++ b/ostd/src/task/mod.rs
@@ -201,12 +201,12 @@ impl TaskOptions {
// have any arguments, so we only need to align the stack pointer to 16 bytes.
ctx.set_stack_pointer(crate::mm::paddr_to_vaddr(new_task.kstack.end_paddr() - 16));
- Ok(Arc::new(new_task))
+ Ok(new_task)
}
/// Builds a new task and run it immediately.
pub fn spawn(self) -> Result<Arc<Task>> {
- let task = self.build()?;
+ let task = Arc::new(self.build()?);
task.run();
Ok(task)
}
diff --git a/ostd/src/task/mod.rs b/ostd/src/task/mod.rs
--- a/ostd/src/task/mod.rs
+++ b/ostd/src/task/mod.rs
@@ -201,12 +201,12 @@ impl TaskOptions {
// have any arguments, so we only need to align the stack pointer to 16 bytes.
ctx.set_stack_pointer(crate::mm::paddr_to_vaddr(new_task.kstack.end_paddr() - 16));
- Ok(Arc::new(new_task))
+ Ok(new_task)
}
/// Builds a new task and run it immediately.
pub fn spawn(self) -> Result<Arc<Task>> {
- let task = self.build()?;
+ let task = Arc::new(self.build()?);
task.run();
Ok(task)
}
diff --git a/ostd/src/task/mod.rs b/ostd/src/task/mod.rs
--- a/ostd/src/task/mod.rs
+++ b/ostd/src/task/mod.rs
@@ -237,11 +237,13 @@ mod test {
let task = || {
assert_eq!(1, 1);
};
- let task_option = crate::task::TaskOptions::new(task)
- .data(())
- .build()
- .unwrap();
- task_option.run();
+ let task = Arc::new(
+ crate::task::TaskOptions::new(task)
+ .data(())
+ .build()
+ .unwrap(),
+ );
+ task.run();
}
#[ktest]
|
2024-09-12T06:03:09Z
|
ae4ac384713e63232b74915593ebdef680049d31
|
|
asterinas/asterinas
|
diff --git a/ostd/src/sync/mutex.rs b/ostd/src/sync/mutex.rs
--- a/ostd/src/sync/mutex.rs
+++ b/ostd/src/sync/mutex.rs
@@ -138,3 +150,27 @@ impl<'a, T: ?Sized> MutexGuard<'a, T> {
guard.mutex
}
}
+
+#[cfg(ktest)]
+mod test {
+ use super::*;
+ use crate::prelude::*;
+
+ // A regression test for a bug fixed in [#1279](https://github.com/asterinas/asterinas/pull/1279).
+ #[ktest]
+ fn test_mutex_try_lock_does_not_unlock() {
+ let lock = Mutex::new(0);
+ assert!(!lock.lock.load(Ordering::Relaxed));
+
+ // A successful lock
+ let guard1 = lock.lock();
+ assert!(lock.lock.load(Ordering::Relaxed));
+
+ // A failed `try_lock` won't drop the lock
+ assert!(lock.try_lock().is_none());
+ assert!(lock.lock.load(Ordering::Relaxed));
+
+ // Ensure the lock is held until here
+ drop(guard1);
+ }
+}
|
[
"1274"
] |
0.8
|
963874471284ed014b76d268d933b6d13073c2cc
|
Potential mutex lock bug leading to multiple threads entering critical section
### Describe the bug
Hi there!
I'm working on a testcase for issue #1261 to reproduce the bug, and I noticed a weird behavior. It seems that `mutex.lock()` does not block when another thread has already acquired the lock in `ktest`. This causes multiple threads to enter the critical section simultaneously.
### To Reproduce
1. `git apply ./patch.diff`
2. `make ktest`
Here is the `path.diff` file:
**Note**: I'm not sure if I inited the test environment and used `timer::Jiffies` and `Thread::yield_now()` correctly. I observed that without using `yield_now()`, thread scheduling does not occur. In other words, if `Thread::yield_now()` is commented out, this test case will pass.
```diff
diff --git a/kernel/src/process/sync/condvar.rs b/kernel/src/process/sync/condvar.rs
index 944fe070..52f3e971 100644
--- a/kernel/src/process/sync/condvar.rs
+++ b/kernel/src/process/sync/condvar.rs
@@ -363,4 +363,51 @@ mod test {
assert!(!*started);
}
}
+
+ use ostd::arch::timer::Jiffies;
+
+ fn wait_jiffies(value: u64) {
+ let mut previous = Jiffies::elapsed().as_u64();
+ let ddl = previous + value;
+ loop {
+ let current = Jiffies::elapsed().as_u64();
+ if current >= ddl {
+ break;
+ }
+ if current - previous >= 10 {
+ previous = current;
+ Thread::yield_now();
+ }
+ }
+ }
+
+ #[ktest]
+ fn test_mutex_cs() {
+ let pair = Arc::new((Mutex::new(0), Condvar::new()));
+ let pair2 = Arc::clone(&pair);
+
+ Thread::spawn_kernel_thread(ThreadOptions::new(move || {
+ wait_jiffies(1000);
+ let (lock, _) = &*pair;
+ let mut val = lock.lock();
+ *val = 1;
+ wait_jiffies(1000);
+ assert!(*val == 1);
+ *val = 2;
+ wait_jiffies(1000);
+ assert!(*val == 2);
+ }));
+
+ {
+ let (lock2, _) = &*pair2;
+ let mut val = lock2.lock();
+ *val = 10;
+ wait_jiffies(1000);
+ assert!(*val == 10);
+ *val = 20;
+ wait_jiffies(1000);
+ assert!(*val == 20);
+ }
+
+ }
}
```
### Expected behavior
Only one thread should enter the critical section at a time.
### Screenshots

### Environment
Official Docker environment, version 0.8.1
|
asterinas__asterinas-1279
| 1,279
|
diff --git a/ostd/src/sync/mutex.rs b/ostd/src/sync/mutex.rs
--- a/ostd/src/sync/mutex.rs
+++ b/ostd/src/sync/mutex.rs
@@ -50,7 +50,9 @@ impl<T: ?Sized> Mutex<T> {
pub fn try_lock(&self) -> Option<MutexGuard<T>> {
// Cannot be reduced to `then_some`, or the possible dropping of the temporary
// guard will cause an unexpected unlock.
- self.acquire_lock().then_some(MutexGuard { mutex: self })
+ // SAFETY: The lock is successfully acquired when creating the guard.
+ self.acquire_lock()
+ .then(|| unsafe { MutexGuard::new(self) })
}
/// Tries acquire the mutex through an [`Arc`].
diff --git a/ostd/src/sync/mutex.rs b/ostd/src/sync/mutex.rs
--- a/ostd/src/sync/mutex.rs
+++ b/ostd/src/sync/mutex.rs
@@ -50,7 +50,9 @@ impl<T: ?Sized> Mutex<T> {
pub fn try_lock(&self) -> Option<MutexGuard<T>> {
// Cannot be reduced to `then_some`, or the possible dropping of the temporary
// guard will cause an unexpected unlock.
- self.acquire_lock().then_some(MutexGuard { mutex: self })
+ // SAFETY: The lock is successfully acquired when creating the guard.
+ self.acquire_lock()
+ .then(|| unsafe { MutexGuard::new(self) })
}
/// Tries acquire the mutex through an [`Arc`].
diff --git a/ostd/src/sync/mutex.rs b/ostd/src/sync/mutex.rs
--- a/ostd/src/sync/mutex.rs
+++ b/ostd/src/sync/mutex.rs
@@ -100,6 +102,16 @@ pub struct MutexGuard_<T: ?Sized, R: Deref<Target = Mutex<T>>> {
/// A guard that provides exclusive access to the data protected by a [`Mutex`].
pub type MutexGuard<'a, T> = MutexGuard_<T, &'a Mutex<T>>;
+impl<'a, T: ?Sized> MutexGuard<'a, T> {
+ /// # Safety
+ ///
+ /// The caller must ensure that the given reference of [`Mutex`] lock has been successfully acquired
+ /// in the current context. When the created [`MutexGuard`] is dropped, it will unlock the [`Mutex`].
+ unsafe fn new(mutex: &'a Mutex<T>) -> MutexGuard<'a, T> {
+ MutexGuard { mutex }
+ }
+}
+
/// An guard that provides exclusive access to the data protected by a `Arc<Mutex>`.
pub type ArcMutexGuard<T> = MutexGuard_<T, Arc<Mutex<T>>>;
diff --git a/ostd/src/sync/mutex.rs b/ostd/src/sync/mutex.rs
--- a/ostd/src/sync/mutex.rs
+++ b/ostd/src/sync/mutex.rs
@@ -100,6 +102,16 @@ pub struct MutexGuard_<T: ?Sized, R: Deref<Target = Mutex<T>>> {
/// A guard that provides exclusive access to the data protected by a [`Mutex`].
pub type MutexGuard<'a, T> = MutexGuard_<T, &'a Mutex<T>>;
+impl<'a, T: ?Sized> MutexGuard<'a, T> {
+ /// # Safety
+ ///
+ /// The caller must ensure that the given reference of [`Mutex`] lock has been successfully acquired
+ /// in the current context. When the created [`MutexGuard`] is dropped, it will unlock the [`Mutex`].
+ unsafe fn new(mutex: &'a Mutex<T>) -> MutexGuard<'a, T> {
+ MutexGuard { mutex }
+ }
+}
+
/// An guard that provides exclusive access to the data protected by a `Arc<Mutex>`.
pub type ArcMutexGuard<T> = MutexGuard_<T, Arc<Mutex<T>>>;
diff --git a/ostd/src/sync/mutex.rs b/ostd/src/sync/mutex.rs
--- a/ostd/src/sync/mutex.rs
+++ b/ostd/src/sync/mutex.rs
@@ -138,3 +150,27 @@ impl<'a, T: ?Sized> MutexGuard<'a, T> {
guard.mutex
}
}
+
+#[cfg(ktest)]
+mod test {
+ use super::*;
+ use crate::prelude::*;
+
+ // A regression test for a bug fixed in [#1279](https://github.com/asterinas/asterinas/pull/1279).
+ #[ktest]
+ fn test_mutex_try_lock_does_not_unlock() {
+ let lock = Mutex::new(0);
+ assert!(!lock.lock.load(Ordering::Relaxed));
+
+ // A successful lock
+ let guard1 = lock.lock();
+ assert!(lock.lock.load(Ordering::Relaxed));
+
+ // A failed `try_lock` won't drop the lock
+ assert!(lock.try_lock().is_none());
+ assert!(lock.lock.load(Ordering::Relaxed));
+
+ // Ensure the lock is held until here
+ drop(guard1);
+ }
+}
|
The bug introduced in this commit: https://github.com/asterinas/asterinas/commit/d15b4d9115cf33490245c06a93928995765f0d3f#r146080074
A potential fix: #497
|
2024-09-02T06:56:20Z
|
ae4ac384713e63232b74915593ebdef680049d31
|
asterinas/asterinas
|
diff --git a/osdk/src/config/manifest.rs b/osdk/src/config/manifest.rs
--- a/osdk/src/config/manifest.rs
+++ b/osdk/src/config/manifest.rs
@@ -128,82 +128,7 @@ fn deserialize_toml_manifest(path: impl AsRef<Path>) -> Option<TomlManifest> {
for scheme in manifest.map.values_mut() {
scheme.work_dir = Some(cwd.to_path_buf());
}
- // Canonicalize all the path fields
- let canonicalize = |target: &mut PathBuf| {
- let last_cwd = std::env::current_dir().unwrap();
- std::env::set_current_dir(cwd).unwrap();
- *target = target.canonicalize().unwrap_or_else(|err| {
- error_msg!(
- "Cannot canonicalize path `{}`: {}",
- target.to_string_lossy(),
- err,
- );
- std::env::set_current_dir(&last_cwd).unwrap();
- process::exit(Errno::GetMetadata as _);
- });
- std::env::set_current_dir(last_cwd).unwrap();
- };
- let canonicalize_scheme = |scheme: &mut Scheme| {
- macro_rules! canonicalize_paths_in_scheme {
- ($scheme:expr) => {
- if let Some(ref mut boot) = $scheme.boot {
- if let Some(ref mut initramfs) = boot.initramfs {
- canonicalize(initramfs);
- }
- }
- if let Some(ref mut qemu) = $scheme.qemu {
- if let Some(ref mut qemu_path) = qemu.path {
- canonicalize(qemu_path);
- }
- }
- if let Some(ref mut grub) = $scheme.grub {
- if let Some(ref mut grub_mkrescue_path) = grub.grub_mkrescue {
- canonicalize(grub_mkrescue_path);
- }
- }
- };
- }
- canonicalize_paths_in_scheme!(scheme);
- if let Some(ref mut run) = scheme.run {
- canonicalize_paths_in_scheme!(run);
- }
- if let Some(ref mut test) = scheme.test {
- canonicalize_paths_in_scheme!(test);
- }
- };
- canonicalize_scheme(&mut manifest.default_scheme);
- for scheme in manifest.map.values_mut() {
- canonicalize_scheme(scheme);
- }
- // Do evaluations on the need to be evaluated string field, namely,
- // QEMU arguments.
- use super::eval::eval;
- let eval_scheme = |scheme: &mut Scheme| {
- let eval_qemu = |qemu: &mut Option<QemuScheme>| {
- if let Some(ref mut qemu) = qemu {
- if let Some(ref mut args) = qemu.args {
- *args = match eval(cwd, args) {
- Ok(v) => v,
- Err(e) => {
- error_msg!("Failed to evaluate qemu args: {:#?}", e);
- process::exit(Errno::ParseMetadata as _);
- }
- }
- }
- }
- };
- eval_qemu(&mut scheme.qemu);
- if let Some(ref mut run) = scheme.run {
- eval_qemu(&mut run.qemu);
- }
- if let Some(ref mut test) = scheme.test {
- eval_qemu(&mut test.qemu);
- }
- };
- eval_scheme(&mut manifest.default_scheme);
- for scheme in manifest.map.values_mut() {
- eval_scheme(scheme);
- }
+
Some(manifest)
}
diff --git a/osdk/src/config/mod.rs b/osdk/src/config/mod.rs
--- a/osdk/src/config/mod.rs
+++ b/osdk/src/config/mod.rs
@@ -5,8 +5,6 @@
//! arguments if the arguments is missing, e.g., the path of QEMU. The final configuration is stored in `BuildConfig`,
//! `RunConfig` and `TestConfig`. These `*Config` are used for `build`, `run` and `test` subcommand.
-mod eval;
-
pub mod manifest;
pub mod scheme;
pub mod unix_args;
diff --git a/osdk/src/config/mod.rs b/osdk/src/config/mod.rs
--- a/osdk/src/config/mod.rs
+++ b/osdk/src/config/mod.rs
@@ -14,7 +12,11 @@ pub mod unix_args;
#[cfg(test)]
mod test;
-use std::{env, path::PathBuf};
+use std::{
+ env, io,
+ path::{Path, PathBuf},
+ process,
+};
use linux_bzimage_builder::PayloadEncoding;
use scheme::{
diff --git a/osdk/src/config/mod.rs b/osdk/src/config/mod.rs
--- a/osdk/src/config/mod.rs
+++ b/osdk/src/config/mod.rs
@@ -37,7 +41,11 @@ pub struct Config {
pub test: Action,
}
-fn apply_args_before_finalize(action_scheme: &mut ActionScheme, args: &CommonArgs) {
+fn apply_args_before_finalize(
+ action_scheme: &mut ActionScheme,
+ args: &CommonArgs,
+ workdir: &PathBuf,
+) {
if action_scheme.grub.is_none() {
action_scheme.grub = Some(GrubScheme::default());
}
diff --git a/osdk/src/config/mod.rs b/osdk/src/config/mod.rs
--- a/osdk/src/config/mod.rs
+++ b/osdk/src/config/mod.rs
@@ -120,7 +210,7 @@ impl Config {
let test = {
let mut test = scheme.test.clone().unwrap_or_default();
test.inherit(&default_scheme);
- apply_args_before_finalize(&mut test, common_args);
+ apply_args_before_finalize(&mut test, common_args, scheme.work_dir.as_ref().unwrap());
let mut test = test.finalize(target_arch);
apply_args_after_finalize(&mut test, common_args);
check_compatibility(test.grub.boot_protocol, test.build.encoding.clone());
|
[
"1237"
] |
0.8
|
539984bbed414969b0c40cf181a10e9341ed2359
|
OSDK should not check the options that have been overridden
### Describe the bug
OSDK will (but should not) keep checking the existence of the file, despite that option is overridden .
### To Reproduce
1. Create a `OSDK.toml` whose `initramfs` points to a non-exist file.
``` toml
[boot]
initramfs = "non/exist/directory/initramfs.cpio.gz"
```
2. Run OSDK with command line `initramfs` option, e.g. `cargo osdk build --initramfs="test/build/initramfs.cpio.gz"`, where `initramfs.cpio.gz` does exist.
3. OSDK will report that `non/exist/directory/initramfs.cpio.gz` does not exist, despite it's overridden by command-line `--initramfs`.
```
$ cargo osdk build --initramfs="test/build/initramfs.cpio.gz"
[Error]: Cannot canonicalize path `non/exist/directory/initramfs.cpio.gz`: No such file or directory (os error 2)
```
### Expected behavior
It should work, and don't need to check `non/exist/directory/initramfs.cpio.gz`.
### Screenshots
<img width="1192" alt="image" src="https://github.com/user-attachments/assets/c80d5a9c-1cf0-4647-aefc-735c469667d4">
where `result/initrd.gz` exists while `test/build/initramfs.cpio.gz` does not.
|
asterinas__asterinas-1256
| 1,256
|
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -146,7 +146,7 @@ dependencies = [
[[package]]
name = "cargo-osdk"
-version = "0.8.0"
+version = "0.8.1"
dependencies = [
"assert_cmd",
"clap",
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -146,7 +146,7 @@ dependencies = [
[[package]]
name = "cargo-osdk"
-version = "0.8.0"
+version = "0.8.1"
dependencies = [
"assert_cmd",
"clap",
diff --git a/osdk/src/config/eval.rs /dev/null
--- a/osdk/src/config/eval.rs
+++ /dev/null
@@ -1,24 +0,0 @@
-// SPDX-License-Identifier: MPL-2.0
-
-//! The module implementing the evaluation feature.
-
-use std::{io, path::Path, process};
-
-/// This function is used to evaluate the string using the host's shell recursively
-/// in order.
-pub fn eval(cwd: impl AsRef<Path>, s: &String) -> io::Result<String> {
- let mut eval = process::Command::new("bash");
- eval.arg("-c");
- eval.arg(format!("echo \"{}\"", s));
- eval.current_dir(cwd.as_ref());
- let output = eval.output()?;
- if !output.stderr.is_empty() {
- println!(
- "[Info] {}",
- String::from_utf8_lossy(&output.stderr).trim_end_matches('\n')
- );
- }
- Ok(String::from_utf8_lossy(&output.stdout)
- .trim_end_matches('\n')
- .to_string())
-}
diff --git a/osdk/src/config/eval.rs /dev/null
--- a/osdk/src/config/eval.rs
+++ /dev/null
@@ -1,24 +0,0 @@
-// SPDX-License-Identifier: MPL-2.0
-
-//! The module implementing the evaluation feature.
-
-use std::{io, path::Path, process};
-
-/// This function is used to evaluate the string using the host's shell recursively
-/// in order.
-pub fn eval(cwd: impl AsRef<Path>, s: &String) -> io::Result<String> {
- let mut eval = process::Command::new("bash");
- eval.arg("-c");
- eval.arg(format!("echo \"{}\"", s));
- eval.current_dir(cwd.as_ref());
- let output = eval.output()?;
- if !output.stderr.is_empty() {
- println!(
- "[Info] {}",
- String::from_utf8_lossy(&output.stderr).trim_end_matches('\n')
- );
- }
- Ok(String::from_utf8_lossy(&output.stdout)
- .trim_end_matches('\n')
- .to_string())
-}
diff --git a/osdk/src/config/manifest.rs b/osdk/src/config/manifest.rs
--- a/osdk/src/config/manifest.rs
+++ b/osdk/src/config/manifest.rs
@@ -12,7 +12,7 @@ use serde::{de, Deserialize, Deserializer, Serialize};
use super::scheme::Scheme;
-use crate::{config::scheme::QemuScheme, error::Errno, error_msg, util::get_cargo_metadata};
+use crate::{error::Errno, error_msg, util::get_cargo_metadata};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OsdkMeta {
diff --git a/osdk/src/config/manifest.rs b/osdk/src/config/manifest.rs
--- a/osdk/src/config/manifest.rs
+++ b/osdk/src/config/manifest.rs
@@ -12,7 +12,7 @@ use serde::{de, Deserialize, Deserializer, Serialize};
use super::scheme::Scheme;
-use crate::{config::scheme::QemuScheme, error::Errno, error_msg, util::get_cargo_metadata};
+use crate::{error::Errno, error_msg, util::get_cargo_metadata};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OsdkMeta {
diff --git a/osdk/src/config/manifest.rs b/osdk/src/config/manifest.rs
--- a/osdk/src/config/manifest.rs
+++ b/osdk/src/config/manifest.rs
@@ -128,82 +128,7 @@ fn deserialize_toml_manifest(path: impl AsRef<Path>) -> Option<TomlManifest> {
for scheme in manifest.map.values_mut() {
scheme.work_dir = Some(cwd.to_path_buf());
}
- // Canonicalize all the path fields
- let canonicalize = |target: &mut PathBuf| {
- let last_cwd = std::env::current_dir().unwrap();
- std::env::set_current_dir(cwd).unwrap();
- *target = target.canonicalize().unwrap_or_else(|err| {
- error_msg!(
- "Cannot canonicalize path `{}`: {}",
- target.to_string_lossy(),
- err,
- );
- std::env::set_current_dir(&last_cwd).unwrap();
- process::exit(Errno::GetMetadata as _);
- });
- std::env::set_current_dir(last_cwd).unwrap();
- };
- let canonicalize_scheme = |scheme: &mut Scheme| {
- macro_rules! canonicalize_paths_in_scheme {
- ($scheme:expr) => {
- if let Some(ref mut boot) = $scheme.boot {
- if let Some(ref mut initramfs) = boot.initramfs {
- canonicalize(initramfs);
- }
- }
- if let Some(ref mut qemu) = $scheme.qemu {
- if let Some(ref mut qemu_path) = qemu.path {
- canonicalize(qemu_path);
- }
- }
- if let Some(ref mut grub) = $scheme.grub {
- if let Some(ref mut grub_mkrescue_path) = grub.grub_mkrescue {
- canonicalize(grub_mkrescue_path);
- }
- }
- };
- }
- canonicalize_paths_in_scheme!(scheme);
- if let Some(ref mut run) = scheme.run {
- canonicalize_paths_in_scheme!(run);
- }
- if let Some(ref mut test) = scheme.test {
- canonicalize_paths_in_scheme!(test);
- }
- };
- canonicalize_scheme(&mut manifest.default_scheme);
- for scheme in manifest.map.values_mut() {
- canonicalize_scheme(scheme);
- }
- // Do evaluations on the need to be evaluated string field, namely,
- // QEMU arguments.
- use super::eval::eval;
- let eval_scheme = |scheme: &mut Scheme| {
- let eval_qemu = |qemu: &mut Option<QemuScheme>| {
- if let Some(ref mut qemu) = qemu {
- if let Some(ref mut args) = qemu.args {
- *args = match eval(cwd, args) {
- Ok(v) => v,
- Err(e) => {
- error_msg!("Failed to evaluate qemu args: {:#?}", e);
- process::exit(Errno::ParseMetadata as _);
- }
- }
- }
- }
- };
- eval_qemu(&mut scheme.qemu);
- if let Some(ref mut run) = scheme.run {
- eval_qemu(&mut run.qemu);
- }
- if let Some(ref mut test) = scheme.test {
- eval_qemu(&mut test.qemu);
- }
- };
- eval_scheme(&mut manifest.default_scheme);
- for scheme in manifest.map.values_mut() {
- eval_scheme(scheme);
- }
+
Some(manifest)
}
diff --git a/osdk/src/config/mod.rs b/osdk/src/config/mod.rs
--- a/osdk/src/config/mod.rs
+++ b/osdk/src/config/mod.rs
@@ -5,8 +5,6 @@
//! arguments if the arguments is missing, e.g., the path of QEMU. The final configuration is stored in `BuildConfig`,
//! `RunConfig` and `TestConfig`. These `*Config` are used for `build`, `run` and `test` subcommand.
-mod eval;
-
pub mod manifest;
pub mod scheme;
pub mod unix_args;
diff --git a/osdk/src/config/mod.rs b/osdk/src/config/mod.rs
--- a/osdk/src/config/mod.rs
+++ b/osdk/src/config/mod.rs
@@ -14,7 +12,11 @@ pub mod unix_args;
#[cfg(test)]
mod test;
-use std::{env, path::PathBuf};
+use std::{
+ env, io,
+ path::{Path, PathBuf},
+ process,
+};
use linux_bzimage_builder::PayloadEncoding;
use scheme::{
diff --git a/osdk/src/config/mod.rs b/osdk/src/config/mod.rs
--- a/osdk/src/config/mod.rs
+++ b/osdk/src/config/mod.rs
@@ -25,6 +27,8 @@ use crate::{
arch::{get_default_arch, Arch},
cli::CommonArgs,
config::unix_args::apply_kv_array,
+ error::Errno,
+ error_msg,
};
/// The global configuration for the OSDK actions.
diff --git a/osdk/src/config/mod.rs b/osdk/src/config/mod.rs
--- a/osdk/src/config/mod.rs
+++ b/osdk/src/config/mod.rs
@@ -25,6 +27,8 @@ use crate::{
arch::{get_default_arch, Arch},
cli::CommonArgs,
config::unix_args::apply_kv_array,
+ error::Errno,
+ error_msg,
};
/// The global configuration for the OSDK actions.
diff --git a/osdk/src/config/mod.rs b/osdk/src/config/mod.rs
--- a/osdk/src/config/mod.rs
+++ b/osdk/src/config/mod.rs
@@ -37,7 +41,11 @@ pub struct Config {
pub test: Action,
}
-fn apply_args_before_finalize(action_scheme: &mut ActionScheme, args: &CommonArgs) {
+fn apply_args_before_finalize(
+ action_scheme: &mut ActionScheme,
+ args: &CommonArgs,
+ workdir: &PathBuf,
+) {
if action_scheme.grub.is_none() {
action_scheme.grub = Some(GrubScheme::default());
}
diff --git a/osdk/src/config/mod.rs b/osdk/src/config/mod.rs
--- a/osdk/src/config/mod.rs
+++ b/osdk/src/config/mod.rs
@@ -61,7 +69,11 @@ fn apply_args_before_finalize(action_scheme: &mut ActionScheme, args: &CommonArg
}
}
if let Some(initramfs) = &args.initramfs {
- boot.initramfs = Some(initramfs.clone());
+ let Ok(initramfs) = initramfs.canonicalize() else {
+ error_msg!("The initramfs path provided with argument `--initramfs` does not match any files.");
+ process::exit(Errno::GetMetadata as _);
+ };
+ boot.initramfs = Some(initramfs);
}
if let Some(boot_method) = args.boot_method {
boot.method = Some(boot_method);
diff --git a/osdk/src/config/mod.rs b/osdk/src/config/mod.rs
--- a/osdk/src/config/mod.rs
+++ b/osdk/src/config/mod.rs
@@ -61,7 +69,11 @@ fn apply_args_before_finalize(action_scheme: &mut ActionScheme, args: &CommonArg
}
}
if let Some(initramfs) = &args.initramfs {
- boot.initramfs = Some(initramfs.clone());
+ let Ok(initramfs) = initramfs.canonicalize() else {
+ error_msg!("The initramfs path provided with argument `--initramfs` does not match any files.");
+ process::exit(Errno::GetMetadata as _);
+ };
+ boot.initramfs = Some(initramfs);
}
if let Some(boot_method) = args.boot_method {
boot.method = Some(boot_method);
diff --git a/osdk/src/config/mod.rs b/osdk/src/config/mod.rs
--- a/osdk/src/config/mod.rs
+++ b/osdk/src/config/mod.rs
@@ -73,12 +85,90 @@ fn apply_args_before_finalize(action_scheme: &mut ActionScheme, args: &CommonArg
}
if let Some(ref mut qemu) = action_scheme.qemu {
if let Some(path) = &args.qemu_exe {
- qemu.path = Some(path.clone());
+ let Ok(qemu_path) = path.canonicalize() else {
+ error_msg!(
+ "The QEMU path provided with argument `--qemu-exe` does not match any files."
+ );
+ process::exit(Errno::GetMetadata as _);
+ };
+ qemu.path = Some(qemu_path);
}
if let Some(bootdev_options) = &args.bootdev_append_options {
qemu.bootdev_append_options = Some(bootdev_options.clone());
}
}
+
+ canonicalize_and_eval(action_scheme, workdir);
+}
+
+fn canonicalize_and_eval(action_scheme: &mut ActionScheme, workdir: &PathBuf) {
+ let canonicalize = |target: &mut PathBuf| {
+ let last_cwd = std::env::current_dir().unwrap();
+ std::env::set_current_dir(workdir).unwrap();
+
+ *target = target.canonicalize().unwrap_or_else(|err| {
+ error_msg!(
+ "Cannot canonicalize path `{}`: {}",
+ target.to_string_lossy(),
+ err,
+ );
+ std::env::set_current_dir(&last_cwd).unwrap();
+ process::exit(Errno::GetMetadata as _);
+ });
+ std::env::set_current_dir(last_cwd).unwrap();
+ };
+
+ if let Some(ref mut boot) = action_scheme.boot {
+ if let Some(ref mut initramfs) = boot.initramfs {
+ canonicalize(initramfs);
+ }
+
+ if let Some(ref mut qemu) = action_scheme.qemu {
+ if let Some(ref mut qemu_path) = qemu.path {
+ canonicalize(qemu_path);
+ }
+ }
+
+ if let Some(ref mut grub) = action_scheme.grub {
+ if let Some(ref mut grub_mkrescue_path) = grub.grub_mkrescue {
+ canonicalize(grub_mkrescue_path);
+ }
+ }
+ }
+
+ // Do evaluations on the need to be evaluated string field, namely,
+ // QEMU arguments.
+
+ if let Some(ref mut qemu) = action_scheme.qemu {
+ if let Some(ref mut args) = qemu.args {
+ *args = match eval(workdir, args) {
+ Ok(v) => v,
+ Err(e) => {
+ error_msg!("Failed to evaluate qemu args: {:#?}", e);
+ process::exit(Errno::ParseMetadata as _);
+ }
+ }
+ }
+ }
+}
+
+/// This function is used to evaluate the string using the host's shell recursively
+/// in order.
+pub fn eval(cwd: impl AsRef<Path>, s: &String) -> io::Result<String> {
+ let mut eval = process::Command::new("bash");
+ eval.arg("-c");
+ eval.arg(format!("echo \"{}\"", s));
+ eval.current_dir(cwd.as_ref());
+ let output = eval.output()?;
+ if !output.stderr.is_empty() {
+ println!(
+ "[Info] {}",
+ String::from_utf8_lossy(&output.stderr).trim_end_matches('\n')
+ );
+ }
+ Ok(String::from_utf8_lossy(&output.stdout)
+ .trim_end_matches('\n')
+ .to_string())
}
fn apply_args_after_finalize(action: &mut Action, args: &CommonArgs) {
diff --git a/osdk/src/config/mod.rs b/osdk/src/config/mod.rs
--- a/osdk/src/config/mod.rs
+++ b/osdk/src/config/mod.rs
@@ -73,12 +85,90 @@ fn apply_args_before_finalize(action_scheme: &mut ActionScheme, args: &CommonArg
}
if let Some(ref mut qemu) = action_scheme.qemu {
if let Some(path) = &args.qemu_exe {
- qemu.path = Some(path.clone());
+ let Ok(qemu_path) = path.canonicalize() else {
+ error_msg!(
+ "The QEMU path provided with argument `--qemu-exe` does not match any files."
+ );
+ process::exit(Errno::GetMetadata as _);
+ };
+ qemu.path = Some(qemu_path);
}
if let Some(bootdev_options) = &args.bootdev_append_options {
qemu.bootdev_append_options = Some(bootdev_options.clone());
}
}
+
+ canonicalize_and_eval(action_scheme, workdir);
+}
+
+fn canonicalize_and_eval(action_scheme: &mut ActionScheme, workdir: &PathBuf) {
+ let canonicalize = |target: &mut PathBuf| {
+ let last_cwd = std::env::current_dir().unwrap();
+ std::env::set_current_dir(workdir).unwrap();
+
+ *target = target.canonicalize().unwrap_or_else(|err| {
+ error_msg!(
+ "Cannot canonicalize path `{}`: {}",
+ target.to_string_lossy(),
+ err,
+ );
+ std::env::set_current_dir(&last_cwd).unwrap();
+ process::exit(Errno::GetMetadata as _);
+ });
+ std::env::set_current_dir(last_cwd).unwrap();
+ };
+
+ if let Some(ref mut boot) = action_scheme.boot {
+ if let Some(ref mut initramfs) = boot.initramfs {
+ canonicalize(initramfs);
+ }
+
+ if let Some(ref mut qemu) = action_scheme.qemu {
+ if let Some(ref mut qemu_path) = qemu.path {
+ canonicalize(qemu_path);
+ }
+ }
+
+ if let Some(ref mut grub) = action_scheme.grub {
+ if let Some(ref mut grub_mkrescue_path) = grub.grub_mkrescue {
+ canonicalize(grub_mkrescue_path);
+ }
+ }
+ }
+
+ // Do evaluations on the need to be evaluated string field, namely,
+ // QEMU arguments.
+
+ if let Some(ref mut qemu) = action_scheme.qemu {
+ if let Some(ref mut args) = qemu.args {
+ *args = match eval(workdir, args) {
+ Ok(v) => v,
+ Err(e) => {
+ error_msg!("Failed to evaluate qemu args: {:#?}", e);
+ process::exit(Errno::ParseMetadata as _);
+ }
+ }
+ }
+ }
+}
+
+/// This function is used to evaluate the string using the host's shell recursively
+/// in order.
+pub fn eval(cwd: impl AsRef<Path>, s: &String) -> io::Result<String> {
+ let mut eval = process::Command::new("bash");
+ eval.arg("-c");
+ eval.arg(format!("echo \"{}\"", s));
+ eval.current_dir(cwd.as_ref());
+ let output = eval.output()?;
+ if !output.stderr.is_empty() {
+ println!(
+ "[Info] {}",
+ String::from_utf8_lossy(&output.stderr).trim_end_matches('\n')
+ );
+ }
+ Ok(String::from_utf8_lossy(&output.stdout)
+ .trim_end_matches('\n')
+ .to_string())
}
fn apply_args_after_finalize(action: &mut Action, args: &CommonArgs) {
diff --git a/osdk/src/config/mod.rs b/osdk/src/config/mod.rs
--- a/osdk/src/config/mod.rs
+++ b/osdk/src/config/mod.rs
@@ -111,7 +201,7 @@ impl Config {
let run = {
let mut run = scheme.run.clone().unwrap_or_default();
run.inherit(&default_scheme);
- apply_args_before_finalize(&mut run, common_args);
+ apply_args_before_finalize(&mut run, common_args, scheme.work_dir.as_ref().unwrap());
let mut run = run.finalize(target_arch);
apply_args_after_finalize(&mut run, common_args);
check_compatibility(run.grub.boot_protocol, run.build.encoding.clone());
diff --git a/osdk/src/config/mod.rs b/osdk/src/config/mod.rs
--- a/osdk/src/config/mod.rs
+++ b/osdk/src/config/mod.rs
@@ -111,7 +201,7 @@ impl Config {
let run = {
let mut run = scheme.run.clone().unwrap_or_default();
run.inherit(&default_scheme);
- apply_args_before_finalize(&mut run, common_args);
+ apply_args_before_finalize(&mut run, common_args, scheme.work_dir.as_ref().unwrap());
let mut run = run.finalize(target_arch);
apply_args_after_finalize(&mut run, common_args);
check_compatibility(run.grub.boot_protocol, run.build.encoding.clone());
diff --git a/osdk/src/config/mod.rs b/osdk/src/config/mod.rs
--- a/osdk/src/config/mod.rs
+++ b/osdk/src/config/mod.rs
@@ -120,7 +210,7 @@ impl Config {
let test = {
let mut test = scheme.test.clone().unwrap_or_default();
test.inherit(&default_scheme);
- apply_args_before_finalize(&mut test, common_args);
+ apply_args_before_finalize(&mut test, common_args, scheme.work_dir.as_ref().unwrap());
let mut test = test.finalize(target_arch);
apply_args_after_finalize(&mut test, common_args);
check_compatibility(test.grub.boot_protocol, test.build.encoding.clone());
|
2024-08-28T11:24:08Z
|
ae4ac384713e63232b74915593ebdef680049d31
|
|
asterinas/asterinas
|
diff --git a/kernel/aster-nix/src/process/process_filter.rs b/kernel/aster-nix/src/process/process_filter.rs
--- a/kernel/aster-nix/src/process/process_filter.rs
+++ b/kernel/aster-nix/src/process/process_filter.rs
@@ -14,14 +14,15 @@ pub enum ProcessFilter {
impl ProcessFilter {
// used for waitid
- pub fn from_which_and_id(which: u64, id: u64) -> Self {
+ pub fn from_which_and_id(which: u64, id: u64) -> Result<Self> {
// Does not support PID_FD now(which = 3)
// https://elixir.bootlin.com/linux/latest/source/include/uapi/linux/wait.h#L20
match which {
- 0 => ProcessFilter::Any,
- 1 => ProcessFilter::WithPid(id as Pid),
- 2 => ProcessFilter::WithPgid(id as Pgid),
- _ => panic!("Unknown id type"),
+ 0 => Ok(ProcessFilter::Any),
+ 1 => Ok(ProcessFilter::WithPid(id as Pid)),
+ 2 => Ok(ProcessFilter::WithPgid(id as Pgid)),
+ 3 => todo!(),
+ _ => return_errno_with_message!(Errno::EINVAL, "invalid which"),
}
}
|
[
"1197"
] |
0.6
|
562e64437584279783f244edba10b512beddc81d
|
Reachable unwrap panic in `ProcessFilter::from_which_and_id()`
### Describe the bug
There is a reachable unwrap panic in `ProcessFilter::from_which_and_id()` at kernel/aster-nix/src/process/process_filter.rs:24 when make a `waitid` syscall.
https://github.com/asterinas/asterinas/blob/ce2af1eb057077753a7a757edc1833e677a83918/kernel/aster-nix/src/process/process_filter.rs#L17-L26
### To Reproduce
1. Compile a program which calls `waitid`:
```C
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
waitid(0x31142aad0bc93209, 15, 0x1, -10);
return 0;
}
```
2. Run the compiled program in Asterinas.
### Expected behavior
Asterinas reports panic and is terminated.
### Environment
- Official docker asterinas/asterinas:0.6.2
- 11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz
- Asterinas version: main ce2af1eb
### Logs
```
~ # /root/waitpid.c
panicked at /root/asterinas/kernel/aster-nix/src/process/process_filter.rs:24:18:
Unknown id type
Printing stack trace:
1: fn 0xffffffff8876b840 - pc 0xffffffff8876b858 / registers:
rax 0x12; rdx 0xffffffff889fd930; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff80000122a370;
2: fn 0xffffffff8876b620 - pc 0xffffffff8876b798 / registers:
rax 0x12; rdx 0xffffffff889fd930; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff80000122a380;
3: fn 0xffffffff88049000 - pc 0xffffffff8804900a / registers:
rax 0x12; rdx 0xffffffff889fd930; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff80000122a500;
4: fn 0xffffffff8897ee20 - pc 0xffffffff8897eea2 / registers:
rax 0x12; rdx 0xffffffff889fd930; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff80000122a510;
5: fn 0xffffffff88163050 - pc 0xffffffff881630b0 / registers:
rax 0x12; rdx 0xffffffff889fd930; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff80000122a5a0;
6: fn 0xffffffff8822cc20 - pc 0xffffffff8822cc8d / registers:
rax 0x12; rdx 0xffffffff889fd930; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff80000122a610;
7: fn 0xffffffff88292390 - pc 0xffffffff882bebda / registers:
rax 0x12; rdx 0xffffffff889fd930; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff80000122a730;
8: fn 0xffffffff88291f70 - pc 0xffffffff88291ffe / registers:
rax 0x12; rdx 0xffffffff889fd930; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff8000012403d0;
9: fn 0xffffffff8836de80 - pc 0xffffffff8836e9ff / registers:
rax 0x12; rdx 0xffffffff889fd930; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff800001240570;
10: fn 0xffffffff885a49f0 - pc 0xffffffff885a49fe / registers:
rax 0x12; rdx 0xffffffff889fd930; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff800001240f90;
11: fn 0xffffffff88781b90 - pc 0xffffffff88781ba6 / registers:
rax 0x12; rdx 0xffffffff889fd930; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff800001240fb0;
12: fn 0xffffffff887b9740 - pc 0xffffffff887b97a9 / registers:
rax 0x12; rdx 0xffffffff889fd930; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff800001240fd0;
13: fn 0x0 - pc 0x0 / registers:
rax 0x12; rdx 0xffffffff889fd930; rcx 0x1; rbx 0x0;
rsi 0x0; rdi 0x0; rbp 0x0; rsp 0xffff800001241000;
[OSDK] The kernel seems panicked. Parsing stack trace for source lines:
( 1) /root/asterinas/ostd/src/panicking.rs:107
( 2) /root/asterinas/ostd/src/panicking.rs:59
( 3) 2aghao2n2kcoquuybdyjuveav:?
( 4) ??:?
( 5) /root/asterinas/kernel/aster-nix/src/process/process_filter.rs:21
( 6) /root/asterinas/kernel/aster-nix/src/syscall/waitid.rs:18
( 7) /root/asterinas/kernel/aster-nix/src/syscall/mod.rs:195
( 8) /root/asterinas/kernel/aster-nix/src/syscall/mod.rs:325
( 9) /root/asterinas/kernel/aster-nix/src/thread/task.rs:69
( 10) /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:79
( 11) /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2077
( 12) /root/asterinas/ostd/src/task/task/mod.rs:310
make: *** [Makefile:153: run] Error 1
```
|
asterinas__asterinas-1215
| 1,215
|
diff --git a/kernel/aster-nix/src/process/process_filter.rs b/kernel/aster-nix/src/process/process_filter.rs
--- a/kernel/aster-nix/src/process/process_filter.rs
+++ b/kernel/aster-nix/src/process/process_filter.rs
@@ -14,14 +14,15 @@ pub enum ProcessFilter {
impl ProcessFilter {
// used for waitid
- pub fn from_which_and_id(which: u64, id: u64) -> Self {
+ pub fn from_which_and_id(which: u64, id: u64) -> Result<Self> {
// Does not support PID_FD now(which = 3)
// https://elixir.bootlin.com/linux/latest/source/include/uapi/linux/wait.h#L20
match which {
- 0 => ProcessFilter::Any,
- 1 => ProcessFilter::WithPid(id as Pid),
- 2 => ProcessFilter::WithPgid(id as Pgid),
- _ => panic!("Unknown id type"),
+ 0 => Ok(ProcessFilter::Any),
+ 1 => Ok(ProcessFilter::WithPid(id as Pid)),
+ 2 => Ok(ProcessFilter::WithPgid(id as Pgid)),
+ 3 => todo!(),
+ _ => return_errno_with_message!(Errno::EINVAL, "invalid which"),
}
}
diff --git a/kernel/aster-nix/src/syscall/waitid.rs b/kernel/aster-nix/src/syscall/waitid.rs
--- a/kernel/aster-nix/src/syscall/waitid.rs
+++ b/kernel/aster-nix/src/syscall/waitid.rs
@@ -15,8 +15,9 @@ pub fn sys_waitid(
_ctx: &Context,
) -> Result<SyscallReturn> {
// FIXME: what does infoq and rusage use for?
- let process_filter = ProcessFilter::from_which_and_id(which, upid);
- let wait_options = WaitOptions::from_bits(options as u32).expect("Unknown wait options");
+ let process_filter = ProcessFilter::from_which_and_id(which, upid)?;
+ let wait_options = WaitOptions::from_bits(options as u32)
+ .ok_or(Error::with_message(Errno::EINVAL, "invalid options"))?;
let waited_process = wait_child_exit(process_filter, wait_options)?;
let pid = waited_process.map_or(0, |process| process.pid());
Ok(SyscallReturn::Return(pid as _))
diff --git a/kernel/aster-nix/src/syscall/waitid.rs b/kernel/aster-nix/src/syscall/waitid.rs
--- a/kernel/aster-nix/src/syscall/waitid.rs
+++ b/kernel/aster-nix/src/syscall/waitid.rs
@@ -15,8 +15,9 @@ pub fn sys_waitid(
_ctx: &Context,
) -> Result<SyscallReturn> {
// FIXME: what does infoq and rusage use for?
- let process_filter = ProcessFilter::from_which_and_id(which, upid);
- let wait_options = WaitOptions::from_bits(options as u32).expect("Unknown wait options");
+ let process_filter = ProcessFilter::from_which_and_id(which, upid)?;
+ let wait_options = WaitOptions::from_bits(options as u32)
+ .ok_or(Error::with_message(Errno::EINVAL, "invalid options"))?;
let waited_process = wait_child_exit(process_filter, wait_options)?;
let pid = waited_process.map_or(0, |process| process.pid());
Ok(SyscallReturn::Return(pid as _))
|
2024-08-21T12:44:17Z
|
562e64437584279783f244edba10b512beddc81d
|
|
asterinas/asterinas
|
diff --git a/test/benchmark/lmbench-mem-fcp/config.json b/test/benchmark/lmbench-mem-fcp/config.json
--- a/test/benchmark/lmbench-mem-fcp/config.json
+++ b/test/benchmark/lmbench-mem-fcp/config.json
@@ -1,7 +1,7 @@
{
"alert_threshold": "125%",
"alert_tool": "customBiggerIsBetter",
- "search_pattern": "134.22",
+ "search_pattern": "536.87",
"result_index": "2",
- "description": "The memory bandwidth for copying 128 MB of data on a single processor using the fcp (fast copy) method."
+ "description": "The memory bandwidth for copying 512 MB of data on a single processor using the fcp (fast copy) method."
}
diff --git a/test/benchmark/lmbench-mem-fcp/run.sh b/test/benchmark/lmbench-mem-fcp/run.sh
--- a/test/benchmark/lmbench-mem-fcp/run.sh
+++ b/test/benchmark/lmbench-mem-fcp/run.sh
@@ -6,4 +6,4 @@ set -e
echo "*** Running the LMbench memory-copy bandwidth test ***"
-/benchmark/bin/lmbench/bw_mem -P 1 128m fcp
\ No newline at end of file
+/benchmark/bin/lmbench/bw_mem -P 1 -N 50 512m fcp
\ No newline at end of file
diff --git a/test/benchmark/lmbench-mem-frd/config.json b/test/benchmark/lmbench-mem-frd/config.json
--- a/test/benchmark/lmbench-mem-frd/config.json
+++ b/test/benchmark/lmbench-mem-frd/config.json
@@ -1,7 +1,7 @@
{
"alert_threshold": "125%",
"alert_tool": "customBiggerIsBetter",
- "search_pattern": "268.44",
+ "search_pattern": "536.87",
"result_index": "2",
- "description": "The memory bandwidth for reading 256 MB of data on a single processor."
+ "description": "The memory bandwidth for reading 512 MB of data on a single processor."
}
diff --git a/test/benchmark/lmbench-mem-frd/run.sh b/test/benchmark/lmbench-mem-frd/run.sh
--- a/test/benchmark/lmbench-mem-frd/run.sh
+++ b/test/benchmark/lmbench-mem-frd/run.sh
@@ -6,4 +6,4 @@ set -e
echo "*** Running the LMbench memory-read bandwidth test ***"
-/benchmark/bin/lmbench/bw_mem -P 1 256m frd
\ No newline at end of file
+/benchmark/bin/lmbench/bw_mem -P 1 -N 50 512m frd
\ No newline at end of file
diff --git a/test/benchmark/lmbench-mem-fwr/config.json b/test/benchmark/lmbench-mem-fwr/config.json
--- a/test/benchmark/lmbench-mem-fwr/config.json
+++ b/test/benchmark/lmbench-mem-fwr/config.json
@@ -1,7 +1,7 @@
{
"alert_threshold": "125%",
"alert_tool": "customBiggerIsBetter",
- "search_pattern": "268.44",
+ "search_pattern": "536.87",
"result_index": "2",
- "description": "The memory bandwidth for writing 256 MB of data on a single processor using the fwr (fast write) method."
+ "description": "The memory bandwidth for writing 512 MB of data on a single processor using the fwr (fast write) method."
}
diff --git a/test/benchmark/lmbench-mem-fwr/run.sh b/test/benchmark/lmbench-mem-fwr/run.sh
--- a/test/benchmark/lmbench-mem-fwr/run.sh
+++ b/test/benchmark/lmbench-mem-fwr/run.sh
@@ -6,4 +6,4 @@ set -e
echo "*** Running the LMbench memory-write bandwidth test ***"
-/benchmark/bin/lmbench/bw_mem -P 1 256m fwr
\ No newline at end of file
+/benchmark/bin/lmbench/bw_mem -P 1 -N 50 512m fwr
\ No newline at end of file
|
[
"1155"
] |
0.6
|
0291b5dc6bb142b9c6165c1cb29b7658eefdaa63
|
Unexpected benchmark alert triggered
I've observed that the recent benchmark workflow has consistently failed due to the `lmbench-mem` alert being triggered. This benchmark exhibits considerable instability on both Asterinas and Linux platforms. Notably, even identical commits can yield divergent results. In light of the existing benchmark alerts, it might be prudent to increase the `alert_threshold` to `1.5`.

<!-- TRIAGEBOT_START -->
<!-- TRIAGEBOT_ASSIGN_START -->
<!-- TRIAGEBOT_ASSIGN_DATA_START$${"user":"grief8"}$$TRIAGEBOT_ASSIGN_DATA_END -->
<!-- TRIAGEBOT_ASSIGN_END -->
<!-- TRIAGEBOT_END -->
|
asterinas__asterinas-1187
| 1,187
|
diff --git a/test/benchmark/lmbench-mem-fcp/config.json b/test/benchmark/lmbench-mem-fcp/config.json
--- a/test/benchmark/lmbench-mem-fcp/config.json
+++ b/test/benchmark/lmbench-mem-fcp/config.json
@@ -1,7 +1,7 @@
{
"alert_threshold": "125%",
"alert_tool": "customBiggerIsBetter",
- "search_pattern": "134.22",
+ "search_pattern": "536.87",
"result_index": "2",
- "description": "The memory bandwidth for copying 128 MB of data on a single processor using the fcp (fast copy) method."
+ "description": "The memory bandwidth for copying 512 MB of data on a single processor using the fcp (fast copy) method."
}
diff --git a/test/benchmark/lmbench-mem-fcp/run.sh b/test/benchmark/lmbench-mem-fcp/run.sh
--- a/test/benchmark/lmbench-mem-fcp/run.sh
+++ b/test/benchmark/lmbench-mem-fcp/run.sh
@@ -6,4 +6,4 @@ set -e
echo "*** Running the LMbench memory-copy bandwidth test ***"
-/benchmark/bin/lmbench/bw_mem -P 1 128m fcp
\ No newline at end of file
+/benchmark/bin/lmbench/bw_mem -P 1 -N 50 512m fcp
\ No newline at end of file
diff --git a/test/benchmark/lmbench-mem-frd/config.json b/test/benchmark/lmbench-mem-frd/config.json
--- a/test/benchmark/lmbench-mem-frd/config.json
+++ b/test/benchmark/lmbench-mem-frd/config.json
@@ -1,7 +1,7 @@
{
"alert_threshold": "125%",
"alert_tool": "customBiggerIsBetter",
- "search_pattern": "268.44",
+ "search_pattern": "536.87",
"result_index": "2",
- "description": "The memory bandwidth for reading 256 MB of data on a single processor."
+ "description": "The memory bandwidth for reading 512 MB of data on a single processor."
}
diff --git a/test/benchmark/lmbench-mem-frd/run.sh b/test/benchmark/lmbench-mem-frd/run.sh
--- a/test/benchmark/lmbench-mem-frd/run.sh
+++ b/test/benchmark/lmbench-mem-frd/run.sh
@@ -6,4 +6,4 @@ set -e
echo "*** Running the LMbench memory-read bandwidth test ***"
-/benchmark/bin/lmbench/bw_mem -P 1 256m frd
\ No newline at end of file
+/benchmark/bin/lmbench/bw_mem -P 1 -N 50 512m frd
\ No newline at end of file
diff --git a/test/benchmark/lmbench-mem-fwr/config.json b/test/benchmark/lmbench-mem-fwr/config.json
--- a/test/benchmark/lmbench-mem-fwr/config.json
+++ b/test/benchmark/lmbench-mem-fwr/config.json
@@ -1,7 +1,7 @@
{
"alert_threshold": "125%",
"alert_tool": "customBiggerIsBetter",
- "search_pattern": "268.44",
+ "search_pattern": "536.87",
"result_index": "2",
- "description": "The memory bandwidth for writing 256 MB of data on a single processor using the fwr (fast write) method."
+ "description": "The memory bandwidth for writing 512 MB of data on a single processor using the fwr (fast write) method."
}
diff --git a/test/benchmark/lmbench-mem-fwr/run.sh b/test/benchmark/lmbench-mem-fwr/run.sh
--- a/test/benchmark/lmbench-mem-fwr/run.sh
+++ b/test/benchmark/lmbench-mem-fwr/run.sh
@@ -6,4 +6,4 @@ set -e
echo "*** Running the LMbench memory-write bandwidth test ***"
-/benchmark/bin/lmbench/bw_mem -P 1 256m fwr
\ No newline at end of file
+/benchmark/bin/lmbench/bw_mem -P 1 -N 50 512m fwr
\ No newline at end of file
|
Or we can run the benchmark for more times?
@boterinas claim
|
2024-08-16T08:24:13Z
|
562e64437584279783f244edba10b512beddc81d
|
asterinas/asterinas
|
diff --git a/.github/workflows/publish_osdk_and_ostd.yml b/.github/workflows/publish_osdk_and_ostd.yml
--- a/.github/workflows/publish_osdk_and_ostd.yml
+++ b/.github/workflows/publish_osdk_and_ostd.yml
@@ -16,7 +16,7 @@ jobs:
osdk-publish:
runs-on: ubuntu-latest
timeout-minutes: 10
- container: asterinas/asterinas:0.7.0
+ container: asterinas/asterinas:0.8.0
steps:
- uses: actions/checkout@v4
diff --git a/.github/workflows/publish_osdk_and_ostd.yml b/.github/workflows/publish_osdk_and_ostd.yml
--- a/.github/workflows/publish_osdk_and_ostd.yml
+++ b/.github/workflows/publish_osdk_and_ostd.yml
@@ -39,7 +39,7 @@ jobs:
ostd-publish:
runs-on: ubuntu-latest
timeout-minutes: 10
- container: asterinas/asterinas:0.7.0
+ container: asterinas/asterinas:0.8.0
strategy:
matrix:
# All supported targets, this array should keep consistent with
diff --git a/.github/workflows/publish_osdk_and_ostd.yml b/.github/workflows/publish_osdk_and_ostd.yml
--- a/.github/workflows/publish_osdk_and_ostd.yml
+++ b/.github/workflows/publish_osdk_and_ostd.yml
@@ -48,15 +48,18 @@ jobs:
steps:
- uses: actions/checkout@v4
- - name: Check Publish OSTD
+ - name: Check Publish OSTD and the test runner
# On pull request, set `--dry-run` to check whether OSDK can publish
if: github.event_name == 'pull_request'
run: |
cd ostd
cargo publish --target ${{ matrix.target }} --dry-run
cargo doc --target ${{ matrix.target }}
+ cd osdk/test-kernel
+ cargo publish --target ${{ matrix.target }} --dry-run
+ cargo doc --target ${{ matrix.target }}
- - name: Publish OSTD
+ - name: Publish OSTD and the test runner
if: github.event_name == 'push'
env:
REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
diff --git a/.github/workflows/publish_osdk_and_ostd.yml b/.github/workflows/publish_osdk_and_ostd.yml
--- a/.github/workflows/publish_osdk_and_ostd.yml
+++ b/.github/workflows/publish_osdk_and_ostd.yml
@@ -66,4 +69,6 @@ jobs:
run: |
cd ostd
cargo publish --target x86_64-unknown-none --token ${REGISTRY_TOKEN}
-
+ cd osdk/test-kernel
+ cargo publish --target x86_64-unknown-none --token ${REGISTRY_TOKEN}
+
\ No newline at end of file
diff --git a/.github/workflows/publish_website.yml b/.github/workflows/publish_website.yml
--- a/.github/workflows/publish_website.yml
+++ b/.github/workflows/publish_website.yml
@@ -16,7 +16,7 @@ jobs:
build_and_deploy:
runs-on: ubuntu-latest
timeout-minutes: 15
- container: asterinas/asterinas:0.7.0
+ container: asterinas/asterinas:0.8.0
steps:
- uses: actions/checkout@v2
with:
diff --git a/.github/workflows/test_asterinas.yml b/.github/workflows/test_asterinas.yml
--- a/.github/workflows/test_asterinas.yml
+++ b/.github/workflows/test_asterinas.yml
@@ -14,9 +14,9 @@ jobs:
if: github.event_name == 'push' || github.event_name == 'pull_request'
runs-on: ubuntu-latest
timeout-minutes: 15
- container: asterinas/asterinas:0.7.0
+ container: asterinas/asterinas:0.8.0
steps:
- - run: echo "Running in asterinas/asterinas:0.7.0"
+ - run: echo "Running in asterinas/asterinas:0.8.0"
- uses: actions/checkout@v4
diff --git a/.github/workflows/test_asterinas.yml b/.github/workflows/test_asterinas.yml
--- a/.github/workflows/test_asterinas.yml
+++ b/.github/workflows/test_asterinas.yml
@@ -28,9 +28,9 @@ jobs:
if: github.event_name == 'push' || github.event_name == 'pull_request'
runs-on: ubuntu-latest
timeout-minutes: 15
- container: asterinas/asterinas:0.7.0
+ container: asterinas/asterinas:0.8.0
steps:
- - run: echo "Running in asterinas/asterinas:0.7.0"
+ - run: echo "Running in asterinas/asterinas:0.8.0"
- uses: actions/checkout@v4
diff --git a/.github/workflows/test_asterinas.yml b/.github/workflows/test_asterinas.yml
--- a/.github/workflows/test_asterinas.yml
+++ b/.github/workflows/test_asterinas.yml
@@ -49,10 +49,10 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 30
container:
- image: asterinas/asterinas:0.7.0
+ image: asterinas/asterinas:0.8.0
options: --device=/dev/kvm
steps:
- - run: echo "Running in asterinas/asterinas:0.7.0"
+ - run: echo "Running in asterinas/asterinas:0.8.0"
- uses: actions/checkout@v4
diff --git a/.github/workflows/test_asterinas.yml b/.github/workflows/test_asterinas.yml
--- a/.github/workflows/test_asterinas.yml
+++ b/.github/workflows/test_asterinas.yml
@@ -88,7 +88,7 @@ jobs:
runs-on: self-hosted
timeout-minutes: 30
container:
- image: asterinas/asterinas:0.7.0-tdx
+ image: asterinas/asterinas:0.8.0-tdx
options: --device=/dev/kvm --privileged
env:
# Need to set up proxy since the self-hosted CI server is located in China,
diff --git a/.github/workflows/test_asterinas.yml b/.github/workflows/test_asterinas.yml
--- a/.github/workflows/test_asterinas.yml
+++ b/.github/workflows/test_asterinas.yml
@@ -96,7 +96,7 @@ jobs:
RUSTUP_DIST_SERVER: https://mirrors.ustc.edu.cn/rust-static
RUSTUP_UPDATE_ROOT: https://mirrors.ustc.edu.cn/rust-static/rustup
steps:
- - run: echo "Running in asterinas/asterinas:0.7.0-tdx"
+ - run: echo "Running in asterinas/asterinas:0.8.0-tdx"
- uses: actions/checkout@v4
- name: Set up the environment
run: |
diff --git a/.github/workflows/test_asterinas_vsock.yml b/.github/workflows/test_asterinas_vsock.yml
--- a/.github/workflows/test_asterinas_vsock.yml
+++ b/.github/workflows/test_asterinas_vsock.yml
@@ -23,7 +23,7 @@ jobs:
run: |
docker run \
--privileged --network=host --device=/dev/kvm \
- -v ./:/root/asterinas asterinas/asterinas:0.7.0 \
+ -v ./:/root/asterinas asterinas/asterinas:0.8.0 \
make run AUTO_TEST=vsock ENABLE_KVM=0 SCHEME=microvm RELEASE_MODE=1 &
- name: Run Vsock Client on Host
id: host_vsock_client
diff --git a/.github/workflows/test_osdk.yml b/.github/workflows/test_osdk.yml
--- a/.github/workflows/test_osdk.yml
+++ b/.github/workflows/test_osdk.yml
@@ -21,9 +21,9 @@ jobs:
timeout-minutes: 30
strategy:
matrix:
- # asterinas/asterinas:0.7.0 container is the developing container of asterinas,
- # asterinas/osdk:0.7.0 container is built with the intructions from Asterinas Book
- container: ['asterinas/asterinas:0.7.0', 'asterinas/osdk:0.7.0']
+ # asterinas/asterinas:0.8.0 container is the developing container of asterinas,
+ # asterinas/osdk:0.8.0 container is built with the intructions from Asterinas Book
+ container: ['asterinas/asterinas:0.8.0', 'asterinas/osdk:0.8.0']
container: ${{ matrix.container }}
steps:
- run: echo "Running in ${{ matrix.container }}"
diff --git a/.github/workflows/test_osdk.yml b/.github/workflows/test_osdk.yml
--- a/.github/workflows/test_osdk.yml
+++ b/.github/workflows/test_osdk.yml
@@ -32,7 +32,7 @@ jobs:
- name: Lint
id: lint
- if: matrix.container == 'asterinas/asterinas:0.7.0'
+ if: matrix.container == 'asterinas/asterinas:0.8.0'
run: make check_osdk
# Github's actions/checkout@v4 will result in a new user (not root)
diff --git a/.github/workflows/test_osdk.yml b/.github/workflows/test_osdk.yml
--- a/.github/workflows/test_osdk.yml
+++ b/.github/workflows/test_osdk.yml
@@ -56,9 +56,9 @@ jobs:
RUSTUP_UPDATE_ROOT: https://mirrors.ustc.edu.cn/rust-static/rustup
strategy:
matrix:
- # asterinas/asterinas:0.7.0-tdx container is the developing container of asterinas,
- # asterinas/osdk:0.7.0-tdx container is built with the intructions from Asterinas Book
- container: ['asterinas/asterinas:0.7.0-tdx', 'asterinas/osdk:0.7.0-tdx']
+ # asterinas/asterinas:0.8.0-tdx container is the developing container of asterinas,
+ # asterinas/osdk:0.8.0-tdx container is built with the intructions from Asterinas Book
+ container: ['asterinas/asterinas:0.8.0-tdx', 'asterinas/osdk:0.8.0-tdx']
container:
image: ${{ matrix.container }}
options: --device=/dev/kvm --privileged
diff --git a/.github/workflows/test_osdk.yml b/.github/workflows/test_osdk.yml
--- a/.github/workflows/test_osdk.yml
+++ b/.github/workflows/test_osdk.yml
@@ -67,7 +67,7 @@ jobs:
- uses: actions/checkout@v4
- name: Lint
id: lint
- if: matrix.container == 'asterinas/asterinas:0.7.0-tdx'
+ if: matrix.container == 'asterinas/asterinas:0.8.0-tdx'
run: make check_osdk
# Github's actions/checkout@v4 will result in a new user (not root)
# and thus not using the Rust environment we set up in the container.
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1045,9 +1034,18 @@ version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d"
+[[package]]
+name = "osdk-test-kernel"
+version = "0.8.0"
+dependencies = [
+ "ostd",
+ "owo-colors 4.0.0",
+ "unwinding",
+]
+
[[package]]
name = "ostd"
-version = "0.7.0"
+version = "0.8.0"
dependencies = [
"acpi",
"align_ext",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1075,7 +1073,7 @@ dependencies = [
"ostd-macros",
"ostd-pod",
"ostd-test",
- "owo-colors",
+ "owo-colors 3.5.0",
"rsdp",
"spin 0.9.8",
"static_assertions",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1119,9 +1117,6 @@ dependencies = [
[[package]]
name = "ostd-test"
version = "0.1.0"
-dependencies = [
- "owo-colors",
-]
[[package]]
name = "owo-colors"
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,7 @@
[workspace]
resolver = "2"
members = [
+ "osdk/test-kernel",
"ostd",
"ostd/libs/align_ext",
"ostd/libs/ostd-macros",
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -10,7 +11,6 @@ members = [
"ostd/libs/linux-bzimage/setup",
"ostd/libs/ostd-test",
"kernel",
- "kernel/aster-nix",
"kernel/comps/block",
"kernel/comps/console",
"kernel/comps/framebuffer",
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -110,10 +110,10 @@ NON_OSDK_CRATES := \
# In contrast, OSDK crates depend on OSTD (or being `ostd` itself)
# and need to be built or tested with OSDK.
OSDK_CRATES := \
+ osdk/test-kernel \
ostd \
ostd/libs/linux-bzimage/setup \
kernel \
- kernel/aster-nix \
kernel/comps/block \
kernel/comps/console \
kernel/comps/framebuffer \
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -206,7 +209,7 @@ format:
@make --no-print-directory -C test format
.PHONY: check
-check: $(CARGO_OSDK)
+check: initramfs $(CARGO_OSDK)
@./tools/format_all.sh --check # Check Rust format issues
@# Check if STD_CRATES and NOSTD_CRATES combined is the same as all workspace members
@sed -n '/^\[workspace\]/,/^\[.*\]/{/members = \[/,/\]/p}' Cargo.toml | \
diff --git a/kernel/aster-nix/src/lib.rs /dev/null
--- a/kernel/aster-nix/src/lib.rs
+++ /dev/null
@@ -1,154 +0,0 @@
-// SPDX-License-Identifier: MPL-2.0
-
-//! The std library of Asterinas.
-#![no_std]
-#![deny(unsafe_code)]
-#![allow(incomplete_features)]
-#![feature(btree_cursors)]
-#![feature(btree_extract_if)]
-#![feature(const_option)]
-#![feature(extend_one)]
-#![feature(fn_traits)]
-#![feature(format_args_nl)]
-#![feature(int_roundings)]
-#![feature(iter_repeat_n)]
-#![feature(let_chains)]
-#![feature(linked_list_remove)]
-#![feature(negative_impls)]
-#![feature(register_tool)]
-// FIXME: This feature is used to support vm capbility now as a work around.
-// Since this is an incomplete feature, use this feature is unsafe.
-// We should find a proper method to replace this feature with min_specialization, which is a sound feature.
-#![feature(specialization)]
-#![feature(step_trait)]
-#![feature(trait_alias)]
-#![feature(trait_upcasting)]
-#![feature(linked_list_retain)]
-#![register_tool(component_access_control)]
-
-use ostd::{
- arch::qemu::{exit_qemu, QemuExitCode},
- boot,
-};
-use process::Process;
-
-use crate::{
- prelude::*,
- thread::{
- kernel_thread::{KernelThreadExt, ThreadOptions},
- Thread,
- },
-};
-
-extern crate alloc;
-extern crate lru;
-#[macro_use]
-extern crate controlled;
-#[macro_use]
-extern crate getset;
-
-pub mod arch;
-pub mod console;
-pub mod context;
-pub mod cpu;
-pub mod device;
-pub mod driver;
-pub mod error;
-pub mod events;
-pub mod fs;
-pub mod ipc;
-pub mod net;
-pub mod prelude;
-mod process;
-mod sched;
-pub mod softirq_id;
-pub mod syscall;
-mod taskless;
-pub mod thread;
-pub mod time;
-mod util;
-pub(crate) mod vdso;
-pub mod vm;
-
-pub fn init() {
- util::random::init();
- driver::init();
- time::init();
- net::init();
- sched::init();
- fs::rootfs::init(boot::initramfs()).unwrap();
- device::init().unwrap();
- vdso::init();
- taskless::init();
- process::init();
-}
-
-fn init_thread() {
- println!(
- "[kernel] Spawn init thread, tid = {}",
- current_thread!().tid()
- );
- // Work queue should be initialized before interrupt is enabled,
- // in case any irq handler uses work queue as bottom half
- thread::work_queue::init();
- net::lazy_init();
- fs::lazy_init();
- ipc::init();
- // driver::pci::virtio::block::block_device_test();
- let thread = Thread::spawn_kernel_thread(ThreadOptions::new(|| {
- println!("[kernel] Hello world from kernel!");
- let current = current_thread!();
- let tid = current.tid();
- debug!("current tid = {}", tid);
- }));
- thread.join();
- info!(
- "[aster-nix/lib.rs] spawn kernel thread, tid = {}",
- thread.tid()
- );
-
- print_banner();
-
- let karg = boot::kernel_cmdline();
-
- let initproc = Process::spawn_user_process(
- karg.get_initproc_path().unwrap(),
- karg.get_initproc_argv().to_vec(),
- karg.get_initproc_envp().to_vec(),
- )
- .expect("Run init process failed.");
- // Wait till initproc become zombie.
- while !initproc.is_zombie() {
- // We don't have preemptive scheduler now.
- // The long running init thread should yield its own execution to allow other tasks to go on.
- Thread::yield_now();
- }
-
- // TODO: exit via qemu isa debug device should not be the only way.
- let exit_code = if initproc.exit_code().unwrap() == 0 {
- QemuExitCode::Success
- } else {
- QemuExitCode::Failed
- };
- exit_qemu(exit_code);
-}
-
-/// first process never return
-#[controlled]
-pub fn run_first_process() -> ! {
- Thread::spawn_kernel_thread(ThreadOptions::new(init_thread));
- unreachable!()
-}
-
-fn print_banner() {
- println!("\x1B[36m");
- println!(
- r"
- _ ___ _____ ___ ___ ___ _ _ _ ___
- /_\ / __|_ _| __| _ \_ _| \| | /_\ / __|
- / _ \\__ \ | | | _|| /| || .` |/ _ \\__ \
-/_/ \_\___/ |_| |___|_|_\___|_|\_/_/ \_\___/
-"
- );
- println!("\x1B[0m");
-}
diff --git a/kernel/libs/aster-util/src/coeff.rs b/kernel/libs/aster-util/src/coeff.rs
--- a/kernel/libs/aster-util/src/coeff.rs
+++ b/kernel/libs/aster-util/src/coeff.rs
@@ -134,8 +134,8 @@ mod test {
#[ktest]
fn calculation() {
let coeff = Coeff::new(23456, 56789, 1_000_000_000);
- assert!(coeff * 0 as u64 == 0);
- assert!(coeff * 100 as u64 == 100 * 23456 / 56789);
- assert!(coeff * 1_000_000_000 as u64 == 1_000_000_000 * 23456 / 56789);
+ assert!(coeff * 0_u64 == 0);
+ assert!(coeff * 100_u64 == 100 * 23456 / 56789);
+ assert!(coeff * 1_000_000_000_u64 == 1_000_000_000 * 23456 / 56789);
}
}
diff --git a/kernel/aster-nix/src/fs/exfat/mod.rs b/kernel/src/fs/exfat/mod.rs
--- a/kernel/aster-nix/src/fs/exfat/mod.rs
+++ b/kernel/src/fs/exfat/mod.rs
@@ -107,7 +107,7 @@ mod test {
}
}
/// Exfat disk image
- static EXFAT_IMAGE: &[u8] = include_bytes!("../../../../../test/build/exfat.img");
+ static EXFAT_IMAGE: &[u8] = include_bytes!("../../../../test/build/exfat.img");
/// Read exfat disk image
fn new_vm_segment_from_image() -> Segment {
diff --git a/kernel/aster-nix/src/fs/exfat/mod.rs b/kernel/src/fs/exfat/mod.rs
--- a/kernel/aster-nix/src/fs/exfat/mod.rs
+++ b/kernel/src/fs/exfat/mod.rs
@@ -484,7 +484,7 @@ mod test {
let mut read = vec![0u8; BUF_SIZE];
let read_after_rename = a_inode_new.read_bytes_at(0, &mut read);
assert!(
- read_after_rename.is_ok() && read_after_rename.clone().unwrap() == BUF_SIZE,
+ read_after_rename.is_ok() && read_after_rename.unwrap() == BUF_SIZE,
"Fail to read after rename: {:?}",
read_after_rename.unwrap_err()
);
diff --git a/kernel/aster-nix/src/fs/exfat/mod.rs b/kernel/src/fs/exfat/mod.rs
--- a/kernel/aster-nix/src/fs/exfat/mod.rs
+++ b/kernel/src/fs/exfat/mod.rs
@@ -495,8 +495,7 @@ mod test {
let new_buf = vec![7u8; NEW_BUF_SIZE];
let new_write_after_rename = a_inode_new.write_bytes_at(0, &new_buf);
assert!(
- new_write_after_rename.is_ok()
- && new_write_after_rename.clone().unwrap() == NEW_BUF_SIZE,
+ new_write_after_rename.is_ok() && new_write_after_rename.unwrap() == NEW_BUF_SIZE,
"Fail to write file after rename: {:?}",
new_write_after_rename.unwrap_err()
);
diff --git a/kernel/aster-nix/src/fs/exfat/mod.rs b/kernel/src/fs/exfat/mod.rs
--- a/kernel/aster-nix/src/fs/exfat/mod.rs
+++ b/kernel/src/fs/exfat/mod.rs
@@ -984,7 +983,7 @@ mod test {
let mut file_names: Vec<String> = (0..file_num).map(|x| x.to_string()).collect();
file_names.sort();
let mut file_inodes: Vec<Arc<dyn Inode>> = Vec::new();
- for (_file_id, file_name) in file_names.iter().enumerate() {
+ for file_name in file_names.iter() {
let inode = create_file(root.clone(), file_name);
file_inodes.push(inode);
}
diff --git a/kernel/aster-nix/src/fs/exfat/utils.rs b/kernel/src/fs/exfat/utils.rs
--- a/kernel/aster-nix/src/fs/exfat/utils.rs
+++ b/kernel/src/fs/exfat/utils.rs
@@ -60,7 +60,6 @@ impl DosTimestamp {
#[cfg(not(ktest))]
{
use crate::time::clocks::RealTimeClock;
-
DosTimestamp::from_duration(RealTimeClock::get().read_time())
}
diff --git a/kernel/aster-nix/src/fs/exfat/utils.rs b/kernel/src/fs/exfat/utils.rs
--- a/kernel/aster-nix/src/fs/exfat/utils.rs
+++ b/kernel/src/fs/exfat/utils.rs
@@ -68,9 +67,9 @@ impl DosTimestamp {
#[cfg(ktest)]
{
use crate::time::SystemTime;
- return DosTimestamp::from_duration(
+ DosTimestamp::from_duration(
SystemTime::UNIX_EPOCH.duration_since(&SystemTime::UNIX_EPOCH)?,
- );
+ )
}
}
diff --git a/kernel/aster-nix/src/fs/pipe.rs b/kernel/src/fs/pipe.rs
--- a/kernel/aster-nix/src/fs/pipe.rs
+++ b/kernel/src/fs/pipe.rs
@@ -331,7 +331,7 @@ mod test {
#[ktest]
fn test_read_closed() {
test_blocking(
- |writer| drop(writer),
+ drop,
|reader| {
let mut buf = [0; 1];
assert_eq!(reader.read(&mut writer_from(&mut buf)).unwrap(), 0);
diff --git a/kernel/aster-nix/src/fs/pipe.rs b/kernel/src/fs/pipe.rs
--- a/kernel/aster-nix/src/fs/pipe.rs
+++ b/kernel/src/fs/pipe.rs
@@ -350,7 +350,7 @@ mod test {
Errno::EPIPE
);
},
- |reader| drop(reader),
+ drop,
Ordering::WriteThenRead,
);
}
diff --git a/kernel/src/lib.rs b/kernel/src/lib.rs
--- a/kernel/src/lib.rs
+++ b/kernel/src/lib.rs
@@ -1,16 +1,161 @@
// SPDX-License-Identifier: MPL-2.0
+//! Aster-nix is the Asterinas kernel, a safe, efficient unix-like
+//! operating system kernel built on top of OSTD and OSDK.
+
#![no_std]
#![no_main]
#![deny(unsafe_code)]
-extern crate ostd;
+#![allow(incomplete_features)]
+#![feature(btree_cursors)]
+#![feature(btree_extract_if)]
+#![feature(const_option)]
+#![feature(extend_one)]
+#![feature(fn_traits)]
+#![feature(format_args_nl)]
+#![feature(int_roundings)]
+#![feature(iter_repeat_n)]
+#![feature(let_chains)]
+#![feature(linkage)]
+#![feature(linked_list_remove)]
+#![feature(negative_impls)]
+#![feature(register_tool)]
+// FIXME: This feature is used to support vm capbility now as a work around.
+// Since this is an incomplete feature, use this feature is unsafe.
+// We should find a proper method to replace this feature with min_specialization, which is a sound feature.
+#![feature(specialization)]
+#![feature(step_trait)]
+#![feature(trait_alias)]
+#![feature(trait_upcasting)]
+#![feature(linked_list_retain)]
+#![register_tool(component_access_control)]
+
+use ostd::{
+ arch::qemu::{exit_qemu, QemuExitCode},
+ boot,
+};
+use process::Process;
+
+use crate::{
+ prelude::*,
+ thread::{
+ kernel_thread::{KernelThreadExt, ThreadOptions},
+ Thread,
+ },
+};
+
+extern crate alloc;
+extern crate lru;
+#[macro_use]
+extern crate controlled;
+#[macro_use]
+extern crate getset;
-use ostd::prelude::*;
+pub mod arch;
+pub mod console;
+pub mod context;
+pub mod cpu;
+pub mod device;
+pub mod driver;
+pub mod error;
+pub mod events;
+pub mod fs;
+pub mod ipc;
+pub mod net;
+pub mod prelude;
+mod process;
+mod sched;
+pub mod softirq_id;
+pub mod syscall;
+mod taskless;
+pub mod thread;
+pub mod time;
+mod util;
+pub(crate) mod vdso;
+pub mod vm;
#[ostd::main]
+#[controlled]
pub fn main() {
- println!("[kernel] finish init ostd");
+ ostd::early_println!("[kernel] OSTD initialized. Preparing components.");
component::init_all(component::parse_metadata!()).unwrap();
- aster_nix::init();
- aster_nix::run_first_process();
+ init();
+ Thread::spawn_kernel_thread(ThreadOptions::new(init_thread));
+ unreachable!()
+}
+
+pub fn init() {
+ util::random::init();
+ driver::init();
+ time::init();
+ net::init();
+ sched::init();
+ fs::rootfs::init(boot::initramfs()).unwrap();
+ device::init().unwrap();
+ vdso::init();
+ taskless::init();
+ process::init();
+}
+
+fn init_thread() {
+ println!(
+ "[kernel] Spawn init thread, tid = {}",
+ current_thread!().tid()
+ );
+ // Work queue should be initialized before interrupt is enabled,
+ // in case any irq handler uses work queue as bottom half
+ thread::work_queue::init();
+ net::lazy_init();
+ fs::lazy_init();
+ ipc::init();
+ // driver::pci::virtio::block::block_device_test();
+ let thread = Thread::spawn_kernel_thread(ThreadOptions::new(|| {
+ println!("[kernel] Hello world from kernel!");
+ let current = current_thread!();
+ let tid = current.tid();
+ debug!("current tid = {}", tid);
+ }));
+ thread.join();
+ info!(
+ "[aster-nix/lib.rs] spawn kernel thread, tid = {}",
+ thread.tid()
+ );
+
+ print_banner();
+
+ let karg = boot::kernel_cmdline();
+
+ let initproc = Process::spawn_user_process(
+ karg.get_initproc_path().unwrap(),
+ karg.get_initproc_argv().to_vec(),
+ karg.get_initproc_envp().to_vec(),
+ )
+ .expect("Run init process failed.");
+ // Wait till initproc become zombie.
+ while !initproc.is_zombie() {
+ // We don't have preemptive scheduler now.
+ // The long running init thread should yield its own execution to allow other tasks to go on.
+ Thread::yield_now();
+ }
+
+ // TODO: exit via qemu isa debug device should not be the only way.
+ let exit_code = if initproc.exit_code().unwrap() == 0 {
+ QemuExitCode::Success
+ } else {
+ QemuExitCode::Failed
+ };
+ exit_qemu(exit_code);
+}
+
+fn print_banner() {
+ println!("\x1B[36m");
+ println!(
+ r"
+ _ ___ _____ ___ ___ ___ _ _ _ ___
+ /_\ / __|_ _| __| _ \_ _| \| | /_\ / __|
+ / _ \\__ \ | | | _|| /| || .` |/ _ \\__ \
+/_/ \_\___/ |_| |___|_|_\___|_|\_/_/ \_\___/
+"
+ );
+ println!("\x1B[0m");
}
diff --git a/kernel/aster-nix/src/process/sync/condvar.rs b/kernel/src/process/sync/condvar.rs
--- a/kernel/aster-nix/src/process/sync/condvar.rs
+++ b/kernel/src/process/sync/condvar.rs
@@ -291,7 +291,7 @@ mod test {
while !*started {
started = cvar.wait(started).unwrap_or_else(|err| err.into_guard());
}
- assert_eq!(*started, true);
+ assert!(*started);
}
}
diff --git a/kernel/aster-nix/src/process/sync/condvar.rs b/kernel/src/process/sync/condvar.rs
--- a/kernel/aster-nix/src/process/sync/condvar.rs
+++ b/kernel/src/process/sync/condvar.rs
@@ -316,7 +316,7 @@ mod test {
.wait_timeout(started, Duration::from_secs(1))
.unwrap_or_else(|err| err.into_guard());
}
- assert_eq!(*started, true);
+ assert!(*started);
}
}
diff --git a/kernel/aster-nix/src/process/sync/condvar.rs b/kernel/src/process/sync/condvar.rs
--- a/kernel/aster-nix/src/process/sync/condvar.rs
+++ b/kernel/src/process/sync/condvar.rs
@@ -338,7 +338,7 @@ mod test {
let started = cvar
.wait_while(lock.lock(), |started| *started)
.unwrap_or_else(|err| err.into_guard());
- assert_eq!(*started, false);
+ assert!(!*started);
}
}
diff --git a/kernel/aster-nix/src/process/sync/condvar.rs b/kernel/src/process/sync/condvar.rs
--- a/kernel/aster-nix/src/process/sync/condvar.rs
+++ b/kernel/src/process/sync/condvar.rs
@@ -360,7 +360,7 @@ mod test {
let (started, _) = cvar
.wait_timeout_while(lock.lock(), Duration::from_secs(1), |started| *started)
.unwrap_or_else(|err| err.into_guard());
- assert_eq!(*started, false);
+ assert!(!*started);
}
}
}
diff --git a/kernel/aster-nix/src/taskless.rs b/kernel/src/taskless.rs
--- a/kernel/aster-nix/src/taskless.rs
+++ b/kernel/src/taskless.rs
@@ -216,7 +216,7 @@ mod test {
let mut counter = 0;
// Schedule this taskless for `SCHEDULE_TIMES`.
- while taskless.is_scheduled.load(Ordering::Acquire) == false {
+ while !taskless.is_scheduled.load(Ordering::Acquire) {
taskless.schedule();
counter += 1;
if counter == SCHEDULE_TIMES {
diff --git a/kernel/aster-nix/src/taskless.rs b/kernel/src/taskless.rs
--- a/kernel/aster-nix/src/taskless.rs
+++ b/kernel/src/taskless.rs
@@ -227,7 +227,9 @@ mod test {
// Wait for all taskless having finished.
while taskless.is_running.load(Ordering::Acquire)
|| taskless.is_scheduled.load(Ordering::Acquire)
- {}
+ {
+ core::hint::spin_loop()
+ }
assert_eq!(counter, COUNTER.load(Ordering::Relaxed));
}
diff --git a/kernel/aster-nix/src/vm/vmar/options.rs b/kernel/src/vm/vmar/options.rs
--- a/kernel/aster-nix/src/vm/vmar/options.rs
+++ b/kernel/src/vm/vmar/options.rs
@@ -136,7 +136,7 @@ impl<R> VmarChildOptions<R> {
#[cfg(ktest)]
mod test {
use aster_rights::Full;
- use ostd::{mm::VmIo, prelude::*};
+ use ostd::prelude::*;
use super::*;
use crate::vm::{
diff --git a/osdk/src/base_crate/mod.rs b/osdk/src/base_crate/mod.rs
--- a/osdk/src/base_crate/mod.rs
+++ b/osdk/src/base_crate/mod.rs
@@ -1,8 +1,7 @@
// SPDX-License-Identifier: MPL-2.0
//! The base crate is the OSDK generated crate that is ultimately built by cargo.
-//! It will depend on the kernel crate.
-//!
+//! It will depend on the to-be-built kernel crate or the to-be-tested crate.
use std::{
fs,
diff --git a/osdk/src/base_crate/mod.rs b/osdk/src/base_crate/mod.rs
--- a/osdk/src/base_crate/mod.rs
+++ b/osdk/src/base_crate/mod.rs
@@ -12,10 +11,16 @@ use std::{
use crate::util::get_cargo_metadata;
+/// Create a new base crate that will be built by cargo.
+///
+/// The dependencies of the base crate will be the target crate. If
+/// `link_unit_test_runner` is set to true, the base crate will also depend on
+/// the `ostd-test-runner` crate.
pub fn new_base_crate(
base_crate_path: impl AsRef<Path>,
dep_crate_name: &str,
dep_crate_path: impl AsRef<Path>,
+ link_unit_test_runner: bool,
) {
let workspace_root = {
let meta = get_cargo_metadata(None::<&str>, None::<&[&str]>).unwrap();
diff --git a/osdk/src/base_crate/mod.rs b/osdk/src/base_crate/mod.rs
--- a/osdk/src/base_crate/mod.rs
+++ b/osdk/src/base_crate/mod.rs
@@ -82,7 +87,7 @@ pub fn new_base_crate(
fs::write("src/main.rs", main_rs).unwrap();
// Add dependencies to the Cargo.toml
- add_manifest_dependency(dep_crate_name, dep_crate_path);
+ add_manifest_dependency(dep_crate_name, dep_crate_path, link_unit_test_runner);
// Copy the manifest configurations from the target crate to the base crate
copy_profile_configurations(workspace_root);
diff --git a/osdk/src/base_crate/mod.rs b/osdk/src/base_crate/mod.rs
--- a/osdk/src/base_crate/mod.rs
+++ b/osdk/src/base_crate/mod.rs
@@ -94,7 +99,11 @@ pub fn new_base_crate(
std::env::set_current_dir(original_dir).unwrap();
}
-fn add_manifest_dependency(crate_name: &str, crate_path: impl AsRef<Path>) {
+fn add_manifest_dependency(
+ crate_name: &str,
+ crate_path: impl AsRef<Path>,
+ link_unit_test_runner: bool,
+) {
let mainfest_path = "Cargo.toml";
let mut manifest: toml::Table = {
diff --git a/osdk/src/base_crate/mod.rs b/osdk/src/base_crate/mod.rs
--- a/osdk/src/base_crate/mod.rs
+++ b/osdk/src/base_crate/mod.rs
@@ -112,13 +121,26 @@ fn add_manifest_dependency(crate_name: &str, crate_path: impl AsRef<Path>) {
let dependencies = manifest.get_mut("dependencies").unwrap();
- let dep = toml::Table::from_str(&format!(
+ let target_dep = toml::Table::from_str(&format!(
"{} = {{ path = \"{}\", default-features = false }}",
crate_name,
crate_path.as_ref().display()
))
.unwrap();
- dependencies.as_table_mut().unwrap().extend(dep);
+ dependencies.as_table_mut().unwrap().extend(target_dep);
+
+ if link_unit_test_runner {
+ let dep_str = match option_env!("OSDK_LOCAL_DEV") {
+ Some("1") => "osdk-test-kernel = { path = \"../../../osdk/test-kernel\" }",
+ _ => concat!(
+ "osdk-test-kernel = { version = \"",
+ env!("CARGO_PKG_VERSION"),
+ "\" }"
+ ),
+ };
+ let test_runner_dep = toml::Table::from_str(dep_str).unwrap();
+ dependencies.as_table_mut().unwrap().extend(test_runner_dep);
+ }
let content = toml::to_string(&manifest).unwrap();
fs::write(mainfest_path, content).unwrap();
diff --git a/osdk/src/cli.rs b/osdk/src/cli.rs
--- a/osdk/src/cli.rs
+++ b/osdk/src/cli.rs
@@ -49,9 +49,9 @@ pub fn main() {
OsdkSubcommand::Test(test_args) => {
execute_test_command(&load_config(&test_args.common_args), test_args);
}
- OsdkSubcommand::Check(args) => execute_forwarded_command("check", &args.args),
- OsdkSubcommand::Clippy(args) => execute_forwarded_command("clippy", &args.args),
- OsdkSubcommand::Doc(args) => execute_forwarded_command("doc", &args.args),
+ OsdkSubcommand::Check(args) => execute_forwarded_command("check", &args.args, true),
+ OsdkSubcommand::Clippy(args) => execute_forwarded_command("clippy", &args.args, true),
+ OsdkSubcommand::Doc(args) => execute_forwarded_command("doc", &args.args, false),
}
}
diff --git a/osdk/src/commands/mod.rs b/osdk/src/commands/mod.rs
--- a/osdk/src/commands/mod.rs
+++ b/osdk/src/commands/mod.rs
@@ -16,8 +16,10 @@ pub use self::{
use crate::arch::get_default_arch;
-/// Execute the forwarded cargo command with args containing the subcommand and its arguments.
-pub fn execute_forwarded_command(subcommand: &str, args: &Vec<String>) -> ! {
+/// Execute the forwarded cargo command with arguments.
+///
+/// The `cfg_ktest` parameter controls whether `cfg(ktest)` is enabled.
+pub fn execute_forwarded_command(subcommand: &str, args: &Vec<String>, cfg_ktest: bool) -> ! {
let mut cargo = util::cargo();
cargo.arg(subcommand).args(util::COMMON_CARGO_ARGS);
if !args.contains(&"--target".to_owned()) {
diff --git a/osdk/src/commands/mod.rs b/osdk/src/commands/mod.rs
--- a/osdk/src/commands/mod.rs
+++ b/osdk/src/commands/mod.rs
@@ -27,6 +29,11 @@ pub fn execute_forwarded_command(subcommand: &str, args: &Vec<String>) -> ! {
let env_rustflags = std::env::var("RUSTFLAGS").unwrap_or_default();
let rustflags = env_rustflags + " --check-cfg cfg(ktest)";
+ let rustflags = if cfg_ktest {
+ rustflags + " --cfg ktest"
+ } else {
+ rustflags
+ };
cargo.env("RUSTFLAGS", rustflags);
diff --git a/osdk/src/commands/test.rs b/osdk/src/commands/test.rs
--- a/osdk/src/commands/test.rs
+++ b/osdk/src/commands/test.rs
@@ -7,6 +7,8 @@ use crate::{
base_crate::new_base_crate,
cli::TestArgs,
config::{scheme::ActionChoice, Config},
+ error::Errno,
+ error_msg,
util::{
get_cargo_metadata, get_current_crate_info, get_target_directory, parse_package_id_string,
},
diff --git a/osdk/src/commands/test.rs b/osdk/src/commands/test.rs
--- a/osdk/src/commands/test.rs
+++ b/osdk/src/commands/test.rs
@@ -25,7 +27,26 @@ pub fn test_current_crate(config: &Config, args: &TestArgs) {
let cargo_target_directory = get_target_directory();
let osdk_output_directory = cargo_target_directory.join(DEFAULT_TARGET_RELPATH);
let target_crate_dir = osdk_output_directory.join("base");
- new_base_crate(&target_crate_dir, ¤t_crate.name, ¤t_crate.path);
+
+ // A special case is that we use OSDK to test the OSDK test runner crate
+ // itself. We check it by name.
+ let runner_self_test = if current_crate.name == "osdk-test-kernel" {
+ if matches!(option_env!("OSDK_LOCAL_DEV"), Some("1")) {
+ true
+ } else {
+ error_msg!("The tested crate name collides with the OSDK test runner crate");
+ std::process::exit(Errno::BadCrateName as _);
+ }
+ } else {
+ false
+ };
+
+ new_base_crate(
+ &target_crate_dir,
+ ¤t_crate.name,
+ ¤t_crate.path,
+ !runner_self_test,
+ );
let main_rs_path = target_crate_dir.join("src").join("main.rs");
diff --git a/osdk/src/commands/test.rs b/osdk/src/commands/test.rs
--- a/osdk/src/commands/test.rs
+++ b/osdk/src/commands/test.rs
@@ -39,19 +60,29 @@ pub fn test_current_crate(config: &Config, args: &TestArgs) {
ktest_crate_whitelist.push(name.clone());
}
- let ktest_static_var = format!(
+ // Append the ktest static variable and the runner reference to the
+ // `main.rs` file.
+ let ktest_main_rs = format!(
r#"
+
+{}
+
#[no_mangle]
pub static KTEST_TEST_WHITELIST: Option<&[&str]> = {};
#[no_mangle]
pub static KTEST_CRATE_WHITELIST: Option<&[&str]> = Some(&{:#?});
+
"#,
- ktest_test_whitelist, ktest_crate_whitelist,
+ if runner_self_test {
+ ""
+ } else {
+ "extern crate osdk_test_kernel;"
+ },
+ ktest_test_whitelist,
+ ktest_crate_whitelist,
);
-
- // Append the ktest static variable to the main.rs file
let mut main_rs_content = fs::read_to_string(&main_rs_path).unwrap();
- main_rs_content.push_str(&ktest_static_var);
+ main_rs_content.push_str(&ktest_main_rs);
fs::write(&main_rs_path, main_rs_content).unwrap();
// Build the kernel with the given base crate
diff --git /dev/null b/osdk/test-kernel/Cargo.toml
new file mode 100644
--- /dev/null
+++ b/osdk/test-kernel/Cargo.toml
@@ -0,0 +1,14 @@
+[package]
+name = "osdk-test-kernel"
+version = "0.8.0"
+edition = "2021"
+description = "The OSTD-based kernel for running unit tests with OSDK."
+license = "MPL-2.0"
+repository ="https://github.com/asterinas/asterinas"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+ostd = { version = "0.8.0", path = "../../ostd" }
+owo-colors = "4.0.0"
+unwinding = { version = "0.2.2", default-features = false, features = ["fde-gnu-eh-frame-hdr", "hide-trace", "panic", "personality", "unwinder"] }
diff --git a/ostd/libs/ostd-test/src/runner.rs b/osdk/test-kernel/src/lib.rs
--- a/ostd/libs/ostd-test/src/runner.rs
+++ b/osdk/test-kernel/src/lib.rs
@@ -1,24 +1,59 @@
// SPDX-License-Identifier: MPL-2.0
-//! Test runner enabling control over the tests.
-//!
+//! The OSTD unit test runner is a kernel that runs the tests defined by the
+//! `#[ostd::ktest]` attribute. The kernel should be automatically selected to
+//! run when OSDK is used to test a specific crate.
-use alloc::{collections::BTreeSet, string::String, vec::Vec};
-use core::format_args;
+#![no_std]
+#![forbid(unsafe_code)]
-use owo_colors::OwoColorize;
+extern crate alloc;
+
+mod path;
+mod tree;
+
+use alloc::{boxed::Box, collections::BTreeSet, string::String, vec::Vec};
+use core::{any::Any, format_args};
-use crate::{
- path::{KtestPath, SuffixTrie},
- tree::{KtestCrate, KtestTree},
- CatchUnwindImpl, KtestError, KtestItem, KtestIter,
+use ostd::{
+ early_print,
+ ktest::{
+ get_ktest_crate_whitelist, get_ktest_test_whitelist, KtestError, KtestItem, KtestIter,
+ },
};
+use owo_colors::OwoColorize;
+use path::{KtestPath, SuffixTrie};
+use tree::{KtestCrate, KtestTree};
pub enum KtestResult {
Ok,
Failed,
}
+/// The entry point of the test runner.
+#[ostd::ktest::main]
+fn main() {
+ use ostd::task::TaskOptions;
+
+ let test_task = move || {
+ use alloc::string::ToString;
+
+ use ostd::arch::qemu::{exit_qemu, QemuExitCode};
+
+ match run_ktests(
+ get_ktest_test_whitelist().map(|s| s.iter().map(|s| s.to_string())),
+ get_ktest_crate_whitelist(),
+ ) {
+ KtestResult::Ok => exit_qemu(QemuExitCode::Success),
+ KtestResult::Failed => exit_qemu(QemuExitCode::Failed),
+ };
+ };
+
+ let _ = TaskOptions::new(test_task).data(()).spawn();
+
+ unreachable!("The spawn method will NOT return in the boot context")
+}
+
/// Run all the tests registered by `#[ktest]` in the `.ktest_array` section.
///
/// Need to provide a print function `print` to print the test result, and a `catch_unwind`
diff --git a/ostd/libs/ostd-test/src/runner.rs b/osdk/test-kernel/src/lib.rs
--- a/ostd/libs/ostd-test/src/runner.rs
+++ b/osdk/test-kernel/src/lib.rs
@@ -32,27 +67,18 @@ pub enum KtestResult {
///
/// If a test inside a crate fails, the test runner will continue to run the rest of the tests
/// inside the crate. But the tests in the following crates will not be run.
-pub fn run_ktests<PrintFn, PathsIter>(
- print: &PrintFn,
- catch_unwind: &CatchUnwindImpl,
+fn run_ktests<PathsIter>(
test_whitelist: Option<PathsIter>,
crate_whitelist: Option<&[&str]>,
) -> KtestResult
where
- PrintFn: Fn(core::fmt::Arguments),
PathsIter: Iterator<Item = String>,
{
- macro_rules! print {
- ($fmt: literal $(, $($arg: tt)+)?) => {
- print(format_args!($fmt $(, $($arg)+)?))
- }
- }
-
let whitelist_trie =
test_whitelist.map(|paths| SuffixTrie::from_paths(paths.map(|p| KtestPath::from(&p))));
let tree = KtestTree::from_iter(KtestIter::new());
- print!(
+ early_print!(
"\n[ktest runner] running {} tests in {} crates\n",
tree.nr_tot_tests(),
tree.nr_tot_crates()
diff --git a/ostd/libs/ostd-test/src/runner.rs b/osdk/test-kernel/src/lib.rs
--- a/ostd/libs/ostd-test/src/runner.rs
+++ b/osdk/test-kernel/src/lib.rs
@@ -62,36 +88,22 @@ where
for crate_ in tree.iter() {
if let Some(crate_set) = &crate_set {
if !crate_set.contains(crate_.name()) {
- print!("\n[ktest runner] skipping crate \"{}\".\n", crate_.name());
+ early_print!("\n[ktest runner] skipping crate \"{}\".\n", crate_.name());
continue;
}
}
- match run_crate_ktests(crate_, print, catch_unwind, &whitelist_trie) {
+ match run_crate_ktests(crate_, &whitelist_trie) {
KtestResult::Ok => {}
KtestResult::Failed => return KtestResult::Failed,
}
}
- print!("\n[ktest runner] All crates tested.\n");
+ early_print!("\n[ktest runner] All crates tested.\n");
KtestResult::Ok
}
-fn run_crate_ktests<PrintFn>(
- crate_: &KtestCrate,
- print: &PrintFn,
- catch_unwind: &CatchUnwindImpl,
- whitelist: &Option<SuffixTrie>,
-) -> KtestResult
-where
- PrintFn: Fn(core::fmt::Arguments),
-{
- macro_rules! print {
- ($fmt: literal $(, $($arg: tt)+)?) => {
- print(format_args!($fmt $(, $($arg)+)?))
- }
- }
-
+fn run_crate_ktests(crate_: &KtestCrate, whitelist: &Option<SuffixTrie>) -> KtestResult {
let crate_name = crate_.name();
- print!(
+ early_print!(
"\nrunning {} tests in crate \"{}\"\n\n",
crate_.nr_tot_tests(),
crate_name
diff --git a/ostd/libs/ostd-test/src/runner.rs b/osdk/test-kernel/src/lib.rs
--- a/ostd/libs/ostd-test/src/runner.rs
+++ b/osdk/test-kernel/src/lib.rs
@@ -110,19 +122,22 @@ where
continue;
}
}
- print!(
+ early_print!(
"test {}::{} ...",
test.info().module_path,
test.info().fn_name
);
debug_assert_eq!(test.info().package, crate_name);
- match test.run(catch_unwind) {
+ match test.run(
+ &(unwinding::panic::catch_unwind::<(), fn()>
+ as fn(fn()) -> Result<(), Box<(dyn Any + Send + 'static)>>),
+ ) {
Ok(()) => {
- print!(" {}\n", "ok".green());
+ early_print!(" {}\n", "ok".green());
passed += 1;
}
Err(e) => {
- print!(" {}\n", "FAILED".red());
+ early_print!(" {}\n", "FAILED".red());
failed_tests.push((test.clone(), e.clone()));
}
}
diff --git a/ostd/libs/ostd-test/src/runner.rs b/osdk/test-kernel/src/lib.rs
--- a/ostd/libs/ostd-test/src/runner.rs
+++ b/osdk/test-kernel/src/lib.rs
@@ -130,19 +145,21 @@ where
}
let failed = failed_tests.len();
if failed == 0 {
- print!("\ntest result: {}.", "ok".green());
+ early_print!("\ntest result: {}.", "ok".green());
} else {
- print!("\ntest result: {}.", "FAILED".red());
+ early_print!("\ntest result: {}.", "FAILED".red());
}
- print!(
+ early_print!(
" {} passed; {} failed; {} filtered out.\n",
- passed, failed, filtered
+ passed,
+ failed,
+ filtered
);
assert!(passed + failed + filtered == crate_.nr_tot_tests());
if failed > 0 {
- print!("\nfailures:\n\n");
+ early_print!("\nfailures:\n\n");
for (t, e) in failed_tests {
- print!(
+ early_print!(
"---- {}:{}:{} - {} ----\n\n",
t.info().source,
t.info().line,
diff --git a/ostd/libs/ostd-test/src/runner.rs b/osdk/test-kernel/src/lib.rs
--- a/ostd/libs/ostd-test/src/runner.rs
+++ b/osdk/test-kernel/src/lib.rs
@@ -151,18 +168,18 @@ where
);
match e {
KtestError::Panic(s) => {
- print!("[caught panic] {}\n", s);
+ early_print!("[caught panic] {}\n", s);
}
KtestError::ShouldPanicButNoPanic => {
- print!("test did not panic as expected\n");
+ early_print!("test did not panic as expected\n");
}
KtestError::ExpectedPanicNotMatch(expected, s) => {
- print!("[caught panic] expected panic not match\n");
- print!("expected: {}\n", expected);
- print!("caught: {}\n", s);
+ early_print!("[caught panic] expected panic not match\n");
+ early_print!("expected: {}\n", expected);
+ early_print!("caught: {}\n", s);
}
KtestError::Unknown => {
- print!("[caught panic] unknown panic payload! (fatal panic handling error in ktest)\n");
+ early_print!("[caught panic] unknown panic payload! (fatal panic handling error in ktest)\n");
}
}
}
diff --git a/ostd/libs/ostd-test/src/path.rs b/osdk/test-kernel/src/path.rs
--- a/ostd/libs/ostd-test/src/path.rs
+++ b/osdk/test-kernel/src/path.rs
@@ -112,11 +112,13 @@ impl Display for KtestPath {
}
}
-#[cfg(test)]
+#[cfg(ktest)]
mod path_test {
+ use ostd::prelude::ktest;
+
use super::*;
- #[test]
+ #[ktest]
fn test_ktest_path() {
let mut path = KtestPath::new();
path.push_back("a");
diff --git a/ostd/libs/ostd-test/src/path.rs b/osdk/test-kernel/src/path.rs
--- a/ostd/libs/ostd-test/src/path.rs
+++ b/osdk/test-kernel/src/path.rs
@@ -129,7 +131,7 @@ mod path_test {
assert_eq!(path.pop_back(), None);
}
- #[test]
+ #[ktest]
fn test_ktest_path_starts_with() {
let mut path = KtestPath::new();
path.push_back("a");
diff --git a/ostd/libs/ostd-test/src/path.rs b/osdk/test-kernel/src/path.rs
--- a/ostd/libs/ostd-test/src/path.rs
+++ b/osdk/test-kernel/src/path.rs
@@ -144,7 +146,7 @@ mod path_test {
assert!(!path.starts_with(&KtestPath::from("d")));
}
- #[test]
+ #[ktest]
fn test_ktest_path_ends_with() {
let mut path = KtestPath::new();
path.push_back("a");
diff --git a/ostd/libs/ostd-test/src/path.rs b/osdk/test-kernel/src/path.rs
--- a/ostd/libs/ostd-test/src/path.rs
+++ b/osdk/test-kernel/src/path.rs
@@ -238,8 +240,10 @@ impl Default for SuffixTrie {
}
}
-#[cfg(test)]
+#[cfg(ktest)]
mod suffix_trie_test {
+ use ostd::prelude::ktest;
+
use super::*;
static TEST_PATHS: &[&str] = &[
diff --git a/ostd/libs/ostd-test/src/path.rs b/osdk/test-kernel/src/path.rs
--- a/ostd/libs/ostd-test/src/path.rs
+++ b/osdk/test-kernel/src/path.rs
@@ -252,7 +256,7 @@ mod suffix_trie_test {
"m::n",
];
- #[test]
+ #[ktest]
fn test_contains() {
let trie = SuffixTrie::from_paths(TEST_PATHS.iter().map(|&s| KtestPath::from(s)));
diff --git a/ostd/libs/ostd-test/src/path.rs b/osdk/test-kernel/src/path.rs
--- a/ostd/libs/ostd-test/src/path.rs
+++ b/osdk/test-kernel/src/path.rs
@@ -269,7 +273,7 @@ mod suffix_trie_test {
assert!(!trie.contains(KtestPath::from("n").iter()));
}
- #[test]
+ #[ktest]
fn test_matches() {
let trie = SuffixTrie::from_paths(TEST_PATHS.iter().map(|&s| KtestPath::from(s)));
diff --git a/ostd/libs/ostd-test/src/tree.rs b/osdk/test-kernel/src/tree.rs
--- a/ostd/libs/ostd-test/src/tree.rs
+++ b/osdk/test-kernel/src/tree.rs
@@ -213,21 +213,21 @@ impl<'a> Iterator for KtestModuleIter<'a> {
}
}
-#[cfg(test)]
+#[cfg(ktest)]
mod tests {
+ use ostd::prelude::ktest;
+
use super::*;
macro_rules! gen_test_case {
() => {{
- fn dummy_fn() {
- ()
- }
+ fn dummy_fn() {}
let mut tree = KtestTree::new();
let new = |m: &'static str, f: &'static str, p: &'static str| {
KtestItem::new(
dummy_fn,
(false, None),
- crate::KtestItemInfo {
+ ostd::ktest::KtestItemInfo {
module_path: m,
fn_name: f,
package: p,
diff --git a/ostd/libs/ostd-test/src/tree.rs b/osdk/test-kernel/src/tree.rs
--- a/ostd/libs/ostd-test/src/tree.rs
+++ b/osdk/test-kernel/src/tree.rs
@@ -250,7 +250,7 @@ mod tests {
}};
}
- #[test]
+ #[ktest]
fn test_tree_iter() {
let tree = gen_test_case!();
let mut iter = tree.iter();
diff --git a/ostd/libs/ostd-test/src/tree.rs b/osdk/test-kernel/src/tree.rs
--- a/ostd/libs/ostd-test/src/tree.rs
+++ b/osdk/test-kernel/src/tree.rs
@@ -261,7 +261,7 @@ mod tests {
assert!(iter.next().is_none());
}
- #[test]
+ #[ktest]
fn test_crate_iter() {
let tree = gen_test_case!();
for crate_ in tree.iter() {
diff --git a/ostd/libs/ostd-test/src/tree.rs b/osdk/test-kernel/src/tree.rs
--- a/ostd/libs/ostd-test/src/tree.rs
+++ b/osdk/test-kernel/src/tree.rs
@@ -285,7 +285,7 @@ mod tests {
}
}
- #[test]
+ #[ktest]
fn test_module_iter() {
let tree = gen_test_case!();
let mut collection = Vec::<&KtestItem>::new();
diff --git a/ostd/libs/ostd-test/src/tree.rs b/osdk/test-kernel/src/tree.rs
--- a/ostd/libs/ostd-test/src/tree.rs
+++ b/osdk/test-kernel/src/tree.rs
@@ -293,7 +293,7 @@ mod tests {
for mov in crate_.iter() {
let module = mov;
for test in module.iter() {
- collection.push(&test);
+ collection.push(test);
}
}
}
diff --git a/osdk/tests/examples_in_book/work_in_workspace_templates/myos/src/lib.rs b/osdk/tests/examples_in_book/work_in_workspace_templates/myos/src/lib.rs
--- a/osdk/tests/examples_in_book/work_in_workspace_templates/myos/src/lib.rs
+++ b/osdk/tests/examples_in_book/work_in_workspace_templates/myos/src/lib.rs
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: MPL-2.0
#![no_std]
+#![feature(linkage)]
#![deny(unsafe_code)]
use ostd::prelude::*;
diff --git a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
--- a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
+++ b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
@@ -1,6 +1,8 @@
// SPDX-License-Identifier: MPL-2.0
#![no_std]
+// The feature `linkage` is required for `ostd::main` to work.
+#![feature(linkage)]
extern crate alloc;
diff --git a/ostd/libs/ostd-macros/src/lib.rs b/ostd/libs/ostd-macros/src/lib.rs
--- a/ostd/libs/ostd-macros/src/lib.rs
+++ b/ostd/libs/ostd-macros/src/lib.rs
@@ -28,8 +29,37 @@ pub fn main(_attr: TokenStream, item: TokenStream) -> TokenStream {
quote!(
#[no_mangle]
- pub fn __ostd_main() -> ! {
- ostd::init();
+ #[linkage = "weak"]
+ extern "Rust" fn __ostd_main() -> ! {
+ // SAFETY: The function is called only once on the BSP.
+ unsafe { ostd::init() };
+ #main_fn_name();
+ ostd::prelude::abort();
+ }
+
+ #main_fn
+ )
+ .into()
+}
+
+/// A macro attribute for the unit test kernel entry point.
+///
+/// This macro is used for internal OSDK implementation. Do not use it
+/// directly.
+///
+/// It is a strong version of the `main` macro attribute. So if it exists (
+/// which means the unit test kernel is linked to perform testing), the actual
+/// kernel entry point will be replaced by this one.
+#[proc_macro_attribute]
+pub fn test_main(_attr: TokenStream, item: TokenStream) -> TokenStream {
+ let main_fn = parse_macro_input!(item as ItemFn);
+ let main_fn_name = &main_fn.sig.ident;
+
+ quote!(
+ #[no_mangle]
+ extern "Rust" fn __ostd_main() -> ! {
+ // SAFETY: The function is called only once on the BSP.
+ unsafe { ostd::init() };
#main_fn_name();
ostd::prelude::abort();
}
diff --git a/ostd/libs/ostd-test/Cargo.toml b/ostd/libs/ostd-test/Cargo.toml
--- a/ostd/libs/ostd-test/Cargo.toml
+++ b/ostd/libs/ostd-test/Cargo.toml
@@ -2,11 +2,8 @@
name = "ostd-test"
version = "0.1.0"
edition = "2021"
-description = "The kernel mode testing framework of OSTD"
+description = "The kernel mode unit testing framework of OSTD"
license = "MPL-2.0"
repository ="https://github.com/asterinas/asterinas"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
-
-[dependencies]
-owo-colors = "3.5.0"
diff --git a/ostd/libs/ostd-test/src/lib.rs b/ostd/libs/ostd-test/src/lib.rs
--- a/ostd/libs/ostd-test/src/lib.rs
+++ b/ostd/libs/ostd-test/src/lib.rs
@@ -45,12 +45,6 @@
//!
//! Any crates using the ostd-test framework should be linked with ostd.
//!
-//! ```toml
-//! # Cargo.toml
-//! [dependencies]
-//! ostd = { path = "relative/path/to/ostd" }
-//! ```
-//!
//! By the way, `#[ktest]` attribute along also works, but it hinders test control
//! using cfgs since plain attribute marked test will be executed in all test runs
//! no matter what cfgs are passed to the compiler. More importantly, using `#[ktest]`
diff --git a/ostd/libs/ostd-test/src/lib.rs b/ostd/libs/ostd-test/src/lib.rs
--- a/ostd/libs/ostd-test/src/lib.rs
+++ b/ostd/libs/ostd-test/src/lib.rs
@@ -58,27 +52,10 @@
//! explicitly stripped in normal builds.
//!
//! Rust cfg is used to control the compilation of the test module. In cooperation
-//! with the `ktest` framework, the Makefile will set the `RUSTFLAGS` environment
-//! variable to pass the cfgs to all rustc invocations. To run the tests, you simply
-//! need to set a list of cfgs by specifying `KTEST=1` to the Makefile, e.g.:
-//!
-//! ```bash
-//! make run KTEST=1
-//! ```
-//!
-//! Also, you can run a subset of tests by specifying the `KTEST_WHITELIST` variable.
-//! This is achieved by a whitelist filter on the test name.
-//!
-//! ```bash
-//! make run KTEST=1 KTEST_WHITELIST=failing_assertion,ostd::test::expect_panic
-//! ```
-//!
-//! `KTEST_CRATES` variable is used to specify in which crates the tests to be run.
-//! This is achieved by conditionally compiling the test module using the `#[cfg]`.
-//!
-//! ```bash
-//! make run KTEST=1 KTEST_CRATES=ostd
-//! ``
+//! with the `ktest` framework, OSDK will set the `RUSTFLAGS` environment variable
+//! to pass the cfgs to all rustc invocations. To run the tests, you simply need
+//! to use the command `cargo osdk test` in the crate directory. For more information,
+//! please refer to the OSDK documentation.
//!
//! We support the `#[should_panic]` attribute just in the same way as the standard
//! library do, but the implementation is quite slow currently. Use it with cautious.
diff --git a/ostd/libs/ostd-test/src/lib.rs b/ostd/libs/ostd-test/src/lib.rs
--- a/ostd/libs/ostd-test/src/lib.rs
+++ b/ostd/libs/ostd-test/src/lib.rs
@@ -90,10 +67,6 @@
#![cfg_attr(not(test), no_std)]
#![feature(panic_info_message)]
-pub mod path;
-pub mod runner;
-pub mod tree;
-
extern crate alloc;
use alloc::{boxed::Box, string::String};
diff --git a/ostd/libs/ostd-test/src/lib.rs b/ostd/libs/ostd-test/src/lib.rs
--- a/ostd/libs/ostd-test/src/lib.rs
+++ b/ostd/libs/ostd-test/src/lib.rs
@@ -113,6 +86,7 @@ impl core::fmt::Display for PanicInfo {
}
}
+/// The error that may occur during the test.
#[derive(Clone)]
pub enum KtestError {
Panic(Box<PanicInfo>),
diff --git a/ostd/libs/ostd-test/src/lib.rs b/ostd/libs/ostd-test/src/lib.rs
--- a/ostd/libs/ostd-test/src/lib.rs
+++ b/ostd/libs/ostd-test/src/lib.rs
@@ -121,13 +95,22 @@ pub enum KtestError {
Unknown,
}
+/// The information of the unit test.
#[derive(Clone, PartialEq, Debug)]
pub struct KtestItemInfo {
+ /// The path of the module, not including the function name.
+ ///
+ /// It would be separated by `::`.
pub module_path: &'static str,
+ /// The name of the unit test function.
pub fn_name: &'static str,
+ /// The name of the crate.
pub package: &'static str,
+ /// The source file where the test function resides.
pub source: &'static str,
+ /// The line number of the test function in the file.
pub line: usize,
+ /// The column number of the test function in the file.
pub col: usize,
}
diff --git a/ostd/libs/ostd-test/src/lib.rs b/ostd/libs/ostd-test/src/lib.rs
--- a/ostd/libs/ostd-test/src/lib.rs
+++ b/ostd/libs/ostd-test/src/lib.rs
@@ -141,6 +124,11 @@ pub struct KtestItem {
type CatchUnwindImpl = fn(f: fn() -> ()) -> Result<(), Box<dyn core::any::Any + Send>>;
impl KtestItem {
+ /// Create a new [`KtestItem`].
+ ///
+ /// Do not use this function directly. Instead, use the `#[ktest]`
+ /// attribute to mark the test function.
+ #[doc(hidden)]
pub const fn new(
fn_: fn() -> (),
should_panic: (bool, Option<&'static str>),
diff --git a/ostd/libs/ostd-test/src/lib.rs b/ostd/libs/ostd-test/src/lib.rs
--- a/ostd/libs/ostd-test/src/lib.rs
+++ b/ostd/libs/ostd-test/src/lib.rs
@@ -153,6 +141,7 @@ impl KtestItem {
}
}
+ /// Get the information of the test.
pub fn info(&self) -> &KtestItemInfo {
&self.info
}
diff --git a/ostd/libs/ostd-test/src/lib.rs b/ostd/libs/ostd-test/src/lib.rs
--- a/ostd/libs/ostd-test/src/lib.rs
+++ b/ostd/libs/ostd-test/src/lib.rs
@@ -206,12 +195,22 @@ macro_rules! ktest_array {
}};
}
+/// The iterator of the ktest array.
pub struct KtestIter {
index: usize,
}
+impl Default for KtestIter {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl KtestIter {
- fn new() -> Self {
+ /// Create a new [`KtestIter`].
+ ///
+ /// It will iterate over all the tests (marked with `#[ktest]`).
+ pub fn new() -> Self {
Self { index: 0 }
}
}
diff --git a/ostd/libs/ostd-test/src/lib.rs b/ostd/libs/ostd-test/src/lib.rs
--- a/ostd/libs/ostd-test/src/lib.rs
+++ b/ostd/libs/ostd-test/src/lib.rs
@@ -225,3 +224,28 @@ impl core::iter::Iterator for KtestIter {
Some(ktest_item.clone())
}
}
+
+// The whitelists that will be generated by the OSDK as static consts.
+// They deliver the target tests that the user wants to run.
+extern "Rust" {
+ static KTEST_TEST_WHITELIST: Option<&'static [&'static str]>;
+ static KTEST_CRATE_WHITELIST: Option<&'static [&'static str]>;
+}
+
+/// Get the whitelist of the tests.
+///
+/// The whitelist is generated by the OSDK runner, indicating name of the
+/// target tests that the user wants to run.
+pub fn get_ktest_test_whitelist() -> Option<&'static [&'static str]> {
+ // SAFETY: The two extern statics in the base crate are generated by OSDK.
+ unsafe { KTEST_TEST_WHITELIST }
+}
+
+/// Get the whitelist of the crates.
+///
+/// The whitelist is generated by the OSDK runner, indicating the target crate
+/// that the user wants to test.
+pub fn get_ktest_crate_whitelist() -> Option<&'static [&'static str]> {
+ // SAFETY: The two extern statics in the base crate are generated by OSDK.
+ unsafe { KTEST_CRATE_WHITELIST }
+}
diff --git a/ostd/src/boot/mod.rs b/ostd/src/boot/mod.rs
--- a/ostd/src/boot/mod.rs
+++ b/ostd/src/boot/mod.rs
@@ -115,8 +115,9 @@ pub fn init() {
///
/// Any kernel that uses the `ostd` crate should define a function marked with
/// `ostd::main` as the entrypoint.
-pub fn call_ostd_main() -> ! {
- #[cfg(not(ktest))]
+///
+/// This function should be only called from the bootloader-specific module.
+pub(crate) fn call_ostd_main() -> ! {
unsafe {
// The entry point of kernel code, which should be defined by the package that
// uses OSTD.
diff --git a/ostd/src/boot/mod.rs b/ostd/src/boot/mod.rs
--- a/ostd/src/boot/mod.rs
+++ b/ostd/src/boot/mod.rs
@@ -125,42 +126,4 @@ pub fn call_ostd_main() -> ! {
}
__ostd_main();
}
- #[cfg(ktest)]
- unsafe {
- use crate::task::TaskOptions;
-
- crate::init();
- // The whitelists that will be generated by OSDK runner as static consts.
- extern "Rust" {
- static KTEST_TEST_WHITELIST: Option<&'static [&'static str]>;
- static KTEST_CRATE_WHITELIST: Option<&'static [&'static str]>;
- }
-
- let test_task = move || {
- run_ktests(KTEST_TEST_WHITELIST, KTEST_CRATE_WHITELIST);
- };
- let _ = TaskOptions::new(test_task).data(()).spawn();
- unreachable!("The spawn method will NOT return in the boot context")
- }
-}
-
-fn run_ktests(test_whitelist: Option<&[&str]>, crate_whitelist: Option<&[&str]>) -> ! {
- use alloc::{boxed::Box, string::ToString};
- use core::any::Any;
-
- use crate::arch::qemu::{exit_qemu, QemuExitCode};
-
- let fn_catch_unwind = &(unwinding::panic::catch_unwind::<(), fn()>
- as fn(fn()) -> Result<(), Box<(dyn Any + Send + 'static)>>);
-
- use ostd_test::runner::{run_ktests, KtestResult};
- match run_ktests(
- &crate::console::early_print,
- fn_catch_unwind,
- test_whitelist.map(|s| s.iter().map(|s| s.to_string())),
- crate_whitelist,
- ) {
- KtestResult::Ok => exit_qemu(QemuExitCode::Success),
- KtestResult::Failed => exit_qemu(QemuExitCode::Failed),
- };
}
diff --git a/ostd/src/lib.rs b/ostd/src/lib.rs
--- a/ostd/src/lib.rs
+++ b/ostd/src/lib.rs
@@ -114,6 +119,7 @@ mod test {
use crate::prelude::*;
#[ktest]
+ #[allow(clippy::eq_op)]
fn trivial_assertion() {
assert_eq!(0, 0);
}
diff --git a/ostd/src/lib.rs b/ostd/src/lib.rs
--- a/ostd/src/lib.rs
+++ b/ostd/src/lib.rs
@@ -131,8 +137,14 @@ mod test {
}
}
-/// The module re-exports everything from the ktest crate
-#[cfg(ktest)]
+#[doc(hidden)]
pub mod ktest {
+ //! The module re-exports everything from the [`ostd_test`] crate, as well
+ //! as the test entry point macro.
+ //!
+ //! It is rather discouraged to use the definitions here directly. The
+ //! `ktest` attribute is sufficient for all normal use cases.
+
+ pub use ostd_macros::test_main as main;
pub use ostd_test::*;
}
diff --git a/ostd/src/mm/dma/dma_stream.rs b/ostd/src/mm/dma/dma_stream.rs
--- a/ostd/src/mm/dma/dma_stream.rs
+++ b/ostd/src/mm/dma/dma_stream.rs
@@ -334,9 +334,10 @@ mod test {
.alloc_contiguous()
.unwrap();
let vm_segment_child = vm_segment_parent.range(0..1);
- let _dma_stream_parent =
+ let dma_stream_parent =
DmaStream::map(vm_segment_parent, DmaDirection::Bidirectional, false);
let dma_stream_child = DmaStream::map(vm_segment_child, DmaDirection::Bidirectional, false);
+ assert!(dma_stream_parent.is_ok());
assert!(dma_stream_child.is_err());
}
diff --git a/ostd/src/sync/atomic_bits.rs b/ostd/src/sync/atomic_bits.rs
--- a/ostd/src/sync/atomic_bits.rs
+++ b/ostd/src/sync/atomic_bits.rs
@@ -313,24 +313,24 @@ mod test {
fn set_get() {
let bits = AtomicBits::new_zeroes(128);
for i in 0..bits.len() {
- assert!(bits.get(i) == false);
+ assert!(!bits.get(i));
bits.set(i, true);
- assert!(bits.get(i) == true);
+ assert!(bits.get(i));
bits.set(i, false);
- assert!(bits.get(i) == false);
+ assert!(!bits.get(i));
}
let bits = AtomicBits::new_ones(128);
for i in 0..bits.len() {
- assert!(bits.get(i) == true);
+ assert!(bits.get(i));
bits.set(i, false);
- assert!(bits.get(i) == false);
+ assert!(!bits.get(i));
bits.set(i, true);
- assert!(bits.get(i) == true);
+ assert!(bits.get(i));
}
}
diff --git a/ostd/src/sync/atomic_bits.rs b/ostd/src/sync/atomic_bits.rs
--- a/ostd/src/sync/atomic_bits.rs
+++ b/ostd/src/sync/atomic_bits.rs
@@ -389,9 +389,9 @@ mod test {
#[ktest]
fn iter() {
let bits = AtomicBits::new_zeroes(7);
- assert!(bits.iter().all(|bit| bit == false));
+ assert!(bits.iter().all(|bit| !bit));
let bits = AtomicBits::new_ones(128);
- assert!(bits.iter().all(|bit| bit == true));
+ assert!(bits.iter().all(|bit| bit));
}
}
diff --git a/ostd/src/sync/wait.rs b/ostd/src/sync/wait.rs
--- a/ostd/src/sync/wait.rs
+++ b/ostd/src/sync/wait.rs
@@ -293,7 +293,7 @@ mod test {
Task::yield_now();
cond_cloned.store(true, Ordering::Relaxed);
- wake(&*queue_cloned);
+ wake(&queue_cloned);
})
.data(())
.spawn()
diff --git a/ostd/src/task/task/mod.rs b/ostd/src/task/task/mod.rs
--- a/ostd/src/task/task/mod.rs
+++ b/ostd/src/task/task/mod.rs
@@ -383,6 +383,7 @@ mod test {
#[ktest]
fn create_task() {
+ #[allow(clippy::eq_op)]
let task = || {
assert_eq!(1, 1);
};
diff --git a/ostd/src/task/task/mod.rs b/ostd/src/task/task/mod.rs
--- a/ostd/src/task/task/mod.rs
+++ b/ostd/src/task/task/mod.rs
@@ -395,6 +396,7 @@ mod test {
#[ktest]
fn spawn_task() {
+ #[allow(clippy::eq_op)]
let task = || {
assert_eq!(1, 1);
};
diff --git a/tools/bump_version.sh b/tools/bump_version.sh
--- a/tools/bump_version.sh
+++ b/tools/bump_version.sh
@@ -98,6 +105,7 @@ ASTER_SRC_DIR=${SCRIPT_DIR}/..
DOCS_DIR=${ASTER_SRC_DIR}/docs
OSTD_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/Cargo.toml
OSDK_CARGO_TOML_PATH=${ASTER_SRC_DIR}/osdk/Cargo.toml
+OSTD_TEST_RUNNER_CARGO_TOML_PATH=${ASTER_SRC_DIR}/osdk/test-kernel/Cargo.toml
VERSION_PATH=${ASTER_SRC_DIR}/VERSION
current_version=$(cat ${VERSION_PATH})
|
[
"975"
] |
0.7
|
c2a83427520f8263a8eb2c36edacdba261ad5cae
|
ktest as a kernel
<!-- Thank you for taking the time to propose a new idea or significant change. Please provide a comprehensive overview of the concepts and motivations at play. -->
### Summary
<!-- Briefly summarize the idea, change, or feature you are proposing. What is it about, and what does it aim to achieve? -->
Well, I want to make ktest as a kernel built on top of aster-frame (OSTD), and run as a kernel. Currently the ktest crate is a dependency of aster-frame, which leads to many problems such as:
- a lot of runtime needed when running ktest, which need to be passed as parameters #834 ;
- need to pass cfg to aster-frame when rebuilding the test #974 ;
By making ktest a kernel depending on aster-frame, which has it's entrypoint as `#[aster_main]` (`#[ostd::main]`), it works for all the above problems.
### Context and Problem Statement
<!-- Describe the problem or inadequacy of the current situation/state that your proposal is addressing. This is a key aspect of putting your RFC into context. -->
### Proposal
<!-- Clearly and comprehensively describe your proposal including high-level technical specifics, any new interfaces or APIs, and how it should integrate into the existing system. -->
Originally the dependency chain of testing a target crate `A` is:
```text
ktest <---------------- ostd <--- A <--- base_crate
/ /
ktest_proc_macro <----'---------'
```
The proposed one is:
```text
.-- ktest <----(if testing)----.
v \
.-- ostd <---------- A <--------- base_crate
v /
ktest_proc_macro <---'
```
Instead of a conditional compilation to choose the ktest entry point at `aster_frame::boot::call_aster_main`, the ktest entry point should be registered as **STRONG** `#[aster_main]`, while other kernel's `#[aster_main]` should be WEAK. So during linking, if the ktest main exist ktests will be excecuted, other wise kernel main would be executed.
### Motivation and Rationale
<!-- Elaborate on why this proposal is important. Provide justifications for why it should be considered and what benefits it brings. Include use cases, user stories, and pain points it intends to solve. -->
### Detailed Design
<!-- Dive into the nitty-gritty details of your proposal. Discuss possible implementation strategies, potential issues, and how the proposal would alter workflows, behaviors, or structures. Include pseudocode, diagrams, or mock-ups if possible. -->
### Alternatives Considered
<!-- Detail any alternative solutions or features you've considered. Why were they discarded in favor of this proposal? -->
### Additional Information and Resources
<!-- Offer any additional information, context, links, or resources that stakeholders might find helpful for understanding the proposal. -->
### Open Questions
<!-- List any questions that you have that might need further discussion. This can include areas where you are seeking feedback or require input to finalize decisions. -->
### Future Possibilities
<!-- If your RFC is likely to lead to subsequent changes, provide a brief outline of what those might be and how your proposal may lay the groundwork for them. -->
<!-- We appreciate your effort in contributing to the evolution of our system and look forward to reviewing and discussing your ideas! -->
|
asterinas__asterinas-1159
| 1,159
|
diff --git a/.github/workflows/benchmark_asterinas.yml b/.github/workflows/benchmark_asterinas.yml
--- a/.github/workflows/benchmark_asterinas.yml
+++ b/.github/workflows/benchmark_asterinas.yml
@@ -57,7 +57,7 @@ jobs:
fail-fast: false
timeout-minutes: 60
container:
- image: asterinas/asterinas:0.7.0
+ image: asterinas/asterinas:0.8.0
options: --device=/dev/kvm
env:
# Need to set up proxy since the self-hosted CI server is located in China,
diff --git a/.github/workflows/benchmark_asterinas.yml b/.github/workflows/benchmark_asterinas.yml
--- a/.github/workflows/benchmark_asterinas.yml
+++ b/.github/workflows/benchmark_asterinas.yml
@@ -57,7 +57,7 @@ jobs:
fail-fast: false
timeout-minutes: 60
container:
- image: asterinas/asterinas:0.7.0
+ image: asterinas/asterinas:0.8.0
options: --device=/dev/kvm
env:
# Need to set up proxy since the self-hosted CI server is located in China,
diff --git a/.github/workflows/publish_osdk_and_ostd.yml b/.github/workflows/publish_osdk_and_ostd.yml
--- a/.github/workflows/publish_osdk_and_ostd.yml
+++ b/.github/workflows/publish_osdk_and_ostd.yml
@@ -16,7 +16,7 @@ jobs:
osdk-publish:
runs-on: ubuntu-latest
timeout-minutes: 10
- container: asterinas/asterinas:0.7.0
+ container: asterinas/asterinas:0.8.0
steps:
- uses: actions/checkout@v4
diff --git a/.github/workflows/publish_osdk_and_ostd.yml b/.github/workflows/publish_osdk_and_ostd.yml
--- a/.github/workflows/publish_osdk_and_ostd.yml
+++ b/.github/workflows/publish_osdk_and_ostd.yml
@@ -39,7 +39,7 @@ jobs:
ostd-publish:
runs-on: ubuntu-latest
timeout-minutes: 10
- container: asterinas/asterinas:0.7.0
+ container: asterinas/asterinas:0.8.0
strategy:
matrix:
# All supported targets, this array should keep consistent with
diff --git a/.github/workflows/publish_osdk_and_ostd.yml b/.github/workflows/publish_osdk_and_ostd.yml
--- a/.github/workflows/publish_osdk_and_ostd.yml
+++ b/.github/workflows/publish_osdk_and_ostd.yml
@@ -48,15 +48,18 @@ jobs:
steps:
- uses: actions/checkout@v4
- - name: Check Publish OSTD
+ - name: Check Publish OSTD and the test runner
# On pull request, set `--dry-run` to check whether OSDK can publish
if: github.event_name == 'pull_request'
run: |
cd ostd
cargo publish --target ${{ matrix.target }} --dry-run
cargo doc --target ${{ matrix.target }}
+ cd osdk/test-kernel
+ cargo publish --target ${{ matrix.target }} --dry-run
+ cargo doc --target ${{ matrix.target }}
- - name: Publish OSTD
+ - name: Publish OSTD and the test runner
if: github.event_name == 'push'
env:
REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
diff --git a/.github/workflows/publish_osdk_and_ostd.yml b/.github/workflows/publish_osdk_and_ostd.yml
--- a/.github/workflows/publish_osdk_and_ostd.yml
+++ b/.github/workflows/publish_osdk_and_ostd.yml
@@ -66,4 +69,6 @@ jobs:
run: |
cd ostd
cargo publish --target x86_64-unknown-none --token ${REGISTRY_TOKEN}
-
+ cd osdk/test-kernel
+ cargo publish --target x86_64-unknown-none --token ${REGISTRY_TOKEN}
+
\ No newline at end of file
diff --git a/.github/workflows/publish_website.yml b/.github/workflows/publish_website.yml
--- a/.github/workflows/publish_website.yml
+++ b/.github/workflows/publish_website.yml
@@ -16,7 +16,7 @@ jobs:
build_and_deploy:
runs-on: ubuntu-latest
timeout-minutes: 15
- container: asterinas/asterinas:0.7.0
+ container: asterinas/asterinas:0.8.0
steps:
- uses: actions/checkout@v2
with:
diff --git a/.github/workflows/push_git_tag.yml b/.github/workflows/push_git_tag.yml
--- a/.github/workflows/push_git_tag.yml
+++ b/.github/workflows/push_git_tag.yml
@@ -17,4 +17,4 @@ jobs:
uses: pxpm/github-tag-action@1.0.1
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
- tag: v0.7.0
+ tag: v0.8.0
diff --git a/.github/workflows/push_git_tag.yml b/.github/workflows/push_git_tag.yml
--- a/.github/workflows/push_git_tag.yml
+++ b/.github/workflows/push_git_tag.yml
@@ -17,4 +17,4 @@ jobs:
uses: pxpm/github-tag-action@1.0.1
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
- tag: v0.7.0
+ tag: v0.8.0
diff --git a/.github/workflows/test_asterinas.yml b/.github/workflows/test_asterinas.yml
--- a/.github/workflows/test_asterinas.yml
+++ b/.github/workflows/test_asterinas.yml
@@ -14,9 +14,9 @@ jobs:
if: github.event_name == 'push' || github.event_name == 'pull_request'
runs-on: ubuntu-latest
timeout-minutes: 15
- container: asterinas/asterinas:0.7.0
+ container: asterinas/asterinas:0.8.0
steps:
- - run: echo "Running in asterinas/asterinas:0.7.0"
+ - run: echo "Running in asterinas/asterinas:0.8.0"
- uses: actions/checkout@v4
diff --git a/.github/workflows/test_asterinas.yml b/.github/workflows/test_asterinas.yml
--- a/.github/workflows/test_asterinas.yml
+++ b/.github/workflows/test_asterinas.yml
@@ -28,9 +28,9 @@ jobs:
if: github.event_name == 'push' || github.event_name == 'pull_request'
runs-on: ubuntu-latest
timeout-minutes: 15
- container: asterinas/asterinas:0.7.0
+ container: asterinas/asterinas:0.8.0
steps:
- - run: echo "Running in asterinas/asterinas:0.7.0"
+ - run: echo "Running in asterinas/asterinas:0.8.0"
- uses: actions/checkout@v4
diff --git a/.github/workflows/test_asterinas.yml b/.github/workflows/test_asterinas.yml
--- a/.github/workflows/test_asterinas.yml
+++ b/.github/workflows/test_asterinas.yml
@@ -49,10 +49,10 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 30
container:
- image: asterinas/asterinas:0.7.0
+ image: asterinas/asterinas:0.8.0
options: --device=/dev/kvm
steps:
- - run: echo "Running in asterinas/asterinas:0.7.0"
+ - run: echo "Running in asterinas/asterinas:0.8.0"
- uses: actions/checkout@v4
diff --git a/.github/workflows/test_asterinas.yml b/.github/workflows/test_asterinas.yml
--- a/.github/workflows/test_asterinas.yml
+++ b/.github/workflows/test_asterinas.yml
@@ -88,7 +88,7 @@ jobs:
runs-on: self-hosted
timeout-minutes: 30
container:
- image: asterinas/asterinas:0.7.0-tdx
+ image: asterinas/asterinas:0.8.0-tdx
options: --device=/dev/kvm --privileged
env:
# Need to set up proxy since the self-hosted CI server is located in China,
diff --git a/.github/workflows/test_asterinas.yml b/.github/workflows/test_asterinas.yml
--- a/.github/workflows/test_asterinas.yml
+++ b/.github/workflows/test_asterinas.yml
@@ -96,7 +96,7 @@ jobs:
RUSTUP_DIST_SERVER: https://mirrors.ustc.edu.cn/rust-static
RUSTUP_UPDATE_ROOT: https://mirrors.ustc.edu.cn/rust-static/rustup
steps:
- - run: echo "Running in asterinas/asterinas:0.7.0-tdx"
+ - run: echo "Running in asterinas/asterinas:0.8.0-tdx"
- uses: actions/checkout@v4
- name: Set up the environment
run: |
diff --git a/.github/workflows/test_asterinas_vsock.yml b/.github/workflows/test_asterinas_vsock.yml
--- a/.github/workflows/test_asterinas_vsock.yml
+++ b/.github/workflows/test_asterinas_vsock.yml
@@ -23,7 +23,7 @@ jobs:
run: |
docker run \
--privileged --network=host --device=/dev/kvm \
- -v ./:/root/asterinas asterinas/asterinas:0.7.0 \
+ -v ./:/root/asterinas asterinas/asterinas:0.8.0 \
make run AUTO_TEST=vsock ENABLE_KVM=0 SCHEME=microvm RELEASE_MODE=1 &
- name: Run Vsock Client on Host
id: host_vsock_client
diff --git a/.github/workflows/test_osdk.yml b/.github/workflows/test_osdk.yml
--- a/.github/workflows/test_osdk.yml
+++ b/.github/workflows/test_osdk.yml
@@ -21,9 +21,9 @@ jobs:
timeout-minutes: 30
strategy:
matrix:
- # asterinas/asterinas:0.7.0 container is the developing container of asterinas,
- # asterinas/osdk:0.7.0 container is built with the intructions from Asterinas Book
- container: ['asterinas/asterinas:0.7.0', 'asterinas/osdk:0.7.0']
+ # asterinas/asterinas:0.8.0 container is the developing container of asterinas,
+ # asterinas/osdk:0.8.0 container is built with the intructions from Asterinas Book
+ container: ['asterinas/asterinas:0.8.0', 'asterinas/osdk:0.8.0']
container: ${{ matrix.container }}
steps:
- run: echo "Running in ${{ matrix.container }}"
diff --git a/.github/workflows/test_osdk.yml b/.github/workflows/test_osdk.yml
--- a/.github/workflows/test_osdk.yml
+++ b/.github/workflows/test_osdk.yml
@@ -32,7 +32,7 @@ jobs:
- name: Lint
id: lint
- if: matrix.container == 'asterinas/asterinas:0.7.0'
+ if: matrix.container == 'asterinas/asterinas:0.8.0'
run: make check_osdk
# Github's actions/checkout@v4 will result in a new user (not root)
diff --git a/.github/workflows/test_osdk.yml b/.github/workflows/test_osdk.yml
--- a/.github/workflows/test_osdk.yml
+++ b/.github/workflows/test_osdk.yml
@@ -56,9 +56,9 @@ jobs:
RUSTUP_UPDATE_ROOT: https://mirrors.ustc.edu.cn/rust-static/rustup
strategy:
matrix:
- # asterinas/asterinas:0.7.0-tdx container is the developing container of asterinas,
- # asterinas/osdk:0.7.0-tdx container is built with the intructions from Asterinas Book
- container: ['asterinas/asterinas:0.7.0-tdx', 'asterinas/osdk:0.7.0-tdx']
+ # asterinas/asterinas:0.8.0-tdx container is the developing container of asterinas,
+ # asterinas/osdk:0.8.0-tdx container is built with the intructions from Asterinas Book
+ container: ['asterinas/asterinas:0.8.0-tdx', 'asterinas/osdk:0.8.0-tdx']
container:
image: ${{ matrix.container }}
options: --device=/dev/kvm --privileged
diff --git a/.github/workflows/test_osdk.yml b/.github/workflows/test_osdk.yml
--- a/.github/workflows/test_osdk.yml
+++ b/.github/workflows/test_osdk.yml
@@ -67,7 +67,7 @@ jobs:
- uses: actions/checkout@v4
- name: Lint
id: lint
- if: matrix.container == 'asterinas/asterinas:0.7.0-tdx'
+ if: matrix.container == 'asterinas/asterinas:0.8.0-tdx'
run: make check_osdk
# Github's actions/checkout@v4 will result in a new user (not root)
# and thus not using the Rust environment we set up in the container.
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -153,6 +153,7 @@ dependencies = [
"ascii",
"aster-block",
"aster-console",
+ "aster-framebuffer",
"aster-input",
"aster-network",
"aster-rights",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -153,6 +153,7 @@ dependencies = [
"ascii",
"aster-block",
"aster-console",
+ "aster-framebuffer",
"aster-input",
"aster-network",
"aster-rights",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -166,6 +167,7 @@ dependencies = [
"bytemuck",
"bytemuck_derive",
"cfg-if",
+ "component",
"controlled",
"core2",
"cpio-decoder",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -166,6 +167,7 @@ dependencies = [
"bytemuck",
"bytemuck_derive",
"cfg-if",
+ "component",
"controlled",
"core2",
"cpio-decoder",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -262,19 +264,6 @@ dependencies = [
"typeflags-util",
]
-[[package]]
-name = "asterinas"
-version = "0.4.0"
-dependencies = [
- "aster-framebuffer",
- "aster-nix",
- "aster-time",
- "component",
- "id-alloc",
- "ostd",
- "x86_64 0.14.11",
-]
-
[[package]]
name = "atomic"
version = "0.6.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -262,19 +264,6 @@ dependencies = [
"typeflags-util",
]
-[[package]]
-name = "asterinas"
-version = "0.4.0"
-dependencies = [
- "aster-framebuffer",
- "aster-nix",
- "aster-time",
- "component",
- "id-alloc",
- "ostd",
- "x86_64 0.14.11",
-]
-
[[package]]
name = "atomic"
version = "0.6.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1045,9 +1034,18 @@ version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d"
+[[package]]
+name = "osdk-test-kernel"
+version = "0.8.0"
+dependencies = [
+ "ostd",
+ "owo-colors 4.0.0",
+ "unwinding",
+]
+
[[package]]
name = "ostd"
-version = "0.7.0"
+version = "0.8.0"
dependencies = [
"acpi",
"align_ext",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1075,7 +1073,7 @@ dependencies = [
"ostd-macros",
"ostd-pod",
"ostd-test",
- "owo-colors",
+ "owo-colors 3.5.0",
"rsdp",
"spin 0.9.8",
"static_assertions",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1119,9 +1117,6 @@ dependencies = [
[[package]]
name = "ostd-test"
version = "0.1.0"
-dependencies = [
- "owo-colors",
-]
[[package]]
name = "owo-colors"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1129,6 +1124,12 @@ version = "3.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1b04fb49957986fdce4d6ee7a65027d55d4b6d2265e5848bbb507b58ccfdb6f"
+[[package]]
+name = "owo-colors"
+version = "4.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "caff54706df99d2a78a5a4e3455ff45448d81ef1bb63c22cd14052ca0e993a3f"
+
[[package]]
name = "paste"
version = "1.0.14"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1129,6 +1124,12 @@ version = "3.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1b04fb49957986fdce4d6ee7a65027d55d4b6d2265e5848bbb507b58ccfdb6f"
+[[package]]
+name = "owo-colors"
+version = "4.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "caff54706df99d2a78a5a4e3455ff45448d81ef1bb63c22cd14052ca0e993a3f"
+
[[package]]
name = "paste"
version = "1.0.14"
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,7 @@
[workspace]
resolver = "2"
members = [
+ "osdk/test-kernel",
"ostd",
"ostd/libs/align_ext",
"ostd/libs/ostd-macros",
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -10,7 +11,6 @@ members = [
"ostd/libs/linux-bzimage/setup",
"ostd/libs/ostd-test",
"kernel",
- "kernel/aster-nix",
"kernel/comps/block",
"kernel/comps/console",
"kernel/comps/framebuffer",
diff --git a/Components.toml b/Components.toml
--- a/Components.toml
+++ b/Components.toml
@@ -8,8 +8,7 @@ console = { name = "aster-console" }
time = { name = "aster-time" }
framebuffer = { name = "aster-framebuffer" }
network = { name = "aster-network" }
-main = { name = "asterinas" }
[whitelist]
-[whitelist.nix.run_first_process]
+[whitelist.nix.main]
main = true
diff --git a/Components.toml b/Components.toml
--- a/Components.toml
+++ b/Components.toml
@@ -8,8 +8,7 @@ console = { name = "aster-console" }
time = { name = "aster-time" }
framebuffer = { name = "aster-framebuffer" }
network = { name = "aster-network" }
-main = { name = "asterinas" }
[whitelist]
-[whitelist.nix.run_first_process]
+[whitelist.nix.main]
main = true
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -110,10 +110,10 @@ NON_OSDK_CRATES := \
# In contrast, OSDK crates depend on OSTD (or being `ostd` itself)
# and need to be built or tested with OSDK.
OSDK_CRATES := \
+ osdk/test-kernel \
ostd \
ostd/libs/linux-bzimage/setup \
kernel \
- kernel/aster-nix \
kernel/comps/block \
kernel/comps/console \
kernel/comps/framebuffer \
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -130,7 +130,10 @@ all: build
# To uninstall, do `cargo uninstall cargo-osdk`
.PHONY: install_osdk
install_osdk:
- @cargo install cargo-osdk --path osdk
+ @# The `OSDK_LOCAL_DEV` environment variable is used for local development
+ @# without the need to publish the changes of OSDK's self-hosted
+ @# dependencies to `crates.io`.
+ @OSDK_LOCAL_DEV=1 cargo install cargo-osdk --path osdk
# This will install OSDK if it is not already installed
# To update OSDK, we need to run `install_osdk` manually
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -130,7 +130,10 @@ all: build
# To uninstall, do `cargo uninstall cargo-osdk`
.PHONY: install_osdk
install_osdk:
- @cargo install cargo-osdk --path osdk
+ @# The `OSDK_LOCAL_DEV` environment variable is used for local development
+ @# without the need to publish the changes of OSDK's self-hosted
+ @# dependencies to `crates.io`.
+ @OSDK_LOCAL_DEV=1 cargo install cargo-osdk --path osdk
# This will install OSDK if it is not already installed
# To update OSDK, we need to run `install_osdk` manually
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -206,7 +209,7 @@ format:
@make --no-print-directory -C test format
.PHONY: check
-check: $(CARGO_OSDK)
+check: initramfs $(CARGO_OSDK)
@./tools/format_all.sh --check # Check Rust format issues
@# Check if STD_CRATES and NOSTD_CRATES combined is the same as all workspace members
@sed -n '/^\[workspace\]/,/^\[.*\]/{/members = \[/,/\]/p}' Cargo.toml | \
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -52,7 +52,7 @@ git clone https://github.com/asterinas/asterinas
2. Run a Docker container as the development environment.
```bash
-docker run -it --privileged --network=host --device=/dev/kvm -v $(pwd)/asterinas:/root/asterinas asterinas/asterinas:0.7.0
+docker run -it --privileged --network=host --device=/dev/kvm -v $(pwd)/asterinas:/root/asterinas asterinas/asterinas:0.8.0
```
3. Inside the container, go to the project folder to build and run Asterinas.
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -52,7 +52,7 @@ git clone https://github.com/asterinas/asterinas
2. Run a Docker container as the development environment.
```bash
-docker run -it --privileged --network=host --device=/dev/kvm -v $(pwd)/asterinas:/root/asterinas asterinas/asterinas:0.7.0
+docker run -it --privileged --network=host --device=/dev/kvm -v $(pwd)/asterinas:/root/asterinas asterinas/asterinas:0.8.0
```
3. Inside the container, go to the project folder to build and run Asterinas.
diff --git a/README_CN.md b/README_CN.md
--- a/README_CN.md
+++ b/README_CN.md
@@ -49,7 +49,7 @@ git clone https://github.com/asterinas/asterinas
2. 运行一个作为开发环境的Docker容器。
```bash
-docker run -it --privileged --network=host --device=/dev/kvm -v $(pwd)/asterinas:/root/asterinas asterinas/asterinas:0.7.0
+docker run -it --privileged --network=host --device=/dev/kvm -v $(pwd)/asterinas:/root/asterinas asterinas/asterinas:0.8.0
```
3. 在容器内,进入项目文件夹构建并运行星绽。
diff --git a/README_CN.md b/README_CN.md
--- a/README_CN.md
+++ b/README_CN.md
@@ -49,7 +49,7 @@ git clone https://github.com/asterinas/asterinas
2. 运行一个作为开发环境的Docker容器。
```bash
-docker run -it --privileged --network=host --device=/dev/kvm -v $(pwd)/asterinas:/root/asterinas asterinas/asterinas:0.7.0
+docker run -it --privileged --network=host --device=/dev/kvm -v $(pwd)/asterinas:/root/asterinas asterinas/asterinas:0.8.0
```
3. 在容器内,进入项目文件夹构建并运行星绽。
diff --git a/VERSION b/VERSION
--- a/VERSION
+++ b/VERSION
@@ -1,1 +1,1 @@
-0.7.0
\ No newline at end of file
+0.8.0
\ No newline at end of file
diff --git a/VERSION b/VERSION
--- a/VERSION
+++ b/VERSION
@@ -1,1 +1,1 @@
-0.7.0
\ No newline at end of file
+0.8.0
\ No newline at end of file
diff --git a/docs/src/kernel/README.md b/docs/src/kernel/README.md
--- a/docs/src/kernel/README.md
+++ b/docs/src/kernel/README.md
@@ -44,7 +44,7 @@ git clone https://github.com/asterinas/asterinas
2. Run a Docker container as the development environment.
```bash
-docker run -it --privileged --network=host --device=/dev/kvm -v $(pwd)/asterinas:/root/asterinas asterinas/asterinas:0.7.0
+docker run -it --privileged --network=host --device=/dev/kvm -v $(pwd)/asterinas:/root/asterinas asterinas/asterinas:0.8.0
```
3. Inside the container, go to the project folder to build and run Asterinas.
diff --git a/docs/src/kernel/README.md b/docs/src/kernel/README.md
--- a/docs/src/kernel/README.md
+++ b/docs/src/kernel/README.md
@@ -44,7 +44,7 @@ git clone https://github.com/asterinas/asterinas
2. Run a Docker container as the development environment.
```bash
-docker run -it --privileged --network=host --device=/dev/kvm -v $(pwd)/asterinas:/root/asterinas asterinas/asterinas:0.7.0
+docker run -it --privileged --network=host --device=/dev/kvm -v $(pwd)/asterinas:/root/asterinas asterinas/asterinas:0.8.0
```
3. Inside the container, go to the project folder to build and run Asterinas.
diff --git a/docs/src/kernel/intel_tdx.md b/docs/src/kernel/intel_tdx.md
--- a/docs/src/kernel/intel_tdx.md
+++ b/docs/src/kernel/intel_tdx.md
@@ -66,7 +66,7 @@ git clone https://github.com/asterinas/asterinas
2. Run a Docker container as the development environment.
```bash
-docker run -it --privileged --network=host --device=/dev/kvm -v $(pwd)/asterinas:/root/asterinas asterinas/asterinas:0.7.0-tdx
+docker run -it --privileged --network=host --device=/dev/kvm -v $(pwd)/asterinas:/root/asterinas asterinas/asterinas:0.8.0-tdx
```
3. Inside the container,
diff --git a/docs/src/kernel/intel_tdx.md b/docs/src/kernel/intel_tdx.md
--- a/docs/src/kernel/intel_tdx.md
+++ b/docs/src/kernel/intel_tdx.md
@@ -66,7 +66,7 @@ git clone https://github.com/asterinas/asterinas
2. Run a Docker container as the development environment.
```bash
-docker run -it --privileged --network=host --device=/dev/kvm -v $(pwd)/asterinas:/root/asterinas asterinas/asterinas:0.7.0-tdx
+docker run -it --privileged --network=host --device=/dev/kvm -v $(pwd)/asterinas:/root/asterinas asterinas/asterinas:0.8.0-tdx
```
3. Inside the container,
diff --git a/docs/src/osdk/reference/manifest.md b/docs/src/osdk/reference/manifest.md
--- a/docs/src/osdk/reference/manifest.md
+++ b/docs/src/osdk/reference/manifest.md
@@ -15,10 +15,10 @@ one is of the workspace
(in the same directory as the workspace's `Cargo.toml`)
and one of the crate
(in the same directory as the crate's `Cargo.toml`).
-OSDK will first refer to the crate-level manifest, then
-query the workspace-level manifest for undefined fields.
-In other words, missing fields of the crate manifest
-will inherit values from the workspace manifest.
+OSDK will firstly try to find the crate-level manifest.
+If the crate-level manifest is found, OSDK uses it only.
+If the manifest is not found, OSDK will look into the
+workspace-level manifest.
## Configurations
diff --git a/docs/src/osdk/reference/manifest.md b/docs/src/osdk/reference/manifest.md
--- a/docs/src/osdk/reference/manifest.md
+++ b/docs/src/osdk/reference/manifest.md
@@ -15,10 +15,10 @@ one is of the workspace
(in the same directory as the workspace's `Cargo.toml`)
and one of the crate
(in the same directory as the crate's `Cargo.toml`).
-OSDK will first refer to the crate-level manifest, then
-query the workspace-level manifest for undefined fields.
-In other words, missing fields of the crate manifest
-will inherit values from the workspace manifest.
+OSDK will firstly try to find the crate-level manifest.
+If the crate-level manifest is found, OSDK uses it only.
+If the manifest is not found, OSDK will look into the
+workspace-level manifest.
## Configurations
diff --git a/kernel/Cargo.toml b/kernel/Cargo.toml
--- a/kernel/Cargo.toml
+++ b/kernel/Cargo.toml
@@ -1,18 +1,82 @@
[package]
-name = "asterinas"
-version = "0.4.0"
+name = "aster-nix"
+version = "0.1.0"
edition = "2021"
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
[dependencies]
-id-alloc = { path = "../ostd/libs/id-alloc" }
-ostd = { path = "../ostd" }
-aster-nix = { path = "aster-nix" }
+align_ext = { path = "../ostd/libs/align_ext" }
+aster-input = { path = "comps/input" }
+aster-block = { path = "comps/block" }
+aster-network = { path = "comps/network" }
+aster-console = { path = "comps/console" }
+aster-framebuffer = { path = "comps/framebuffer" }
+aster-time = { path = "comps/time" }
+aster-virtio = { path = "comps/virtio" }
+aster-rights = { path = "libs/aster-rights" }
component = { path = "libs/comp-sys/component" }
+controlled = { path = "libs/comp-sys/controlled" }
+ostd = { path = "../ostd" }
+typeflags = { path = "libs/typeflags" }
+typeflags-util = { path = "libs/typeflags-util" }
+aster-rights-proc = { path = "libs/aster-rights-proc" }
+aster-util = { path = "libs/aster-util" }
+id-alloc = { path = "../ostd/libs/id-alloc" }
+int-to-c-enum = { path = "libs/int-to-c-enum" }
+cpio-decoder = { path = "libs/cpio-decoder" }
+ascii = { version = "1.1", default-features = false, features = ["alloc"] }
+intrusive-collections = "0.9.5"
+paste = "1.0"
+time = { version = "0.3", default-features = false, features = ["alloc"] }
+smoltcp = { git = "https://github.com/smoltcp-rs/smoltcp", rev = "dc08e0b", default-features = false, features = [
+ "alloc",
+ "log",
+ "medium-ethernet",
+ "medium-ip",
+ "proto-dhcpv4",
+ "proto-ipv4",
+ "proto-igmp",
+ "socket-icmp",
+ "socket-udp",
+ "socket-tcp",
+ "socket-raw",
+ "socket-dhcpv4",
+] }
+tdx-guest = { version = "0.1.7", optional = true }
-[dev-dependencies]
-x86_64 = "0.14.2"
-aster-time = { path = "comps/time" }
-aster-framebuffer = { path = "comps/framebuffer" }
+# parse elf file
+xmas-elf = "0.8.0"
+# data-structures
+bitflags = "1.3"
+ringbuf = { version = "0.3.2", default-features = false, features = ["alloc"] }
+keyable-arc = { path = "libs/keyable-arc" }
+# unzip initramfs
+libflate = { version = "2", default-features = false }
+core2 = { version = "0.4", default-features = false, features = ["alloc"] }
+lending-iterator = "0.1.7"
+spin = "0.9.4"
+vte = "0.10"
+lru = "0.12.3"
+log = "0.4"
+bitvec = { version = "1.0", default-features = false, features = ["alloc"] }
+hashbrown = "0.14"
+rand = { version = "0.8.5", default-features = false, features = [
+ "small_rng",
+ "std_rng",
+] }
+static_assertions = "1.1.0"
+inherit-methods-macro = { git = "https://github.com/asterinas/inherit-methods-macro", rev = "98f7e3e" }
+getset = "0.1.2"
+atomic = "0.6"
+bytemuck = "1.14.3"
+bytemuck_derive = "1.5.0"
+takeable = "0.2.2"
+cfg-if = "1.0"
+
+[dependencies.lazy_static]
+version = "1.0"
+features = ["spin_no_std"]
[features]
-cvm_guest = ["ostd/cvm_guest", "aster-nix/cvm_guest"]
+cvm_guest = ["dep:tdx-guest", "ostd/cvm_guest"]
diff --git a/kernel/Cargo.toml b/kernel/Cargo.toml
--- a/kernel/Cargo.toml
+++ b/kernel/Cargo.toml
@@ -1,18 +1,82 @@
[package]
-name = "asterinas"
-version = "0.4.0"
+name = "aster-nix"
+version = "0.1.0"
edition = "2021"
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
[dependencies]
-id-alloc = { path = "../ostd/libs/id-alloc" }
-ostd = { path = "../ostd" }
-aster-nix = { path = "aster-nix" }
+align_ext = { path = "../ostd/libs/align_ext" }
+aster-input = { path = "comps/input" }
+aster-block = { path = "comps/block" }
+aster-network = { path = "comps/network" }
+aster-console = { path = "comps/console" }
+aster-framebuffer = { path = "comps/framebuffer" }
+aster-time = { path = "comps/time" }
+aster-virtio = { path = "comps/virtio" }
+aster-rights = { path = "libs/aster-rights" }
component = { path = "libs/comp-sys/component" }
+controlled = { path = "libs/comp-sys/controlled" }
+ostd = { path = "../ostd" }
+typeflags = { path = "libs/typeflags" }
+typeflags-util = { path = "libs/typeflags-util" }
+aster-rights-proc = { path = "libs/aster-rights-proc" }
+aster-util = { path = "libs/aster-util" }
+id-alloc = { path = "../ostd/libs/id-alloc" }
+int-to-c-enum = { path = "libs/int-to-c-enum" }
+cpio-decoder = { path = "libs/cpio-decoder" }
+ascii = { version = "1.1", default-features = false, features = ["alloc"] }
+intrusive-collections = "0.9.5"
+paste = "1.0"
+time = { version = "0.3", default-features = false, features = ["alloc"] }
+smoltcp = { git = "https://github.com/smoltcp-rs/smoltcp", rev = "dc08e0b", default-features = false, features = [
+ "alloc",
+ "log",
+ "medium-ethernet",
+ "medium-ip",
+ "proto-dhcpv4",
+ "proto-ipv4",
+ "proto-igmp",
+ "socket-icmp",
+ "socket-udp",
+ "socket-tcp",
+ "socket-raw",
+ "socket-dhcpv4",
+] }
+tdx-guest = { version = "0.1.7", optional = true }
-[dev-dependencies]
-x86_64 = "0.14.2"
-aster-time = { path = "comps/time" }
-aster-framebuffer = { path = "comps/framebuffer" }
+# parse elf file
+xmas-elf = "0.8.0"
+# data-structures
+bitflags = "1.3"
+ringbuf = { version = "0.3.2", default-features = false, features = ["alloc"] }
+keyable-arc = { path = "libs/keyable-arc" }
+# unzip initramfs
+libflate = { version = "2", default-features = false }
+core2 = { version = "0.4", default-features = false, features = ["alloc"] }
+lending-iterator = "0.1.7"
+spin = "0.9.4"
+vte = "0.10"
+lru = "0.12.3"
+log = "0.4"
+bitvec = { version = "1.0", default-features = false, features = ["alloc"] }
+hashbrown = "0.14"
+rand = { version = "0.8.5", default-features = false, features = [
+ "small_rng",
+ "std_rng",
+] }
+static_assertions = "1.1.0"
+inherit-methods-macro = { git = "https://github.com/asterinas/inherit-methods-macro", rev = "98f7e3e" }
+getset = "0.1.2"
+atomic = "0.6"
+bytemuck = "1.14.3"
+bytemuck_derive = "1.5.0"
+takeable = "0.2.2"
+cfg-if = "1.0"
+
+[dependencies.lazy_static]
+version = "1.0"
+features = ["spin_no_std"]
[features]
-cvm_guest = ["ostd/cvm_guest", "aster-nix/cvm_guest"]
+cvm_guest = ["dep:tdx-guest", "ostd/cvm_guest"]
diff --git a/kernel/aster-nix/Cargo.toml /dev/null
--- a/kernel/aster-nix/Cargo.toml
+++ /dev/null
@@ -1,81 +0,0 @@
-[package]
-name = "aster-nix"
-version = "0.1.0"
-edition = "2021"
-
-# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
-
-[dependencies]
-align_ext = { path = "../../ostd/libs/align_ext" }
-aster-input = { path = "../comps/input" }
-aster-block = { path = "../comps/block" }
-aster-network = { path = "../comps/network" }
-aster-console = { path = "../comps/console" }
-aster-time = { path = "../comps/time" }
-aster-virtio = { path = "../comps/virtio" }
-aster-rights = { path = "../libs/aster-rights" }
-controlled = { path = "../libs/comp-sys/controlled" }
-ostd = { path = "../../ostd" }
-typeflags = { path = "../libs/typeflags" }
-typeflags-util = { path = "../libs/typeflags-util" }
-aster-rights-proc = { path = "../libs/aster-rights-proc" }
-aster-util = { path = "../libs/aster-util" }
-id-alloc = { path = "../../ostd/libs/id-alloc" }
-int-to-c-enum = { path = "../libs/int-to-c-enum" }
-cpio-decoder = { path = "../libs/cpio-decoder" }
-ascii = { version = "1.1", default-features = false, features = ["alloc"] }
-intrusive-collections = "0.9.5"
-paste = "1.0"
-time = { version = "0.3", default-features = false, features = ["alloc"] }
-smoltcp = { git = "https://github.com/smoltcp-rs/smoltcp", rev = "dc08e0b", default-features = false, features = [
- "alloc",
- "log",
- "medium-ethernet",
- "medium-ip",
- "proto-dhcpv4",
- "proto-ipv4",
- "proto-igmp",
- "socket-icmp",
- "socket-udp",
- "socket-tcp",
- "socket-raw",
- "socket-dhcpv4",
-] }
-tdx-guest = { version = "0.1.7", optional = true }
-
-# parse elf file
-xmas-elf = "0.8.0"
-# goblin = {version= "0.5.3", default-features = false, features = ["elf64"]}
-# data-structures
-bitflags = "1.3"
-ringbuf = { version = "0.3.2", default-features = false, features = ["alloc"] }
-keyable-arc = { path = "../libs/keyable-arc" }
-# unzip initramfs
-libflate = { version = "2", default-features = false }
-core2 = { version = "0.4", default-features = false, features = ["alloc"] }
-lending-iterator = "0.1.7"
-spin = "0.9.4"
-vte = "0.10"
-lru = "0.12.3"
-log = "0.4"
-bitvec = { version = "1.0", default-features = false, features = ["alloc"] }
-hashbrown = "0.14"
-rand = { version = "0.8.5", default-features = false, features = [
- "small_rng",
- "std_rng",
-] }
-static_assertions = "1.1.0"
-inherit-methods-macro = { git = "https://github.com/asterinas/inherit-methods-macro", rev = "98f7e3e" }
-getset = "0.1.2"
-atomic = "0.6"
-bytemuck = "1.14.3"
-bytemuck_derive = "1.5.0"
-takeable = "0.2.2"
-cfg-if = "1.0"
-
-[dependencies.lazy_static]
-version = "1.0"
-features = ["spin_no_std"]
-
-[features]
-cvm_guest = ["dep:tdx-guest"]
diff --git a/kernel/aster-nix/Cargo.toml /dev/null
--- a/kernel/aster-nix/Cargo.toml
+++ /dev/null
@@ -1,81 +0,0 @@
-[package]
-name = "aster-nix"
-version = "0.1.0"
-edition = "2021"
-
-# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
-
-[dependencies]
-align_ext = { path = "../../ostd/libs/align_ext" }
-aster-input = { path = "../comps/input" }
-aster-block = { path = "../comps/block" }
-aster-network = { path = "../comps/network" }
-aster-console = { path = "../comps/console" }
-aster-time = { path = "../comps/time" }
-aster-virtio = { path = "../comps/virtio" }
-aster-rights = { path = "../libs/aster-rights" }
-controlled = { path = "../libs/comp-sys/controlled" }
-ostd = { path = "../../ostd" }
-typeflags = { path = "../libs/typeflags" }
-typeflags-util = { path = "../libs/typeflags-util" }
-aster-rights-proc = { path = "../libs/aster-rights-proc" }
-aster-util = { path = "../libs/aster-util" }
-id-alloc = { path = "../../ostd/libs/id-alloc" }
-int-to-c-enum = { path = "../libs/int-to-c-enum" }
-cpio-decoder = { path = "../libs/cpio-decoder" }
-ascii = { version = "1.1", default-features = false, features = ["alloc"] }
-intrusive-collections = "0.9.5"
-paste = "1.0"
-time = { version = "0.3", default-features = false, features = ["alloc"] }
-smoltcp = { git = "https://github.com/smoltcp-rs/smoltcp", rev = "dc08e0b", default-features = false, features = [
- "alloc",
- "log",
- "medium-ethernet",
- "medium-ip",
- "proto-dhcpv4",
- "proto-ipv4",
- "proto-igmp",
- "socket-icmp",
- "socket-udp",
- "socket-tcp",
- "socket-raw",
- "socket-dhcpv4",
-] }
-tdx-guest = { version = "0.1.7", optional = true }
-
-# parse elf file
-xmas-elf = "0.8.0"
-# goblin = {version= "0.5.3", default-features = false, features = ["elf64"]}
-# data-structures
-bitflags = "1.3"
-ringbuf = { version = "0.3.2", default-features = false, features = ["alloc"] }
-keyable-arc = { path = "../libs/keyable-arc" }
-# unzip initramfs
-libflate = { version = "2", default-features = false }
-core2 = { version = "0.4", default-features = false, features = ["alloc"] }
-lending-iterator = "0.1.7"
-spin = "0.9.4"
-vte = "0.10"
-lru = "0.12.3"
-log = "0.4"
-bitvec = { version = "1.0", default-features = false, features = ["alloc"] }
-hashbrown = "0.14"
-rand = { version = "0.8.5", default-features = false, features = [
- "small_rng",
- "std_rng",
-] }
-static_assertions = "1.1.0"
-inherit-methods-macro = { git = "https://github.com/asterinas/inherit-methods-macro", rev = "98f7e3e" }
-getset = "0.1.2"
-atomic = "0.6"
-bytemuck = "1.14.3"
-bytemuck_derive = "1.5.0"
-takeable = "0.2.2"
-cfg-if = "1.0"
-
-[dependencies.lazy_static]
-version = "1.0"
-features = ["spin_no_std"]
-
-[features]
-cvm_guest = ["dep:tdx-guest"]
diff --git a/kernel/aster-nix/src/lib.rs /dev/null
--- a/kernel/aster-nix/src/lib.rs
+++ /dev/null
@@ -1,154 +0,0 @@
-// SPDX-License-Identifier: MPL-2.0
-
-//! The std library of Asterinas.
-#![no_std]
-#![deny(unsafe_code)]
-#![allow(incomplete_features)]
-#![feature(btree_cursors)]
-#![feature(btree_extract_if)]
-#![feature(const_option)]
-#![feature(extend_one)]
-#![feature(fn_traits)]
-#![feature(format_args_nl)]
-#![feature(int_roundings)]
-#![feature(iter_repeat_n)]
-#![feature(let_chains)]
-#![feature(linked_list_remove)]
-#![feature(negative_impls)]
-#![feature(register_tool)]
-// FIXME: This feature is used to support vm capbility now as a work around.
-// Since this is an incomplete feature, use this feature is unsafe.
-// We should find a proper method to replace this feature with min_specialization, which is a sound feature.
-#![feature(specialization)]
-#![feature(step_trait)]
-#![feature(trait_alias)]
-#![feature(trait_upcasting)]
-#![feature(linked_list_retain)]
-#![register_tool(component_access_control)]
-
-use ostd::{
- arch::qemu::{exit_qemu, QemuExitCode},
- boot,
-};
-use process::Process;
-
-use crate::{
- prelude::*,
- thread::{
- kernel_thread::{KernelThreadExt, ThreadOptions},
- Thread,
- },
-};
-
-extern crate alloc;
-extern crate lru;
-#[macro_use]
-extern crate controlled;
-#[macro_use]
-extern crate getset;
-
-pub mod arch;
-pub mod console;
-pub mod context;
-pub mod cpu;
-pub mod device;
-pub mod driver;
-pub mod error;
-pub mod events;
-pub mod fs;
-pub mod ipc;
-pub mod net;
-pub mod prelude;
-mod process;
-mod sched;
-pub mod softirq_id;
-pub mod syscall;
-mod taskless;
-pub mod thread;
-pub mod time;
-mod util;
-pub(crate) mod vdso;
-pub mod vm;
-
-pub fn init() {
- util::random::init();
- driver::init();
- time::init();
- net::init();
- sched::init();
- fs::rootfs::init(boot::initramfs()).unwrap();
- device::init().unwrap();
- vdso::init();
- taskless::init();
- process::init();
-}
-
-fn init_thread() {
- println!(
- "[kernel] Spawn init thread, tid = {}",
- current_thread!().tid()
- );
- // Work queue should be initialized before interrupt is enabled,
- // in case any irq handler uses work queue as bottom half
- thread::work_queue::init();
- net::lazy_init();
- fs::lazy_init();
- ipc::init();
- // driver::pci::virtio::block::block_device_test();
- let thread = Thread::spawn_kernel_thread(ThreadOptions::new(|| {
- println!("[kernel] Hello world from kernel!");
- let current = current_thread!();
- let tid = current.tid();
- debug!("current tid = {}", tid);
- }));
- thread.join();
- info!(
- "[aster-nix/lib.rs] spawn kernel thread, tid = {}",
- thread.tid()
- );
-
- print_banner();
-
- let karg = boot::kernel_cmdline();
-
- let initproc = Process::spawn_user_process(
- karg.get_initproc_path().unwrap(),
- karg.get_initproc_argv().to_vec(),
- karg.get_initproc_envp().to_vec(),
- )
- .expect("Run init process failed.");
- // Wait till initproc become zombie.
- while !initproc.is_zombie() {
- // We don't have preemptive scheduler now.
- // The long running init thread should yield its own execution to allow other tasks to go on.
- Thread::yield_now();
- }
-
- // TODO: exit via qemu isa debug device should not be the only way.
- let exit_code = if initproc.exit_code().unwrap() == 0 {
- QemuExitCode::Success
- } else {
- QemuExitCode::Failed
- };
- exit_qemu(exit_code);
-}
-
-/// first process never return
-#[controlled]
-pub fn run_first_process() -> ! {
- Thread::spawn_kernel_thread(ThreadOptions::new(init_thread));
- unreachable!()
-}
-
-fn print_banner() {
- println!("\x1B[36m");
- println!(
- r"
- _ ___ _____ ___ ___ ___ _ _ _ ___
- /_\ / __|_ _| __| _ \_ _| \| | /_\ / __|
- / _ \\__ \ | | | _|| /| || .` |/ _ \\__ \
-/_/ \_\___/ |_| |___|_|_\___|_|\_/_/ \_\___/
-"
- );
- println!("\x1B[0m");
-}
diff --git a/kernel/libs/aster-util/src/coeff.rs b/kernel/libs/aster-util/src/coeff.rs
--- a/kernel/libs/aster-util/src/coeff.rs
+++ b/kernel/libs/aster-util/src/coeff.rs
@@ -134,8 +134,8 @@ mod test {
#[ktest]
fn calculation() {
let coeff = Coeff::new(23456, 56789, 1_000_000_000);
- assert!(coeff * 0 as u64 == 0);
- assert!(coeff * 100 as u64 == 100 * 23456 / 56789);
- assert!(coeff * 1_000_000_000 as u64 == 1_000_000_000 * 23456 / 56789);
+ assert!(coeff * 0_u64 == 0);
+ assert!(coeff * 100_u64 == 100 * 23456 / 56789);
+ assert!(coeff * 1_000_000_000_u64 == 1_000_000_000 * 23456 / 56789);
}
}
diff --git a/kernel/aster-nix/src/fs/exfat/mod.rs b/kernel/src/fs/exfat/mod.rs
--- a/kernel/aster-nix/src/fs/exfat/mod.rs
+++ b/kernel/src/fs/exfat/mod.rs
@@ -107,7 +107,7 @@ mod test {
}
}
/// Exfat disk image
- static EXFAT_IMAGE: &[u8] = include_bytes!("../../../../../test/build/exfat.img");
+ static EXFAT_IMAGE: &[u8] = include_bytes!("../../../../test/build/exfat.img");
/// Read exfat disk image
fn new_vm_segment_from_image() -> Segment {
diff --git a/kernel/aster-nix/src/fs/exfat/mod.rs b/kernel/src/fs/exfat/mod.rs
--- a/kernel/aster-nix/src/fs/exfat/mod.rs
+++ b/kernel/src/fs/exfat/mod.rs
@@ -484,7 +484,7 @@ mod test {
let mut read = vec![0u8; BUF_SIZE];
let read_after_rename = a_inode_new.read_bytes_at(0, &mut read);
assert!(
- read_after_rename.is_ok() && read_after_rename.clone().unwrap() == BUF_SIZE,
+ read_after_rename.is_ok() && read_after_rename.unwrap() == BUF_SIZE,
"Fail to read after rename: {:?}",
read_after_rename.unwrap_err()
);
diff --git a/kernel/aster-nix/src/fs/exfat/mod.rs b/kernel/src/fs/exfat/mod.rs
--- a/kernel/aster-nix/src/fs/exfat/mod.rs
+++ b/kernel/src/fs/exfat/mod.rs
@@ -495,8 +495,7 @@ mod test {
let new_buf = vec![7u8; NEW_BUF_SIZE];
let new_write_after_rename = a_inode_new.write_bytes_at(0, &new_buf);
assert!(
- new_write_after_rename.is_ok()
- && new_write_after_rename.clone().unwrap() == NEW_BUF_SIZE,
+ new_write_after_rename.is_ok() && new_write_after_rename.unwrap() == NEW_BUF_SIZE,
"Fail to write file after rename: {:?}",
new_write_after_rename.unwrap_err()
);
diff --git a/kernel/aster-nix/src/fs/exfat/mod.rs b/kernel/src/fs/exfat/mod.rs
--- a/kernel/aster-nix/src/fs/exfat/mod.rs
+++ b/kernel/src/fs/exfat/mod.rs
@@ -984,7 +983,7 @@ mod test {
let mut file_names: Vec<String> = (0..file_num).map(|x| x.to_string()).collect();
file_names.sort();
let mut file_inodes: Vec<Arc<dyn Inode>> = Vec::new();
- for (_file_id, file_name) in file_names.iter().enumerate() {
+ for file_name in file_names.iter() {
let inode = create_file(root.clone(), file_name);
file_inodes.push(inode);
}
diff --git a/kernel/aster-nix/src/fs/exfat/utils.rs b/kernel/src/fs/exfat/utils.rs
--- a/kernel/aster-nix/src/fs/exfat/utils.rs
+++ b/kernel/src/fs/exfat/utils.rs
@@ -60,7 +60,6 @@ impl DosTimestamp {
#[cfg(not(ktest))]
{
use crate::time::clocks::RealTimeClock;
-
DosTimestamp::from_duration(RealTimeClock::get().read_time())
}
diff --git a/kernel/aster-nix/src/fs/exfat/utils.rs b/kernel/src/fs/exfat/utils.rs
--- a/kernel/aster-nix/src/fs/exfat/utils.rs
+++ b/kernel/src/fs/exfat/utils.rs
@@ -68,9 +67,9 @@ impl DosTimestamp {
#[cfg(ktest)]
{
use crate::time::SystemTime;
- return DosTimestamp::from_duration(
+ DosTimestamp::from_duration(
SystemTime::UNIX_EPOCH.duration_since(&SystemTime::UNIX_EPOCH)?,
- );
+ )
}
}
diff --git a/kernel/aster-nix/src/fs/pipe.rs b/kernel/src/fs/pipe.rs
--- a/kernel/aster-nix/src/fs/pipe.rs
+++ b/kernel/src/fs/pipe.rs
@@ -331,7 +331,7 @@ mod test {
#[ktest]
fn test_read_closed() {
test_blocking(
- |writer| drop(writer),
+ drop,
|reader| {
let mut buf = [0; 1];
assert_eq!(reader.read(&mut writer_from(&mut buf)).unwrap(), 0);
diff --git a/kernel/aster-nix/src/fs/pipe.rs b/kernel/src/fs/pipe.rs
--- a/kernel/aster-nix/src/fs/pipe.rs
+++ b/kernel/src/fs/pipe.rs
@@ -350,7 +350,7 @@ mod test {
Errno::EPIPE
);
},
- |reader| drop(reader),
+ drop,
Ordering::WriteThenRead,
);
}
diff --git a/kernel/src/lib.rs b/kernel/src/lib.rs
--- a/kernel/src/lib.rs
+++ b/kernel/src/lib.rs
@@ -1,16 +1,161 @@
// SPDX-License-Identifier: MPL-2.0
+//! Aster-nix is the Asterinas kernel, a safe, efficient unix-like
+//! operating system kernel built on top of OSTD and OSDK.
+
#![no_std]
#![no_main]
#![deny(unsafe_code)]
-extern crate ostd;
+#![allow(incomplete_features)]
+#![feature(btree_cursors)]
+#![feature(btree_extract_if)]
+#![feature(const_option)]
+#![feature(extend_one)]
+#![feature(fn_traits)]
+#![feature(format_args_nl)]
+#![feature(int_roundings)]
+#![feature(iter_repeat_n)]
+#![feature(let_chains)]
+#![feature(linkage)]
+#![feature(linked_list_remove)]
+#![feature(negative_impls)]
+#![feature(register_tool)]
+// FIXME: This feature is used to support vm capbility now as a work around.
+// Since this is an incomplete feature, use this feature is unsafe.
+// We should find a proper method to replace this feature with min_specialization, which is a sound feature.
+#![feature(specialization)]
+#![feature(step_trait)]
+#![feature(trait_alias)]
+#![feature(trait_upcasting)]
+#![feature(linked_list_retain)]
+#![register_tool(component_access_control)]
+
+use ostd::{
+ arch::qemu::{exit_qemu, QemuExitCode},
+ boot,
+};
+use process::Process;
+
+use crate::{
+ prelude::*,
+ thread::{
+ kernel_thread::{KernelThreadExt, ThreadOptions},
+ Thread,
+ },
+};
+
+extern crate alloc;
+extern crate lru;
+#[macro_use]
+extern crate controlled;
+#[macro_use]
+extern crate getset;
-use ostd::prelude::*;
+pub mod arch;
+pub mod console;
+pub mod context;
+pub mod cpu;
+pub mod device;
+pub mod driver;
+pub mod error;
+pub mod events;
+pub mod fs;
+pub mod ipc;
+pub mod net;
+pub mod prelude;
+mod process;
+mod sched;
+pub mod softirq_id;
+pub mod syscall;
+mod taskless;
+pub mod thread;
+pub mod time;
+mod util;
+pub(crate) mod vdso;
+pub mod vm;
#[ostd::main]
+#[controlled]
pub fn main() {
- println!("[kernel] finish init ostd");
+ ostd::early_println!("[kernel] OSTD initialized. Preparing components.");
component::init_all(component::parse_metadata!()).unwrap();
- aster_nix::init();
- aster_nix::run_first_process();
+ init();
+ Thread::spawn_kernel_thread(ThreadOptions::new(init_thread));
+ unreachable!()
+}
+
+pub fn init() {
+ util::random::init();
+ driver::init();
+ time::init();
+ net::init();
+ sched::init();
+ fs::rootfs::init(boot::initramfs()).unwrap();
+ device::init().unwrap();
+ vdso::init();
+ taskless::init();
+ process::init();
+}
+
+fn init_thread() {
+ println!(
+ "[kernel] Spawn init thread, tid = {}",
+ current_thread!().tid()
+ );
+ // Work queue should be initialized before interrupt is enabled,
+ // in case any irq handler uses work queue as bottom half
+ thread::work_queue::init();
+ net::lazy_init();
+ fs::lazy_init();
+ ipc::init();
+ // driver::pci::virtio::block::block_device_test();
+ let thread = Thread::spawn_kernel_thread(ThreadOptions::new(|| {
+ println!("[kernel] Hello world from kernel!");
+ let current = current_thread!();
+ let tid = current.tid();
+ debug!("current tid = {}", tid);
+ }));
+ thread.join();
+ info!(
+ "[aster-nix/lib.rs] spawn kernel thread, tid = {}",
+ thread.tid()
+ );
+
+ print_banner();
+
+ let karg = boot::kernel_cmdline();
+
+ let initproc = Process::spawn_user_process(
+ karg.get_initproc_path().unwrap(),
+ karg.get_initproc_argv().to_vec(),
+ karg.get_initproc_envp().to_vec(),
+ )
+ .expect("Run init process failed.");
+ // Wait till initproc become zombie.
+ while !initproc.is_zombie() {
+ // We don't have preemptive scheduler now.
+ // The long running init thread should yield its own execution to allow other tasks to go on.
+ Thread::yield_now();
+ }
+
+ // TODO: exit via qemu isa debug device should not be the only way.
+ let exit_code = if initproc.exit_code().unwrap() == 0 {
+ QemuExitCode::Success
+ } else {
+ QemuExitCode::Failed
+ };
+ exit_qemu(exit_code);
+}
+
+fn print_banner() {
+ println!("\x1B[36m");
+ println!(
+ r"
+ _ ___ _____ ___ ___ ___ _ _ _ ___
+ /_\ / __|_ _| __| _ \_ _| \| | /_\ / __|
+ / _ \\__ \ | | | _|| /| || .` |/ _ \\__ \
+/_/ \_\___/ |_| |___|_|_\___|_|\_/_/ \_\___/
+"
+ );
+ println!("\x1B[0m");
}
diff --git a/kernel/aster-nix/src/process/sync/condvar.rs b/kernel/src/process/sync/condvar.rs
--- a/kernel/aster-nix/src/process/sync/condvar.rs
+++ b/kernel/src/process/sync/condvar.rs
@@ -291,7 +291,7 @@ mod test {
while !*started {
started = cvar.wait(started).unwrap_or_else(|err| err.into_guard());
}
- assert_eq!(*started, true);
+ assert!(*started);
}
}
diff --git a/kernel/aster-nix/src/process/sync/condvar.rs b/kernel/src/process/sync/condvar.rs
--- a/kernel/aster-nix/src/process/sync/condvar.rs
+++ b/kernel/src/process/sync/condvar.rs
@@ -316,7 +316,7 @@ mod test {
.wait_timeout(started, Duration::from_secs(1))
.unwrap_or_else(|err| err.into_guard());
}
- assert_eq!(*started, true);
+ assert!(*started);
}
}
diff --git a/kernel/aster-nix/src/process/sync/condvar.rs b/kernel/src/process/sync/condvar.rs
--- a/kernel/aster-nix/src/process/sync/condvar.rs
+++ b/kernel/src/process/sync/condvar.rs
@@ -338,7 +338,7 @@ mod test {
let started = cvar
.wait_while(lock.lock(), |started| *started)
.unwrap_or_else(|err| err.into_guard());
- assert_eq!(*started, false);
+ assert!(!*started);
}
}
diff --git a/kernel/aster-nix/src/process/sync/condvar.rs b/kernel/src/process/sync/condvar.rs
--- a/kernel/aster-nix/src/process/sync/condvar.rs
+++ b/kernel/src/process/sync/condvar.rs
@@ -360,7 +360,7 @@ mod test {
let (started, _) = cvar
.wait_timeout_while(lock.lock(), Duration::from_secs(1), |started| *started)
.unwrap_or_else(|err| err.into_guard());
- assert_eq!(*started, false);
+ assert!(!*started);
}
}
}
diff --git a/kernel/aster-nix/src/taskless.rs b/kernel/src/taskless.rs
--- a/kernel/aster-nix/src/taskless.rs
+++ b/kernel/src/taskless.rs
@@ -216,7 +216,7 @@ mod test {
let mut counter = 0;
// Schedule this taskless for `SCHEDULE_TIMES`.
- while taskless.is_scheduled.load(Ordering::Acquire) == false {
+ while !taskless.is_scheduled.load(Ordering::Acquire) {
taskless.schedule();
counter += 1;
if counter == SCHEDULE_TIMES {
diff --git a/kernel/aster-nix/src/taskless.rs b/kernel/src/taskless.rs
--- a/kernel/aster-nix/src/taskless.rs
+++ b/kernel/src/taskless.rs
@@ -227,7 +227,9 @@ mod test {
// Wait for all taskless having finished.
while taskless.is_running.load(Ordering::Acquire)
|| taskless.is_scheduled.load(Ordering::Acquire)
- {}
+ {
+ core::hint::spin_loop()
+ }
assert_eq!(counter, COUNTER.load(Ordering::Relaxed));
}
diff --git a/kernel/aster-nix/src/vm/vmar/options.rs b/kernel/src/vm/vmar/options.rs
--- a/kernel/aster-nix/src/vm/vmar/options.rs
+++ b/kernel/src/vm/vmar/options.rs
@@ -136,7 +136,7 @@ impl<R> VmarChildOptions<R> {
#[cfg(ktest)]
mod test {
use aster_rights::Full;
- use ostd::{mm::VmIo, prelude::*};
+ use ostd::prelude::*;
use super::*;
use crate::vm::{
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -146,7 +146,7 @@ dependencies = [
[[package]]
name = "cargo-osdk"
-version = "0.6.2"
+version = "0.7.0"
dependencies = [
"assert_cmd",
"clap",
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
--- a/osdk/Cargo.lock
+++ b/osdk/Cargo.lock
@@ -146,7 +146,7 @@ dependencies = [
[[package]]
name = "cargo-osdk"
-version = "0.6.2"
+version = "0.7.0"
dependencies = [
"assert_cmd",
"clap",
diff --git a/osdk/Cargo.toml b/osdk/Cargo.toml
--- a/osdk/Cargo.toml
+++ b/osdk/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "cargo-osdk"
-version = "0.7.0"
+version = "0.8.0"
edition = "2021"
description = "Accelerate OS development with Asterinas OSDK"
license = "MPL-2.0"
diff --git a/osdk/Cargo.toml b/osdk/Cargo.toml
--- a/osdk/Cargo.toml
+++ b/osdk/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "cargo-osdk"
-version = "0.7.0"
+version = "0.8.0"
edition = "2021"
description = "Accelerate OS development with Asterinas OSDK"
license = "MPL-2.0"
diff --git a/osdk/src/base_crate/mod.rs b/osdk/src/base_crate/mod.rs
--- a/osdk/src/base_crate/mod.rs
+++ b/osdk/src/base_crate/mod.rs
@@ -1,8 +1,7 @@
// SPDX-License-Identifier: MPL-2.0
//! The base crate is the OSDK generated crate that is ultimately built by cargo.
-//! It will depend on the kernel crate.
-//!
+//! It will depend on the to-be-built kernel crate or the to-be-tested crate.
use std::{
fs,
diff --git a/osdk/src/base_crate/mod.rs b/osdk/src/base_crate/mod.rs
--- a/osdk/src/base_crate/mod.rs
+++ b/osdk/src/base_crate/mod.rs
@@ -12,10 +11,16 @@ use std::{
use crate::util::get_cargo_metadata;
+/// Create a new base crate that will be built by cargo.
+///
+/// The dependencies of the base crate will be the target crate. If
+/// `link_unit_test_runner` is set to true, the base crate will also depend on
+/// the `ostd-test-runner` crate.
pub fn new_base_crate(
base_crate_path: impl AsRef<Path>,
dep_crate_name: &str,
dep_crate_path: impl AsRef<Path>,
+ link_unit_test_runner: bool,
) {
let workspace_root = {
let meta = get_cargo_metadata(None::<&str>, None::<&[&str]>).unwrap();
diff --git a/osdk/src/base_crate/mod.rs b/osdk/src/base_crate/mod.rs
--- a/osdk/src/base_crate/mod.rs
+++ b/osdk/src/base_crate/mod.rs
@@ -82,7 +87,7 @@ pub fn new_base_crate(
fs::write("src/main.rs", main_rs).unwrap();
// Add dependencies to the Cargo.toml
- add_manifest_dependency(dep_crate_name, dep_crate_path);
+ add_manifest_dependency(dep_crate_name, dep_crate_path, link_unit_test_runner);
// Copy the manifest configurations from the target crate to the base crate
copy_profile_configurations(workspace_root);
diff --git a/osdk/src/base_crate/mod.rs b/osdk/src/base_crate/mod.rs
--- a/osdk/src/base_crate/mod.rs
+++ b/osdk/src/base_crate/mod.rs
@@ -94,7 +99,11 @@ pub fn new_base_crate(
std::env::set_current_dir(original_dir).unwrap();
}
-fn add_manifest_dependency(crate_name: &str, crate_path: impl AsRef<Path>) {
+fn add_manifest_dependency(
+ crate_name: &str,
+ crate_path: impl AsRef<Path>,
+ link_unit_test_runner: bool,
+) {
let mainfest_path = "Cargo.toml";
let mut manifest: toml::Table = {
diff --git a/osdk/src/base_crate/mod.rs b/osdk/src/base_crate/mod.rs
--- a/osdk/src/base_crate/mod.rs
+++ b/osdk/src/base_crate/mod.rs
@@ -112,13 +121,26 @@ fn add_manifest_dependency(crate_name: &str, crate_path: impl AsRef<Path>) {
let dependencies = manifest.get_mut("dependencies").unwrap();
- let dep = toml::Table::from_str(&format!(
+ let target_dep = toml::Table::from_str(&format!(
"{} = {{ path = \"{}\", default-features = false }}",
crate_name,
crate_path.as_ref().display()
))
.unwrap();
- dependencies.as_table_mut().unwrap().extend(dep);
+ dependencies.as_table_mut().unwrap().extend(target_dep);
+
+ if link_unit_test_runner {
+ let dep_str = match option_env!("OSDK_LOCAL_DEV") {
+ Some("1") => "osdk-test-kernel = { path = \"../../../osdk/test-kernel\" }",
+ _ => concat!(
+ "osdk-test-kernel = { version = \"",
+ env!("CARGO_PKG_VERSION"),
+ "\" }"
+ ),
+ };
+ let test_runner_dep = toml::Table::from_str(dep_str).unwrap();
+ dependencies.as_table_mut().unwrap().extend(test_runner_dep);
+ }
let content = toml::to_string(&manifest).unwrap();
fs::write(mainfest_path, content).unwrap();
diff --git a/osdk/src/cli.rs b/osdk/src/cli.rs
--- a/osdk/src/cli.rs
+++ b/osdk/src/cli.rs
@@ -49,9 +49,9 @@ pub fn main() {
OsdkSubcommand::Test(test_args) => {
execute_test_command(&load_config(&test_args.common_args), test_args);
}
- OsdkSubcommand::Check(args) => execute_forwarded_command("check", &args.args),
- OsdkSubcommand::Clippy(args) => execute_forwarded_command("clippy", &args.args),
- OsdkSubcommand::Doc(args) => execute_forwarded_command("doc", &args.args),
+ OsdkSubcommand::Check(args) => execute_forwarded_command("check", &args.args, true),
+ OsdkSubcommand::Clippy(args) => execute_forwarded_command("clippy", &args.args, true),
+ OsdkSubcommand::Doc(args) => execute_forwarded_command("doc", &args.args, false),
}
}
diff --git a/osdk/src/commands/build/bin.rs b/osdk/src/commands/build/bin.rs
--- a/osdk/src/commands/build/bin.rs
+++ b/osdk/src/commands/build/bin.rs
@@ -171,7 +171,7 @@ fn install_setup_with_arch(
cmd.arg("install").arg("linux-bzimage-setup");
cmd.arg("--force");
cmd.arg("--root").arg(install_dir.as_ref());
- if std::env::var("AUTO_TEST").is_ok() || std::env::var("OSDK_INTEGRATION_TEST").is_ok() {
+ if matches!(option_env!("OSDK_LOCAL_DEV"), Some("1")) {
cmd.arg("--path")
.arg("../../../ostd/libs/linux-bzimage/setup");
}
diff --git a/osdk/src/commands/build/bin.rs b/osdk/src/commands/build/bin.rs
--- a/osdk/src/commands/build/bin.rs
+++ b/osdk/src/commands/build/bin.rs
@@ -171,7 +171,7 @@ fn install_setup_with_arch(
cmd.arg("install").arg("linux-bzimage-setup");
cmd.arg("--force");
cmd.arg("--root").arg(install_dir.as_ref());
- if std::env::var("AUTO_TEST").is_ok() || std::env::var("OSDK_INTEGRATION_TEST").is_ok() {
+ if matches!(option_env!("OSDK_LOCAL_DEV"), Some("1")) {
cmd.arg("--path")
.arg("../../../ostd/libs/linux-bzimage/setup");
}
diff --git a/osdk/src/commands/build/mod.rs b/osdk/src/commands/build/mod.rs
--- a/osdk/src/commands/build/mod.rs
+++ b/osdk/src/commands/build/mod.rs
@@ -72,6 +72,7 @@ pub fn create_base_and_cached_build(
&base_crate_path,
&get_current_crate_info().name,
get_current_crate_info().path,
+ false,
);
let original_dir = std::env::current_dir().unwrap();
std::env::set_current_dir(&base_crate_path).unwrap();
diff --git a/osdk/src/commands/build/mod.rs b/osdk/src/commands/build/mod.rs
--- a/osdk/src/commands/build/mod.rs
+++ b/osdk/src/commands/build/mod.rs
@@ -72,6 +72,7 @@ pub fn create_base_and_cached_build(
&base_crate_path,
&get_current_crate_info().name,
get_current_crate_info().path,
+ false,
);
let original_dir = std::env::current_dir().unwrap();
std::env::set_current_dir(&base_crate_path).unwrap();
diff --git a/osdk/src/commands/mod.rs b/osdk/src/commands/mod.rs
--- a/osdk/src/commands/mod.rs
+++ b/osdk/src/commands/mod.rs
@@ -16,8 +16,10 @@ pub use self::{
use crate::arch::get_default_arch;
-/// Execute the forwarded cargo command with args containing the subcommand and its arguments.
-pub fn execute_forwarded_command(subcommand: &str, args: &Vec<String>) -> ! {
+/// Execute the forwarded cargo command with arguments.
+///
+/// The `cfg_ktest` parameter controls whether `cfg(ktest)` is enabled.
+pub fn execute_forwarded_command(subcommand: &str, args: &Vec<String>, cfg_ktest: bool) -> ! {
let mut cargo = util::cargo();
cargo.arg(subcommand).args(util::COMMON_CARGO_ARGS);
if !args.contains(&"--target".to_owned()) {
diff --git a/osdk/src/commands/mod.rs b/osdk/src/commands/mod.rs
--- a/osdk/src/commands/mod.rs
+++ b/osdk/src/commands/mod.rs
@@ -27,6 +29,11 @@ pub fn execute_forwarded_command(subcommand: &str, args: &Vec<String>) -> ! {
let env_rustflags = std::env::var("RUSTFLAGS").unwrap_or_default();
let rustflags = env_rustflags + " --check-cfg cfg(ktest)";
+ let rustflags = if cfg_ktest {
+ rustflags + " --cfg ktest"
+ } else {
+ rustflags
+ };
cargo.env("RUSTFLAGS", rustflags);
diff --git a/osdk/src/commands/new/kernel.template b/osdk/src/commands/new/kernel.template
--- a/osdk/src/commands/new/kernel.template
+++ b/osdk/src/commands/new/kernel.template
@@ -1,4 +1,6 @@
#![no_std]
+// The feature `linkage` is required for `ostd::main` to work.
+#![feature(linkage)]
#![deny(unsafe_code)]
use ostd::prelude::*;
diff --git a/osdk/src/commands/new/kernel.template b/osdk/src/commands/new/kernel.template
--- a/osdk/src/commands/new/kernel.template
+++ b/osdk/src/commands/new/kernel.template
@@ -1,4 +1,6 @@
#![no_std]
+// The feature `linkage` is required for `ostd::main` to work.
+#![feature(linkage)]
#![deny(unsafe_code)]
use ostd::prelude::*;
diff --git a/osdk/src/commands/test.rs b/osdk/src/commands/test.rs
--- a/osdk/src/commands/test.rs
+++ b/osdk/src/commands/test.rs
@@ -7,6 +7,8 @@ use crate::{
base_crate::new_base_crate,
cli::TestArgs,
config::{scheme::ActionChoice, Config},
+ error::Errno,
+ error_msg,
util::{
get_cargo_metadata, get_current_crate_info, get_target_directory, parse_package_id_string,
},
diff --git a/osdk/src/commands/test.rs b/osdk/src/commands/test.rs
--- a/osdk/src/commands/test.rs
+++ b/osdk/src/commands/test.rs
@@ -25,7 +27,26 @@ pub fn test_current_crate(config: &Config, args: &TestArgs) {
let cargo_target_directory = get_target_directory();
let osdk_output_directory = cargo_target_directory.join(DEFAULT_TARGET_RELPATH);
let target_crate_dir = osdk_output_directory.join("base");
- new_base_crate(&target_crate_dir, ¤t_crate.name, ¤t_crate.path);
+
+ // A special case is that we use OSDK to test the OSDK test runner crate
+ // itself. We check it by name.
+ let runner_self_test = if current_crate.name == "osdk-test-kernel" {
+ if matches!(option_env!("OSDK_LOCAL_DEV"), Some("1")) {
+ true
+ } else {
+ error_msg!("The tested crate name collides with the OSDK test runner crate");
+ std::process::exit(Errno::BadCrateName as _);
+ }
+ } else {
+ false
+ };
+
+ new_base_crate(
+ &target_crate_dir,
+ ¤t_crate.name,
+ ¤t_crate.path,
+ !runner_self_test,
+ );
let main_rs_path = target_crate_dir.join("src").join("main.rs");
diff --git a/osdk/src/commands/test.rs b/osdk/src/commands/test.rs
--- a/osdk/src/commands/test.rs
+++ b/osdk/src/commands/test.rs
@@ -39,19 +60,29 @@ pub fn test_current_crate(config: &Config, args: &TestArgs) {
ktest_crate_whitelist.push(name.clone());
}
- let ktest_static_var = format!(
+ // Append the ktest static variable and the runner reference to the
+ // `main.rs` file.
+ let ktest_main_rs = format!(
r#"
+
+{}
+
#[no_mangle]
pub static KTEST_TEST_WHITELIST: Option<&[&str]> = {};
#[no_mangle]
pub static KTEST_CRATE_WHITELIST: Option<&[&str]> = Some(&{:#?});
+
"#,
- ktest_test_whitelist, ktest_crate_whitelist,
+ if runner_self_test {
+ ""
+ } else {
+ "extern crate osdk_test_kernel;"
+ },
+ ktest_test_whitelist,
+ ktest_crate_whitelist,
);
-
- // Append the ktest static variable to the main.rs file
let mut main_rs_content = fs::read_to_string(&main_rs_path).unwrap();
- main_rs_content.push_str(&ktest_static_var);
+ main_rs_content.push_str(&ktest_main_rs);
fs::write(&main_rs_path, main_rs_content).unwrap();
// Build the kernel with the given base crate
diff --git a/osdk/src/config/manifest.rs b/osdk/src/config/manifest.rs
--- a/osdk/src/config/manifest.rs
+++ b/osdk/src/config/manifest.rs
@@ -50,60 +50,33 @@ impl TomlManifest {
.unwrap(),
)
};
- // All the custom schemes should inherit settings from the default scheme, this is a helper.
- fn finalize(current_manifest: Option<TomlManifest>) -> TomlManifest {
- let Some(mut current_manifest) = current_manifest else {
- error_msg!(
- "Cannot find `OSDK.toml` in the current directory or the workspace root"
- );
- process::exit(Errno::GetMetadata as _);
- };
- for scheme in current_manifest.map.values_mut() {
- scheme.inherit(¤t_manifest.default_scheme);
- }
- current_manifest
- }
// Search for OSDK.toml in the current directory first.
- let current_manifest_path = PathBuf::from("OSDK.toml").canonicalize().ok();
- let mut current_manifest = match ¤t_manifest_path {
- Some(path) => deserialize_toml_manifest(path),
- None => None,
- };
- // Then search in the workspace root.
- let workspace_manifest_path = workspace_root.join("OSDK.toml").canonicalize().ok();
- // The case that the current directory is also the workspace root.
- if let Some(current) = ¤t_manifest_path {
- if let Some(workspace) = &workspace_manifest_path {
- if current == workspace {
- return finalize(current_manifest);
+ let current_manifest_path = PathBuf::from("OSDK.toml").canonicalize();
+ let current_manifest = match ¤t_manifest_path {
+ Ok(path) => deserialize_toml_manifest(path),
+ Err(_) => {
+ // If not found, search in the workspace root.
+ if let Ok(workspace_manifest_path) = workspace_root.join("OSDK.toml").canonicalize()
+ {
+ deserialize_toml_manifest(workspace_manifest_path)
+ } else {
+ None
}
}
- }
- let workspace_manifest = match workspace_manifest_path {
- Some(path) => deserialize_toml_manifest(path),
- None => None,
};
- // The current manifest should inherit settings from the workspace manifest.
- if let Some(workspace_manifest) = workspace_manifest {
- if current_manifest.is_none() {
- current_manifest = Some(workspace_manifest);
- } else {
- // Inherit one scheme at a time.
- let current_manifest = current_manifest.as_mut().unwrap();
- current_manifest
- .default_scheme
- .inherit(&workspace_manifest.default_scheme);
- for (scheme_string, scheme) in workspace_manifest.map {
- let current_scheme = current_manifest
- .map
- .entry(scheme_string)
- .or_insert_with(Scheme::empty);
- current_scheme.inherit(&scheme);
- }
- }
+
+ let Some(mut current_manifest) = current_manifest else {
+ error_msg!("Cannot find `OSDK.toml` in the current directory or the workspace root");
+ process::exit(Errno::GetMetadata as _);
+ };
+
+ // All the schemes should inherit from the default scheme.
+ for scheme in current_manifest.map.values_mut() {
+ scheme.inherit(¤t_manifest.default_scheme);
}
- finalize(current_manifest)
+
+ current_manifest
}
/// Get the scheme given the scheme from the command line arguments.
diff --git a/osdk/src/config/manifest.rs b/osdk/src/config/manifest.rs
--- a/osdk/src/config/manifest.rs
+++ b/osdk/src/config/manifest.rs
@@ -50,60 +50,33 @@ impl TomlManifest {
.unwrap(),
)
};
- // All the custom schemes should inherit settings from the default scheme, this is a helper.
- fn finalize(current_manifest: Option<TomlManifest>) -> TomlManifest {
- let Some(mut current_manifest) = current_manifest else {
- error_msg!(
- "Cannot find `OSDK.toml` in the current directory or the workspace root"
- );
- process::exit(Errno::GetMetadata as _);
- };
- for scheme in current_manifest.map.values_mut() {
- scheme.inherit(¤t_manifest.default_scheme);
- }
- current_manifest
- }
// Search for OSDK.toml in the current directory first.
- let current_manifest_path = PathBuf::from("OSDK.toml").canonicalize().ok();
- let mut current_manifest = match ¤t_manifest_path {
- Some(path) => deserialize_toml_manifest(path),
- None => None,
- };
- // Then search in the workspace root.
- let workspace_manifest_path = workspace_root.join("OSDK.toml").canonicalize().ok();
- // The case that the current directory is also the workspace root.
- if let Some(current) = ¤t_manifest_path {
- if let Some(workspace) = &workspace_manifest_path {
- if current == workspace {
- return finalize(current_manifest);
+ let current_manifest_path = PathBuf::from("OSDK.toml").canonicalize();
+ let current_manifest = match ¤t_manifest_path {
+ Ok(path) => deserialize_toml_manifest(path),
+ Err(_) => {
+ // If not found, search in the workspace root.
+ if let Ok(workspace_manifest_path) = workspace_root.join("OSDK.toml").canonicalize()
+ {
+ deserialize_toml_manifest(workspace_manifest_path)
+ } else {
+ None
}
}
- }
- let workspace_manifest = match workspace_manifest_path {
- Some(path) => deserialize_toml_manifest(path),
- None => None,
};
- // The current manifest should inherit settings from the workspace manifest.
- if let Some(workspace_manifest) = workspace_manifest {
- if current_manifest.is_none() {
- current_manifest = Some(workspace_manifest);
- } else {
- // Inherit one scheme at a time.
- let current_manifest = current_manifest.as_mut().unwrap();
- current_manifest
- .default_scheme
- .inherit(&workspace_manifest.default_scheme);
- for (scheme_string, scheme) in workspace_manifest.map {
- let current_scheme = current_manifest
- .map
- .entry(scheme_string)
- .or_insert_with(Scheme::empty);
- current_scheme.inherit(&scheme);
- }
- }
+
+ let Some(mut current_manifest) = current_manifest else {
+ error_msg!("Cannot find `OSDK.toml` in the current directory or the workspace root");
+ process::exit(Errno::GetMetadata as _);
+ };
+
+ // All the schemes should inherit from the default scheme.
+ for scheme in current_manifest.map.values_mut() {
+ scheme.inherit(¤t_manifest.default_scheme);
}
- finalize(current_manifest)
+
+ current_manifest
}
/// Get the scheme given the scheme from the command line arguments.
diff --git a/osdk/src/error.rs b/osdk/src/error.rs
--- a/osdk/src/error.rs
+++ b/osdk/src/error.rs
@@ -10,6 +10,7 @@ pub enum Errno {
ExecuteCommand = 5,
BuildCrate = 6,
RunBundle = 7,
+ BadCrateName = 8,
}
/// Print error message to console
diff --git a/osdk/src/error.rs b/osdk/src/error.rs
--- a/osdk/src/error.rs
+++ b/osdk/src/error.rs
@@ -10,6 +10,7 @@ pub enum Errno {
ExecuteCommand = 5,
BuildCrate = 6,
RunBundle = 7,
+ BadCrateName = 8,
}
/// Print error message to console
diff --git /dev/null b/osdk/test-kernel/Cargo.toml
new file mode 100644
--- /dev/null
+++ b/osdk/test-kernel/Cargo.toml
@@ -0,0 +1,14 @@
+[package]
+name = "osdk-test-kernel"
+version = "0.8.0"
+edition = "2021"
+description = "The OSTD-based kernel for running unit tests with OSDK."
+license = "MPL-2.0"
+repository ="https://github.com/asterinas/asterinas"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+ostd = { version = "0.8.0", path = "../../ostd" }
+owo-colors = "4.0.0"
+unwinding = { version = "0.2.2", default-features = false, features = ["fde-gnu-eh-frame-hdr", "hide-trace", "panic", "personality", "unwinder"] }
diff --git a/ostd/libs/ostd-test/src/runner.rs b/osdk/test-kernel/src/lib.rs
--- a/ostd/libs/ostd-test/src/runner.rs
+++ b/osdk/test-kernel/src/lib.rs
@@ -1,24 +1,59 @@
// SPDX-License-Identifier: MPL-2.0
-//! Test runner enabling control over the tests.
-//!
+//! The OSTD unit test runner is a kernel that runs the tests defined by the
+//! `#[ostd::ktest]` attribute. The kernel should be automatically selected to
+//! run when OSDK is used to test a specific crate.
-use alloc::{collections::BTreeSet, string::String, vec::Vec};
-use core::format_args;
+#![no_std]
+#![forbid(unsafe_code)]
-use owo_colors::OwoColorize;
+extern crate alloc;
+
+mod path;
+mod tree;
+
+use alloc::{boxed::Box, collections::BTreeSet, string::String, vec::Vec};
+use core::{any::Any, format_args};
-use crate::{
- path::{KtestPath, SuffixTrie},
- tree::{KtestCrate, KtestTree},
- CatchUnwindImpl, KtestError, KtestItem, KtestIter,
+use ostd::{
+ early_print,
+ ktest::{
+ get_ktest_crate_whitelist, get_ktest_test_whitelist, KtestError, KtestItem, KtestIter,
+ },
};
+use owo_colors::OwoColorize;
+use path::{KtestPath, SuffixTrie};
+use tree::{KtestCrate, KtestTree};
pub enum KtestResult {
Ok,
Failed,
}
+/// The entry point of the test runner.
+#[ostd::ktest::main]
+fn main() {
+ use ostd::task::TaskOptions;
+
+ let test_task = move || {
+ use alloc::string::ToString;
+
+ use ostd::arch::qemu::{exit_qemu, QemuExitCode};
+
+ match run_ktests(
+ get_ktest_test_whitelist().map(|s| s.iter().map(|s| s.to_string())),
+ get_ktest_crate_whitelist(),
+ ) {
+ KtestResult::Ok => exit_qemu(QemuExitCode::Success),
+ KtestResult::Failed => exit_qemu(QemuExitCode::Failed),
+ };
+ };
+
+ let _ = TaskOptions::new(test_task).data(()).spawn();
+
+ unreachable!("The spawn method will NOT return in the boot context")
+}
+
/// Run all the tests registered by `#[ktest]` in the `.ktest_array` section.
///
/// Need to provide a print function `print` to print the test result, and a `catch_unwind`
diff --git a/ostd/libs/ostd-test/src/runner.rs b/osdk/test-kernel/src/lib.rs
--- a/ostd/libs/ostd-test/src/runner.rs
+++ b/osdk/test-kernel/src/lib.rs
@@ -32,27 +67,18 @@ pub enum KtestResult {
///
/// If a test inside a crate fails, the test runner will continue to run the rest of the tests
/// inside the crate. But the tests in the following crates will not be run.
-pub fn run_ktests<PrintFn, PathsIter>(
- print: &PrintFn,
- catch_unwind: &CatchUnwindImpl,
+fn run_ktests<PathsIter>(
test_whitelist: Option<PathsIter>,
crate_whitelist: Option<&[&str]>,
) -> KtestResult
where
- PrintFn: Fn(core::fmt::Arguments),
PathsIter: Iterator<Item = String>,
{
- macro_rules! print {
- ($fmt: literal $(, $($arg: tt)+)?) => {
- print(format_args!($fmt $(, $($arg)+)?))
- }
- }
-
let whitelist_trie =
test_whitelist.map(|paths| SuffixTrie::from_paths(paths.map(|p| KtestPath::from(&p))));
let tree = KtestTree::from_iter(KtestIter::new());
- print!(
+ early_print!(
"\n[ktest runner] running {} tests in {} crates\n",
tree.nr_tot_tests(),
tree.nr_tot_crates()
diff --git a/ostd/libs/ostd-test/src/runner.rs b/osdk/test-kernel/src/lib.rs
--- a/ostd/libs/ostd-test/src/runner.rs
+++ b/osdk/test-kernel/src/lib.rs
@@ -62,36 +88,22 @@ where
for crate_ in tree.iter() {
if let Some(crate_set) = &crate_set {
if !crate_set.contains(crate_.name()) {
- print!("\n[ktest runner] skipping crate \"{}\".\n", crate_.name());
+ early_print!("\n[ktest runner] skipping crate \"{}\".\n", crate_.name());
continue;
}
}
- match run_crate_ktests(crate_, print, catch_unwind, &whitelist_trie) {
+ match run_crate_ktests(crate_, &whitelist_trie) {
KtestResult::Ok => {}
KtestResult::Failed => return KtestResult::Failed,
}
}
- print!("\n[ktest runner] All crates tested.\n");
+ early_print!("\n[ktest runner] All crates tested.\n");
KtestResult::Ok
}
-fn run_crate_ktests<PrintFn>(
- crate_: &KtestCrate,
- print: &PrintFn,
- catch_unwind: &CatchUnwindImpl,
- whitelist: &Option<SuffixTrie>,
-) -> KtestResult
-where
- PrintFn: Fn(core::fmt::Arguments),
-{
- macro_rules! print {
- ($fmt: literal $(, $($arg: tt)+)?) => {
- print(format_args!($fmt $(, $($arg)+)?))
- }
- }
-
+fn run_crate_ktests(crate_: &KtestCrate, whitelist: &Option<SuffixTrie>) -> KtestResult {
let crate_name = crate_.name();
- print!(
+ early_print!(
"\nrunning {} tests in crate \"{}\"\n\n",
crate_.nr_tot_tests(),
crate_name
diff --git a/ostd/libs/ostd-test/src/runner.rs b/osdk/test-kernel/src/lib.rs
--- a/ostd/libs/ostd-test/src/runner.rs
+++ b/osdk/test-kernel/src/lib.rs
@@ -110,19 +122,22 @@ where
continue;
}
}
- print!(
+ early_print!(
"test {}::{} ...",
test.info().module_path,
test.info().fn_name
);
debug_assert_eq!(test.info().package, crate_name);
- match test.run(catch_unwind) {
+ match test.run(
+ &(unwinding::panic::catch_unwind::<(), fn()>
+ as fn(fn()) -> Result<(), Box<(dyn Any + Send + 'static)>>),
+ ) {
Ok(()) => {
- print!(" {}\n", "ok".green());
+ early_print!(" {}\n", "ok".green());
passed += 1;
}
Err(e) => {
- print!(" {}\n", "FAILED".red());
+ early_print!(" {}\n", "FAILED".red());
failed_tests.push((test.clone(), e.clone()));
}
}
diff --git a/ostd/libs/ostd-test/src/runner.rs b/osdk/test-kernel/src/lib.rs
--- a/ostd/libs/ostd-test/src/runner.rs
+++ b/osdk/test-kernel/src/lib.rs
@@ -130,19 +145,21 @@ where
}
let failed = failed_tests.len();
if failed == 0 {
- print!("\ntest result: {}.", "ok".green());
+ early_print!("\ntest result: {}.", "ok".green());
} else {
- print!("\ntest result: {}.", "FAILED".red());
+ early_print!("\ntest result: {}.", "FAILED".red());
}
- print!(
+ early_print!(
" {} passed; {} failed; {} filtered out.\n",
- passed, failed, filtered
+ passed,
+ failed,
+ filtered
);
assert!(passed + failed + filtered == crate_.nr_tot_tests());
if failed > 0 {
- print!("\nfailures:\n\n");
+ early_print!("\nfailures:\n\n");
for (t, e) in failed_tests {
- print!(
+ early_print!(
"---- {}:{}:{} - {} ----\n\n",
t.info().source,
t.info().line,
diff --git a/ostd/libs/ostd-test/src/runner.rs b/osdk/test-kernel/src/lib.rs
--- a/ostd/libs/ostd-test/src/runner.rs
+++ b/osdk/test-kernel/src/lib.rs
@@ -151,18 +168,18 @@ where
);
match e {
KtestError::Panic(s) => {
- print!("[caught panic] {}\n", s);
+ early_print!("[caught panic] {}\n", s);
}
KtestError::ShouldPanicButNoPanic => {
- print!("test did not panic as expected\n");
+ early_print!("test did not panic as expected\n");
}
KtestError::ExpectedPanicNotMatch(expected, s) => {
- print!("[caught panic] expected panic not match\n");
- print!("expected: {}\n", expected);
- print!("caught: {}\n", s);
+ early_print!("[caught panic] expected panic not match\n");
+ early_print!("expected: {}\n", expected);
+ early_print!("caught: {}\n", s);
}
KtestError::Unknown => {
- print!("[caught panic] unknown panic payload! (fatal panic handling error in ktest)\n");
+ early_print!("[caught panic] unknown panic payload! (fatal panic handling error in ktest)\n");
}
}
}
diff --git a/ostd/libs/ostd-test/src/path.rs b/osdk/test-kernel/src/path.rs
--- a/ostd/libs/ostd-test/src/path.rs
+++ b/osdk/test-kernel/src/path.rs
@@ -112,11 +112,13 @@ impl Display for KtestPath {
}
}
-#[cfg(test)]
+#[cfg(ktest)]
mod path_test {
+ use ostd::prelude::ktest;
+
use super::*;
- #[test]
+ #[ktest]
fn test_ktest_path() {
let mut path = KtestPath::new();
path.push_back("a");
diff --git a/ostd/libs/ostd-test/src/path.rs b/osdk/test-kernel/src/path.rs
--- a/ostd/libs/ostd-test/src/path.rs
+++ b/osdk/test-kernel/src/path.rs
@@ -129,7 +131,7 @@ mod path_test {
assert_eq!(path.pop_back(), None);
}
- #[test]
+ #[ktest]
fn test_ktest_path_starts_with() {
let mut path = KtestPath::new();
path.push_back("a");
diff --git a/ostd/libs/ostd-test/src/path.rs b/osdk/test-kernel/src/path.rs
--- a/ostd/libs/ostd-test/src/path.rs
+++ b/osdk/test-kernel/src/path.rs
@@ -144,7 +146,7 @@ mod path_test {
assert!(!path.starts_with(&KtestPath::from("d")));
}
- #[test]
+ #[ktest]
fn test_ktest_path_ends_with() {
let mut path = KtestPath::new();
path.push_back("a");
diff --git a/ostd/libs/ostd-test/src/path.rs b/osdk/test-kernel/src/path.rs
--- a/ostd/libs/ostd-test/src/path.rs
+++ b/osdk/test-kernel/src/path.rs
@@ -238,8 +240,10 @@ impl Default for SuffixTrie {
}
}
-#[cfg(test)]
+#[cfg(ktest)]
mod suffix_trie_test {
+ use ostd::prelude::ktest;
+
use super::*;
static TEST_PATHS: &[&str] = &[
diff --git a/ostd/libs/ostd-test/src/path.rs b/osdk/test-kernel/src/path.rs
--- a/ostd/libs/ostd-test/src/path.rs
+++ b/osdk/test-kernel/src/path.rs
@@ -252,7 +256,7 @@ mod suffix_trie_test {
"m::n",
];
- #[test]
+ #[ktest]
fn test_contains() {
let trie = SuffixTrie::from_paths(TEST_PATHS.iter().map(|&s| KtestPath::from(s)));
diff --git a/ostd/libs/ostd-test/src/path.rs b/osdk/test-kernel/src/path.rs
--- a/ostd/libs/ostd-test/src/path.rs
+++ b/osdk/test-kernel/src/path.rs
@@ -269,7 +273,7 @@ mod suffix_trie_test {
assert!(!trie.contains(KtestPath::from("n").iter()));
}
- #[test]
+ #[ktest]
fn test_matches() {
let trie = SuffixTrie::from_paths(TEST_PATHS.iter().map(|&s| KtestPath::from(s)));
diff --git a/ostd/libs/ostd-test/src/tree.rs b/osdk/test-kernel/src/tree.rs
--- a/ostd/libs/ostd-test/src/tree.rs
+++ b/osdk/test-kernel/src/tree.rs
@@ -213,21 +213,21 @@ impl<'a> Iterator for KtestModuleIter<'a> {
}
}
-#[cfg(test)]
+#[cfg(ktest)]
mod tests {
+ use ostd::prelude::ktest;
+
use super::*;
macro_rules! gen_test_case {
() => {{
- fn dummy_fn() {
- ()
- }
+ fn dummy_fn() {}
let mut tree = KtestTree::new();
let new = |m: &'static str, f: &'static str, p: &'static str| {
KtestItem::new(
dummy_fn,
(false, None),
- crate::KtestItemInfo {
+ ostd::ktest::KtestItemInfo {
module_path: m,
fn_name: f,
package: p,
diff --git a/ostd/libs/ostd-test/src/tree.rs b/osdk/test-kernel/src/tree.rs
--- a/ostd/libs/ostd-test/src/tree.rs
+++ b/osdk/test-kernel/src/tree.rs
@@ -250,7 +250,7 @@ mod tests {
}};
}
- #[test]
+ #[ktest]
fn test_tree_iter() {
let tree = gen_test_case!();
let mut iter = tree.iter();
diff --git a/ostd/libs/ostd-test/src/tree.rs b/osdk/test-kernel/src/tree.rs
--- a/ostd/libs/ostd-test/src/tree.rs
+++ b/osdk/test-kernel/src/tree.rs
@@ -261,7 +261,7 @@ mod tests {
assert!(iter.next().is_none());
}
- #[test]
+ #[ktest]
fn test_crate_iter() {
let tree = gen_test_case!();
for crate_ in tree.iter() {
diff --git a/ostd/libs/ostd-test/src/tree.rs b/osdk/test-kernel/src/tree.rs
--- a/ostd/libs/ostd-test/src/tree.rs
+++ b/osdk/test-kernel/src/tree.rs
@@ -285,7 +285,7 @@ mod tests {
}
}
- #[test]
+ #[ktest]
fn test_module_iter() {
let tree = gen_test_case!();
let mut collection = Vec::<&KtestItem>::new();
diff --git a/ostd/libs/ostd-test/src/tree.rs b/osdk/test-kernel/src/tree.rs
--- a/ostd/libs/ostd-test/src/tree.rs
+++ b/osdk/test-kernel/src/tree.rs
@@ -293,7 +293,7 @@ mod tests {
for mov in crate_.iter() {
let module = mov;
for test in module.iter() {
- collection.push(&test);
+ collection.push(test);
}
}
}
diff --git a/osdk/tests/examples_in_book/work_in_workspace_templates/myos/src/lib.rs b/osdk/tests/examples_in_book/work_in_workspace_templates/myos/src/lib.rs
--- a/osdk/tests/examples_in_book/work_in_workspace_templates/myos/src/lib.rs
+++ b/osdk/tests/examples_in_book/work_in_workspace_templates/myos/src/lib.rs
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: MPL-2.0
#![no_std]
+#![feature(linkage)]
#![deny(unsafe_code)]
use ostd::prelude::*;
diff --git a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
--- a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
+++ b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
@@ -1,6 +1,8 @@
// SPDX-License-Identifier: MPL-2.0
#![no_std]
+// The feature `linkage` is required for `ostd::main` to work.
+#![feature(linkage)]
extern crate alloc;
diff --git a/ostd/Cargo.toml b/ostd/Cargo.toml
--- a/ostd/Cargo.toml
+++ b/ostd/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "ostd"
-version = "0.7.0"
+version = "0.8.0"
edition = "2021"
description = "Rust OS framework that facilitates the development of and innovation in OS kernels"
license = "MPL-2.0"
diff --git a/ostd/Cargo.toml b/ostd/Cargo.toml
--- a/ostd/Cargo.toml
+++ b/ostd/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "ostd"
-version = "0.7.0"
+version = "0.8.0"
edition = "2021"
description = "Rust OS framework that facilitates the development of and innovation in OS kernels"
license = "MPL-2.0"
diff --git a/ostd/libs/ostd-macros/src/lib.rs b/ostd/libs/ostd-macros/src/lib.rs
--- a/ostd/libs/ostd-macros/src/lib.rs
+++ b/ostd/libs/ostd-macros/src/lib.rs
@@ -7,12 +7,13 @@ use quote::quote;
use rand::{distributions::Alphanumeric, Rng};
use syn::{parse_macro_input, Expr, Ident, ItemFn};
-/// This macro is used to mark the kernel entry point.
+/// A macro attribute to mark the kernel entry point.
///
/// # Example
///
/// ```ignore
/// #![no_std]
+/// #![feature(linkage)]
///
/// use ostd::prelude::*;
///
diff --git a/ostd/libs/ostd-macros/src/lib.rs b/ostd/libs/ostd-macros/src/lib.rs
--- a/ostd/libs/ostd-macros/src/lib.rs
+++ b/ostd/libs/ostd-macros/src/lib.rs
@@ -7,12 +7,13 @@ use quote::quote;
use rand::{distributions::Alphanumeric, Rng};
use syn::{parse_macro_input, Expr, Ident, ItemFn};
-/// This macro is used to mark the kernel entry point.
+/// A macro attribute to mark the kernel entry point.
///
/// # Example
///
/// ```ignore
/// #![no_std]
+/// #![feature(linkage)]
///
/// use ostd::prelude::*;
///
diff --git a/ostd/libs/ostd-macros/src/lib.rs b/ostd/libs/ostd-macros/src/lib.rs
--- a/ostd/libs/ostd-macros/src/lib.rs
+++ b/ostd/libs/ostd-macros/src/lib.rs
@@ -28,8 +29,37 @@ pub fn main(_attr: TokenStream, item: TokenStream) -> TokenStream {
quote!(
#[no_mangle]
- pub fn __ostd_main() -> ! {
- ostd::init();
+ #[linkage = "weak"]
+ extern "Rust" fn __ostd_main() -> ! {
+ // SAFETY: The function is called only once on the BSP.
+ unsafe { ostd::init() };
+ #main_fn_name();
+ ostd::prelude::abort();
+ }
+
+ #main_fn
+ )
+ .into()
+}
+
+/// A macro attribute for the unit test kernel entry point.
+///
+/// This macro is used for internal OSDK implementation. Do not use it
+/// directly.
+///
+/// It is a strong version of the `main` macro attribute. So if it exists (
+/// which means the unit test kernel is linked to perform testing), the actual
+/// kernel entry point will be replaced by this one.
+#[proc_macro_attribute]
+pub fn test_main(_attr: TokenStream, item: TokenStream) -> TokenStream {
+ let main_fn = parse_macro_input!(item as ItemFn);
+ let main_fn_name = &main_fn.sig.ident;
+
+ quote!(
+ #[no_mangle]
+ extern "Rust" fn __ostd_main() -> ! {
+ // SAFETY: The function is called only once on the BSP.
+ unsafe { ostd::init() };
#main_fn_name();
ostd::prelude::abort();
}
diff --git a/ostd/libs/ostd-test/Cargo.toml b/ostd/libs/ostd-test/Cargo.toml
--- a/ostd/libs/ostd-test/Cargo.toml
+++ b/ostd/libs/ostd-test/Cargo.toml
@@ -2,11 +2,8 @@
name = "ostd-test"
version = "0.1.0"
edition = "2021"
-description = "The kernel mode testing framework of OSTD"
+description = "The kernel mode unit testing framework of OSTD"
license = "MPL-2.0"
repository ="https://github.com/asterinas/asterinas"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
-
-[dependencies]
-owo-colors = "3.5.0"
diff --git a/ostd/libs/ostd-test/src/lib.rs b/ostd/libs/ostd-test/src/lib.rs
--- a/ostd/libs/ostd-test/src/lib.rs
+++ b/ostd/libs/ostd-test/src/lib.rs
@@ -45,12 +45,6 @@
//!
//! Any crates using the ostd-test framework should be linked with ostd.
//!
-//! ```toml
-//! # Cargo.toml
-//! [dependencies]
-//! ostd = { path = "relative/path/to/ostd" }
-//! ```
-//!
//! By the way, `#[ktest]` attribute along also works, but it hinders test control
//! using cfgs since plain attribute marked test will be executed in all test runs
//! no matter what cfgs are passed to the compiler. More importantly, using `#[ktest]`
diff --git a/ostd/libs/ostd-test/src/lib.rs b/ostd/libs/ostd-test/src/lib.rs
--- a/ostd/libs/ostd-test/src/lib.rs
+++ b/ostd/libs/ostd-test/src/lib.rs
@@ -58,27 +52,10 @@
//! explicitly stripped in normal builds.
//!
//! Rust cfg is used to control the compilation of the test module. In cooperation
-//! with the `ktest` framework, the Makefile will set the `RUSTFLAGS` environment
-//! variable to pass the cfgs to all rustc invocations. To run the tests, you simply
-//! need to set a list of cfgs by specifying `KTEST=1` to the Makefile, e.g.:
-//!
-//! ```bash
-//! make run KTEST=1
-//! ```
-//!
-//! Also, you can run a subset of tests by specifying the `KTEST_WHITELIST` variable.
-//! This is achieved by a whitelist filter on the test name.
-//!
-//! ```bash
-//! make run KTEST=1 KTEST_WHITELIST=failing_assertion,ostd::test::expect_panic
-//! ```
-//!
-//! `KTEST_CRATES` variable is used to specify in which crates the tests to be run.
-//! This is achieved by conditionally compiling the test module using the `#[cfg]`.
-//!
-//! ```bash
-//! make run KTEST=1 KTEST_CRATES=ostd
-//! ``
+//! with the `ktest` framework, OSDK will set the `RUSTFLAGS` environment variable
+//! to pass the cfgs to all rustc invocations. To run the tests, you simply need
+//! to use the command `cargo osdk test` in the crate directory. For more information,
+//! please refer to the OSDK documentation.
//!
//! We support the `#[should_panic]` attribute just in the same way as the standard
//! library do, but the implementation is quite slow currently. Use it with cautious.
diff --git a/ostd/libs/ostd-test/src/lib.rs b/ostd/libs/ostd-test/src/lib.rs
--- a/ostd/libs/ostd-test/src/lib.rs
+++ b/ostd/libs/ostd-test/src/lib.rs
@@ -90,10 +67,6 @@
#![cfg_attr(not(test), no_std)]
#![feature(panic_info_message)]
-pub mod path;
-pub mod runner;
-pub mod tree;
-
extern crate alloc;
use alloc::{boxed::Box, string::String};
diff --git a/ostd/libs/ostd-test/src/lib.rs b/ostd/libs/ostd-test/src/lib.rs
--- a/ostd/libs/ostd-test/src/lib.rs
+++ b/ostd/libs/ostd-test/src/lib.rs
@@ -113,6 +86,7 @@ impl core::fmt::Display for PanicInfo {
}
}
+/// The error that may occur during the test.
#[derive(Clone)]
pub enum KtestError {
Panic(Box<PanicInfo>),
diff --git a/ostd/libs/ostd-test/src/lib.rs b/ostd/libs/ostd-test/src/lib.rs
--- a/ostd/libs/ostd-test/src/lib.rs
+++ b/ostd/libs/ostd-test/src/lib.rs
@@ -121,13 +95,22 @@ pub enum KtestError {
Unknown,
}
+/// The information of the unit test.
#[derive(Clone, PartialEq, Debug)]
pub struct KtestItemInfo {
+ /// The path of the module, not including the function name.
+ ///
+ /// It would be separated by `::`.
pub module_path: &'static str,
+ /// The name of the unit test function.
pub fn_name: &'static str,
+ /// The name of the crate.
pub package: &'static str,
+ /// The source file where the test function resides.
pub source: &'static str,
+ /// The line number of the test function in the file.
pub line: usize,
+ /// The column number of the test function in the file.
pub col: usize,
}
diff --git a/ostd/libs/ostd-test/src/lib.rs b/ostd/libs/ostd-test/src/lib.rs
--- a/ostd/libs/ostd-test/src/lib.rs
+++ b/ostd/libs/ostd-test/src/lib.rs
@@ -141,6 +124,11 @@ pub struct KtestItem {
type CatchUnwindImpl = fn(f: fn() -> ()) -> Result<(), Box<dyn core::any::Any + Send>>;
impl KtestItem {
+ /// Create a new [`KtestItem`].
+ ///
+ /// Do not use this function directly. Instead, use the `#[ktest]`
+ /// attribute to mark the test function.
+ #[doc(hidden)]
pub const fn new(
fn_: fn() -> (),
should_panic: (bool, Option<&'static str>),
diff --git a/ostd/libs/ostd-test/src/lib.rs b/ostd/libs/ostd-test/src/lib.rs
--- a/ostd/libs/ostd-test/src/lib.rs
+++ b/ostd/libs/ostd-test/src/lib.rs
@@ -153,6 +141,7 @@ impl KtestItem {
}
}
+ /// Get the information of the test.
pub fn info(&self) -> &KtestItemInfo {
&self.info
}
diff --git a/ostd/libs/ostd-test/src/lib.rs b/ostd/libs/ostd-test/src/lib.rs
--- a/ostd/libs/ostd-test/src/lib.rs
+++ b/ostd/libs/ostd-test/src/lib.rs
@@ -206,12 +195,22 @@ macro_rules! ktest_array {
}};
}
+/// The iterator of the ktest array.
pub struct KtestIter {
index: usize,
}
+impl Default for KtestIter {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl KtestIter {
- fn new() -> Self {
+ /// Create a new [`KtestIter`].
+ ///
+ /// It will iterate over all the tests (marked with `#[ktest]`).
+ pub fn new() -> Self {
Self { index: 0 }
}
}
diff --git a/ostd/libs/ostd-test/src/lib.rs b/ostd/libs/ostd-test/src/lib.rs
--- a/ostd/libs/ostd-test/src/lib.rs
+++ b/ostd/libs/ostd-test/src/lib.rs
@@ -225,3 +224,28 @@ impl core::iter::Iterator for KtestIter {
Some(ktest_item.clone())
}
}
+
+// The whitelists that will be generated by the OSDK as static consts.
+// They deliver the target tests that the user wants to run.
+extern "Rust" {
+ static KTEST_TEST_WHITELIST: Option<&'static [&'static str]>;
+ static KTEST_CRATE_WHITELIST: Option<&'static [&'static str]>;
+}
+
+/// Get the whitelist of the tests.
+///
+/// The whitelist is generated by the OSDK runner, indicating name of the
+/// target tests that the user wants to run.
+pub fn get_ktest_test_whitelist() -> Option<&'static [&'static str]> {
+ // SAFETY: The two extern statics in the base crate are generated by OSDK.
+ unsafe { KTEST_TEST_WHITELIST }
+}
+
+/// Get the whitelist of the crates.
+///
+/// The whitelist is generated by the OSDK runner, indicating the target crate
+/// that the user wants to test.
+pub fn get_ktest_crate_whitelist() -> Option<&'static [&'static str]> {
+ // SAFETY: The two extern statics in the base crate are generated by OSDK.
+ unsafe { KTEST_CRATE_WHITELIST }
+}
diff --git a/ostd/src/boot/mod.rs b/ostd/src/boot/mod.rs
--- a/ostd/src/boot/mod.rs
+++ b/ostd/src/boot/mod.rs
@@ -115,8 +115,9 @@ pub fn init() {
///
/// Any kernel that uses the `ostd` crate should define a function marked with
/// `ostd::main` as the entrypoint.
-pub fn call_ostd_main() -> ! {
- #[cfg(not(ktest))]
+///
+/// This function should be only called from the bootloader-specific module.
+pub(crate) fn call_ostd_main() -> ! {
unsafe {
// The entry point of kernel code, which should be defined by the package that
// uses OSTD.
diff --git a/ostd/src/boot/mod.rs b/ostd/src/boot/mod.rs
--- a/ostd/src/boot/mod.rs
+++ b/ostd/src/boot/mod.rs
@@ -125,42 +126,4 @@ pub fn call_ostd_main() -> ! {
}
__ostd_main();
}
- #[cfg(ktest)]
- unsafe {
- use crate::task::TaskOptions;
-
- crate::init();
- // The whitelists that will be generated by OSDK runner as static consts.
- extern "Rust" {
- static KTEST_TEST_WHITELIST: Option<&'static [&'static str]>;
- static KTEST_CRATE_WHITELIST: Option<&'static [&'static str]>;
- }
-
- let test_task = move || {
- run_ktests(KTEST_TEST_WHITELIST, KTEST_CRATE_WHITELIST);
- };
- let _ = TaskOptions::new(test_task).data(()).spawn();
- unreachable!("The spawn method will NOT return in the boot context")
- }
-}
-
-fn run_ktests(test_whitelist: Option<&[&str]>, crate_whitelist: Option<&[&str]>) -> ! {
- use alloc::{boxed::Box, string::ToString};
- use core::any::Any;
-
- use crate::arch::qemu::{exit_qemu, QemuExitCode};
-
- let fn_catch_unwind = &(unwinding::panic::catch_unwind::<(), fn()>
- as fn(fn()) -> Result<(), Box<(dyn Any + Send + 'static)>>);
-
- use ostd_test::runner::{run_ktests, KtestResult};
- match run_ktests(
- &crate::console::early_print,
- fn_catch_unwind,
- test_whitelist.map(|s| s.iter().map(|s| s.to_string())),
- crate_whitelist,
- ) {
- KtestResult::Ok => exit_qemu(QemuExitCode::Success),
- KtestResult::Failed => exit_qemu(QemuExitCode::Failed),
- };
}
diff --git a/ostd/src/lib.rs b/ostd/src/lib.rs
--- a/ostd/src/lib.rs
+++ b/ostd/src/lib.rs
@@ -56,10 +56,15 @@ pub(crate) use crate::cpu::local::cpu_local_cell;
/// This function represents the first phase booting up the system. It makes
/// all functionalities of OSTD available after the call.
///
-/// TODO: We need to refactor this function to make it more modular and
-/// make inter-initialization-dependencies more clear and reduce usages of
-/// boot stage only global variables.
-pub fn init() {
+/// # Safety
+///
+/// This function should be called only once and only on the BSP.
+//
+// TODO: We need to refactor this function to make it more modular and
+// make inter-initialization-dependencies more clear and reduce usages of
+// boot stage only global variables.
+#[doc(hidden)]
+pub unsafe fn init() {
arch::enable_cpu_features();
arch::serial::init();
diff --git a/ostd/src/lib.rs b/ostd/src/lib.rs
--- a/ostd/src/lib.rs
+++ b/ostd/src/lib.rs
@@ -56,10 +56,15 @@ pub(crate) use crate::cpu::local::cpu_local_cell;
/// This function represents the first phase booting up the system. It makes
/// all functionalities of OSTD available after the call.
///
-/// TODO: We need to refactor this function to make it more modular and
-/// make inter-initialization-dependencies more clear and reduce usages of
-/// boot stage only global variables.
-pub fn init() {
+/// # Safety
+///
+/// This function should be called only once and only on the BSP.
+//
+// TODO: We need to refactor this function to make it more modular and
+// make inter-initialization-dependencies more clear and reduce usages of
+// boot stage only global variables.
+#[doc(hidden)]
+pub unsafe fn init() {
arch::enable_cpu_features();
arch::serial::init();
diff --git a/ostd/src/lib.rs b/ostd/src/lib.rs
--- a/ostd/src/lib.rs
+++ b/ostd/src/lib.rs
@@ -114,6 +119,7 @@ mod test {
use crate::prelude::*;
#[ktest]
+ #[allow(clippy::eq_op)]
fn trivial_assertion() {
assert_eq!(0, 0);
}
diff --git a/ostd/src/lib.rs b/ostd/src/lib.rs
--- a/ostd/src/lib.rs
+++ b/ostd/src/lib.rs
@@ -131,8 +137,14 @@ mod test {
}
}
-/// The module re-exports everything from the ktest crate
-#[cfg(ktest)]
+#[doc(hidden)]
pub mod ktest {
+ //! The module re-exports everything from the [`ostd_test`] crate, as well
+ //! as the test entry point macro.
+ //!
+ //! It is rather discouraged to use the definitions here directly. The
+ //! `ktest` attribute is sufficient for all normal use cases.
+
+ pub use ostd_macros::test_main as main;
pub use ostd_test::*;
}
diff --git a/ostd/src/mm/dma/dma_stream.rs b/ostd/src/mm/dma/dma_stream.rs
--- a/ostd/src/mm/dma/dma_stream.rs
+++ b/ostd/src/mm/dma/dma_stream.rs
@@ -334,9 +334,10 @@ mod test {
.alloc_contiguous()
.unwrap();
let vm_segment_child = vm_segment_parent.range(0..1);
- let _dma_stream_parent =
+ let dma_stream_parent =
DmaStream::map(vm_segment_parent, DmaDirection::Bidirectional, false);
let dma_stream_child = DmaStream::map(vm_segment_child, DmaDirection::Bidirectional, false);
+ assert!(dma_stream_parent.is_ok());
assert!(dma_stream_child.is_err());
}
diff --git a/ostd/src/sync/atomic_bits.rs b/ostd/src/sync/atomic_bits.rs
--- a/ostd/src/sync/atomic_bits.rs
+++ b/ostd/src/sync/atomic_bits.rs
@@ -313,24 +313,24 @@ mod test {
fn set_get() {
let bits = AtomicBits::new_zeroes(128);
for i in 0..bits.len() {
- assert!(bits.get(i) == false);
+ assert!(!bits.get(i));
bits.set(i, true);
- assert!(bits.get(i) == true);
+ assert!(bits.get(i));
bits.set(i, false);
- assert!(bits.get(i) == false);
+ assert!(!bits.get(i));
}
let bits = AtomicBits::new_ones(128);
for i in 0..bits.len() {
- assert!(bits.get(i) == true);
+ assert!(bits.get(i));
bits.set(i, false);
- assert!(bits.get(i) == false);
+ assert!(!bits.get(i));
bits.set(i, true);
- assert!(bits.get(i) == true);
+ assert!(bits.get(i));
}
}
diff --git a/ostd/src/sync/atomic_bits.rs b/ostd/src/sync/atomic_bits.rs
--- a/ostd/src/sync/atomic_bits.rs
+++ b/ostd/src/sync/atomic_bits.rs
@@ -389,9 +389,9 @@ mod test {
#[ktest]
fn iter() {
let bits = AtomicBits::new_zeroes(7);
- assert!(bits.iter().all(|bit| bit == false));
+ assert!(bits.iter().all(|bit| !bit));
let bits = AtomicBits::new_ones(128);
- assert!(bits.iter().all(|bit| bit == true));
+ assert!(bits.iter().all(|bit| bit));
}
}
diff --git a/ostd/src/sync/wait.rs b/ostd/src/sync/wait.rs
--- a/ostd/src/sync/wait.rs
+++ b/ostd/src/sync/wait.rs
@@ -293,7 +293,7 @@ mod test {
Task::yield_now();
cond_cloned.store(true, Ordering::Relaxed);
- wake(&*queue_cloned);
+ wake(&queue_cloned);
})
.data(())
.spawn()
diff --git a/ostd/src/task/task/mod.rs b/ostd/src/task/task/mod.rs
--- a/ostd/src/task/task/mod.rs
+++ b/ostd/src/task/task/mod.rs
@@ -383,6 +383,7 @@ mod test {
#[ktest]
fn create_task() {
+ #[allow(clippy::eq_op)]
let task = || {
assert_eq!(1, 1);
};
diff --git a/ostd/src/task/task/mod.rs b/ostd/src/task/task/mod.rs
--- a/ostd/src/task/task/mod.rs
+++ b/ostd/src/task/task/mod.rs
@@ -395,6 +396,7 @@ mod test {
#[ktest]
fn spawn_task() {
+ #[allow(clippy::eq_op)]
let task = || {
assert_eq!(1, 1);
};
diff --git a/tools/bump_version.sh b/tools/bump_version.sh
--- a/tools/bump_version.sh
+++ b/tools/bump_version.sh
@@ -20,6 +20,13 @@ update_package_version() {
sed -i "0,/${pattern}/s/${pattern}/version = \"${new_version}\"/1" $1
}
+# Update the version of the `ostd` dependency (`ostd = { version = "", ...`) in file $1
+update_ostd_dep_version() {
+ echo "Updating file $1"
+ pattern="^ostd = { version = \"[[:digit:]]\+\.[[:digit:]]\+\.[[:digit:]]\+\""
+ sed -i "0,/${pattern}/s/${pattern}/ostd = { version = \"${new_version}\"/1" $1
+}
+
# Update Docker image versions (`asterinas/asterinas:{version}`) in file $1
update_image_versions() {
echo "Updating file $1"
diff --git a/tools/bump_version.sh b/tools/bump_version.sh
--- a/tools/bump_version.sh
+++ b/tools/bump_version.sh
@@ -20,6 +20,13 @@ update_package_version() {
sed -i "0,/${pattern}/s/${pattern}/version = \"${new_version}\"/1" $1
}
+# Update the version of the `ostd` dependency (`ostd = { version = "", ...`) in file $1
+update_ostd_dep_version() {
+ echo "Updating file $1"
+ pattern="^ostd = { version = \"[[:digit:]]\+\.[[:digit:]]\+\.[[:digit:]]\+\""
+ sed -i "0,/${pattern}/s/${pattern}/ostd = { version = \"${new_version}\"/1" $1
+}
+
# Update Docker image versions (`asterinas/asterinas:{version}`) in file $1
update_image_versions() {
echo "Updating file $1"
diff --git a/tools/bump_version.sh b/tools/bump_version.sh
--- a/tools/bump_version.sh
+++ b/tools/bump_version.sh
@@ -98,6 +105,7 @@ ASTER_SRC_DIR=${SCRIPT_DIR}/..
DOCS_DIR=${ASTER_SRC_DIR}/docs
OSTD_CARGO_TOML_PATH=${ASTER_SRC_DIR}/ostd/Cargo.toml
OSDK_CARGO_TOML_PATH=${ASTER_SRC_DIR}/osdk/Cargo.toml
+OSTD_TEST_RUNNER_CARGO_TOML_PATH=${ASTER_SRC_DIR}/osdk/test-kernel/Cargo.toml
VERSION_PATH=${ASTER_SRC_DIR}/VERSION
current_version=$(cat ${VERSION_PATH})
diff --git a/tools/bump_version.sh b/tools/bump_version.sh
--- a/tools/bump_version.sh
+++ b/tools/bump_version.sh
@@ -114,9 +122,11 @@ new_version=$(bump_version ${current_version})
# Update the package version in Cargo.toml
update_package_version ${OSTD_CARGO_TOML_PATH}
update_package_version ${OSDK_CARGO_TOML_PATH}
+update_package_version ${OSTD_TEST_RUNNER_CARGO_TOML_PATH}
+update_ostd_dep_version ${OSTD_TEST_RUNNER_CARGO_TOML_PATH}
# Automatically bump Cargo.lock file
-cargo update -p asterinas --precise $new_version
+cargo update -p aster-nix --precise $new_version
# Update Docker image versions in README files
update_image_versions ${ASTER_SRC_DIR}/README.md
diff --git a/tools/bump_version.sh b/tools/bump_version.sh
--- a/tools/bump_version.sh
+++ b/tools/bump_version.sh
@@ -114,9 +122,11 @@ new_version=$(bump_version ${current_version})
# Update the package version in Cargo.toml
update_package_version ${OSTD_CARGO_TOML_PATH}
update_package_version ${OSDK_CARGO_TOML_PATH}
+update_package_version ${OSTD_TEST_RUNNER_CARGO_TOML_PATH}
+update_ostd_dep_version ${OSTD_TEST_RUNNER_CARGO_TOML_PATH}
# Automatically bump Cargo.lock file
-cargo update -p asterinas --precise $new_version
+cargo update -p aster-nix --precise $new_version
# Update Docker image versions in README files
update_image_versions ${ASTER_SRC_DIR}/README.md
diff --git a/tools/bump_version.sh b/tools/bump_version.sh
--- a/tools/bump_version.sh
+++ b/tools/bump_version.sh
@@ -142,4 +152,4 @@ update_image_versions $GET_STARTED_PATH
# `-n` is used to avoid adding a '\n' in the VERSION file.
echo -n "${new_version}" > ${VERSION_PATH}
-echo "Bumped Asterinas & OSDK version to $new_version"
+echo "Bumped Asterinas OSTD & OSDK version to $new_version"
diff --git a/tools/bump_version.sh b/tools/bump_version.sh
--- a/tools/bump_version.sh
+++ b/tools/bump_version.sh
@@ -142,4 +152,4 @@ update_image_versions $GET_STARTED_PATH
# `-n` is used to avoid adding a '\n' in the VERSION file.
echo -n "${new_version}" > ${VERSION_PATH}
-echo "Bumped Asterinas & OSDK version to $new_version"
+echo "Bumped Asterinas OSTD & OSDK version to $new_version"
|
This proposal aims to address to problems.
> * a lot of runtime needed when running ktest, which need to be passed as parameters https://github.com/asterinas/asterinas/pull/834 ;
> * need to pass cfg to aster-frame when rebuilding the test https://github.com/asterinas/asterinas/issues/974 ;
I can see why this proposal is able to resolve the first problem. But why can it address the second?
> The proposed one is:
```plain
.-- ktest <----(if testing)----.
v \
.-- ostd <---------- A <--------- base_crate
v /
ktest_proc_macro <---'
```
Users don't need to be aware of the existence of the `ktest_proc_macro` and `ktest` crates, correct? The `ktest` crate is solely a dependency of the `base_crate`, and the `ktest_proc_macro` is now re-exported from `ostd`. Therefore, the crate A to be tested can only depend on `ostd`.
Due to the current implementation of both `#[ostd::ktest]` and `ktest` relying on `KtestItem` and `KtestItemInfo`, we cannot directly move `ktest` above `ostd`.
The most naive implementation would be to move the logic for running `ktest` to the top level, creating a `ktest_run`. However, the definition of `KtestItem` would still need to be retained within `OSTD` to allow the use of `#[ostd::ktest]`. This approach would still leave `OSTD` partially dependent on `ktest`.
```text
.-- ktest_run <---(if testing)---.
v \
ktest_proc_macro <-----ostd <---------- A <------------- base_crate
\ v
.-----> ktest
```
An alternative solution might be to place the parameters that originally needed to be wrapped in `KtestItem` into a `.ktest_array`, and then retrieve these parameters to generate `KtestItem` objects during execution. However, this might not be an elegant solution.
I haven't been able to think of a better approach☹️. Could you give me some input @junyang-zh ?
> The most naive implementation would be to move the logic for running `ktest` to the top level, creating a `ktest_run`. However, the definition of `KtestItem` would still need to be retained within `OSTD` to allow the use of `#[ostd::ktest]`. This approach would still leave `OSTD` partially dependent on `ktest`.
>
> ```
> .-- ktest_run <---(if testing)---.
> v \
> ktest_proc_macro <-----ostd <---------- A <------------- base_crate
> \ v
> .-----> ktest
> ```
Your question makes sense. And the best solution I can think of is just like yours, splitting the crate into two.
So it seems that we are just making the ktest runner a kernel. The ktest item definitions are still a dependency of OSTD.
|
2024-08-13T11:21:28Z
|
c2a83427520f8263a8eb2c36edacdba261ad5cae
|
asterinas/asterinas
|
diff --git a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
--- a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
+++ b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
@@ -57,6 +57,7 @@ fn create_user_space(program: &[u8]) -> UserSpace {
for frame in user_pages {
cursor.map(frame, map_prop);
}
+ drop(cursor);
Arc::new(vm_space)
};
let user_cpu_state = {
|
[
"1264"
] |
0.8
|
c68302f7007225fa47f22a1085a8c59dcdae2ad4
|
Sporadic SMP syscall test aborts
<!-- Thank you for taking the time to report a bug. Your input is valuable to us.
Please replace all the <angle brackets> below with your own information. -->
### Describe the bug
<!-- A clear and concise description of what the bug is. -->
The SMP syscall test aborts with no panicking information randomly. The abort does not happen in a specific test case. And there's possibility of such failures both in the CI ([an example](https://github.com/asterinas/asterinas/actions/runs/10615729536/job/29424463727)) and locally.
Other CI failure logs:
https://github.com/asterinas/asterinas/actions/runs/10600745276/job/29378943424
Link #999
|
asterinas__asterinas-1158
| 1,158
|
diff --git a/kernel/src/sched/priority_scheduler.rs b/kernel/src/sched/priority_scheduler.rs
--- a/kernel/src/sched/priority_scheduler.rs
+++ b/kernel/src/sched/priority_scheduler.rs
@@ -50,12 +50,12 @@ impl<T: PreemptSchedInfo> PreemptScheduler<T> {
let mut minimum_load = usize::MAX;
for candidate in runnable.cpu_affinity().iter() {
- let rq = self.rq[candidate].lock();
+ let rq = self.rq[candidate as usize].lock();
// A wild guess measuring the load of a runqueue. We assume that
// real-time tasks are 4-times as important as normal tasks.
let load = rq.real_time_entities.len() * 4 + rq.normal_entities.len();
if load < minimum_load {
- selected = candidate as u32;
+ selected = candidate;
minimum_load = load;
}
}
diff --git a/kernel/src/sched/priority_scheduler.rs b/kernel/src/sched/priority_scheduler.rs
--- a/kernel/src/sched/priority_scheduler.rs
+++ b/kernel/src/sched/priority_scheduler.rs
@@ -50,12 +50,12 @@ impl<T: PreemptSchedInfo> PreemptScheduler<T> {
let mut minimum_load = usize::MAX;
for candidate in runnable.cpu_affinity().iter() {
- let rq = self.rq[candidate].lock();
+ let rq = self.rq[candidate as usize].lock();
// A wild guess measuring the load of a runqueue. We assume that
// real-time tasks are 4-times as important as normal tasks.
let load = rq.real_time_entities.len() * 4 + rq.normal_entities.len();
if load < minimum_load {
- selected = candidate as u32;
+ selected = candidate;
minimum_load = load;
}
}
diff --git a/kernel/src/thread/work_queue/simple_scheduler.rs b/kernel/src/thread/work_queue/simple_scheduler.rs
--- a/kernel/src/thread/work_queue/simple_scheduler.rs
+++ b/kernel/src/thread/work_queue/simple_scheduler.rs
@@ -24,12 +24,12 @@ impl WorkerScheduler for SimpleScheduler {
fn schedule(&self) {
let worker_pool = self.worker_pool.upgrade().unwrap();
for cpu_id in worker_pool.cpu_set().iter() {
- if !worker_pool.heartbeat(cpu_id as u32)
- && worker_pool.has_pending_work_items(cpu_id as u32)
- && !worker_pool.wake_worker(cpu_id as u32)
- && worker_pool.num_workers(cpu_id as u32) < WORKER_LIMIT
+ if !worker_pool.heartbeat(cpu_id)
+ && worker_pool.has_pending_work_items(cpu_id)
+ && !worker_pool.wake_worker(cpu_id)
+ && worker_pool.num_workers(cpu_id) < WORKER_LIMIT
{
- worker_pool.add_worker(cpu_id as u32);
+ worker_pool.add_worker(cpu_id);
}
}
}
diff --git a/kernel/src/thread/work_queue/simple_scheduler.rs b/kernel/src/thread/work_queue/simple_scheduler.rs
--- a/kernel/src/thread/work_queue/simple_scheduler.rs
+++ b/kernel/src/thread/work_queue/simple_scheduler.rs
@@ -24,12 +24,12 @@ impl WorkerScheduler for SimpleScheduler {
fn schedule(&self) {
let worker_pool = self.worker_pool.upgrade().unwrap();
for cpu_id in worker_pool.cpu_set().iter() {
- if !worker_pool.heartbeat(cpu_id as u32)
- && worker_pool.has_pending_work_items(cpu_id as u32)
- && !worker_pool.wake_worker(cpu_id as u32)
- && worker_pool.num_workers(cpu_id as u32) < WORKER_LIMIT
+ if !worker_pool.heartbeat(cpu_id)
+ && worker_pool.has_pending_work_items(cpu_id)
+ && !worker_pool.wake_worker(cpu_id)
+ && worker_pool.num_workers(cpu_id) < WORKER_LIMIT
{
- worker_pool.add_worker(cpu_id as u32);
+ worker_pool.add_worker(cpu_id);
}
}
}
diff --git a/kernel/src/thread/work_queue/worker_pool.rs b/kernel/src/thread/work_queue/worker_pool.rs
--- a/kernel/src/thread/work_queue/worker_pool.rs
+++ b/kernel/src/thread/work_queue/worker_pool.rs
@@ -128,10 +128,7 @@ impl WorkerPool {
Arc::new_cyclic(|pool_ref| {
let mut local_pools = Vec::new();
for cpu_id in cpu_set.iter() {
- local_pools.push(Arc::new(LocalWorkerPool::new(
- pool_ref.clone(),
- cpu_id as u32,
- )));
+ local_pools.push(Arc::new(LocalWorkerPool::new(pool_ref.clone(), cpu_id)));
}
WorkerPool {
local_pools,
diff --git a/kernel/src/thread/work_queue/worker_pool.rs b/kernel/src/thread/work_queue/worker_pool.rs
--- a/kernel/src/thread/work_queue/worker_pool.rs
+++ b/kernel/src/thread/work_queue/worker_pool.rs
@@ -128,10 +128,7 @@ impl WorkerPool {
Arc::new_cyclic(|pool_ref| {
let mut local_pools = Vec::new();
for cpu_id in cpu_set.iter() {
- local_pools.push(Arc::new(LocalWorkerPool::new(
- pool_ref.clone(),
- cpu_id as u32,
- )));
+ local_pools.push(Arc::new(LocalWorkerPool::new(pool_ref.clone(), cpu_id)));
}
WorkerPool {
local_pools,
diff --git a/kernel/src/vm/vmar/mod.rs b/kernel/src/vm/vmar/mod.rs
--- a/kernel/src/vm/vmar/mod.rs
+++ b/kernel/src/vm/vmar/mod.rs
@@ -336,7 +336,7 @@ impl Vmar_ {
if !self.is_root_vmar() {
return_errno_with_message!(Errno::EACCES, "The vmar is not root vmar");
}
- self.vm_space.clear();
+ self.clear_vm_space();
let mut inner = self.inner.lock();
inner.child_vmar_s.clear();
inner.vm_mappings.clear();
diff --git a/kernel/src/vm/vmar/mod.rs b/kernel/src/vm/vmar/mod.rs
--- a/kernel/src/vm/vmar/mod.rs
+++ b/kernel/src/vm/vmar/mod.rs
@@ -336,7 +336,7 @@ impl Vmar_ {
if !self.is_root_vmar() {
return_errno_with_message!(Errno::EACCES, "The vmar is not root vmar");
}
- self.vm_space.clear();
+ self.clear_vm_space();
let mut inner = self.inner.lock();
inner.child_vmar_s.clear();
inner.vm_mappings.clear();
diff --git a/kernel/src/vm/vmar/mod.rs b/kernel/src/vm/vmar/mod.rs
--- a/kernel/src/vm/vmar/mod.rs
+++ b/kernel/src/vm/vmar/mod.rs
@@ -346,6 +346,13 @@ impl Vmar_ {
Ok(())
}
+ fn clear_vm_space(&self) {
+ let start = ROOT_VMAR_LOWEST_ADDR;
+ let end = ROOT_VMAR_CAP_ADDR;
+ let mut cursor = self.vm_space.cursor_mut(&(start..end)).unwrap();
+ cursor.unmap(end - start);
+ }
+
pub fn destroy(&self, range: Range<usize>) -> Result<()> {
self.check_destroy_range(&range)?;
let mut inner = self.inner.lock();
diff --git a/kernel/src/vm/vmar/mod.rs b/kernel/src/vm/vmar/mod.rs
--- a/kernel/src/vm/vmar/mod.rs
+++ b/kernel/src/vm/vmar/mod.rs
@@ -346,6 +346,13 @@ impl Vmar_ {
Ok(())
}
+ fn clear_vm_space(&self) {
+ let start = ROOT_VMAR_LOWEST_ADDR;
+ let end = ROOT_VMAR_CAP_ADDR;
+ let mut cursor = self.vm_space.cursor_mut(&(start..end)).unwrap();
+ cursor.unmap(end - start);
+ }
+
pub fn destroy(&self, range: Range<usize>) -> Result<()> {
self.check_destroy_range(&range)?;
let mut inner = self.inner.lock();
diff --git a/kernel/src/vm/vmar/vm_mapping.rs b/kernel/src/vm/vmar/vm_mapping.rs
--- a/kernel/src/vm/vmar/vm_mapping.rs
+++ b/kernel/src/vm/vmar/vm_mapping.rs
@@ -167,16 +167,6 @@ impl VmMapping {
self.vmo.as_ref()
}
- /// Adds a new committed page and map it to vmspace. If copy on write is set, it's allowed to unmap the page at the same address.
- /// FIXME: This implementation based on the truth that we map one page at a time. If multiple pages are mapped together, this implementation may have problems
- fn map_one_page(&self, map_addr: usize, frame: Frame, is_readonly: bool) -> Result<()> {
- let parent = self.parent.upgrade().unwrap();
- let vm_space = parent.vm_space();
- self.inner
- .lock()
- .map_one_page(vm_space, map_addr, frame, is_readonly)
- }
-
/// Returns the mapping's start address.
pub fn map_to_addr(&self) -> Vaddr {
self.inner.lock().map_to_addr
diff --git a/kernel/src/vm/vmar/vm_mapping.rs b/kernel/src/vm/vmar/vm_mapping.rs
--- a/kernel/src/vm/vmar/vm_mapping.rs
+++ b/kernel/src/vm/vmar/vm_mapping.rs
@@ -167,16 +167,6 @@ impl VmMapping {
self.vmo.as_ref()
}
- /// Adds a new committed page and map it to vmspace. If copy on write is set, it's allowed to unmap the page at the same address.
- /// FIXME: This implementation based on the truth that we map one page at a time. If multiple pages are mapped together, this implementation may have problems
- fn map_one_page(&self, map_addr: usize, frame: Frame, is_readonly: bool) -> Result<()> {
- let parent = self.parent.upgrade().unwrap();
- let vm_space = parent.vm_space();
- self.inner
- .lock()
- .map_one_page(vm_space, map_addr, frame, is_readonly)
- }
-
/// Returns the mapping's start address.
pub fn map_to_addr(&self) -> Vaddr {
self.inner.lock().map_to_addr
diff --git a/kernel/src/vm/vmar/vm_mapping.rs b/kernel/src/vm/vmar/vm_mapping.rs
--- a/kernel/src/vm/vmar/vm_mapping.rs
+++ b/kernel/src/vm/vmar/vm_mapping.rs
@@ -193,11 +183,6 @@ impl VmMapping {
self.inner.lock().map_size
}
- /// Returns the mapping's offset in the VMO.
- pub fn vmo_offset(&self) -> Option<usize> {
- self.inner.lock().vmo_offset
- }
-
/// Unmaps pages in the range
pub fn unmap(&self, range: &Range<usize>, may_destroy: bool) -> Result<()> {
let parent = self.parent.upgrade().unwrap();
diff --git a/kernel/src/vm/vmar/vm_mapping.rs b/kernel/src/vm/vmar/vm_mapping.rs
--- a/kernel/src/vm/vmar/vm_mapping.rs
+++ b/kernel/src/vm/vmar/vm_mapping.rs
@@ -193,11 +183,6 @@ impl VmMapping {
self.inner.lock().map_size
}
- /// Returns the mapping's offset in the VMO.
- pub fn vmo_offset(&self) -> Option<usize> {
- self.inner.lock().vmo_offset
- }
-
/// Unmaps pages in the range
pub fn unmap(&self, range: &Range<usize>, may_destroy: bool) -> Result<()> {
let parent = self.parent.upgrade().unwrap();
diff --git a/kernel/src/vm/vmar/vm_mapping.rs b/kernel/src/vm/vmar/vm_mapping.rs
--- a/kernel/src/vm/vmar/vm_mapping.rs
+++ b/kernel/src/vm/vmar/vm_mapping.rs
@@ -234,43 +219,84 @@ impl VmMapping {
let page_aligned_addr = page_fault_addr.align_down(PAGE_SIZE);
+ let root_vmar = self.parent.upgrade().unwrap();
+ let mut cursor = root_vmar
+ .vm_space()
+ .cursor_mut(&(page_aligned_addr..page_aligned_addr + PAGE_SIZE))?;
+ let current_mapping = cursor.query().unwrap();
+
+ // Perform COW if it is a write access to a shared mapping.
if write && !not_present {
- // Perform COW at page table.
- let root_vmar = self.parent.upgrade().unwrap();
- let mut cursor = root_vmar
- .vm_space()
- .cursor_mut(&(page_aligned_addr..page_aligned_addr + PAGE_SIZE))?;
let VmItem::Mapped {
va: _,
frame,
mut prop,
- } = cursor.query().unwrap()
+ } = current_mapping
else {
return Err(Error::new(Errno::EFAULT));
};
- if self.is_shared {
+ // Skip if the page fault is already handled.
+ if prop.flags.contains(PageFlags::W) {
+ return Ok(());
+ }
+
+ // If the forked child or parent immediately unmaps the page after
+ // the fork without accessing it, we are the only reference to the
+ // frame. We can directly map the frame as writable without
+ // copying. In this case, the reference count of the frame is 2 (
+ // one for the mapping and one for the frame handle itself).
+ let only_reference = frame.reference_count() == 2;
+
+ if self.is_shared || only_reference {
cursor.protect(PAGE_SIZE, |p| p.flags |= PageFlags::W);
} else {
let new_frame = duplicate_frame(&frame)?;
- prop.flags |= PageFlags::W;
+ prop.flags |= PageFlags::W | PageFlags::ACCESSED | PageFlags::DIRTY;
cursor.map(new_frame, prop);
}
return Ok(());
}
- let (frame, is_readonly) = self.prepare_page(page_fault_addr, write)?;
+ // Map a new frame to the page fault address.
+ // Skip if the page fault is already handled.
+ if let VmItem::NotMapped { .. } = current_mapping {
+ let inner_lock = self.inner.lock();
+ let (frame, is_readonly) = self.prepare_page(&inner_lock, page_fault_addr, write)?;
+
+ let vm_perms = {
+ let mut perms = inner_lock.perms;
+ if is_readonly {
+ // COW pages are forced to be read-only.
+ perms -= VmPerms::WRITE;
+ }
+ perms
+ };
+ let mut page_flags = vm_perms.into();
+ page_flags |= PageFlags::ACCESSED;
+ if write {
+ page_flags |= PageFlags::DIRTY;
+ }
+ let map_prop = PageProperty::new(page_flags, CachePolicy::Writeback);
+
+ cursor.map(frame, map_prop);
+ }
- self.map_one_page(page_aligned_addr, frame, is_readonly)
+ Ok(())
}
- fn prepare_page(&self, page_fault_addr: Vaddr, write: bool) -> Result<(Frame, bool)> {
+ fn prepare_page(
+ &self,
+ inner_lock: &MutexGuard<VmMappingInner>,
+ page_fault_addr: Vaddr,
+ write: bool,
+ ) -> Result<(Frame, bool)> {
let mut is_readonly = false;
let Some(vmo) = &self.vmo else {
return Ok((FrameAllocOptions::new(1).alloc_single()?, is_readonly));
};
- let vmo_offset = self.vmo_offset().unwrap() + page_fault_addr - self.map_to_addr();
+ let vmo_offset = inner_lock.vmo_offset.unwrap() + page_fault_addr - inner_lock.map_to_addr;
let page_idx = vmo_offset / PAGE_SIZE;
let Ok(page) = vmo.get_committed_frame(page_idx) else {
if !self.is_shared {
diff --git a/kernel/src/vm/vmar/vm_mapping.rs b/kernel/src/vm/vmar/vm_mapping.rs
--- a/kernel/src/vm/vmar/vm_mapping.rs
+++ b/kernel/src/vm/vmar/vm_mapping.rs
@@ -234,43 +219,84 @@ impl VmMapping {
let page_aligned_addr = page_fault_addr.align_down(PAGE_SIZE);
+ let root_vmar = self.parent.upgrade().unwrap();
+ let mut cursor = root_vmar
+ .vm_space()
+ .cursor_mut(&(page_aligned_addr..page_aligned_addr + PAGE_SIZE))?;
+ let current_mapping = cursor.query().unwrap();
+
+ // Perform COW if it is a write access to a shared mapping.
if write && !not_present {
- // Perform COW at page table.
- let root_vmar = self.parent.upgrade().unwrap();
- let mut cursor = root_vmar
- .vm_space()
- .cursor_mut(&(page_aligned_addr..page_aligned_addr + PAGE_SIZE))?;
let VmItem::Mapped {
va: _,
frame,
mut prop,
- } = cursor.query().unwrap()
+ } = current_mapping
else {
return Err(Error::new(Errno::EFAULT));
};
- if self.is_shared {
+ // Skip if the page fault is already handled.
+ if prop.flags.contains(PageFlags::W) {
+ return Ok(());
+ }
+
+ // If the forked child or parent immediately unmaps the page after
+ // the fork without accessing it, we are the only reference to the
+ // frame. We can directly map the frame as writable without
+ // copying. In this case, the reference count of the frame is 2 (
+ // one for the mapping and one for the frame handle itself).
+ let only_reference = frame.reference_count() == 2;
+
+ if self.is_shared || only_reference {
cursor.protect(PAGE_SIZE, |p| p.flags |= PageFlags::W);
} else {
let new_frame = duplicate_frame(&frame)?;
- prop.flags |= PageFlags::W;
+ prop.flags |= PageFlags::W | PageFlags::ACCESSED | PageFlags::DIRTY;
cursor.map(new_frame, prop);
}
return Ok(());
}
- let (frame, is_readonly) = self.prepare_page(page_fault_addr, write)?;
+ // Map a new frame to the page fault address.
+ // Skip if the page fault is already handled.
+ if let VmItem::NotMapped { .. } = current_mapping {
+ let inner_lock = self.inner.lock();
+ let (frame, is_readonly) = self.prepare_page(&inner_lock, page_fault_addr, write)?;
+
+ let vm_perms = {
+ let mut perms = inner_lock.perms;
+ if is_readonly {
+ // COW pages are forced to be read-only.
+ perms -= VmPerms::WRITE;
+ }
+ perms
+ };
+ let mut page_flags = vm_perms.into();
+ page_flags |= PageFlags::ACCESSED;
+ if write {
+ page_flags |= PageFlags::DIRTY;
+ }
+ let map_prop = PageProperty::new(page_flags, CachePolicy::Writeback);
+
+ cursor.map(frame, map_prop);
+ }
- self.map_one_page(page_aligned_addr, frame, is_readonly)
+ Ok(())
}
- fn prepare_page(&self, page_fault_addr: Vaddr, write: bool) -> Result<(Frame, bool)> {
+ fn prepare_page(
+ &self,
+ inner_lock: &MutexGuard<VmMappingInner>,
+ page_fault_addr: Vaddr,
+ write: bool,
+ ) -> Result<(Frame, bool)> {
let mut is_readonly = false;
let Some(vmo) = &self.vmo else {
return Ok((FrameAllocOptions::new(1).alloc_single()?, is_readonly));
};
- let vmo_offset = self.vmo_offset().unwrap() + page_fault_addr - self.map_to_addr();
+ let vmo_offset = inner_lock.vmo_offset.unwrap() + page_fault_addr - inner_lock.map_to_addr;
let page_idx = vmo_offset / PAGE_SIZE;
let Ok(page) = vmo.get_committed_frame(page_idx) else {
if !self.is_shared {
diff --git a/kernel/src/vm/vmar/vm_mapping.rs b/kernel/src/vm/vmar/vm_mapping.rs
--- a/kernel/src/vm/vmar/vm_mapping.rs
+++ b/kernel/src/vm/vmar/vm_mapping.rs
@@ -314,14 +340,18 @@ impl VmMapping {
);
let vm_perms = inner.perms - VmPerms::WRITE;
- let vm_map_options = { PageProperty::new(vm_perms.into(), CachePolicy::Writeback) };
let parent = self.parent.upgrade().unwrap();
let vm_space = parent.vm_space();
let mut cursor = vm_space.cursor_mut(&(start_addr..end_addr))?;
let operate = move |commit_fn: &mut dyn FnMut() -> Result<Frame>| {
- if let VmItem::NotMapped { .. } = cursor.query().unwrap() {
+ if let VmItem::NotMapped { va, len } = cursor.query().unwrap() {
+ let mut page_flags = vm_perms.into();
+ if (va..len).contains(&page_fault_addr) {
+ page_flags |= PageFlags::ACCESSED;
+ }
+ let page_prop = PageProperty::new(page_flags, CachePolicy::Writeback);
let frame = commit_fn()?;
- cursor.map(frame, vm_map_options);
+ cursor.map(frame, page_prop);
} else {
let next_addr = cursor.virt_addr() + PAGE_SIZE;
if next_addr < end_addr {
diff --git a/kernel/src/vm/vmar/vm_mapping.rs b/kernel/src/vm/vmar/vm_mapping.rs
--- a/kernel/src/vm/vmar/vm_mapping.rs
+++ b/kernel/src/vm/vmar/vm_mapping.rs
@@ -314,14 +340,18 @@ impl VmMapping {
);
let vm_perms = inner.perms - VmPerms::WRITE;
- let vm_map_options = { PageProperty::new(vm_perms.into(), CachePolicy::Writeback) };
let parent = self.parent.upgrade().unwrap();
let vm_space = parent.vm_space();
let mut cursor = vm_space.cursor_mut(&(start_addr..end_addr))?;
let operate = move |commit_fn: &mut dyn FnMut() -> Result<Frame>| {
- if let VmItem::NotMapped { .. } = cursor.query().unwrap() {
+ if let VmItem::NotMapped { va, len } = cursor.query().unwrap() {
+ let mut page_flags = vm_perms.into();
+ if (va..len).contains(&page_fault_addr) {
+ page_flags |= PageFlags::ACCESSED;
+ }
+ let page_prop = PageProperty::new(page_flags, CachePolicy::Writeback);
let frame = commit_fn()?;
- cursor.map(frame, vm_map_options);
+ cursor.map(frame, page_prop);
} else {
let next_addr = cursor.virt_addr() + PAGE_SIZE;
if next_addr < end_addr {
diff --git a/kernel/src/vm/vmar/vm_mapping.rs b/kernel/src/vm/vmar/vm_mapping.rs
--- a/kernel/src/vm/vmar/vm_mapping.rs
+++ b/kernel/src/vm/vmar/vm_mapping.rs
@@ -507,30 +537,6 @@ impl VmMapping {
}
impl VmMappingInner {
- fn map_one_page(
- &mut self,
- vm_space: &VmSpace,
- map_addr: usize,
- frame: Frame,
- is_readonly: bool,
- ) -> Result<()> {
- let map_range = map_addr..map_addr + PAGE_SIZE;
-
- let vm_perms = {
- let mut perms = self.perms;
- if is_readonly {
- // COW pages are forced to be read-only.
- perms -= VmPerms::WRITE;
- }
- perms
- };
- let map_prop = PageProperty::new(vm_perms.into(), CachePolicy::Writeback);
-
- let mut cursor = vm_space.cursor_mut(&map_range).unwrap();
- cursor.map(frame, map_prop);
- Ok(())
- }
-
/// Unmap pages in the range.
fn unmap(&mut self, vm_space: &VmSpace, range: &Range<usize>, may_destroy: bool) -> Result<()> {
let map_addr = range.start.align_down(PAGE_SIZE);
diff --git a/kernel/src/vm/vmar/vm_mapping.rs b/kernel/src/vm/vmar/vm_mapping.rs
--- a/kernel/src/vm/vmar/vm_mapping.rs
+++ b/kernel/src/vm/vmar/vm_mapping.rs
@@ -507,30 +537,6 @@ impl VmMapping {
}
impl VmMappingInner {
- fn map_one_page(
- &mut self,
- vm_space: &VmSpace,
- map_addr: usize,
- frame: Frame,
- is_readonly: bool,
- ) -> Result<()> {
- let map_range = map_addr..map_addr + PAGE_SIZE;
-
- let vm_perms = {
- let mut perms = self.perms;
- if is_readonly {
- // COW pages are forced to be read-only.
- perms -= VmPerms::WRITE;
- }
- perms
- };
- let map_prop = PageProperty::new(vm_perms.into(), CachePolicy::Writeback);
-
- let mut cursor = vm_space.cursor_mut(&map_range).unwrap();
- cursor.map(frame, map_prop);
- Ok(())
- }
-
/// Unmap pages in the range.
fn unmap(&mut self, vm_space: &VmSpace, range: &Range<usize>, may_destroy: bool) -> Result<()> {
let map_addr = range.start.align_down(PAGE_SIZE);
diff --git a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
--- a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
+++ b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
@@ -57,6 +57,7 @@ fn create_user_space(program: &[u8]) -> UserSpace {
for frame in user_pages {
cursor.map(frame, map_prop);
}
+ drop(cursor);
Arc::new(vm_space)
};
let user_cpu_state = {
diff --git a/ostd/src/arch/x86/boot/smp.rs b/ostd/src/arch/x86/boot/smp.rs
--- a/ostd/src/arch/x86/boot/smp.rs
+++ b/ostd/src/arch/x86/boot/smp.rs
@@ -150,7 +150,7 @@ fn send_startup_to_all_aps() {
(AP_BOOT_START_PA / PAGE_SIZE) as u8,
);
// SAFETY: we are sending startup IPI to all APs.
- apic::borrow(|apic| unsafe { apic.send_ipi(icr) });
+ apic::with_borrow(|apic| unsafe { apic.send_ipi(icr) });
}
fn send_init_to_all_aps() {
diff --git a/ostd/src/arch/x86/boot/smp.rs b/ostd/src/arch/x86/boot/smp.rs
--- a/ostd/src/arch/x86/boot/smp.rs
+++ b/ostd/src/arch/x86/boot/smp.rs
@@ -150,7 +150,7 @@ fn send_startup_to_all_aps() {
(AP_BOOT_START_PA / PAGE_SIZE) as u8,
);
// SAFETY: we are sending startup IPI to all APs.
- apic::borrow(|apic| unsafe { apic.send_ipi(icr) });
+ apic::with_borrow(|apic| unsafe { apic.send_ipi(icr) });
}
fn send_init_to_all_aps() {
diff --git a/ostd/src/arch/x86/boot/smp.rs b/ostd/src/arch/x86/boot/smp.rs
--- a/ostd/src/arch/x86/boot/smp.rs
+++ b/ostd/src/arch/x86/boot/smp.rs
@@ -165,7 +165,7 @@ fn send_init_to_all_aps() {
0,
);
// SAFETY: we are sending init IPI to all APs.
- apic::borrow(|apic| unsafe { apic.send_ipi(icr) });
+ apic::with_borrow(|apic| unsafe { apic.send_ipi(icr) });
}
fn send_init_deassert() {
diff --git a/ostd/src/arch/x86/boot/smp.rs b/ostd/src/arch/x86/boot/smp.rs
--- a/ostd/src/arch/x86/boot/smp.rs
+++ b/ostd/src/arch/x86/boot/smp.rs
@@ -165,7 +165,7 @@ fn send_init_to_all_aps() {
0,
);
// SAFETY: we are sending init IPI to all APs.
- apic::borrow(|apic| unsafe { apic.send_ipi(icr) });
+ apic::with_borrow(|apic| unsafe { apic.send_ipi(icr) });
}
fn send_init_deassert() {
diff --git a/ostd/src/arch/x86/boot/smp.rs b/ostd/src/arch/x86/boot/smp.rs
--- a/ostd/src/arch/x86/boot/smp.rs
+++ b/ostd/src/arch/x86/boot/smp.rs
@@ -180,7 +180,7 @@ fn send_init_deassert() {
0,
);
// SAFETY: we are sending deassert IPI to all APs.
- apic::borrow(|apic| unsafe { apic.send_ipi(icr) });
+ apic::with_borrow(|apic| unsafe { apic.send_ipi(icr) });
}
/// Spin wait approximately `c` cycles.
diff --git a/ostd/src/arch/x86/boot/smp.rs b/ostd/src/arch/x86/boot/smp.rs
--- a/ostd/src/arch/x86/boot/smp.rs
+++ b/ostd/src/arch/x86/boot/smp.rs
@@ -180,7 +180,7 @@ fn send_init_deassert() {
0,
);
// SAFETY: we are sending deassert IPI to all APs.
- apic::borrow(|apic| unsafe { apic.send_ipi(icr) });
+ apic::with_borrow(|apic| unsafe { apic.send_ipi(icr) });
}
/// Spin wait approximately `c` cycles.
diff --git a/ostd/src/arch/x86/irq.rs b/ostd/src/arch/x86/irq.rs
--- a/ostd/src/arch/x86/irq.rs
+++ b/ostd/src/arch/x86/irq.rs
@@ -153,3 +153,27 @@ impl Drop for IrqCallbackHandle {
CALLBACK_ID_ALLOCATOR.get().unwrap().lock().free(self.id);
}
}
+
+/// Sends a general inter-processor interrupt (IPI) to the specified CPU.
+///
+/// # Safety
+///
+/// The caller must ensure that the CPU ID and the interrupt number corresponds
+/// to a safe function to call.
+pub(crate) unsafe fn send_ipi(cpu_id: u32, irq_num: u8) {
+ use crate::arch::kernel::apic::{self, Icr};
+
+ let icr = Icr::new(
+ apic::ApicId::from(cpu_id),
+ apic::DestinationShorthand::NoShorthand,
+ apic::TriggerMode::Edge,
+ apic::Level::Assert,
+ apic::DeliveryStatus::Idle,
+ apic::DestinationMode::Physical,
+ apic::DeliveryMode::Fixed,
+ irq_num,
+ );
+ apic::with_borrow(|apic| {
+ apic.send_ipi(icr);
+ });
+}
diff --git a/ostd/src/arch/x86/irq.rs b/ostd/src/arch/x86/irq.rs
--- a/ostd/src/arch/x86/irq.rs
+++ b/ostd/src/arch/x86/irq.rs
@@ -153,3 +153,27 @@ impl Drop for IrqCallbackHandle {
CALLBACK_ID_ALLOCATOR.get().unwrap().lock().free(self.id);
}
}
+
+/// Sends a general inter-processor interrupt (IPI) to the specified CPU.
+///
+/// # Safety
+///
+/// The caller must ensure that the CPU ID and the interrupt number corresponds
+/// to a safe function to call.
+pub(crate) unsafe fn send_ipi(cpu_id: u32, irq_num: u8) {
+ use crate::arch::kernel::apic::{self, Icr};
+
+ let icr = Icr::new(
+ apic::ApicId::from(cpu_id),
+ apic::DestinationShorthand::NoShorthand,
+ apic::TriggerMode::Edge,
+ apic::Level::Assert,
+ apic::DeliveryStatus::Idle,
+ apic::DestinationMode::Physical,
+ apic::DeliveryMode::Fixed,
+ irq_num,
+ );
+ apic::with_borrow(|apic| {
+ apic.send_ipi(icr);
+ });
+}
diff --git a/ostd/src/arch/x86/kernel/apic/mod.rs b/ostd/src/arch/x86/kernel/apic/mod.rs
--- a/ostd/src/arch/x86/kernel/apic/mod.rs
+++ b/ostd/src/arch/x86/kernel/apic/mod.rs
@@ -13,7 +13,7 @@ pub mod x2apic;
pub mod xapic;
cpu_local! {
- static APIC_INSTANCE: Once<RefCell<Box<dyn Apic + 'static>>> = Once::new();
+ static APIC_INSTANCE: RefCell<Option<Box<dyn Apic + 'static>>> = RefCell::new(None);
}
static APIC_TYPE: Once<ApicType> = Once::new();
diff --git a/ostd/src/arch/x86/kernel/apic/mod.rs b/ostd/src/arch/x86/kernel/apic/mod.rs
--- a/ostd/src/arch/x86/kernel/apic/mod.rs
+++ b/ostd/src/arch/x86/kernel/apic/mod.rs
@@ -13,7 +13,7 @@ pub mod x2apic;
pub mod xapic;
cpu_local! {
- static APIC_INSTANCE: Once<RefCell<Box<dyn Apic + 'static>>> = Once::new();
+ static APIC_INSTANCE: RefCell<Option<Box<dyn Apic + 'static>>> = RefCell::new(None);
}
static APIC_TYPE: Once<ApicType> = Once::new();
diff --git a/ostd/src/arch/x86/kernel/apic/mod.rs b/ostd/src/arch/x86/kernel/apic/mod.rs
--- a/ostd/src/arch/x86/kernel/apic/mod.rs
+++ b/ostd/src/arch/x86/kernel/apic/mod.rs
@@ -24,23 +24,29 @@ static APIC_TYPE: Once<ApicType> = Once::new();
/// local APIC instance. During the execution of the closure, the interrupts
/// are guaranteed to be disabled.
///
+/// This function also lazily initializes the Local APIC instance. It does
+/// enable the Local APIC if it is not enabled.
+///
/// Example:
/// ```rust
/// use ostd::arch::x86::kernel::apic;
///
-/// let ticks = apic::borrow(|apic| {
+/// let ticks = apic::with_borrow(|apic| {
/// let ticks = apic.timer_current_count();
/// apic.set_timer_init_count(0);
/// ticks
/// });
/// ```
-pub fn borrow<R>(f: impl FnOnce(&mut (dyn Apic + 'static)) -> R) -> R {
+pub fn with_borrow<R>(f: impl FnOnce(&mut (dyn Apic + 'static)) -> R) -> R {
let irq_guard = crate::trap::disable_local();
let apic_guard = APIC_INSTANCE.get_with(&irq_guard);
+ let mut apic_init_ref = apic_guard.borrow_mut();
// If it is not initialized, lazily initialize it.
- if !apic_guard.is_completed() {
- apic_guard.call_once(|| match APIC_TYPE.get().unwrap() {
+ let apic_ref = if let Some(apic_ref) = apic_init_ref.as_mut() {
+ apic_ref
+ } else {
+ *apic_init_ref = Some(match APIC_TYPE.get().unwrap() {
ApicType::XApic => {
let mut xapic = xapic::XApic::new().unwrap();
xapic.enable();
diff --git a/ostd/src/arch/x86/kernel/apic/mod.rs b/ostd/src/arch/x86/kernel/apic/mod.rs
--- a/ostd/src/arch/x86/kernel/apic/mod.rs
+++ b/ostd/src/arch/x86/kernel/apic/mod.rs
@@ -24,23 +24,29 @@ static APIC_TYPE: Once<ApicType> = Once::new();
/// local APIC instance. During the execution of the closure, the interrupts
/// are guaranteed to be disabled.
///
+/// This function also lazily initializes the Local APIC instance. It does
+/// enable the Local APIC if it is not enabled.
+///
/// Example:
/// ```rust
/// use ostd::arch::x86::kernel::apic;
///
-/// let ticks = apic::borrow(|apic| {
+/// let ticks = apic::with_borrow(|apic| {
/// let ticks = apic.timer_current_count();
/// apic.set_timer_init_count(0);
/// ticks
/// });
/// ```
-pub fn borrow<R>(f: impl FnOnce(&mut (dyn Apic + 'static)) -> R) -> R {
+pub fn with_borrow<R>(f: impl FnOnce(&mut (dyn Apic + 'static)) -> R) -> R {
let irq_guard = crate::trap::disable_local();
let apic_guard = APIC_INSTANCE.get_with(&irq_guard);
+ let mut apic_init_ref = apic_guard.borrow_mut();
// If it is not initialized, lazily initialize it.
- if !apic_guard.is_completed() {
- apic_guard.call_once(|| match APIC_TYPE.get().unwrap() {
+ let apic_ref = if let Some(apic_ref) = apic_init_ref.as_mut() {
+ apic_ref
+ } else {
+ *apic_init_ref = Some(match APIC_TYPE.get().unwrap() {
ApicType::XApic => {
let mut xapic = xapic::XApic::new().unwrap();
xapic.enable();
diff --git a/ostd/src/arch/x86/kernel/apic/mod.rs b/ostd/src/arch/x86/kernel/apic/mod.rs
--- a/ostd/src/arch/x86/kernel/apic/mod.rs
+++ b/ostd/src/arch/x86/kernel/apic/mod.rs
@@ -51,7 +57,7 @@ pub fn borrow<R>(f: impl FnOnce(&mut (dyn Apic + 'static)) -> R) -> R {
version & 0xff,
(version >> 16) & 0xff
);
- RefCell::new(Box::new(xapic))
+ Box::new(xapic)
}
ApicType::X2Apic => {
let mut x2apic = x2apic::X2Apic::new().unwrap();
diff --git a/ostd/src/arch/x86/kernel/apic/mod.rs b/ostd/src/arch/x86/kernel/apic/mod.rs
--- a/ostd/src/arch/x86/kernel/apic/mod.rs
+++ b/ostd/src/arch/x86/kernel/apic/mod.rs
@@ -51,7 +57,7 @@ pub fn borrow<R>(f: impl FnOnce(&mut (dyn Apic + 'static)) -> R) -> R {
version & 0xff,
(version >> 16) & 0xff
);
- RefCell::new(Box::new(xapic))
+ Box::new(xapic)
}
ApicType::X2Apic => {
let mut x2apic = x2apic::X2Apic::new().unwrap();
diff --git a/ostd/src/arch/x86/kernel/apic/mod.rs b/ostd/src/arch/x86/kernel/apic/mod.rs
--- a/ostd/src/arch/x86/kernel/apic/mod.rs
+++ b/ostd/src/arch/x86/kernel/apic/mod.rs
@@ -63,13 +69,12 @@ pub fn borrow<R>(f: impl FnOnce(&mut (dyn Apic + 'static)) -> R) -> R {
version & 0xff,
(version >> 16) & 0xff
);
- RefCell::new(Box::new(x2apic))
+ Box::new(x2apic)
}
});
- }
- let apic_cell = apic_guard.get().unwrap();
- let mut apic_ref = apic_cell.borrow_mut();
+ apic_init_ref.as_mut().unwrap()
+ };
let ret = f.call_once((apic_ref.as_mut(),));
diff --git a/ostd/src/arch/x86/kernel/apic/mod.rs b/ostd/src/arch/x86/kernel/apic/mod.rs
--- a/ostd/src/arch/x86/kernel/apic/mod.rs
+++ b/ostd/src/arch/x86/kernel/apic/mod.rs
@@ -63,13 +69,12 @@ pub fn borrow<R>(f: impl FnOnce(&mut (dyn Apic + 'static)) -> R) -> R {
version & 0xff,
(version >> 16) & 0xff
);
- RefCell::new(Box::new(x2apic))
+ Box::new(x2apic)
}
});
- }
- let apic_cell = apic_guard.get().unwrap();
- let mut apic_ref = apic_cell.borrow_mut();
+ apic_init_ref.as_mut().unwrap()
+ };
let ret = f.call_once((apic_ref.as_mut(),));
diff --git a/ostd/src/arch/x86/kernel/apic/mod.rs b/ostd/src/arch/x86/kernel/apic/mod.rs
--- a/ostd/src/arch/x86/kernel/apic/mod.rs
+++ b/ostd/src/arch/x86/kernel/apic/mod.rs
@@ -238,7 +243,6 @@ impl From<u32> for ApicId {
/// in the system excluding the sender.
#[repr(u64)]
pub enum DestinationShorthand {
- #[allow(dead_code)]
NoShorthand = 0b00,
#[allow(dead_code)]
MySelf = 0b01,
diff --git a/ostd/src/arch/x86/kernel/apic/mod.rs b/ostd/src/arch/x86/kernel/apic/mod.rs
--- a/ostd/src/arch/x86/kernel/apic/mod.rs
+++ b/ostd/src/arch/x86/kernel/apic/mod.rs
@@ -238,7 +243,6 @@ impl From<u32> for ApicId {
/// in the system excluding the sender.
#[repr(u64)]
pub enum DestinationShorthand {
- #[allow(dead_code)]
NoShorthand = 0b00,
#[allow(dead_code)]
MySelf = 0b01,
diff --git a/ostd/src/arch/x86/kernel/apic/mod.rs b/ostd/src/arch/x86/kernel/apic/mod.rs
--- a/ostd/src/arch/x86/kernel/apic/mod.rs
+++ b/ostd/src/arch/x86/kernel/apic/mod.rs
@@ -278,7 +282,6 @@ pub enum DestinationMode {
#[repr(u64)]
pub enum DeliveryMode {
/// Delivers the interrupt specified in the vector field to the target processor or processors.
- #[allow(dead_code)]
Fixed = 0b000,
/// Same as fixed mode, except that the interrupt is delivered to the processor executing at
/// the lowest priority among the set of processors specified in the destination field. The
diff --git a/ostd/src/arch/x86/kernel/apic/mod.rs b/ostd/src/arch/x86/kernel/apic/mod.rs
--- a/ostd/src/arch/x86/kernel/apic/mod.rs
+++ b/ostd/src/arch/x86/kernel/apic/mod.rs
@@ -278,7 +282,6 @@ pub enum DestinationMode {
#[repr(u64)]
pub enum DeliveryMode {
/// Delivers the interrupt specified in the vector field to the target processor or processors.
- #[allow(dead_code)]
Fixed = 0b000,
/// Same as fixed mode, except that the interrupt is delivered to the processor executing at
/// the lowest priority among the set of processors specified in the destination field. The
diff --git a/ostd/src/arch/x86/mod.rs b/ostd/src/arch/x86/mod.rs
--- a/ostd/src/arch/x86/mod.rs
+++ b/ostd/src/arch/x86/mod.rs
@@ -108,10 +108,21 @@ pub(crate) fn init_on_bsp() {
kernel::pic::init();
}
+/// Architecture-specific initialization on the application processor.
+///
+/// # Safety
+///
+/// This function must be called only once on each application processor.
+/// And it should be called after the BSP's call to [`init_on_bsp`].
+pub(crate) unsafe fn init_on_ap() {
+ // Trigger the initialization of the local APIC.
+ crate::arch::x86::kernel::apic::with_borrow(|_| {});
+}
+
pub(crate) fn interrupts_ack(irq_number: usize) {
if !cpu::CpuException::is_cpu_exception(irq_number as u16) {
kernel::pic::ack();
- kernel::apic::borrow(|apic| {
+ kernel::apic::with_borrow(|apic| {
apic.eoi();
});
}
diff --git a/ostd/src/arch/x86/mod.rs b/ostd/src/arch/x86/mod.rs
--- a/ostd/src/arch/x86/mod.rs
+++ b/ostd/src/arch/x86/mod.rs
@@ -108,10 +108,21 @@ pub(crate) fn init_on_bsp() {
kernel::pic::init();
}
+/// Architecture-specific initialization on the application processor.
+///
+/// # Safety
+///
+/// This function must be called only once on each application processor.
+/// And it should be called after the BSP's call to [`init_on_bsp`].
+pub(crate) unsafe fn init_on_ap() {
+ // Trigger the initialization of the local APIC.
+ crate::arch::x86::kernel::apic::with_borrow(|_| {});
+}
+
pub(crate) fn interrupts_ack(irq_number: usize) {
if !cpu::CpuException::is_cpu_exception(irq_number as u16) {
kernel::pic::ack();
- kernel::apic::borrow(|apic| {
+ kernel::apic::with_borrow(|apic| {
apic.eoi();
});
}
diff --git a/ostd/src/arch/x86/timer/apic.rs b/ostd/src/arch/x86/timer/apic.rs
--- a/ostd/src/arch/x86/timer/apic.rs
+++ b/ostd/src/arch/x86/timer/apic.rs
@@ -54,7 +54,7 @@ fn is_tsc_deadline_mode_supported() -> bool {
fn init_tsc_mode() -> IrqLine {
let timer_irq = IrqLine::alloc().unwrap();
// Enable tsc deadline mode
- apic::borrow(|apic| {
+ apic::with_borrow(|apic| {
apic.set_lvt_timer(timer_irq.num() as u64 | (1 << 18));
});
let tsc_step = TSC_FREQ.load(Ordering::Relaxed) / TIMER_FREQ;
diff --git a/ostd/src/arch/x86/timer/apic.rs b/ostd/src/arch/x86/timer/apic.rs
--- a/ostd/src/arch/x86/timer/apic.rs
+++ b/ostd/src/arch/x86/timer/apic.rs
@@ -54,7 +54,7 @@ fn is_tsc_deadline_mode_supported() -> bool {
fn init_tsc_mode() -> IrqLine {
let timer_irq = IrqLine::alloc().unwrap();
// Enable tsc deadline mode
- apic::borrow(|apic| {
+ apic::with_borrow(|apic| {
apic.set_lvt_timer(timer_irq.num() as u64 | (1 << 18));
});
let tsc_step = TSC_FREQ.load(Ordering::Relaxed) / TIMER_FREQ;
diff --git a/ostd/src/arch/x86/timer/apic.rs b/ostd/src/arch/x86/timer/apic.rs
--- a/ostd/src/arch/x86/timer/apic.rs
+++ b/ostd/src/arch/x86/timer/apic.rs
@@ -81,7 +81,7 @@ fn init_periodic_mode() -> IrqLine {
super::pit::enable_ioapic_line(irq.clone());
// Set APIC timer count
- apic::borrow(|apic| {
+ apic::with_borrow(|apic| {
apic.set_timer_div_config(DivideConfig::Divide64);
apic.set_timer_init_count(0xFFFF_FFFF);
});
diff --git a/ostd/src/arch/x86/timer/apic.rs b/ostd/src/arch/x86/timer/apic.rs
--- a/ostd/src/arch/x86/timer/apic.rs
+++ b/ostd/src/arch/x86/timer/apic.rs
@@ -81,7 +81,7 @@ fn init_periodic_mode() -> IrqLine {
super::pit::enable_ioapic_line(irq.clone());
// Set APIC timer count
- apic::borrow(|apic| {
+ apic::with_borrow(|apic| {
apic.set_timer_div_config(DivideConfig::Divide64);
apic.set_timer_init_count(0xFFFF_FFFF);
});
diff --git a/ostd/src/arch/x86/timer/apic.rs b/ostd/src/arch/x86/timer/apic.rs
--- a/ostd/src/arch/x86/timer/apic.rs
+++ b/ostd/src/arch/x86/timer/apic.rs
@@ -99,7 +99,7 @@ fn init_periodic_mode() -> IrqLine {
// Init APIC Timer
let timer_irq = IrqLine::alloc().unwrap();
- apic::borrow(|apic| {
+ apic::with_borrow(|apic| {
apic.set_timer_init_count(INIT_COUNT.load(Ordering::Relaxed));
apic.set_lvt_timer(timer_irq.num() as u64 | (1 << 17));
apic.set_timer_div_config(DivideConfig::Divide64);
diff --git a/ostd/src/arch/x86/timer/apic.rs b/ostd/src/arch/x86/timer/apic.rs
--- a/ostd/src/arch/x86/timer/apic.rs
+++ b/ostd/src/arch/x86/timer/apic.rs
@@ -99,7 +99,7 @@ fn init_periodic_mode() -> IrqLine {
// Init APIC Timer
let timer_irq = IrqLine::alloc().unwrap();
- apic::borrow(|apic| {
+ apic::with_borrow(|apic| {
apic.set_timer_init_count(INIT_COUNT.load(Ordering::Relaxed));
apic.set_lvt_timer(timer_irq.num() as u64 | (1 << 17));
apic.set_timer_div_config(DivideConfig::Divide64);
diff --git a/ostd/src/arch/x86/timer/apic.rs b/ostd/src/arch/x86/timer/apic.rs
--- a/ostd/src/arch/x86/timer/apic.rs
+++ b/ostd/src/arch/x86/timer/apic.rs
@@ -115,7 +115,7 @@ fn init_periodic_mode() -> IrqLine {
if IN_TIME.load(Ordering::Relaxed) < CALLBACK_TIMES || IS_FINISH.load(Ordering::Acquire) {
if IN_TIME.load(Ordering::Relaxed) == 0 {
- let remain_ticks = apic::borrow(|apic| apic.timer_current_count());
+ let remain_ticks = apic::with_borrow(|apic| apic.timer_current_count());
APIC_FIRST_COUNT.store(0xFFFF_FFFF - remain_ticks, Ordering::Relaxed);
}
IN_TIME.fetch_add(1, Ordering::Relaxed);
diff --git a/ostd/src/arch/x86/timer/apic.rs b/ostd/src/arch/x86/timer/apic.rs
--- a/ostd/src/arch/x86/timer/apic.rs
+++ b/ostd/src/arch/x86/timer/apic.rs
@@ -115,7 +115,7 @@ fn init_periodic_mode() -> IrqLine {
if IN_TIME.load(Ordering::Relaxed) < CALLBACK_TIMES || IS_FINISH.load(Ordering::Acquire) {
if IN_TIME.load(Ordering::Relaxed) == 0 {
- let remain_ticks = apic::borrow(|apic| apic.timer_current_count());
+ let remain_ticks = apic::with_borrow(|apic| apic.timer_current_count());
APIC_FIRST_COUNT.store(0xFFFF_FFFF - remain_ticks, Ordering::Relaxed);
}
IN_TIME.fetch_add(1, Ordering::Relaxed);
diff --git a/ostd/src/arch/x86/timer/apic.rs b/ostd/src/arch/x86/timer/apic.rs
--- a/ostd/src/arch/x86/timer/apic.rs
+++ b/ostd/src/arch/x86/timer/apic.rs
@@ -124,7 +124,7 @@ fn init_periodic_mode() -> IrqLine {
// Stop PIT and APIC Timer
super::pit::disable_ioapic_line();
- let remain_ticks = apic::borrow(|apic| {
+ let remain_ticks = apic::with_borrow(|apic| {
let remain_ticks = apic.timer_current_count();
apic.set_timer_init_count(0);
remain_ticks
diff --git a/ostd/src/arch/x86/timer/apic.rs b/ostd/src/arch/x86/timer/apic.rs
--- a/ostd/src/arch/x86/timer/apic.rs
+++ b/ostd/src/arch/x86/timer/apic.rs
@@ -124,7 +124,7 @@ fn init_periodic_mode() -> IrqLine {
// Stop PIT and APIC Timer
super::pit::disable_ioapic_line();
- let remain_ticks = apic::borrow(|apic| {
+ let remain_ticks = apic::with_borrow(|apic| {
let remain_ticks = apic.timer_current_count();
apic.set_timer_init_count(0);
remain_ticks
diff --git a/ostd/src/boot/smp.rs b/ostd/src/boot/smp.rs
--- a/ostd/src/boot/smp.rs
+++ b/ostd/src/boot/smp.rs
@@ -123,6 +123,13 @@ fn ap_early_entry(local_apic_id: u32) -> ! {
unsafe {
trapframe::init();
}
+
+ // SAFETY: this function is only called once on this AP, after the BSP has
+ // done the architecture-specific initialization.
+ unsafe {
+ crate::arch::init_on_ap();
+ }
+
crate::arch::irq::enable_local();
// SAFETY: this function is only called once on this AP.
diff --git a/ostd/src/boot/smp.rs b/ostd/src/boot/smp.rs
--- a/ostd/src/boot/smp.rs
+++ b/ostd/src/boot/smp.rs
@@ -123,6 +123,13 @@ fn ap_early_entry(local_apic_id: u32) -> ! {
unsafe {
trapframe::init();
}
+
+ // SAFETY: this function is only called once on this AP, after the BSP has
+ // done the architecture-specific initialization.
+ unsafe {
+ crate::arch::init_on_ap();
+ }
+
crate::arch::irq::enable_local();
// SAFETY: this function is only called once on this AP.
diff --git a/ostd/src/cpu/mod.rs b/ostd/src/cpu/mod.rs
--- a/ostd/src/cpu/mod.rs
+++ b/ostd/src/cpu/mod.rs
@@ -10,12 +10,7 @@ cfg_if::cfg_if! {
}
}
-use alloc::vec::Vec;
-
-use bitvec::{
- prelude::{BitVec, Lsb0},
- slice::IterOnes,
-};
+use bitvec::prelude::BitVec;
use local::cpu_local_cell;
use spin::Once;
diff --git a/ostd/src/cpu/mod.rs b/ostd/src/cpu/mod.rs
--- a/ostd/src/cpu/mod.rs
+++ b/ostd/src/cpu/mod.rs
@@ -10,12 +10,7 @@ cfg_if::cfg_if! {
}
}
-use alloc::vec::Vec;
-
-use bitvec::{
- prelude::{BitVec, Lsb0},
- slice::IterOnes,
-};
+use bitvec::prelude::BitVec;
use local::cpu_local_cell;
use spin::Once;
diff --git a/ostd/src/cpu/mod.rs b/ostd/src/cpu/mod.rs
--- a/ostd/src/cpu/mod.rs
+++ b/ostd/src/cpu/mod.rs
@@ -122,13 +117,6 @@ impl CpuSet {
self.bitset.set(cpu_id as usize, true);
}
- /// Adds a list of CPUs to the set.
- pub fn add_from_vec(&mut self, cpu_ids: Vec<u32>) {
- for cpu_id in cpu_ids {
- self.add(cpu_id)
- }
- }
-
/// Adds all CPUs to the set.
pub fn add_all(&mut self) {
self.bitset.fill(true);
diff --git a/ostd/src/cpu/mod.rs b/ostd/src/cpu/mod.rs
--- a/ostd/src/cpu/mod.rs
+++ b/ostd/src/cpu/mod.rs
@@ -122,13 +117,6 @@ impl CpuSet {
self.bitset.set(cpu_id as usize, true);
}
- /// Adds a list of CPUs to the set.
- pub fn add_from_vec(&mut self, cpu_ids: Vec<u32>) {
- for cpu_id in cpu_ids {
- self.add(cpu_id)
- }
- }
-
/// Adds all CPUs to the set.
pub fn add_all(&mut self) {
self.bitset.fill(true);
diff --git a/ostd/src/cpu/mod.rs b/ostd/src/cpu/mod.rs
--- a/ostd/src/cpu/mod.rs
+++ b/ostd/src/cpu/mod.rs
@@ -139,13 +127,6 @@ impl CpuSet {
self.bitset.set(cpu_id as usize, false);
}
- /// Removes a list of CPUs from the set.
- pub fn remove_from_vec(&mut self, cpu_ids: Vec<u32>) {
- for cpu_id in cpu_ids {
- self.remove(cpu_id);
- }
- }
-
/// Removes all CPUs from the set.
pub fn clear(&mut self) {
self.bitset.fill(false);
diff --git a/ostd/src/cpu/mod.rs b/ostd/src/cpu/mod.rs
--- a/ostd/src/cpu/mod.rs
+++ b/ostd/src/cpu/mod.rs
@@ -139,13 +127,6 @@ impl CpuSet {
self.bitset.set(cpu_id as usize, false);
}
- /// Removes a list of CPUs from the set.
- pub fn remove_from_vec(&mut self, cpu_ids: Vec<u32>) {
- for cpu_id in cpu_ids {
- self.remove(cpu_id);
- }
- }
-
/// Removes all CPUs from the set.
pub fn clear(&mut self) {
self.bitset.fill(false);
diff --git a/ostd/src/cpu/mod.rs b/ostd/src/cpu/mod.rs
--- a/ostd/src/cpu/mod.rs
+++ b/ostd/src/cpu/mod.rs
@@ -162,8 +143,8 @@ impl CpuSet {
}
/// Iterates over the CPUs in the set.
- pub fn iter(&self) -> IterOnes<'_, usize, Lsb0> {
- self.bitset.iter_ones()
+ pub fn iter(&self) -> impl Iterator<Item = u32> + '_ {
+ self.bitset.iter_ones().map(|idx| idx as u32)
}
}
diff --git a/ostd/src/cpu/mod.rs b/ostd/src/cpu/mod.rs
--- a/ostd/src/cpu/mod.rs
+++ b/ostd/src/cpu/mod.rs
@@ -162,8 +143,8 @@ impl CpuSet {
}
/// Iterates over the CPUs in the set.
- pub fn iter(&self) -> IterOnes<'_, usize, Lsb0> {
- self.bitset.iter_ones()
+ pub fn iter(&self) -> impl Iterator<Item = u32> + '_ {
+ self.bitset.iter_ones().map(|idx| idx as u32)
}
}
diff --git a/ostd/src/lib.rs b/ostd/src/lib.rs
--- a/ostd/src/lib.rs
+++ b/ostd/src/lib.rs
@@ -39,6 +39,7 @@ pub mod logger;
pub mod mm;
pub mod panicking;
pub mod prelude;
+pub mod smp;
pub mod sync;
pub mod task;
pub mod trap;
diff --git a/ostd/src/lib.rs b/ostd/src/lib.rs
--- a/ostd/src/lib.rs
+++ b/ostd/src/lib.rs
@@ -39,6 +39,7 @@ pub mod logger;
pub mod mm;
pub mod panicking;
pub mod prelude;
+pub mod smp;
pub mod sync;
pub mod task;
pub mod trap;
diff --git a/ostd/src/lib.rs b/ostd/src/lib.rs
--- a/ostd/src/lib.rs
+++ b/ostd/src/lib.rs
@@ -90,6 +91,8 @@ pub unsafe fn init() {
unsafe { trap::softirq::init() };
arch::init_on_bsp();
+ smp::init();
+
bus::init();
// SAFETY: This function is called only once on the BSP.
diff --git a/ostd/src/lib.rs b/ostd/src/lib.rs
--- a/ostd/src/lib.rs
+++ b/ostd/src/lib.rs
@@ -90,6 +91,8 @@ pub unsafe fn init() {
unsafe { trap::softirq::init() };
arch::init_on_bsp();
+ smp::init();
+
bus::init();
// SAFETY: This function is called only once on the BSP.
diff --git a/ostd/src/mm/frame/mod.rs b/ostd/src/mm/frame/mod.rs
--- a/ostd/src/mm/frame/mod.rs
+++ b/ostd/src/mm/frame/mod.rs
@@ -80,6 +80,21 @@ impl Frame {
core::ptr::copy_nonoverlapping(src.as_ptr(), self.as_mut_ptr(), self.size());
}
}
+
+ /// Get the reference count of the frame.
+ ///
+ /// It returns the number of all references to the page, including all the
+ /// existing page handles ([`Frame`]) and all the mappings in the page
+ /// table that points to the page.
+ ///
+ /// # Safety
+ ///
+ /// The function is safe to call, but using it requires extra care. The
+ /// reference count can be changed by other threads at any time including
+ /// potentially between calling this method and acting on the result.
+ pub fn reference_count(&self) -> u32 {
+ self.page.reference_count()
+ }
}
impl From<Page<FrameMeta>> for Frame {
diff --git a/ostd/src/mm/frame/mod.rs b/ostd/src/mm/frame/mod.rs
--- a/ostd/src/mm/frame/mod.rs
+++ b/ostd/src/mm/frame/mod.rs
@@ -80,6 +80,21 @@ impl Frame {
core::ptr::copy_nonoverlapping(src.as_ptr(), self.as_mut_ptr(), self.size());
}
}
+
+ /// Get the reference count of the frame.
+ ///
+ /// It returns the number of all references to the page, including all the
+ /// existing page handles ([`Frame`]) and all the mappings in the page
+ /// table that points to the page.
+ ///
+ /// # Safety
+ ///
+ /// The function is safe to call, but using it requires extra care. The
+ /// reference count can be changed by other threads at any time including
+ /// potentially between calling this method and acting on the result.
+ pub fn reference_count(&self) -> u32 {
+ self.page.reference_count()
+ }
}
impl From<Page<FrameMeta>> for Frame {
diff --git a/ostd/src/mm/kspace.rs b/ostd/src/mm/kspace.rs
--- a/ostd/src/mm/kspace.rs
+++ b/ostd/src/mm/kspace.rs
@@ -156,7 +156,7 @@ pub fn init_kernel_page_table(meta_pages: Vec<Page<MetaPageMeta>>) {
for meta_page in meta_pages {
// SAFETY: we are doing the metadata mappings for the kernel.
unsafe {
- cursor.map(meta_page.into(), prop);
+ let _old = cursor.map(meta_page.into(), prop);
}
}
}
diff --git a/ostd/src/mm/kspace.rs b/ostd/src/mm/kspace.rs
--- a/ostd/src/mm/kspace.rs
+++ b/ostd/src/mm/kspace.rs
@@ -156,7 +156,7 @@ pub fn init_kernel_page_table(meta_pages: Vec<Page<MetaPageMeta>>) {
for meta_page in meta_pages {
// SAFETY: we are doing the metadata mappings for the kernel.
unsafe {
- cursor.map(meta_page.into(), prop);
+ let _old = cursor.map(meta_page.into(), prop);
}
}
}
diff --git a/ostd/src/mm/kspace.rs b/ostd/src/mm/kspace.rs
--- a/ostd/src/mm/kspace.rs
+++ b/ostd/src/mm/kspace.rs
@@ -199,7 +199,7 @@ pub fn init_kernel_page_table(meta_pages: Vec<Page<MetaPageMeta>>) {
let page = Page::<KernelMeta>::from_unused(frame_paddr, KernelMeta::default());
// SAFETY: we are doing mappings for the kernel.
unsafe {
- cursor.map(page.into(), prop);
+ let _old = cursor.map(page.into(), prop);
}
}
}
diff --git a/ostd/src/mm/kspace.rs b/ostd/src/mm/kspace.rs
--- a/ostd/src/mm/kspace.rs
+++ b/ostd/src/mm/kspace.rs
@@ -199,7 +199,7 @@ pub fn init_kernel_page_table(meta_pages: Vec<Page<MetaPageMeta>>) {
let page = Page::<KernelMeta>::from_unused(frame_paddr, KernelMeta::default());
// SAFETY: we are doing mappings for the kernel.
unsafe {
- cursor.map(page.into(), prop);
+ let _old = cursor.map(page.into(), prop);
}
}
}
diff --git a/ostd/src/mm/page/mod.rs b/ostd/src/mm/page/mod.rs
--- a/ostd/src/mm/page/mod.rs
+++ b/ostd/src/mm/page/mod.rs
@@ -164,6 +164,21 @@ impl<M: PageMeta> Page<M> {
unsafe { &*(self.ptr as *const M) }
}
+ /// Get the reference count of the page.
+ ///
+ /// It returns the number of all references to the page, including all the
+ /// existing page handles ([`Page`], [`DynPage`]), and all the mappings in the
+ /// page table that points to the page.
+ ///
+ /// # Safety
+ ///
+ /// The function is safe to call, but using it requires extra care. The
+ /// reference count can be changed by other threads at any time including
+ /// potentially between calling this method and acting on the result.
+ pub fn reference_count(&self) -> u32 {
+ self.ref_count().load(Ordering::Relaxed)
+ }
+
fn ref_count(&self) -> &AtomicU32 {
unsafe { &(*self.ptr).ref_count }
}
diff --git a/ostd/src/mm/page/mod.rs b/ostd/src/mm/page/mod.rs
--- a/ostd/src/mm/page/mod.rs
+++ b/ostd/src/mm/page/mod.rs
@@ -164,6 +164,21 @@ impl<M: PageMeta> Page<M> {
unsafe { &*(self.ptr as *const M) }
}
+ /// Get the reference count of the page.
+ ///
+ /// It returns the number of all references to the page, including all the
+ /// existing page handles ([`Page`], [`DynPage`]), and all the mappings in the
+ /// page table that points to the page.
+ ///
+ /// # Safety
+ ///
+ /// The function is safe to call, but using it requires extra care. The
+ /// reference count can be changed by other threads at any time including
+ /// potentially between calling this method and acting on the result.
+ pub fn reference_count(&self) -> u32 {
+ self.ref_count().load(Ordering::Relaxed)
+ }
+
fn ref_count(&self) -> &AtomicU32 {
unsafe { &(*self.ptr).ref_count }
}
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -73,7 +73,10 @@ use super::{
page_size, pte_index, Child, KernelMode, PageTable, PageTableEntryTrait, PageTableError,
PageTableMode, PageTableNode, PagingConstsTrait, PagingLevel, UserMode,
};
-use crate::mm::{page::DynPage, Paddr, PageProperty, Vaddr};
+use crate::{
+ mm::{page::DynPage, Paddr, PageProperty, Vaddr},
+ task::{disable_preempt, DisabledPreemptGuard},
+};
#[derive(Clone, Debug)]
pub enum PageTableItem {
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -73,7 +73,10 @@ use super::{
page_size, pte_index, Child, KernelMode, PageTable, PageTableEntryTrait, PageTableError,
PageTableMode, PageTableNode, PagingConstsTrait, PagingLevel, UserMode,
};
-use crate::mm::{page::DynPage, Paddr, PageProperty, Vaddr};
+use crate::{
+ mm::{page::DynPage, Paddr, PageProperty, Vaddr},
+ task::{disable_preempt, DisabledPreemptGuard},
+};
#[derive(Clone, Debug)]
pub enum PageTableItem {
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -125,7 +128,8 @@ where
va: Vaddr,
/// The virtual address range that is locked.
barrier_va: Range<Vaddr>,
- phantom: PhantomData<&'a PageTable<M, E, C>>,
+ preempt_guard: DisabledPreemptGuard,
+ _phantom: PhantomData<&'a PageTable<M, E, C>>,
}
impl<'a, M: PageTableMode, E: PageTableEntryTrait, C: PagingConstsTrait> Cursor<'a, M, E, C>
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -125,7 +128,8 @@ where
va: Vaddr,
/// The virtual address range that is locked.
barrier_va: Range<Vaddr>,
- phantom: PhantomData<&'a PageTable<M, E, C>>,
+ preempt_guard: DisabledPreemptGuard,
+ _phantom: PhantomData<&'a PageTable<M, E, C>>,
}
impl<'a, M: PageTableMode, E: PageTableEntryTrait, C: PagingConstsTrait> Cursor<'a, M, E, C>
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -162,7 +166,8 @@ where
guard_level: C::NR_LEVELS,
va: va.start,
barrier_va: va.clone(),
- phantom: PhantomData,
+ preempt_guard: disable_preempt(),
+ _phantom: PhantomData,
};
// Go down and get proper locks. The cursor should hold a lock of a
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -162,7 +166,8 @@ where
guard_level: C::NR_LEVELS,
va: va.start,
barrier_va: va.clone(),
- phantom: PhantomData,
+ preempt_guard: disable_preempt(),
+ _phantom: PhantomData,
};
// Go down and get proper locks. The cursor should hold a lock of a
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -204,37 +209,28 @@ where
let level = self.level;
let va = self.va;
- let pte = self.read_cur_pte();
- if !pte.is_present() {
- return Ok(PageTableItem::NotMapped {
- va,
- len: page_size::<C>(level),
- });
- }
- if !pte.is_last(level) {
- self.level_down();
- continue;
- }
-
match self.cur_child() {
- Child::Page(page) => {
- return Ok(PageTableItem::Mapped {
+ Child::PageTable(_) => {
+ self.level_down();
+ continue;
+ }
+ Child::None => {
+ return Ok(PageTableItem::NotMapped {
va,
- page,
- prop: pte.prop(),
+ len: page_size::<C>(level),
});
}
- Child::Untracked(pa) => {
+ Child::Page(page, prop) => {
+ return Ok(PageTableItem::Mapped { va, page, prop });
+ }
+ Child::Untracked(pa, prop) => {
return Ok(PageTableItem::MappedUntracked {
va,
pa,
len: page_size::<C>(level),
- prop: pte.prop(),
+ prop,
});
}
- Child::None | Child::PageTable(_) => {
- unreachable!(); // Already checked with the PTE.
- }
}
}
}
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -204,37 +209,28 @@ where
let level = self.level;
let va = self.va;
- let pte = self.read_cur_pte();
- if !pte.is_present() {
- return Ok(PageTableItem::NotMapped {
- va,
- len: page_size::<C>(level),
- });
- }
- if !pte.is_last(level) {
- self.level_down();
- continue;
- }
-
match self.cur_child() {
- Child::Page(page) => {
- return Ok(PageTableItem::Mapped {
+ Child::PageTable(_) => {
+ self.level_down();
+ continue;
+ }
+ Child::None => {
+ return Ok(PageTableItem::NotMapped {
va,
- page,
- prop: pte.prop(),
+ len: page_size::<C>(level),
});
}
- Child::Untracked(pa) => {
+ Child::Page(page, prop) => {
+ return Ok(PageTableItem::Mapped { va, page, prop });
+ }
+ Child::Untracked(pa, prop) => {
return Ok(PageTableItem::MappedUntracked {
va,
pa,
len: page_size::<C>(level),
- prop: pte.prop(),
+ prop,
});
}
- Child::None | Child::PageTable(_) => {
- unreachable!(); // Already checked with the PTE.
- }
}
}
}
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -289,6 +285,10 @@ where
self.va
}
+ pub fn preempt_guard(&self) -> &DisabledPreemptGuard {
+ &self.preempt_guard
+ }
+
/// Goes up a level. We release the current page if it has no mappings since the cursor only moves
/// forward. And if needed we will do the final cleanup using this method after re-walk when the
/// cursor is dropped.
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -289,6 +285,10 @@ where
self.va
}
+ pub fn preempt_guard(&self) -> &DisabledPreemptGuard {
+ &self.preempt_guard
+ }
+
/// Goes up a level. We release the current page if it has no mappings since the cursor only moves
/// forward. And if needed we will do the final cleanup using this method after re-walk when the
/// cursor is dropped.
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -423,6 +423,8 @@ where
/// Maps the range starting from the current address to a [`DynPage`].
///
+ /// It returns the previously mapped [`DynPage`] if that exists.
+ ///
/// # Panics
///
/// This function will panic if
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -423,6 +423,8 @@ where
/// Maps the range starting from the current address to a [`DynPage`].
///
+ /// It returns the previously mapped [`DynPage`] if that exists.
+ ///
/// # Panics
///
/// This function will panic if
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -434,7 +436,7 @@ where
///
/// The caller should ensure that the virtual range being mapped does
/// not affect kernel's memory safety.
- pub unsafe fn map(&mut self, page: DynPage, prop: PageProperty) {
+ pub unsafe fn map(&mut self, page: DynPage, prop: PageProperty) -> Option<DynPage> {
let end = self.0.va + page.size();
assert!(end <= self.0.barrier_va.end);
debug_assert!(self.0.in_tracked_range());
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -434,7 +436,7 @@ where
///
/// The caller should ensure that the virtual range being mapped does
/// not affect kernel's memory safety.
- pub unsafe fn map(&mut self, page: DynPage, prop: PageProperty) {
+ pub unsafe fn map(&mut self, page: DynPage, prop: PageProperty) -> Option<DynPage> {
let end = self.0.va + page.size();
assert!(end <= self.0.barrier_va.end);
debug_assert!(self.0.in_tracked_range());
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -458,8 +460,19 @@ where
// Map the current page.
let idx = self.0.cur_idx();
- self.cur_node_mut().set_child_page(idx, page, prop);
+ let old = self
+ .cur_node_mut()
+ .replace_child(idx, Child::Page(page, prop), true);
self.0.move_forward();
+
+ match old {
+ Child::Page(old_page, _) => Some(old_page),
+ Child::None => None,
+ Child::PageTable(_) => {
+ todo!("Dropping page table nodes while mapping requires TLB flush")
+ }
+ Child::Untracked(_, _) => panic!("Mapping a tracked page in an untracked range"),
+ }
}
/// Maps the range starting from the current address to a physical address range.
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -458,8 +460,19 @@ where
// Map the current page.
let idx = self.0.cur_idx();
- self.cur_node_mut().set_child_page(idx, page, prop);
+ let old = self
+ .cur_node_mut()
+ .replace_child(idx, Child::Page(page, prop), true);
self.0.move_forward();
+
+ match old {
+ Child::Page(old_page, _) => Some(old_page),
+ Child::None => None,
+ Child::PageTable(_) => {
+ todo!("Dropping page table nodes while mapping requires TLB flush")
+ }
+ Child::Untracked(_, _) => panic!("Mapping a tracked page in an untracked range"),
+ }
}
/// Maps the range starting from the current address to a physical address range.
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -520,7 +533,9 @@ where
// Map the current page.
debug_assert!(!self.0.in_tracked_range());
let idx = self.0.cur_idx();
- self.cur_node_mut().set_child_untracked(idx, pa, prop);
+ let _ = self
+ .cur_node_mut()
+ .replace_child(idx, Child::Untracked(pa, prop), false);
let level = self.0.level;
pa += page_size::<C>(level);
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -520,7 +533,9 @@ where
// Map the current page.
debug_assert!(!self.0.in_tracked_range());
let idx = self.0.cur_idx();
- self.cur_node_mut().set_child_untracked(idx, pa, prop);
+ let _ = self
+ .cur_node_mut()
+ .replace_child(idx, Child::Untracked(pa, prop), false);
let level = self.0.level;
pa += page_size::<C>(level);
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -605,23 +620,25 @@ where
// Unmap the current page and return it.
let idx = self.0.cur_idx();
- let ret = self.cur_node_mut().take_child(idx, is_tracked);
+ let ret = self
+ .cur_node_mut()
+ .replace_child(idx, Child::None, is_tracked);
let ret_page_va = self.0.va;
let ret_page_size = page_size::<C>(self.0.level);
self.0.move_forward();
return match ret {
- Child::Page(page) => PageTableItem::Mapped {
+ Child::Page(page, prop) => PageTableItem::Mapped {
va: ret_page_va,
page,
- prop: cur_pte.prop(),
+ prop,
},
- Child::Untracked(pa) => PageTableItem::MappedUntracked {
+ Child::Untracked(pa, prop) => PageTableItem::MappedUntracked {
va: ret_page_va,
pa,
len: ret_page_size,
- prop: cur_pte.prop(),
+ prop,
},
Child::None | Child::PageTable(_) => unreachable!(),
};
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -605,23 +620,25 @@ where
// Unmap the current page and return it.
let idx = self.0.cur_idx();
- let ret = self.cur_node_mut().take_child(idx, is_tracked);
+ let ret = self
+ .cur_node_mut()
+ .replace_child(idx, Child::None, is_tracked);
let ret_page_va = self.0.va;
let ret_page_size = page_size::<C>(self.0.level);
self.0.move_forward();
return match ret {
- Child::Page(page) => PageTableItem::Mapped {
+ Child::Page(page, prop) => PageTableItem::Mapped {
va: ret_page_va,
page,
- prop: cur_pte.prop(),
+ prop,
},
- Child::Untracked(pa) => PageTableItem::MappedUntracked {
+ Child::Untracked(pa, prop) => PageTableItem::MappedUntracked {
va: ret_page_va,
pa,
len: ret_page_size,
- prop: cur_pte.prop(),
+ prop,
},
Child::None | Child::PageTable(_) => unreachable!(),
};
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -717,6 +734,10 @@ where
None
}
+ pub fn preempt_guard(&self) -> &DisabledPreemptGuard {
+ &self.0.preempt_guard
+ }
+
/// Consumes itself and leak the root guard for the caller if it locked the root level.
///
/// It is useful when the caller wants to keep the root guard while the cursor should be dropped.
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -717,6 +734,10 @@ where
None
}
+ pub fn preempt_guard(&self) -> &DisabledPreemptGuard {
+ &self.0.preempt_guard
+ }
+
/// Consumes itself and leak the root guard for the caller if it locked the root level.
///
/// It is useful when the caller wants to keep the root guard while the cursor should be dropped.
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -743,8 +764,12 @@ where
let new_node = PageTableNode::<E, C>::alloc(self.0.level - 1);
let idx = self.0.cur_idx();
let is_tracked = self.0.in_tracked_range();
- self.cur_node_mut()
- .set_child_pt(idx, new_node.clone_raw(), is_tracked);
+ let old = self.cur_node_mut().replace_child(
+ idx,
+ Child::PageTable(new_node.clone_raw()),
+ is_tracked,
+ );
+ debug_assert!(old.is_none());
self.0.level -= 1;
self.0.guards[(self.0.level - 1) as usize] = Some(new_node);
}
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -743,8 +764,12 @@ where
let new_node = PageTableNode::<E, C>::alloc(self.0.level - 1);
let idx = self.0.cur_idx();
let is_tracked = self.0.in_tracked_range();
- self.cur_node_mut()
- .set_child_pt(idx, new_node.clone_raw(), is_tracked);
+ let old = self.cur_node_mut().replace_child(
+ idx,
+ Child::PageTable(new_node.clone_raw()),
+ is_tracked,
+ );
+ debug_assert!(old.is_none());
self.0.level -= 1;
self.0.guards[(self.0.level - 1) as usize] = Some(new_node);
}
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -162,7 +162,11 @@ impl PageTable<KernelMode> {
for i in start..end {
if !root_node.read_pte(i).is_present() {
let node = PageTableNode::alloc(PagingConsts::NR_LEVELS - 1);
- root_node.set_child_pt(i, node.into_raw(), i < NR_PTES_PER_NODE * 3 / 4);
+ let _ = root_node.replace_child(
+ i,
+ Child::PageTable(node.into_raw()),
+ i < NR_PTES_PER_NODE * 3 / 4,
+ );
}
}
}
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -162,7 +162,11 @@ impl PageTable<KernelMode> {
for i in start..end {
if !root_node.read_pte(i).is_present() {
let node = PageTableNode::alloc(PagingConsts::NR_LEVELS - 1);
- root_node.set_child_pt(i, node.into_raw(), i < NR_PTES_PER_NODE * 3 / 4);
+ let _ = root_node.replace_child(
+ i,
+ Child::PageTable(node.into_raw()),
+ i < NR_PTES_PER_NODE * 3 / 4,
+ );
}
}
}
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -42,7 +42,6 @@ use crate::{
page_prop::PageProperty,
Paddr, PagingConstsTrait, PagingLevel, PAGE_SIZE,
},
- task::{disable_preempt, DisabledPreemptGuard},
};
/// The raw handle to a page table node.
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -42,7 +42,6 @@ use crate::{
page_prop::PageProperty,
Paddr, PagingConstsTrait, PagingLevel, PAGE_SIZE,
},
- task::{disable_preempt, DisabledPreemptGuard},
};
/// The raw handle to a page table node.
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -80,8 +79,6 @@ where
// count is needed.
let page = unsafe { Page::<PageTablePageMeta<E, C>>::from_raw(this.paddr()) };
- let disable_preempt = disable_preempt();
-
// Acquire the lock.
while page
.meta()
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -80,8 +79,6 @@ where
// count is needed.
let page = unsafe { Page::<PageTablePageMeta<E, C>>::from_raw(this.paddr()) };
- let disable_preempt = disable_preempt();
-
// Acquire the lock.
while page
.meta()
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -92,10 +89,7 @@ where
core::hint::spin_loop();
}
- PageTableNode::<E, C> {
- page,
- preempt_guard: disable_preempt,
- }
+ PageTableNode::<E, C> { page, _private: () }
}
/// Creates a copy of the handle.
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -92,10 +89,7 @@ where
core::hint::spin_loop();
}
- PageTableNode::<E, C> {
- page,
- preempt_guard: disable_preempt,
- }
+ PageTableNode::<E, C> { page, _private: () }
}
/// Creates a copy of the handle.
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -190,7 +184,7 @@ pub(super) struct PageTableNode<
[(); C::NR_LEVELS as usize]:,
{
pub(super) page: Page<PageTablePageMeta<E, C>>,
- preempt_guard: DisabledPreemptGuard,
+ _private: (),
}
// FIXME: We cannot `#[derive(Debug)]` here due to `DisabledPreemptGuard`. Should we skip
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -190,7 +184,7 @@ pub(super) struct PageTableNode<
[(); C::NR_LEVELS as usize]:,
{
pub(super) page: Page<PageTablePageMeta<E, C>>,
- preempt_guard: DisabledPreemptGuard,
+ _private: (),
}
// FIXME: We cannot `#[derive(Debug)]` here due to `DisabledPreemptGuard`. Should we skip
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -215,12 +209,21 @@ where
[(); C::NR_LEVELS as usize]:,
{
PageTable(RawPageTableNode<E, C>),
- Page(DynPage),
+ Page(DynPage, PageProperty),
/// Pages not tracked by handles.
- Untracked(Paddr),
+ Untracked(Paddr, PageProperty),
None,
}
+impl<E: PageTableEntryTrait, C: PagingConstsTrait> Child<E, C>
+where
+ [(); C::NR_LEVELS as usize]:,
+{
+ pub(super) fn is_none(&self) -> bool {
+ matches!(self, Child::None)
+ }
+}
+
impl<E: PageTableEntryTrait, C: PagingConstsTrait> PageTableNode<E, C>
where
[(); C::NR_LEVELS as usize]:,
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -215,12 +209,21 @@ where
[(); C::NR_LEVELS as usize]:,
{
PageTable(RawPageTableNode<E, C>),
- Page(DynPage),
+ Page(DynPage, PageProperty),
/// Pages not tracked by handles.
- Untracked(Paddr),
+ Untracked(Paddr, PageProperty),
None,
}
+impl<E: PageTableEntryTrait, C: PagingConstsTrait> Child<E, C>
+where
+ [(); C::NR_LEVELS as usize]:,
+{
+ pub(super) fn is_none(&self) -> bool {
+ matches!(self, Child::None)
+ }
+}
+
impl<E: PageTableEntryTrait, C: PagingConstsTrait> PageTableNode<E, C>
where
[(); C::NR_LEVELS as usize]:,
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -241,10 +244,7 @@ where
unsafe { core::ptr::write_bytes(ptr, 0, PAGE_SIZE) };
debug_assert!(E::new_absent().as_bytes().iter().all(|&b| b == 0));
- Self {
- page,
- preempt_guard: disable_preempt(),
- }
+ Self { page, _private: () }
}
pub fn level(&self) -> PagingLevel {
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -241,10 +244,7 @@ where
unsafe { core::ptr::write_bytes(ptr, 0, PAGE_SIZE) };
debug_assert!(E::new_absent().as_bytes().iter().all(|&b| b == 0));
- Self {
- page,
- preempt_guard: disable_preempt(),
- }
+ Self { page, _private: () }
}
pub fn level(&self) -> PagingLevel {
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -253,16 +253,11 @@ where
/// Converts the handle into a raw handle to be stored in a PTE or CPU.
pub(super) fn into_raw(self) -> RawPageTableNode<E, C> {
- let mut this = ManuallyDrop::new(self);
+ let this = ManuallyDrop::new(self);
let raw = this.page.paddr();
this.page.meta().lock.store(0, Ordering::Release);
- // SAFETY: The field will no longer be accessed and we need to drop the field to release
- // the preempt count.
- unsafe {
- core::ptr::drop_in_place(&mut this.preempt_guard);
- }
RawPageTableNode {
raw,
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -253,16 +253,11 @@ where
/// Converts the handle into a raw handle to be stored in a PTE or CPU.
pub(super) fn into_raw(self) -> RawPageTableNode<E, C> {
- let mut this = ManuallyDrop::new(self);
+ let this = ManuallyDrop::new(self);
let raw = this.page.paddr();
this.page.meta().lock.store(0, Ordering::Release);
- // SAFETY: The field will no longer be accessed and we need to drop the field to release
- // the preempt count.
- unsafe {
- core::ptr::drop_in_place(&mut this.preempt_guard);
- }
RawPageTableNode {
raw,
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -300,40 +295,82 @@ where
_phantom: PhantomData,
})
} else if in_tracked_range {
- // SAFETY: We have a reference count to the page and can safely increase the reference
- // count by one more.
+ // SAFETY: We have a reference count to the page and can safely
+ // increase the reference count by one more.
unsafe {
DynPage::inc_ref_count(paddr);
}
- Child::Page(unsafe { DynPage::from_raw(paddr) })
+ // SAFETY: The physical address of the PTE points to a forgotten
+ // page. It is reclaimed only once.
+ Child::Page(unsafe { DynPage::from_raw(paddr) }, pte.prop())
} else {
- Child::Untracked(paddr)
+ Child::Untracked(paddr, pte.prop())
}
}
}
- /// Remove the child at the given index and return it.
- pub(super) fn take_child(&mut self, idx: usize, in_tracked_range: bool) -> Child<E, C> {
+ /// Replace the child at the given index with a new child.
+ ///
+ /// The old child is returned.
+ pub(super) fn replace_child(
+ &mut self,
+ idx: usize,
+ new_child: Child<E, C>,
+ in_tracked_range: bool,
+ ) -> Child<E, C> {
debug_assert!(idx < nr_subpage_per_huge::<C>());
- let pte = self.read_pte(idx);
- if !pte.is_present() {
- Child::None
- } else {
- let paddr = pte.paddr();
- let is_last = pte.is_last(self.level());
- *self.nr_children_mut() -= 1;
- self.write_pte(idx, E::new_absent());
- if !is_last {
+ let old_pte = self.read_pte(idx);
+
+ let new_child_is_none = match new_child {
+ Child::None => {
+ if old_pte.is_present() {
+ self.write_pte(idx, E::new_absent());
+ }
+ true
+ }
+ Child::PageTable(pt) => {
+ let pt = ManuallyDrop::new(pt);
+ let new_pte = E::new_pt(pt.paddr());
+ self.write_pte(idx, new_pte);
+ false
+ }
+ Child::Page(page, prop) => {
+ debug_assert!(in_tracked_range);
+ let new_pte = E::new_page(page.into_raw(), self.level(), prop);
+ self.write_pte(idx, new_pte);
+ false
+ }
+ Child::Untracked(pa, prop) => {
+ debug_assert!(!in_tracked_range);
+ let new_pte = E::new_page(pa, self.level(), prop);
+ self.write_pte(idx, new_pte);
+ false
+ }
+ };
+
+ if old_pte.is_present() {
+ if new_child_is_none {
+ *self.nr_children_mut() -= 1;
+ }
+ let paddr = old_pte.paddr();
+ if !old_pte.is_last(self.level()) {
Child::PageTable(RawPageTableNode {
raw: paddr,
_phantom: PhantomData,
})
} else if in_tracked_range {
- Child::Page(unsafe { DynPage::from_raw(paddr) })
+ // SAFETY: The physical address of the old PTE points to a
+ // forgotten page. It is reclaimed only once.
+ Child::Page(unsafe { DynPage::from_raw(paddr) }, old_pte.prop())
} else {
- Child::Untracked(paddr)
+ Child::Untracked(paddr, old_pte.prop())
+ }
+ } else {
+ if !new_child_is_none {
+ *self.nr_children_mut() += 1;
}
+ Child::None
}
}
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -300,40 +295,82 @@ where
_phantom: PhantomData,
})
} else if in_tracked_range {
- // SAFETY: We have a reference count to the page and can safely increase the reference
- // count by one more.
+ // SAFETY: We have a reference count to the page and can safely
+ // increase the reference count by one more.
unsafe {
DynPage::inc_ref_count(paddr);
}
- Child::Page(unsafe { DynPage::from_raw(paddr) })
+ // SAFETY: The physical address of the PTE points to a forgotten
+ // page. It is reclaimed only once.
+ Child::Page(unsafe { DynPage::from_raw(paddr) }, pte.prop())
} else {
- Child::Untracked(paddr)
+ Child::Untracked(paddr, pte.prop())
}
}
}
- /// Remove the child at the given index and return it.
- pub(super) fn take_child(&mut self, idx: usize, in_tracked_range: bool) -> Child<E, C> {
+ /// Replace the child at the given index with a new child.
+ ///
+ /// The old child is returned.
+ pub(super) fn replace_child(
+ &mut self,
+ idx: usize,
+ new_child: Child<E, C>,
+ in_tracked_range: bool,
+ ) -> Child<E, C> {
debug_assert!(idx < nr_subpage_per_huge::<C>());
- let pte = self.read_pte(idx);
- if !pte.is_present() {
- Child::None
- } else {
- let paddr = pte.paddr();
- let is_last = pte.is_last(self.level());
- *self.nr_children_mut() -= 1;
- self.write_pte(idx, E::new_absent());
- if !is_last {
+ let old_pte = self.read_pte(idx);
+
+ let new_child_is_none = match new_child {
+ Child::None => {
+ if old_pte.is_present() {
+ self.write_pte(idx, E::new_absent());
+ }
+ true
+ }
+ Child::PageTable(pt) => {
+ let pt = ManuallyDrop::new(pt);
+ let new_pte = E::new_pt(pt.paddr());
+ self.write_pte(idx, new_pte);
+ false
+ }
+ Child::Page(page, prop) => {
+ debug_assert!(in_tracked_range);
+ let new_pte = E::new_page(page.into_raw(), self.level(), prop);
+ self.write_pte(idx, new_pte);
+ false
+ }
+ Child::Untracked(pa, prop) => {
+ debug_assert!(!in_tracked_range);
+ let new_pte = E::new_page(pa, self.level(), prop);
+ self.write_pte(idx, new_pte);
+ false
+ }
+ };
+
+ if old_pte.is_present() {
+ if new_child_is_none {
+ *self.nr_children_mut() -= 1;
+ }
+ let paddr = old_pte.paddr();
+ if !old_pte.is_last(self.level()) {
Child::PageTable(RawPageTableNode {
raw: paddr,
_phantom: PhantomData,
})
} else if in_tracked_range {
- Child::Page(unsafe { DynPage::from_raw(paddr) })
+ // SAFETY: The physical address of the old PTE points to a
+ // forgotten page. It is reclaimed only once.
+ Child::Page(unsafe { DynPage::from_raw(paddr) }, old_pte.prop())
} else {
- Child::Untracked(paddr)
+ Child::Untracked(paddr, old_pte.prop())
+ }
+ } else {
+ if !new_child_is_none {
+ *self.nr_children_mut() += 1;
}
+ Child::None
}
}
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -364,16 +401,17 @@ where
Child::PageTable(pt) => {
let guard = pt.clone_shallow().lock();
let new_child = guard.make_copy(0..nr_subpage_per_huge::<C>(), 0..0);
- new_pt.set_child_pt(i, new_child.into_raw(), true);
+ let old = new_pt.replace_child(i, Child::PageTable(new_child.into_raw()), true);
+ debug_assert!(old.is_none());
copied_child_count -= 1;
}
- Child::Page(page) => {
- let prop = self.read_pte_prop(i);
- new_pt.set_child_page(i, page.clone(), prop);
+ Child::Page(page, prop) => {
+ let old = new_pt.replace_child(i, Child::Page(page.clone(), prop), true);
+ debug_assert!(old.is_none());
copied_child_count -= 1;
}
Child::None => {}
- Child::Untracked(_) => {
+ Child::Untracked(_, _) => {
unreachable!();
}
}
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -364,16 +401,17 @@ where
Child::PageTable(pt) => {
let guard = pt.clone_shallow().lock();
let new_child = guard.make_copy(0..nr_subpage_per_huge::<C>(), 0..0);
- new_pt.set_child_pt(i, new_child.into_raw(), true);
+ let old = new_pt.replace_child(i, Child::PageTable(new_child.into_raw()), true);
+ debug_assert!(old.is_none());
copied_child_count -= 1;
}
- Child::Page(page) => {
- let prop = self.read_pte_prop(i);
- new_pt.set_child_page(i, page.clone(), prop);
+ Child::Page(page, prop) => {
+ let old = new_pt.replace_child(i, Child::Page(page.clone(), prop), true);
+ debug_assert!(old.is_none());
copied_child_count -= 1;
}
Child::None => {}
- Child::Untracked(_) => {
+ Child::Untracked(_, _) => {
unreachable!();
}
}
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -386,11 +424,16 @@ where
debug_assert_eq!(self.level(), C::NR_LEVELS);
match self.child(i, /*meaningless*/ true) {
Child::PageTable(pt) => {
- new_pt.set_child_pt(i, pt.clone_shallow(), /*meaningless*/ true);
+ let old = new_pt.replace_child(
+ i,
+ Child::PageTable(pt.clone_shallow()),
+ /*meaningless*/ true,
+ );
+ debug_assert!(old.is_none());
copied_child_count -= 1;
}
Child::None => {}
- Child::Page(_) | Child::Untracked(_) => {
+ Child::Page(_, _) | Child::Untracked(_, _) => {
unreachable!();
}
}
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -386,11 +424,16 @@ where
debug_assert_eq!(self.level(), C::NR_LEVELS);
match self.child(i, /*meaningless*/ true) {
Child::PageTable(pt) => {
- new_pt.set_child_pt(i, pt.clone_shallow(), /*meaningless*/ true);
+ let old = new_pt.replace_child(
+ i,
+ Child::PageTable(pt.clone_shallow()),
+ /*meaningless*/ true,
+ );
+ debug_assert!(old.is_none());
copied_child_count -= 1;
}
Child::None => {}
- Child::Page(_) | Child::Untracked(_) => {
+ Child::Page(_, _) | Child::Untracked(_, _) => {
unreachable!();
}
}
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -399,73 +442,23 @@ where
new_pt
}
- /// Sets a child page table at a given index.
- pub(super) fn set_child_pt(
- &mut self,
- idx: usize,
- pt: RawPageTableNode<E, C>,
- in_tracked_range: bool,
- ) {
- // They should be ensured by the cursor.
- debug_assert!(idx < nr_subpage_per_huge::<C>());
-
- // The ownership is transferred to a raw PTE. Don't drop the handle.
- let pt = ManuallyDrop::new(pt);
-
- let pte = Some(E::new_pt(pt.paddr()));
- self.overwrite_pte(idx, pte, in_tracked_range);
- }
-
- /// Map a page at a given index.
- pub(super) fn set_child_page(&mut self, idx: usize, page: DynPage, prop: PageProperty) {
- // They should be ensured by the cursor.
- debug_assert!(idx < nr_subpage_per_huge::<C>());
- debug_assert_eq!(page.level(), self.level());
-
- // Use the physical address rather than the page handle to track
- // the page, and record the physical address in the PTE.
- let pte = Some(E::new_page(page.into_raw(), self.level(), prop));
- self.overwrite_pte(idx, pte, true);
- }
-
- /// Sets an untracked child page at a given index.
- ///
- /// # Safety
- ///
- /// The caller must ensure that the physical address is valid and safe to map.
- pub(super) unsafe fn set_child_untracked(&mut self, idx: usize, pa: Paddr, prop: PageProperty) {
- // It should be ensured by the cursor.
- debug_assert!(idx < nr_subpage_per_huge::<C>());
-
- let pte = Some(E::new_page(pa, self.level(), prop));
- self.overwrite_pte(idx, pte, false);
- }
-
- /// Reads the info from a page table entry at a given index.
- pub(super) fn read_pte_prop(&self, idx: usize) -> PageProperty {
- self.read_pte(idx).prop()
- }
-
/// Splits the untracked huge page mapped at `idx` to smaller pages.
pub(super) fn split_untracked_huge(&mut self, idx: usize) {
// These should be ensured by the cursor.
debug_assert!(idx < nr_subpage_per_huge::<C>());
debug_assert!(self.level() > 1);
- let Child::Untracked(pa) = self.child(idx, false) else {
+ let Child::Untracked(pa, prop) = self.child(idx, false) else {
panic!("`split_untracked_huge` not called on an untracked huge page");
};
- let prop = self.read_pte_prop(idx);
let mut new_page = PageTableNode::<E, C>::alloc(self.level() - 1);
for i in 0..nr_subpage_per_huge::<C>() {
let small_pa = pa + i * page_size::<C>(self.level() - 1);
- // SAFETY: the index is within the bound and either physical address and
- // the property are valid.
- unsafe { new_page.set_child_untracked(i, small_pa, prop) };
+ new_page.replace_child(i, Child::Untracked(small_pa, prop), false);
}
- self.set_child_pt(idx, new_page.into_raw(), false);
+ self.replace_child(idx, Child::PageTable(new_page.into_raw()), false);
}
/// Protects an already mapped child at a given index.
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -399,73 +442,23 @@ where
new_pt
}
- /// Sets a child page table at a given index.
- pub(super) fn set_child_pt(
- &mut self,
- idx: usize,
- pt: RawPageTableNode<E, C>,
- in_tracked_range: bool,
- ) {
- // They should be ensured by the cursor.
- debug_assert!(idx < nr_subpage_per_huge::<C>());
-
- // The ownership is transferred to a raw PTE. Don't drop the handle.
- let pt = ManuallyDrop::new(pt);
-
- let pte = Some(E::new_pt(pt.paddr()));
- self.overwrite_pte(idx, pte, in_tracked_range);
- }
-
- /// Map a page at a given index.
- pub(super) fn set_child_page(&mut self, idx: usize, page: DynPage, prop: PageProperty) {
- // They should be ensured by the cursor.
- debug_assert!(idx < nr_subpage_per_huge::<C>());
- debug_assert_eq!(page.level(), self.level());
-
- // Use the physical address rather than the page handle to track
- // the page, and record the physical address in the PTE.
- let pte = Some(E::new_page(page.into_raw(), self.level(), prop));
- self.overwrite_pte(idx, pte, true);
- }
-
- /// Sets an untracked child page at a given index.
- ///
- /// # Safety
- ///
- /// The caller must ensure that the physical address is valid and safe to map.
- pub(super) unsafe fn set_child_untracked(&mut self, idx: usize, pa: Paddr, prop: PageProperty) {
- // It should be ensured by the cursor.
- debug_assert!(idx < nr_subpage_per_huge::<C>());
-
- let pte = Some(E::new_page(pa, self.level(), prop));
- self.overwrite_pte(idx, pte, false);
- }
-
- /// Reads the info from a page table entry at a given index.
- pub(super) fn read_pte_prop(&self, idx: usize) -> PageProperty {
- self.read_pte(idx).prop()
- }
-
/// Splits the untracked huge page mapped at `idx` to smaller pages.
pub(super) fn split_untracked_huge(&mut self, idx: usize) {
// These should be ensured by the cursor.
debug_assert!(idx < nr_subpage_per_huge::<C>());
debug_assert!(self.level() > 1);
- let Child::Untracked(pa) = self.child(idx, false) else {
+ let Child::Untracked(pa, prop) = self.child(idx, false) else {
panic!("`split_untracked_huge` not called on an untracked huge page");
};
- let prop = self.read_pte_prop(idx);
let mut new_page = PageTableNode::<E, C>::alloc(self.level() - 1);
for i in 0..nr_subpage_per_huge::<C>() {
let small_pa = pa + i * page_size::<C>(self.level() - 1);
- // SAFETY: the index is within the bound and either physical address and
- // the property are valid.
- unsafe { new_page.set_child_untracked(i, small_pa, prop) };
+ new_page.replace_child(i, Child::Untracked(small_pa, prop), false);
}
- self.set_child_pt(idx, new_page.into_raw(), false);
+ self.replace_child(idx, Child::PageTable(new_page.into_raw()), false);
}
/// Protects an already mapped child at a given index.
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -512,47 +505,6 @@ where
unsafe { &mut *self.meta().nr_children.get() }
}
- /// Replaces a page table entry at a given index.
- ///
- /// This method will ensure that the child presented by the overwritten
- /// PTE is dropped, and the child count is updated.
- ///
- /// The caller in this module will ensure that the PTE points to initialized
- /// memory if the child is a page table.
- fn overwrite_pte(&mut self, idx: usize, pte: Option<E>, in_tracked_range: bool) {
- let existing_pte = self.read_pte(idx);
-
- if existing_pte.is_present() {
- self.write_pte(idx, pte.unwrap_or(E::new_absent()));
-
- // Drop the child. We must set the PTE before dropping the child.
- // Just restore the handle and drop the handle.
-
- let paddr = existing_pte.paddr();
- // SAFETY: Both the `from_raw` operations here are safe as the physical
- // address is valid and casted from a handle.
- unsafe {
- if !existing_pte.is_last(self.level()) {
- // This is a page table.
- drop(Page::<PageTablePageMeta<E, C>>::from_raw(paddr));
- } else if in_tracked_range {
- // This is a frame.
- drop(DynPage::from_raw(paddr));
- }
- }
-
- // Update the child count.
- if pte.is_none() {
- *self.nr_children_mut() -= 1;
- }
- } else if let Some(e) = pte {
- // SAFETY: This is safe as described in the above branch.
- unsafe { (self.as_ptr() as *mut E).add(idx).write(e) };
-
- *self.nr_children_mut() += 1;
- }
- }
-
fn as_ptr(&self) -> *const E {
paddr_to_vaddr(self.start_paddr()) as *const E
}
diff --git a/ostd/src/mm/page_table/node.rs b/ostd/src/mm/page_table/node.rs
--- a/ostd/src/mm/page_table/node.rs
+++ b/ostd/src/mm/page_table/node.rs
@@ -512,47 +505,6 @@ where
unsafe { &mut *self.meta().nr_children.get() }
}
- /// Replaces a page table entry at a given index.
- ///
- /// This method will ensure that the child presented by the overwritten
- /// PTE is dropped, and the child count is updated.
- ///
- /// The caller in this module will ensure that the PTE points to initialized
- /// memory if the child is a page table.
- fn overwrite_pte(&mut self, idx: usize, pte: Option<E>, in_tracked_range: bool) {
- let existing_pte = self.read_pte(idx);
-
- if existing_pte.is_present() {
- self.write_pte(idx, pte.unwrap_or(E::new_absent()));
-
- // Drop the child. We must set the PTE before dropping the child.
- // Just restore the handle and drop the handle.
-
- let paddr = existing_pte.paddr();
- // SAFETY: Both the `from_raw` operations here are safe as the physical
- // address is valid and casted from a handle.
- unsafe {
- if !existing_pte.is_last(self.level()) {
- // This is a page table.
- drop(Page::<PageTablePageMeta<E, C>>::from_raw(paddr));
- } else if in_tracked_range {
- // This is a frame.
- drop(DynPage::from_raw(paddr));
- }
- }
-
- // Update the child count.
- if pte.is_none() {
- *self.nr_children_mut() -= 1;
- }
- } else if let Some(e) = pte {
- // SAFETY: This is safe as described in the above branch.
- unsafe { (self.as_ptr() as *mut E).add(idx).write(e) };
-
- *self.nr_children_mut() += 1;
- }
- }
-
fn as_ptr(&self) -> *const E {
paddr_to_vaddr(self.start_paddr()) as *const E
}
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -9,29 +9,31 @@
//! powerful concurrent accesses to the page table, and suffers from the same
//! validity concerns as described in [`super::page_table::cursor`].
-use core::ops::Range;
+use alloc::collections::vec_deque::VecDeque;
+use core::{
+ ops::Range,
+ sync::atomic::{AtomicPtr, Ordering},
+};
use spin::Once;
use super::{
io::Fallible,
kspace::KERNEL_PAGE_TABLE,
+ page::DynPage,
page_table::{PageTable, UserMode},
PageFlags, PageProperty, VmReader, VmWriter, PAGE_SIZE,
};
use crate::{
- arch::mm::{
- current_page_table_paddr, tlb_flush_addr, tlb_flush_addr_range,
- tlb_flush_all_excluding_global, PageTableEntry, PagingConsts,
- },
- cpu::{CpuExceptionInfo, CpuSet, PinCurrentCpu},
- cpu_local_cell,
+ arch::mm::{current_page_table_paddr, PageTableEntry, PagingConsts},
+ cpu::{num_cpus, CpuExceptionInfo, CpuSet, PinCurrentCpu},
+ cpu_local,
mm::{
page_table::{self, PageTableItem},
Frame, MAX_USERSPACE_VADDR,
},
prelude::*,
- sync::SpinLock,
+ sync::{RwLock, RwLockReadGuard, SpinLock},
task::disable_preempt,
Error,
};
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -9,29 +9,31 @@
//! powerful concurrent accesses to the page table, and suffers from the same
//! validity concerns as described in [`super::page_table::cursor`].
-use core::ops::Range;
+use alloc::collections::vec_deque::VecDeque;
+use core::{
+ ops::Range,
+ sync::atomic::{AtomicPtr, Ordering},
+};
use spin::Once;
use super::{
io::Fallible,
kspace::KERNEL_PAGE_TABLE,
+ page::DynPage,
page_table::{PageTable, UserMode},
PageFlags, PageProperty, VmReader, VmWriter, PAGE_SIZE,
};
use crate::{
- arch::mm::{
- current_page_table_paddr, tlb_flush_addr, tlb_flush_addr_range,
- tlb_flush_all_excluding_global, PageTableEntry, PagingConsts,
- },
- cpu::{CpuExceptionInfo, CpuSet, PinCurrentCpu},
- cpu_local_cell,
+ arch::mm::{current_page_table_paddr, PageTableEntry, PagingConsts},
+ cpu::{num_cpus, CpuExceptionInfo, CpuSet, PinCurrentCpu},
+ cpu_local,
mm::{
page_table::{self, PageTableItem},
Frame, MAX_USERSPACE_VADDR,
},
prelude::*,
- sync::SpinLock,
+ sync::{RwLock, RwLockReadGuard, SpinLock},
task::disable_preempt,
Error,
};
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -55,28 +57,18 @@ use crate::{
pub struct VmSpace {
pt: PageTable<UserMode>,
page_fault_handler: Once<fn(&VmSpace, &CpuExceptionInfo) -> core::result::Result<(), ()>>,
- /// The CPUs that the `VmSpace` is activated on.
- ///
- /// TODO: implement an atomic bitset to optimize the performance in cases
- /// that the number of CPUs is not large.
- activated_cpus: SpinLock<CpuSet>,
+ /// A CPU can only activate a `VmSpace` when no mutable cursors are alive.
+ /// Cursors hold read locks and activation require a write lock.
+ activation_lock: RwLock<()>,
}
-// Notes on TLB flushing:
-//
-// We currently assume that:
-// 1. `VmSpace` _might_ be activated on the current CPU and the user memory _might_ be used
-// immediately after we make changes to the page table entries. So we must invalidate the
-// corresponding TLB caches accordingly.
-// 2. `VmSpace` must _not_ be activated on another CPU. This assumption is trivial, since SMP
-// support is not yet available. But we need to consider this situation in the future (TODO).
impl VmSpace {
/// Creates a new VM address space.
pub fn new() -> Self {
Self {
pt: KERNEL_PAGE_TABLE.get().unwrap().create_user_page_table(),
page_fault_handler: Once::new(),
- activated_cpus: SpinLock::new(CpuSet::new_empty()),
+ activation_lock: RwLock::new(()),
}
}
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -55,28 +57,18 @@ use crate::{
pub struct VmSpace {
pt: PageTable<UserMode>,
page_fault_handler: Once<fn(&VmSpace, &CpuExceptionInfo) -> core::result::Result<(), ()>>,
- /// The CPUs that the `VmSpace` is activated on.
- ///
- /// TODO: implement an atomic bitset to optimize the performance in cases
- /// that the number of CPUs is not large.
- activated_cpus: SpinLock<CpuSet>,
+ /// A CPU can only activate a `VmSpace` when no mutable cursors are alive.
+ /// Cursors hold read locks and activation require a write lock.
+ activation_lock: RwLock<()>,
}
-// Notes on TLB flushing:
-//
-// We currently assume that:
-// 1. `VmSpace` _might_ be activated on the current CPU and the user memory _might_ be used
-// immediately after we make changes to the page table entries. So we must invalidate the
-// corresponding TLB caches accordingly.
-// 2. `VmSpace` must _not_ be activated on another CPU. This assumption is trivial, since SMP
-// support is not yet available. But we need to consider this situation in the future (TODO).
impl VmSpace {
/// Creates a new VM address space.
pub fn new() -> Self {
Self {
pt: KERNEL_PAGE_TABLE.get().unwrap().create_user_page_table(),
page_fault_handler: Once::new(),
- activated_cpus: SpinLock::new(CpuSet::new_empty()),
+ activation_lock: RwLock::new(()),
}
}
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -102,74 +94,64 @@ impl VmSpace {
/// The creation of the cursor may block if another cursor having an
/// overlapping range is alive. The modification to the mapping by the
/// cursor may also block or be overridden the mapping of another cursor.
- pub fn cursor_mut(&self, va: &Range<Vaddr>) -> Result<CursorMut<'_>> {
- Ok(self.pt.cursor_mut(va).map(CursorMut)?)
+ pub fn cursor_mut(&self, va: &Range<Vaddr>) -> Result<CursorMut<'_, '_>> {
+ Ok(self.pt.cursor_mut(va).map(|pt_cursor| {
+ let activation_lock = self.activation_lock.read();
+
+ let cur_cpu = pt_cursor.preempt_guard().current_cpu();
+
+ let mut activated_cpus = CpuSet::new_empty();
+ let mut need_self_flush = false;
+ let mut need_remote_flush = false;
+
+ for cpu in 0..num_cpus() {
+ // The activation lock is held; other CPUs cannot activate this `VmSpace`.
+ let ptr =
+ ACTIVATED_VM_SPACE.get_on_cpu(cpu).load(Ordering::Relaxed) as *const VmSpace;
+ if ptr == self as *const VmSpace {
+ activated_cpus.add(cpu);
+ if cpu == cur_cpu {
+ need_self_flush = true;
+ } else {
+ need_remote_flush = true;
+ }
+ }
+ }
+
+ CursorMut {
+ pt_cursor,
+ activation_lock,
+ activated_cpus,
+ need_remote_flush,
+ need_self_flush,
+ }
+ })?)
}
/// Activates the page table on the current CPU.
pub(crate) fn activate(self: &Arc<Self>) {
- cpu_local_cell! {
- /// The `Arc` pointer to the last activated VM space on this CPU. If the
- /// pointer is NULL, it means that the last activated page table is merely
- /// the kernel page table.
- static LAST_ACTIVATED_VM_SPACE: *const VmSpace = core::ptr::null();
- }
-
let preempt_guard = disable_preempt();
- let mut activated_cpus = self.activated_cpus.lock();
- let cpu = preempt_guard.current_cpu();
+ // Ensure no mutable cursors (which holds read locks) are alive.
+ let _activation_lock = self.activation_lock.write();
- if !activated_cpus.contains(cpu) {
- activated_cpus.add(cpu);
- self.pt.activate();
+ let cpu = preempt_guard.current_cpu();
+ let activated_vm_space = ACTIVATED_VM_SPACE.get_on_cpu(cpu);
- let last_ptr = LAST_ACTIVATED_VM_SPACE.load();
+ let last_ptr = activated_vm_space.load(Ordering::Relaxed) as *const VmSpace;
+ if last_ptr != Arc::as_ptr(self) {
+ self.pt.activate();
+ let ptr = Arc::into_raw(Arc::clone(self)) as *mut VmSpace;
+ activated_vm_space.store(ptr, Ordering::Relaxed);
if !last_ptr.is_null() {
- // SAFETY: If the pointer is not NULL, it must be a valid
- // pointer casted with `Arc::into_raw` on the last activated
- // `Arc<VmSpace>`.
- let last = unsafe { Arc::from_raw(last_ptr) };
- debug_assert!(!Arc::ptr_eq(self, &last));
- let mut last_cpus = last.activated_cpus.lock();
- debug_assert!(last_cpus.contains(cpu));
- last_cpus.remove(cpu);
+ // SAFETY: The pointer is cast from an `Arc` when it's activated
+ // the last time, so it can be restored and only restored once.
+ drop(unsafe { Arc::from_raw(last_ptr) });
}
-
- LAST_ACTIVATED_VM_SPACE.store(Arc::into_raw(Arc::clone(self)));
- }
-
- if activated_cpus.count() > 1 {
- // We don't support remote TLB flushing yet. It is less desirable
- // to activate a `VmSpace` on more than one CPU.
- log::warn!("A `VmSpace` is activated on more than one CPU");
}
}
- /// Clears all mappings.
- pub fn clear(&self) {
- let mut cursor = self.pt.cursor_mut(&(0..MAX_USERSPACE_VADDR)).unwrap();
- loop {
- // SAFETY: It is safe to un-map memory in the userspace.
- let result = unsafe { cursor.take_next(MAX_USERSPACE_VADDR - cursor.virt_addr()) };
- match result {
- PageTableItem::Mapped { page, .. } => {
- drop(page);
- }
- PageTableItem::NotMapped { .. } => {
- break;
- }
- PageTableItem::MappedUntracked { .. } => {
- panic!("found untracked memory mapped into `VmSpace`");
- }
- }
- }
- // TODO: currently this method calls x86_64::flush_all(), which rewrite the Cr3 register.
- // We should replace it with x86_64::flush_pcid(InvPicdCommand::AllExceptGlobal) after enabling PCID.
- tlb_flush_all_excluding_global();
- }
-
pub(crate) fn handle_page_fault(
&self,
info: &CpuExceptionInfo,
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -102,74 +94,64 @@ impl VmSpace {
/// The creation of the cursor may block if another cursor having an
/// overlapping range is alive. The modification to the mapping by the
/// cursor may also block or be overridden the mapping of another cursor.
- pub fn cursor_mut(&self, va: &Range<Vaddr>) -> Result<CursorMut<'_>> {
- Ok(self.pt.cursor_mut(va).map(CursorMut)?)
+ pub fn cursor_mut(&self, va: &Range<Vaddr>) -> Result<CursorMut<'_, '_>> {
+ Ok(self.pt.cursor_mut(va).map(|pt_cursor| {
+ let activation_lock = self.activation_lock.read();
+
+ let cur_cpu = pt_cursor.preempt_guard().current_cpu();
+
+ let mut activated_cpus = CpuSet::new_empty();
+ let mut need_self_flush = false;
+ let mut need_remote_flush = false;
+
+ for cpu in 0..num_cpus() {
+ // The activation lock is held; other CPUs cannot activate this `VmSpace`.
+ let ptr =
+ ACTIVATED_VM_SPACE.get_on_cpu(cpu).load(Ordering::Relaxed) as *const VmSpace;
+ if ptr == self as *const VmSpace {
+ activated_cpus.add(cpu);
+ if cpu == cur_cpu {
+ need_self_flush = true;
+ } else {
+ need_remote_flush = true;
+ }
+ }
+ }
+
+ CursorMut {
+ pt_cursor,
+ activation_lock,
+ activated_cpus,
+ need_remote_flush,
+ need_self_flush,
+ }
+ })?)
}
/// Activates the page table on the current CPU.
pub(crate) fn activate(self: &Arc<Self>) {
- cpu_local_cell! {
- /// The `Arc` pointer to the last activated VM space on this CPU. If the
- /// pointer is NULL, it means that the last activated page table is merely
- /// the kernel page table.
- static LAST_ACTIVATED_VM_SPACE: *const VmSpace = core::ptr::null();
- }
-
let preempt_guard = disable_preempt();
- let mut activated_cpus = self.activated_cpus.lock();
- let cpu = preempt_guard.current_cpu();
+ // Ensure no mutable cursors (which holds read locks) are alive.
+ let _activation_lock = self.activation_lock.write();
- if !activated_cpus.contains(cpu) {
- activated_cpus.add(cpu);
- self.pt.activate();
+ let cpu = preempt_guard.current_cpu();
+ let activated_vm_space = ACTIVATED_VM_SPACE.get_on_cpu(cpu);
- let last_ptr = LAST_ACTIVATED_VM_SPACE.load();
+ let last_ptr = activated_vm_space.load(Ordering::Relaxed) as *const VmSpace;
+ if last_ptr != Arc::as_ptr(self) {
+ self.pt.activate();
+ let ptr = Arc::into_raw(Arc::clone(self)) as *mut VmSpace;
+ activated_vm_space.store(ptr, Ordering::Relaxed);
if !last_ptr.is_null() {
- // SAFETY: If the pointer is not NULL, it must be a valid
- // pointer casted with `Arc::into_raw` on the last activated
- // `Arc<VmSpace>`.
- let last = unsafe { Arc::from_raw(last_ptr) };
- debug_assert!(!Arc::ptr_eq(self, &last));
- let mut last_cpus = last.activated_cpus.lock();
- debug_assert!(last_cpus.contains(cpu));
- last_cpus.remove(cpu);
+ // SAFETY: The pointer is cast from an `Arc` when it's activated
+ // the last time, so it can be restored and only restored once.
+ drop(unsafe { Arc::from_raw(last_ptr) });
}
-
- LAST_ACTIVATED_VM_SPACE.store(Arc::into_raw(Arc::clone(self)));
- }
-
- if activated_cpus.count() > 1 {
- // We don't support remote TLB flushing yet. It is less desirable
- // to activate a `VmSpace` on more than one CPU.
- log::warn!("A `VmSpace` is activated on more than one CPU");
}
}
- /// Clears all mappings.
- pub fn clear(&self) {
- let mut cursor = self.pt.cursor_mut(&(0..MAX_USERSPACE_VADDR)).unwrap();
- loop {
- // SAFETY: It is safe to un-map memory in the userspace.
- let result = unsafe { cursor.take_next(MAX_USERSPACE_VADDR - cursor.virt_addr()) };
- match result {
- PageTableItem::Mapped { page, .. } => {
- drop(page);
- }
- PageTableItem::NotMapped { .. } => {
- break;
- }
- PageTableItem::MappedUntracked { .. } => {
- panic!("found untracked memory mapped into `VmSpace`");
- }
- }
- }
- // TODO: currently this method calls x86_64::flush_all(), which rewrite the Cr3 register.
- // We should replace it with x86_64::flush_pcid(InvPicdCommand::AllExceptGlobal) after enabling PCID.
- tlb_flush_all_excluding_global();
- }
-
pub(crate) fn handle_page_fault(
&self,
info: &CpuExceptionInfo,
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -199,25 +181,12 @@ impl VmSpace {
pub fn fork_copy_on_write(&self) -> Self {
// Protect the parent VM space as read-only.
let end = MAX_USERSPACE_VADDR;
- let mut cursor = self.pt.cursor_mut(&(0..end)).unwrap();
+ let mut cursor = self.cursor_mut(&(0..end)).unwrap();
let mut op = |prop: &mut PageProperty| {
prop.flags -= PageFlags::W;
};
- loop {
- // SAFETY: It is safe to protect memory in the userspace.
- unsafe {
- if cursor
- .protect_next(end - cursor.virt_addr(), &mut op)
- .is_none()
- {
- break;
- }
- };
- }
- // TODO: currently this method calls x86_64::flush_all(), which rewrite the Cr3 register.
- // We should replace it with x86_64::flush_pcid(InvPicdCommand::AllExceptGlobal) after enabling PCID.
- tlb_flush_all_excluding_global();
+ cursor.protect(end, &mut op);
let page_fault_handler = {
let new_handler = Once::new();
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -199,25 +181,12 @@ impl VmSpace {
pub fn fork_copy_on_write(&self) -> Self {
// Protect the parent VM space as read-only.
let end = MAX_USERSPACE_VADDR;
- let mut cursor = self.pt.cursor_mut(&(0..end)).unwrap();
+ let mut cursor = self.cursor_mut(&(0..end)).unwrap();
let mut op = |prop: &mut PageProperty| {
prop.flags -= PageFlags::W;
};
- loop {
- // SAFETY: It is safe to protect memory in the userspace.
- unsafe {
- if cursor
- .protect_next(end - cursor.virt_addr(), &mut op)
- .is_none()
- {
- break;
- }
- };
- }
- // TODO: currently this method calls x86_64::flush_all(), which rewrite the Cr3 register.
- // We should replace it with x86_64::flush_pcid(InvPicdCommand::AllExceptGlobal) after enabling PCID.
- tlb_flush_all_excluding_global();
+ cursor.protect(end, &mut op);
let page_fault_handler = {
let new_handler = Once::new();
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -227,10 +196,22 @@ impl VmSpace {
new_handler
};
+ let CursorMut {
+ pt_cursor,
+ activation_lock,
+ ..
+ } = cursor;
+
+ let new_pt = self.pt.clone_with(pt_cursor);
+
+ // Release the activation lock after the page table is cloned to
+ // prevent modification to the parent page table while cloning.
+ drop(activation_lock);
+
Self {
- pt: self.pt.clone_with(cursor),
+ pt: new_pt,
page_fault_handler,
- activated_cpus: SpinLock::new(CpuSet::new_empty()),
+ activation_lock: RwLock::new(()),
}
}
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -227,10 +196,22 @@ impl VmSpace {
new_handler
};
+ let CursorMut {
+ pt_cursor,
+ activation_lock,
+ ..
+ } = cursor;
+
+ let new_pt = self.pt.clone_with(pt_cursor);
+
+ // Release the activation lock after the page table is cloned to
+ // prevent modification to the parent page table while cloning.
+ drop(activation_lock);
+
Self {
- pt: self.pt.clone_with(cursor),
+ pt: new_pt,
page_fault_handler,
- activated_cpus: SpinLock::new(CpuSet::new_empty()),
+ activation_lock: RwLock::new(()),
}
}
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -326,52 +307,55 @@ impl Cursor<'_> {
///
/// It exclusively owns a sub-tree of the page table, preventing others from
/// reading or modifying the same sub-tree.
-pub struct CursorMut<'a>(page_table::CursorMut<'a, UserMode, PageTableEntry, PagingConsts>);
-
-impl CursorMut<'_> {
- /// The threshold used to determine whether need to flush TLB all
- /// when flushing a range of TLB addresses. If the range of TLB entries
- /// to be flushed exceeds this threshold, the overhead incurred by
- /// flushing pages individually would surpass the overhead of flushing all entries at once.
- const TLB_FLUSH_THRESHOLD: usize = 32 * PAGE_SIZE;
+pub struct CursorMut<'a, 'b> {
+ pt_cursor: page_table::CursorMut<'a, UserMode, PageTableEntry, PagingConsts>,
+ #[allow(dead_code)]
+ activation_lock: RwLockReadGuard<'b, ()>,
+ // Better to store them here since loading and counting them from the CPUs
+ // list brings non-trivial overhead. We have a read lock so the stored set
+ // is always a superset of actual activated CPUs.
+ activated_cpus: CpuSet,
+ need_remote_flush: bool,
+ need_self_flush: bool,
+}
+impl CursorMut<'_, '_> {
/// Query about the current slot.
///
/// This is the same as [`Cursor::query`].
///
/// This function won't bring the cursor to the next slot.
pub fn query(&mut self) -> Result<VmItem> {
- Ok(self.0.query().map(|item| item.try_into().unwrap())?)
+ Ok(self
+ .pt_cursor
+ .query()
+ .map(|item| item.try_into().unwrap())?)
}
/// Jump to the virtual address.
///
/// This is the same as [`Cursor::jump`].
pub fn jump(&mut self, va: Vaddr) -> Result<()> {
- self.0.jump(va)?;
+ self.pt_cursor.jump(va)?;
Ok(())
}
/// Get the virtual address of the current slot.
pub fn virt_addr(&self) -> Vaddr {
- self.0.virt_addr()
+ self.pt_cursor.virt_addr()
}
/// Map a frame into the current slot.
///
/// This method will bring the cursor to the next slot after the modification.
- pub fn map(&mut self, frame: Frame, mut prop: PageProperty) {
+ pub fn map(&mut self, frame: Frame, prop: PageProperty) {
let start_va = self.virt_addr();
let end_va = start_va + frame.size();
- // TODO: this is a temporary fix to avoid the overhead of setting ACCESSED bit in userspace.
- // When this bit is truly enabled, it needs to be set at a more appropriate location.
- prop.flags |= PageFlags::ACCESSED;
// SAFETY: It is safe to map untyped memory into the userspace.
- unsafe {
- self.0.map(frame.into(), prop);
- }
+ let old = unsafe { self.pt_cursor.map(frame.into(), prop) };
- tlb_flush_addr_range(&(start_va..end_va));
+ self.issue_tlb_flush(TlbFlushOp::Range(start_va..end_va), old);
+ self.dispatch_tlb_flush();
}
/// Clear the mapping starting from the current slot.
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -326,52 +307,55 @@ impl Cursor<'_> {
///
/// It exclusively owns a sub-tree of the page table, preventing others from
/// reading or modifying the same sub-tree.
-pub struct CursorMut<'a>(page_table::CursorMut<'a, UserMode, PageTableEntry, PagingConsts>);
-
-impl CursorMut<'_> {
- /// The threshold used to determine whether need to flush TLB all
- /// when flushing a range of TLB addresses. If the range of TLB entries
- /// to be flushed exceeds this threshold, the overhead incurred by
- /// flushing pages individually would surpass the overhead of flushing all entries at once.
- const TLB_FLUSH_THRESHOLD: usize = 32 * PAGE_SIZE;
+pub struct CursorMut<'a, 'b> {
+ pt_cursor: page_table::CursorMut<'a, UserMode, PageTableEntry, PagingConsts>,
+ #[allow(dead_code)]
+ activation_lock: RwLockReadGuard<'b, ()>,
+ // Better to store them here since loading and counting them from the CPUs
+ // list brings non-trivial overhead. We have a read lock so the stored set
+ // is always a superset of actual activated CPUs.
+ activated_cpus: CpuSet,
+ need_remote_flush: bool,
+ need_self_flush: bool,
+}
+impl CursorMut<'_, '_> {
/// Query about the current slot.
///
/// This is the same as [`Cursor::query`].
///
/// This function won't bring the cursor to the next slot.
pub fn query(&mut self) -> Result<VmItem> {
- Ok(self.0.query().map(|item| item.try_into().unwrap())?)
+ Ok(self
+ .pt_cursor
+ .query()
+ .map(|item| item.try_into().unwrap())?)
}
/// Jump to the virtual address.
///
/// This is the same as [`Cursor::jump`].
pub fn jump(&mut self, va: Vaddr) -> Result<()> {
- self.0.jump(va)?;
+ self.pt_cursor.jump(va)?;
Ok(())
}
/// Get the virtual address of the current slot.
pub fn virt_addr(&self) -> Vaddr {
- self.0.virt_addr()
+ self.pt_cursor.virt_addr()
}
/// Map a frame into the current slot.
///
/// This method will bring the cursor to the next slot after the modification.
- pub fn map(&mut self, frame: Frame, mut prop: PageProperty) {
+ pub fn map(&mut self, frame: Frame, prop: PageProperty) {
let start_va = self.virt_addr();
let end_va = start_va + frame.size();
- // TODO: this is a temporary fix to avoid the overhead of setting ACCESSED bit in userspace.
- // When this bit is truly enabled, it needs to be set at a more appropriate location.
- prop.flags |= PageFlags::ACCESSED;
// SAFETY: It is safe to map untyped memory into the userspace.
- unsafe {
- self.0.map(frame.into(), prop);
- }
+ let old = unsafe { self.pt_cursor.map(frame.into(), prop) };
- tlb_flush_addr_range(&(start_va..end_va));
+ self.issue_tlb_flush(TlbFlushOp::Range(start_va..end_va), old);
+ self.dispatch_tlb_flush();
}
/// Clear the mapping starting from the current slot.
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -388,18 +372,13 @@ impl CursorMut<'_> {
pub fn unmap(&mut self, len: usize) {
assert!(len % super::PAGE_SIZE == 0);
let end_va = self.virt_addr() + len;
- let need_flush_all = len >= Self::TLB_FLUSH_THRESHOLD;
+
loop {
// SAFETY: It is safe to un-map memory in the userspace.
- let result = unsafe { self.0.take_next(end_va - self.virt_addr()) };
+ let result = unsafe { self.pt_cursor.take_next(end_va - self.virt_addr()) };
match result {
PageTableItem::Mapped { va, page, .. } => {
- if !need_flush_all {
- // TODO: Ask other processors to flush the TLB before we
- // release the page back to the allocator.
- tlb_flush_addr(va);
- }
- drop(page);
+ self.issue_tlb_flush(TlbFlushOp::Address(va), Some(page));
}
PageTableItem::NotMapped { .. } => {
break;
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -388,18 +372,13 @@ impl CursorMut<'_> {
pub fn unmap(&mut self, len: usize) {
assert!(len % super::PAGE_SIZE == 0);
let end_va = self.virt_addr() + len;
- let need_flush_all = len >= Self::TLB_FLUSH_THRESHOLD;
+
loop {
// SAFETY: It is safe to un-map memory in the userspace.
- let result = unsafe { self.0.take_next(end_va - self.virt_addr()) };
+ let result = unsafe { self.pt_cursor.take_next(end_va - self.virt_addr()) };
match result {
PageTableItem::Mapped { va, page, .. } => {
- if !need_flush_all {
- // TODO: Ask other processors to flush the TLB before we
- // release the page back to the allocator.
- tlb_flush_addr(va);
- }
- drop(page);
+ self.issue_tlb_flush(TlbFlushOp::Address(va), Some(page));
}
PageTableItem::NotMapped { .. } => {
break;
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -409,9 +388,8 @@ impl CursorMut<'_> {
}
}
}
- if need_flush_all {
- tlb_flush_all_excluding_global();
- }
+
+ self.dispatch_tlb_flush();
}
/// Change the mapping property starting from the current slot.
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -409,9 +388,8 @@ impl CursorMut<'_> {
}
}
}
- if need_flush_all {
- tlb_flush_all_excluding_global();
- }
+
+ self.dispatch_tlb_flush();
}
/// Change the mapping property starting from the current slot.
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -426,17 +404,121 @@ impl CursorMut<'_> {
/// This method will panic if `len` is not page-aligned.
pub fn protect(&mut self, len: usize, mut op: impl FnMut(&mut PageProperty)) {
assert!(len % super::PAGE_SIZE == 0);
- let end = self.0.virt_addr() + len;
- let need_flush_all = len >= Self::TLB_FLUSH_THRESHOLD;
+ let end = self.virt_addr() + len;
+ let tlb_prefer_flush_all = len > TLB_FLUSH_ALL_THRESHOLD * PAGE_SIZE;
+
// SAFETY: It is safe to protect memory in the userspace.
- while let Some(range) = unsafe { self.0.protect_next(end - self.0.virt_addr(), &mut op) } {
- if !need_flush_all {
- tlb_flush_addr(range.start);
+ while let Some(range) =
+ unsafe { self.pt_cursor.protect_next(end - self.virt_addr(), &mut op) }
+ {
+ if !tlb_prefer_flush_all {
+ self.issue_tlb_flush(TlbFlushOp::Range(range), None);
+ }
+ }
+
+ if tlb_prefer_flush_all {
+ self.issue_tlb_flush(TlbFlushOp::All, None);
+ }
+ self.dispatch_tlb_flush();
+ }
+
+ fn issue_tlb_flush(&self, op: TlbFlushOp, drop_after_flush: Option<DynPage>) {
+ let request = TlbFlushRequest {
+ op,
+ drop_after_flush,
+ };
+
+ // Fast path for single CPU cases.
+ if !self.need_remote_flush {
+ if self.need_self_flush {
+ request.do_flush();
+ }
+ return;
+ }
+
+ // Slow path for multi-CPU cases.
+ for cpu in self.activated_cpus.iter() {
+ let mut queue = TLB_FLUSH_REQUESTS.get_on_cpu(cpu).lock();
+ queue.push_back(request.clone());
+ }
+ }
+
+ fn dispatch_tlb_flush(&self) {
+ if !self.need_remote_flush {
+ return;
+ }
+
+ fn do_remote_flush() {
+ let preempt_guard = disable_preempt();
+ let mut requests = TLB_FLUSH_REQUESTS
+ .get_on_cpu(preempt_guard.current_cpu())
+ .lock();
+ if requests.len() > TLB_FLUSH_ALL_THRESHOLD {
+ // TODO: in most cases, we need only to flush all the TLB entries
+ // for an ASID if it is enabled.
+ crate::arch::mm::tlb_flush_all_excluding_global();
+ requests.clear();
+ } else {
+ while let Some(request) = requests.pop_front() {
+ request.do_flush();
+ if matches!(request.op, TlbFlushOp::All) {
+ requests.clear();
+ break;
+ }
+ }
}
}
- if need_flush_all {
- tlb_flush_all_excluding_global();
+ crate::smp::inter_processor_call(&self.activated_cpus.clone(), do_remote_flush);
+ }
+}
+
+/// The threshold used to determine whether we need to flush all TLB entries
+/// when handling a bunch of TLB flush requests. If the number of requests
+/// exceeds this threshold, the overhead incurred by flushing pages
+/// individually would surpass the overhead of flushing all entries at once.
+const TLB_FLUSH_ALL_THRESHOLD: usize = 32;
+
+cpu_local! {
+ /// The queue of pending requests.
+ static TLB_FLUSH_REQUESTS: SpinLock<VecDeque<TlbFlushRequest>> = SpinLock::new(VecDeque::new());
+ /// The `Arc` pointer to the activated VM space on this CPU. If the pointer
+ /// is NULL, it means that the activated page table is merely the kernel
+ /// page table.
+ // TODO: If we are enabling ASID, we need to maintain the TLB state of each
+ // CPU, rather than merely the activated `VmSpace`. When ASID is enabled,
+ // the non-active `VmSpace`s can still have their TLB entries in the CPU!
+ static ACTIVATED_VM_SPACE: AtomicPtr<VmSpace> = AtomicPtr::new(core::ptr::null_mut());
+}
+
+#[derive(Debug, Clone)]
+struct TlbFlushRequest {
+ op: TlbFlushOp,
+ // If we need to remove a mapped page from the page table, we can only
+ // recycle the page after all the relevant TLB entries in all CPUs are
+ // flushed. Otherwise if the page is recycled for other purposes, the user
+ // space program can still access the page through the TLB entries.
+ #[allow(dead_code)]
+ drop_after_flush: Option<DynPage>,
+}
+
+#[derive(Debug, Clone)]
+enum TlbFlushOp {
+ All,
+ Address(Vaddr),
+ Range(Range<Vaddr>),
+}
+
+impl TlbFlushRequest {
+ /// Perform the TLB flush operation on the current CPU.
+ fn do_flush(&self) {
+ use crate::arch::mm::{
+ tlb_flush_addr, tlb_flush_addr_range, tlb_flush_all_excluding_global,
+ };
+ match &self.op {
+ TlbFlushOp::All => tlb_flush_all_excluding_global(),
+ TlbFlushOp::Address(addr) => tlb_flush_addr(*addr),
+ TlbFlushOp::Range(range) => tlb_flush_addr_range(range),
}
}
}
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -426,17 +404,121 @@ impl CursorMut<'_> {
/// This method will panic if `len` is not page-aligned.
pub fn protect(&mut self, len: usize, mut op: impl FnMut(&mut PageProperty)) {
assert!(len % super::PAGE_SIZE == 0);
- let end = self.0.virt_addr() + len;
- let need_flush_all = len >= Self::TLB_FLUSH_THRESHOLD;
+ let end = self.virt_addr() + len;
+ let tlb_prefer_flush_all = len > TLB_FLUSH_ALL_THRESHOLD * PAGE_SIZE;
+
// SAFETY: It is safe to protect memory in the userspace.
- while let Some(range) = unsafe { self.0.protect_next(end - self.0.virt_addr(), &mut op) } {
- if !need_flush_all {
- tlb_flush_addr(range.start);
+ while let Some(range) =
+ unsafe { self.pt_cursor.protect_next(end - self.virt_addr(), &mut op) }
+ {
+ if !tlb_prefer_flush_all {
+ self.issue_tlb_flush(TlbFlushOp::Range(range), None);
+ }
+ }
+
+ if tlb_prefer_flush_all {
+ self.issue_tlb_flush(TlbFlushOp::All, None);
+ }
+ self.dispatch_tlb_flush();
+ }
+
+ fn issue_tlb_flush(&self, op: TlbFlushOp, drop_after_flush: Option<DynPage>) {
+ let request = TlbFlushRequest {
+ op,
+ drop_after_flush,
+ };
+
+ // Fast path for single CPU cases.
+ if !self.need_remote_flush {
+ if self.need_self_flush {
+ request.do_flush();
+ }
+ return;
+ }
+
+ // Slow path for multi-CPU cases.
+ for cpu in self.activated_cpus.iter() {
+ let mut queue = TLB_FLUSH_REQUESTS.get_on_cpu(cpu).lock();
+ queue.push_back(request.clone());
+ }
+ }
+
+ fn dispatch_tlb_flush(&self) {
+ if !self.need_remote_flush {
+ return;
+ }
+
+ fn do_remote_flush() {
+ let preempt_guard = disable_preempt();
+ let mut requests = TLB_FLUSH_REQUESTS
+ .get_on_cpu(preempt_guard.current_cpu())
+ .lock();
+ if requests.len() > TLB_FLUSH_ALL_THRESHOLD {
+ // TODO: in most cases, we need only to flush all the TLB entries
+ // for an ASID if it is enabled.
+ crate::arch::mm::tlb_flush_all_excluding_global();
+ requests.clear();
+ } else {
+ while let Some(request) = requests.pop_front() {
+ request.do_flush();
+ if matches!(request.op, TlbFlushOp::All) {
+ requests.clear();
+ break;
+ }
+ }
}
}
- if need_flush_all {
- tlb_flush_all_excluding_global();
+ crate::smp::inter_processor_call(&self.activated_cpus.clone(), do_remote_flush);
+ }
+}
+
+/// The threshold used to determine whether we need to flush all TLB entries
+/// when handling a bunch of TLB flush requests. If the number of requests
+/// exceeds this threshold, the overhead incurred by flushing pages
+/// individually would surpass the overhead of flushing all entries at once.
+const TLB_FLUSH_ALL_THRESHOLD: usize = 32;
+
+cpu_local! {
+ /// The queue of pending requests.
+ static TLB_FLUSH_REQUESTS: SpinLock<VecDeque<TlbFlushRequest>> = SpinLock::new(VecDeque::new());
+ /// The `Arc` pointer to the activated VM space on this CPU. If the pointer
+ /// is NULL, it means that the activated page table is merely the kernel
+ /// page table.
+ // TODO: If we are enabling ASID, we need to maintain the TLB state of each
+ // CPU, rather than merely the activated `VmSpace`. When ASID is enabled,
+ // the non-active `VmSpace`s can still have their TLB entries in the CPU!
+ static ACTIVATED_VM_SPACE: AtomicPtr<VmSpace> = AtomicPtr::new(core::ptr::null_mut());
+}
+
+#[derive(Debug, Clone)]
+struct TlbFlushRequest {
+ op: TlbFlushOp,
+ // If we need to remove a mapped page from the page table, we can only
+ // recycle the page after all the relevant TLB entries in all CPUs are
+ // flushed. Otherwise if the page is recycled for other purposes, the user
+ // space program can still access the page through the TLB entries.
+ #[allow(dead_code)]
+ drop_after_flush: Option<DynPage>,
+}
+
+#[derive(Debug, Clone)]
+enum TlbFlushOp {
+ All,
+ Address(Vaddr),
+ Range(Range<Vaddr>),
+}
+
+impl TlbFlushRequest {
+ /// Perform the TLB flush operation on the current CPU.
+ fn do_flush(&self) {
+ use crate::arch::mm::{
+ tlb_flush_addr, tlb_flush_addr_range, tlb_flush_all_excluding_global,
+ };
+ match &self.op {
+ TlbFlushOp::All => tlb_flush_all_excluding_global(),
+ TlbFlushOp::Address(addr) => tlb_flush_addr(*addr),
+ TlbFlushOp::Range(range) => tlb_flush_addr_range(range),
}
}
}
diff --git /dev/null b/ostd/src/smp.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/smp.rs
@@ -0,0 +1,87 @@
+// SPDX-License-Identifier: MPL-2.0
+
+//! Symmetric Multi-Processing (SMP) support.
+//!
+//! This module provides a way to execute code on other processors via inter-
+//! processor interrupts.
+
+use alloc::collections::VecDeque;
+
+use spin::Once;
+
+use crate::{
+ cpu::{CpuSet, PinCurrentCpu},
+ cpu_local,
+ sync::SpinLock,
+ trap::{self, IrqLine, TrapFrame},
+};
+
+/// Execute a function on other processors.
+///
+/// The provided function `f` will be executed on all target processors
+/// specified by `targets`. It can also be executed on the current processor.
+/// The function should be short and non-blocking, as it will be executed in
+/// interrupt context with interrupts disabled.
+///
+/// This function does not block until all the target processors acknowledges
+/// the interrupt. So if any of the target processors disables IRQs for too
+/// long that the controller cannot queue them, the function will not be
+/// executed.
+///
+/// The function `f` will be executed asynchronously on the target processors.
+/// However if called on the current processor, it will be synchronous.
+pub fn inter_processor_call(targets: &CpuSet, f: fn()) {
+ let irq_guard = trap::disable_local();
+ let this_cpu_id = irq_guard.current_cpu();
+ let irq_num = INTER_PROCESSOR_CALL_IRQ.get().unwrap().num();
+
+ let mut call_on_self = false;
+ for cpu_id in targets.iter() {
+ if cpu_id == this_cpu_id {
+ call_on_self = true;
+ continue;
+ }
+ CALL_QUEUES.get_on_cpu(cpu_id).lock().push_back(f);
+ }
+ for cpu_id in targets.iter() {
+ if cpu_id == this_cpu_id {
+ continue;
+ }
+ // SAFETY: It is safe to send inter processor call IPI to other CPUs.
+ unsafe {
+ crate::arch::irq::send_ipi(cpu_id, irq_num);
+ }
+ }
+ if call_on_self {
+ // Execute the function synchronously.
+ f();
+ }
+}
+
+static INTER_PROCESSOR_CALL_IRQ: Once<IrqLine> = Once::new();
+
+cpu_local! {
+ static CALL_QUEUES: SpinLock<VecDeque<fn()>> = SpinLock::new(VecDeque::new());
+}
+
+fn do_inter_processor_call(_trapframe: &TrapFrame) {
+ // TODO: in interrupt context, disabling interrupts is not necessary.
+ let preempt_guard = trap::disable_local();
+ let cur_cpu = preempt_guard.current_cpu();
+
+ let mut queue = CALL_QUEUES.get_on_cpu(cur_cpu).lock();
+ while let Some(f) = queue.pop_front() {
+ log::trace!(
+ "Performing inter-processor call to {:#?} on CPU {}",
+ f,
+ cur_cpu
+ );
+ f();
+ }
+}
+
+pub(super) fn init() {
+ let mut irq = IrqLine::alloc().unwrap();
+ irq.on_active(do_inter_processor_call);
+ INTER_PROCESSOR_CALL_IRQ.call_once(|| irq);
+}
diff --git /dev/null b/ostd/src/smp.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/smp.rs
@@ -0,0 +1,87 @@
+// SPDX-License-Identifier: MPL-2.0
+
+//! Symmetric Multi-Processing (SMP) support.
+//!
+//! This module provides a way to execute code on other processors via inter-
+//! processor interrupts.
+
+use alloc::collections::VecDeque;
+
+use spin::Once;
+
+use crate::{
+ cpu::{CpuSet, PinCurrentCpu},
+ cpu_local,
+ sync::SpinLock,
+ trap::{self, IrqLine, TrapFrame},
+};
+
+/// Execute a function on other processors.
+///
+/// The provided function `f` will be executed on all target processors
+/// specified by `targets`. It can also be executed on the current processor.
+/// The function should be short and non-blocking, as it will be executed in
+/// interrupt context with interrupts disabled.
+///
+/// This function does not block until all the target processors acknowledges
+/// the interrupt. So if any of the target processors disables IRQs for too
+/// long that the controller cannot queue them, the function will not be
+/// executed.
+///
+/// The function `f` will be executed asynchronously on the target processors.
+/// However if called on the current processor, it will be synchronous.
+pub fn inter_processor_call(targets: &CpuSet, f: fn()) {
+ let irq_guard = trap::disable_local();
+ let this_cpu_id = irq_guard.current_cpu();
+ let irq_num = INTER_PROCESSOR_CALL_IRQ.get().unwrap().num();
+
+ let mut call_on_self = false;
+ for cpu_id in targets.iter() {
+ if cpu_id == this_cpu_id {
+ call_on_self = true;
+ continue;
+ }
+ CALL_QUEUES.get_on_cpu(cpu_id).lock().push_back(f);
+ }
+ for cpu_id in targets.iter() {
+ if cpu_id == this_cpu_id {
+ continue;
+ }
+ // SAFETY: It is safe to send inter processor call IPI to other CPUs.
+ unsafe {
+ crate::arch::irq::send_ipi(cpu_id, irq_num);
+ }
+ }
+ if call_on_self {
+ // Execute the function synchronously.
+ f();
+ }
+}
+
+static INTER_PROCESSOR_CALL_IRQ: Once<IrqLine> = Once::new();
+
+cpu_local! {
+ static CALL_QUEUES: SpinLock<VecDeque<fn()>> = SpinLock::new(VecDeque::new());
+}
+
+fn do_inter_processor_call(_trapframe: &TrapFrame) {
+ // TODO: in interrupt context, disabling interrupts is not necessary.
+ let preempt_guard = trap::disable_local();
+ let cur_cpu = preempt_guard.current_cpu();
+
+ let mut queue = CALL_QUEUES.get_on_cpu(cur_cpu).lock();
+ while let Some(f) = queue.pop_front() {
+ log::trace!(
+ "Performing inter-processor call to {:#?} on CPU {}",
+ f,
+ cur_cpu
+ );
+ f();
+ }
+}
+
+pub(super) fn init() {
+ let mut irq = IrqLine::alloc().unwrap();
+ irq.on_active(do_inter_processor_call);
+ INTER_PROCESSOR_CALL_IRQ.call_once(|| irq);
+}
diff --git a/ostd/src/task/preempt/guard.rs b/ostd/src/task/preempt/guard.rs
--- a/ostd/src/task/preempt/guard.rs
+++ b/ostd/src/task/preempt/guard.rs
@@ -3,6 +3,7 @@
/// A guard for disable preempt.
#[clippy::has_significant_drop]
#[must_use]
+#[derive(Debug)]
pub struct DisabledPreemptGuard {
// This private field prevents user from constructing values of this type directly.
_private: (),
diff --git a/ostd/src/task/preempt/guard.rs b/ostd/src/task/preempt/guard.rs
--- a/ostd/src/task/preempt/guard.rs
+++ b/ostd/src/task/preempt/guard.rs
@@ -3,6 +3,7 @@
/// A guard for disable preempt.
#[clippy::has_significant_drop]
#[must_use]
+#[derive(Debug)]
pub struct DisabledPreemptGuard {
// This private field prevents user from constructing values of this type directly.
_private: (),
|
2024-08-13T09:28:07Z
|
ae4ac384713e63232b74915593ebdef680049d31
|
|
asterinas/asterinas
|
diff --git a/kernel/aster-nix/src/lib.rs b/kernel/aster-nix/src/lib.rs
--- a/kernel/aster-nix/src/lib.rs
+++ b/kernel/aster-nix/src/lib.rs
@@ -89,9 +89,6 @@ fn init_thread() {
// Work queue should be initialized before interrupt is enabled,
// in case any irq handler uses work queue as bottom half
thread::work_queue::init();
- // FIXME: Remove this if we move the step of mounting
- // the filesystems to be done within the init process.
- ostd::trap::enable_local();
net::lazy_init();
fs::lazy_init();
// driver::pci::virtio::block::block_device_test();
diff --git a/kernel/aster-nix/src/taskless.rs b/kernel/aster-nix/src/taskless.rs
--- a/kernel/aster-nix/src/taskless.rs
+++ b/kernel/aster-nix/src/taskless.rs
@@ -190,7 +190,7 @@ fn taskless_softirq_handler(
mod test {
use core::sync::atomic::AtomicUsize;
- use ostd::{prelude::*, trap::enable_local};
+ use ostd::prelude::*;
use super::*;
diff --git a/kernel/aster-nix/src/taskless.rs b/kernel/aster-nix/src/taskless.rs
--- a/kernel/aster-nix/src/taskless.rs
+++ b/kernel/aster-nix/src/taskless.rs
@@ -198,7 +198,6 @@ mod test {
static DONE: AtomicBool = AtomicBool::new(false);
if !DONE.load(Ordering::SeqCst) {
super::init();
- enable_local();
DONE.store(true, Ordering::SeqCst);
}
}
|
[
"1130"
] |
0.6
|
38b46f7ac3dd206d116f7db1fa33654569a8e443
|
We shouldn't disable preemption when disabling IRQ.
Currently `ostd::trap::disable_local` disables preemption as well when disabling IRQ. However, such a policy would like to be based on an observation that: "we shouldn't do `switch_to_task()` when IRQ is disabled". Indeed we shouldn't do so. But this is not the best way to solve the problem.
We shouldn't disable preemption in `ostd::trap::disable_local`, instead, we should check if the IRQ is disabled in `switch_to_task()`. This alternative solution precisely resolves the problem without other overheads.
In contrast, if we disable preemption in `ostd::trap::disable_local`, an enormous number of places that preemption won't ever happen will try to disable preemption, introducing non negligible costs since a memory write must happen when disabling preemption. Even worse, in the case of #1125, if the architecture don't implement single instruction writes, the fall back implementation will disable IRQ. But disabling preemption would need a CPU-local write, which in turn needs to disable preemption, causing a dead loop here.
So, we need only to check if the IRQ is disabled in `switch_to_task()`. The user should disable both preemption and IRQ if they indeed need both. We should check the entire code base for such needs and add `disable_preempt` delicately.
|
asterinas__asterinas-1154
| 1,154
|
diff --git a/kernel/aster-nix/src/lib.rs b/kernel/aster-nix/src/lib.rs
--- a/kernel/aster-nix/src/lib.rs
+++ b/kernel/aster-nix/src/lib.rs
@@ -89,9 +89,6 @@ fn init_thread() {
// Work queue should be initialized before interrupt is enabled,
// in case any irq handler uses work queue as bottom half
thread::work_queue::init();
- // FIXME: Remove this if we move the step of mounting
- // the filesystems to be done within the init process.
- ostd::trap::enable_local();
net::lazy_init();
fs::lazy_init();
// driver::pci::virtio::block::block_device_test();
diff --git a/kernel/aster-nix/src/process/process/timer_manager.rs b/kernel/aster-nix/src/process/process/timer_manager.rs
--- a/kernel/aster-nix/src/process/process/timer_manager.rs
+++ b/kernel/aster-nix/src/process/process/timer_manager.rs
@@ -18,12 +18,14 @@ use ostd::{
use super::Process;
use crate::{
- prelude::*,
process::{
posix_thread::PosixThreadExt,
signal::{constants::SIGALRM, signals::kernel::KernelSignal},
},
- thread::work_queue::{submit_work_item, work_item::WorkItem},
+ thread::{
+ work_queue::{submit_work_item, work_item::WorkItem},
+ Thread,
+ },
time::{
clocks::{ProfClock, RealTimeClock},
Timer, TimerManager,
diff --git a/kernel/aster-nix/src/process/process/timer_manager.rs b/kernel/aster-nix/src/process/process/timer_manager.rs
--- a/kernel/aster-nix/src/process/process/timer_manager.rs
+++ b/kernel/aster-nix/src/process/process/timer_manager.rs
@@ -18,12 +18,14 @@ use ostd::{
use super::Process;
use crate::{
- prelude::*,
process::{
posix_thread::PosixThreadExt,
signal::{constants::SIGALRM, signals::kernel::KernelSignal},
},
- thread::work_queue::{submit_work_item, work_item::WorkItem},
+ thread::{
+ work_queue::{submit_work_item, work_item::WorkItem},
+ Thread,
+ },
time::{
clocks::{ProfClock, RealTimeClock},
Timer, TimerManager,
diff --git a/kernel/aster-nix/src/process/process/timer_manager.rs b/kernel/aster-nix/src/process/process/timer_manager.rs
--- a/kernel/aster-nix/src/process/process/timer_manager.rs
+++ b/kernel/aster-nix/src/process/process/timer_manager.rs
@@ -36,40 +38,43 @@ use crate::{
/// invoke the callbacks of expired timers which are based on the updated
/// CPU clock.
fn update_cpu_time() {
- let current_thread = current_thread!();
- if let Some(posix_thread) = current_thread.as_posix_thread() {
- let process = posix_thread.process();
- let timer_manager = process.timer_manager();
- let jiffies_interval = Duration::from_millis(1000 / TIMER_FREQ);
- // Based on whether the timer interrupt occurs in kernel mode or user mode,
- // the function will add the duration of one timer interrupt interval to the
- // corresponding CPU clocks.
- if is_kernel_interrupted() {
- posix_thread
- .prof_clock()
- .kernel_clock()
- .add_time(jiffies_interval);
- process
- .prof_clock()
- .kernel_clock()
- .add_time(jiffies_interval);
- } else {
- posix_thread
- .prof_clock()
- .user_clock()
- .add_time(jiffies_interval);
- process.prof_clock().user_clock().add_time(jiffies_interval);
- timer_manager
- .virtual_timer()
- .timer_manager()
- .process_expired_timers();
- }
+ let Some(current_thread) = Thread::current() else {
+ return;
+ };
+ let Some(posix_thread) = current_thread.as_posix_thread() else {
+ return;
+ };
+ let process = posix_thread.process();
+ let timer_manager = process.timer_manager();
+ let jiffies_interval = Duration::from_millis(1000 / TIMER_FREQ);
+ // Based on whether the timer interrupt occurs in kernel mode or user mode,
+ // the function will add the duration of one timer interrupt interval to the
+ // corresponding CPU clocks.
+ if is_kernel_interrupted() {
+ posix_thread
+ .prof_clock()
+ .kernel_clock()
+ .add_time(jiffies_interval);
+ process
+ .prof_clock()
+ .kernel_clock()
+ .add_time(jiffies_interval);
+ } else {
+ posix_thread
+ .prof_clock()
+ .user_clock()
+ .add_time(jiffies_interval);
+ process.prof_clock().user_clock().add_time(jiffies_interval);
timer_manager
- .prof_timer()
+ .virtual_timer()
.timer_manager()
.process_expired_timers();
- posix_thread.process_expired_timers();
}
+ timer_manager
+ .prof_timer()
+ .timer_manager()
+ .process_expired_timers();
+ posix_thread.process_expired_timers();
}
/// Registers a function to update the CPU clock in processes and
diff --git a/kernel/aster-nix/src/process/process/timer_manager.rs b/kernel/aster-nix/src/process/process/timer_manager.rs
--- a/kernel/aster-nix/src/process/process/timer_manager.rs
+++ b/kernel/aster-nix/src/process/process/timer_manager.rs
@@ -36,40 +38,43 @@ use crate::{
/// invoke the callbacks of expired timers which are based on the updated
/// CPU clock.
fn update_cpu_time() {
- let current_thread = current_thread!();
- if let Some(posix_thread) = current_thread.as_posix_thread() {
- let process = posix_thread.process();
- let timer_manager = process.timer_manager();
- let jiffies_interval = Duration::from_millis(1000 / TIMER_FREQ);
- // Based on whether the timer interrupt occurs in kernel mode or user mode,
- // the function will add the duration of one timer interrupt interval to the
- // corresponding CPU clocks.
- if is_kernel_interrupted() {
- posix_thread
- .prof_clock()
- .kernel_clock()
- .add_time(jiffies_interval);
- process
- .prof_clock()
- .kernel_clock()
- .add_time(jiffies_interval);
- } else {
- posix_thread
- .prof_clock()
- .user_clock()
- .add_time(jiffies_interval);
- process.prof_clock().user_clock().add_time(jiffies_interval);
- timer_manager
- .virtual_timer()
- .timer_manager()
- .process_expired_timers();
- }
+ let Some(current_thread) = Thread::current() else {
+ return;
+ };
+ let Some(posix_thread) = current_thread.as_posix_thread() else {
+ return;
+ };
+ let process = posix_thread.process();
+ let timer_manager = process.timer_manager();
+ let jiffies_interval = Duration::from_millis(1000 / TIMER_FREQ);
+ // Based on whether the timer interrupt occurs in kernel mode or user mode,
+ // the function will add the duration of one timer interrupt interval to the
+ // corresponding CPU clocks.
+ if is_kernel_interrupted() {
+ posix_thread
+ .prof_clock()
+ .kernel_clock()
+ .add_time(jiffies_interval);
+ process
+ .prof_clock()
+ .kernel_clock()
+ .add_time(jiffies_interval);
+ } else {
+ posix_thread
+ .prof_clock()
+ .user_clock()
+ .add_time(jiffies_interval);
+ process.prof_clock().user_clock().add_time(jiffies_interval);
timer_manager
- .prof_timer()
+ .virtual_timer()
.timer_manager()
.process_expired_timers();
- posix_thread.process_expired_timers();
}
+ timer_manager
+ .prof_timer()
+ .timer_manager()
+ .process_expired_timers();
+ posix_thread.process_expired_timers();
}
/// Registers a function to update the CPU clock in processes and
diff --git a/kernel/aster-nix/src/taskless.rs b/kernel/aster-nix/src/taskless.rs
--- a/kernel/aster-nix/src/taskless.rs
+++ b/kernel/aster-nix/src/taskless.rs
@@ -190,7 +190,7 @@ fn taskless_softirq_handler(
mod test {
use core::sync::atomic::AtomicUsize;
- use ostd::{prelude::*, trap::enable_local};
+ use ostd::prelude::*;
use super::*;
diff --git a/kernel/aster-nix/src/taskless.rs b/kernel/aster-nix/src/taskless.rs
--- a/kernel/aster-nix/src/taskless.rs
+++ b/kernel/aster-nix/src/taskless.rs
@@ -198,7 +198,6 @@ mod test {
static DONE: AtomicBool = AtomicBool::new(false);
if !DONE.load(Ordering::SeqCst) {
super::init();
- enable_local();
DONE.store(true, Ordering::SeqCst);
}
}
diff --git a/ostd/src/boot/smp.rs b/ostd/src/boot/smp.rs
--- a/ostd/src/boot/smp.rs
+++ b/ostd/src/boot/smp.rs
@@ -119,6 +119,7 @@ fn ap_early_entry(local_apic_id: u32) -> ! {
}
trap::init();
+ crate::arch::irq::enable_local();
// Mark the AP as started.
let ap_boot_info = AP_BOOT_INFO.get().unwrap();
diff --git a/ostd/src/boot/smp.rs b/ostd/src/boot/smp.rs
--- a/ostd/src/boot/smp.rs
+++ b/ostd/src/boot/smp.rs
@@ -119,6 +119,7 @@ fn ap_early_entry(local_apic_id: u32) -> ! {
}
trap::init();
+ crate::arch::irq::enable_local();
// Mark the AP as started.
let ap_boot_info = AP_BOOT_INFO.get().unwrap();
diff --git a/ostd/src/lib.rs b/ostd/src/lib.rs
--- a/ostd/src/lib.rs
+++ b/ostd/src/lib.rs
@@ -86,6 +86,8 @@ pub fn init() {
mm::kspace::activate_kernel_page_table();
+ arch::irq::enable_local();
+
invoke_ffi_init_funcs();
}
diff --git a/ostd/src/lib.rs b/ostd/src/lib.rs
--- a/ostd/src/lib.rs
+++ b/ostd/src/lib.rs
@@ -86,6 +86,8 @@ pub fn init() {
mm::kspace::activate_kernel_page_table();
+ arch::irq::enable_local();
+
invoke_ffi_init_funcs();
}
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -71,6 +71,11 @@ pub fn preempt(task: &Arc<Task>) {
///
/// If the current task's status not [`TaskStatus::Runnable`], it will not be
/// added to the scheduler.
+///
+/// # Panics
+///
+/// This function will panic if called while holding preemption locks or with
+/// local IRQ disabled.
fn switch_to_task(next_task: Arc<Task>) {
let preemt_lock_count = PREEMPT_LOCK_COUNT.load();
if preemt_lock_count != 0 {
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -71,6 +71,11 @@ pub fn preempt(task: &Arc<Task>) {
///
/// If the current task's status not [`TaskStatus::Runnable`], it will not be
/// added to the scheduler.
+///
+/// # Panics
+///
+/// This function will panic if called while holding preemption locks or with
+/// local IRQ disabled.
fn switch_to_task(next_task: Arc<Task>) {
let preemt_lock_count = PREEMPT_LOCK_COUNT.load();
if preemt_lock_count != 0 {
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -80,6 +85,11 @@ fn switch_to_task(next_task: Arc<Task>) {
);
}
+ assert!(
+ crate::arch::irq::is_local_enabled(),
+ "Switching task with local IRQ disabled"
+ );
+
let irq_guard = crate::trap::disable_local();
let current_task_ptr = CURRENT_TASK_PTR.load();
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -80,6 +85,11 @@ fn switch_to_task(next_task: Arc<Task>) {
);
}
+ assert!(
+ crate::arch::irq::is_local_enabled(),
+ "Switching task with local IRQ disabled"
+ );
+
let irq_guard = crate::trap::disable_local();
let current_task_ptr = CURRENT_TASK_PTR.load();
diff --git a/ostd/src/trap/irq.rs b/ostd/src/trap/irq.rs
--- a/ostd/src/trap/irq.rs
+++ b/ostd/src/trap/irq.rs
@@ -9,7 +9,6 @@ use trapframe::TrapFrame;
use crate::{
arch::irq::{self, IrqCallbackHandle, IRQ_ALLOCATOR},
prelude::*,
- task::{disable_preempt, DisablePreemptGuard},
Error,
};
diff --git a/ostd/src/trap/irq.rs b/ostd/src/trap/irq.rs
--- a/ostd/src/trap/irq.rs
+++ b/ostd/src/trap/irq.rs
@@ -9,7 +9,6 @@ use trapframe::TrapFrame;
use crate::{
arch::irq::{self, IrqCallbackHandle, IRQ_ALLOCATOR},
prelude::*,
- task::{disable_preempt, DisablePreemptGuard},
Error,
};
diff --git a/ostd/src/trap/irq.rs b/ostd/src/trap/irq.rs
--- a/ostd/src/trap/irq.rs
+++ b/ostd/src/trap/irq.rs
@@ -135,7 +134,6 @@ pub fn disable_local() -> DisabledLocalIrqGuard {
#[must_use]
pub struct DisabledLocalIrqGuard {
was_enabled: bool,
- preempt_guard: DisablePreemptGuard,
}
impl !Send for DisabledLocalIrqGuard {}
diff --git a/ostd/src/trap/irq.rs b/ostd/src/trap/irq.rs
--- a/ostd/src/trap/irq.rs
+++ b/ostd/src/trap/irq.rs
@@ -135,7 +134,6 @@ pub fn disable_local() -> DisabledLocalIrqGuard {
#[must_use]
pub struct DisabledLocalIrqGuard {
was_enabled: bool,
- preempt_guard: DisablePreemptGuard,
}
impl !Send for DisabledLocalIrqGuard {}
diff --git a/ostd/src/trap/irq.rs b/ostd/src/trap/irq.rs
--- a/ostd/src/trap/irq.rs
+++ b/ostd/src/trap/irq.rs
@@ -146,11 +144,7 @@ impl DisabledLocalIrqGuard {
if was_enabled {
irq::disable_local();
}
- let preempt_guard = disable_preempt();
- Self {
- was_enabled,
- preempt_guard,
- }
+ Self { was_enabled }
}
/// Transfers the saved IRQ status of this guard to a new guard.
diff --git a/ostd/src/trap/irq.rs b/ostd/src/trap/irq.rs
--- a/ostd/src/trap/irq.rs
+++ b/ostd/src/trap/irq.rs
@@ -146,11 +144,7 @@ impl DisabledLocalIrqGuard {
if was_enabled {
irq::disable_local();
}
- let preempt_guard = disable_preempt();
- Self {
- was_enabled,
- preempt_guard,
- }
+ Self { was_enabled }
}
/// Transfers the saved IRQ status of this guard to a new guard.
diff --git a/ostd/src/trap/irq.rs b/ostd/src/trap/irq.rs
--- a/ostd/src/trap/irq.rs
+++ b/ostd/src/trap/irq.rs
@@ -158,10 +152,7 @@ impl DisabledLocalIrqGuard {
pub fn transfer_to(&mut self) -> Self {
let was_enabled = self.was_enabled;
self.was_enabled = false;
- Self {
- was_enabled,
- preempt_guard: disable_preempt(),
- }
+ Self { was_enabled }
}
}
diff --git a/ostd/src/trap/irq.rs b/ostd/src/trap/irq.rs
--- a/ostd/src/trap/irq.rs
+++ b/ostd/src/trap/irq.rs
@@ -158,10 +152,7 @@ impl DisabledLocalIrqGuard {
pub fn transfer_to(&mut self) -> Self {
let was_enabled = self.was_enabled;
self.was_enabled = false;
- Self {
- was_enabled,
- preempt_guard: disable_preempt(),
- }
+ Self { was_enabled }
}
}
diff --git a/ostd/src/trap/irq.rs b/ostd/src/trap/irq.rs
--- a/ostd/src/trap/irq.rs
+++ b/ostd/src/trap/irq.rs
@@ -172,18 +163,3 @@ impl Drop for DisabledLocalIrqGuard {
}
}
}
-
-/// Enables all IRQs on the current CPU.
-///
-/// FIXME: The reason we need to add this API is that currently IRQs
-/// are enabled when the CPU enters the user space for the first time,
-/// which is too late. During the OS initialization phase,
-/// we need to get the block device working and mount the filesystems,
-/// thus requiring the IRQs should be enabled as early as possible.
-///
-/// FIXME: this method may be unsound.
-pub fn enable_local() {
- if !crate::arch::irq::is_local_enabled() {
- crate::arch::irq::enable_local();
- }
-}
diff --git a/ostd/src/trap/irq.rs b/ostd/src/trap/irq.rs
--- a/ostd/src/trap/irq.rs
+++ b/ostd/src/trap/irq.rs
@@ -172,18 +163,3 @@ impl Drop for DisabledLocalIrqGuard {
}
}
}
-
-/// Enables all IRQs on the current CPU.
-///
-/// FIXME: The reason we need to add this API is that currently IRQs
-/// are enabled when the CPU enters the user space for the first time,
-/// which is too late. During the OS initialization phase,
-/// we need to get the block device working and mount the filesystems,
-/// thus requiring the IRQs should be enabled as early as possible.
-///
-/// FIXME: this method may be unsound.
-pub fn enable_local() {
- if !crate::arch::irq::is_local_enabled() {
- crate::arch::irq::enable_local();
- }
-}
diff --git a/ostd/src/trap/mod.rs b/ostd/src/trap/mod.rs
--- a/ostd/src/trap/mod.rs
+++ b/ostd/src/trap/mod.rs
@@ -11,9 +11,7 @@ pub use softirq::SoftIrqLine;
pub use trapframe::TrapFrame;
pub(crate) use self::handler::call_irq_callback_functions;
-pub use self::irq::{
- disable_local, enable_local, DisabledLocalIrqGuard, IrqCallbackFunction, IrqLine,
-};
+pub use self::irq::{disable_local, DisabledLocalIrqGuard, IrqCallbackFunction, IrqLine};
pub(crate) fn init() {
unsafe {
diff --git a/ostd/src/trap/mod.rs b/ostd/src/trap/mod.rs
--- a/ostd/src/trap/mod.rs
+++ b/ostd/src/trap/mod.rs
@@ -11,9 +11,7 @@ pub use softirq::SoftIrqLine;
pub use trapframe::TrapFrame;
pub(crate) use self::handler::call_irq_callback_functions;
-pub use self::irq::{
- disable_local, enable_local, DisabledLocalIrqGuard, IrqCallbackFunction, IrqLine,
-};
+pub use self::irq::{disable_local, DisabledLocalIrqGuard, IrqCallbackFunction, IrqLine};
pub(crate) fn init() {
unsafe {
|
2024-08-12T13:23:15Z
|
562e64437584279783f244edba10b512beddc81d
|
|
asterinas/asterinas
|
diff --git a/osdk/tests/cli/mod.rs b/osdk/tests/cli/mod.rs
--- a/osdk/tests/cli/mod.rs
+++ b/osdk/tests/cli/mod.rs
@@ -1,5 +1,7 @@
// SPDX-License-Identifier: MPL-2.0
+use std::fs;
+
use crate::util::*;
#[test]
diff --git a/osdk/tests/cli/mod.rs b/osdk/tests/cli/mod.rs
--- a/osdk/tests/cli/mod.rs
+++ b/osdk/tests/cli/mod.rs
@@ -50,3 +52,13 @@ fn cli_clippy_help_message() {
assert_success(&output);
assert_stdout_contains_msg(&output, "cargo osdk clippy");
}
+
+#[test]
+fn cli_new_crate_with_hyphen() {
+ let output = cargo_osdk(&["new", "--kernel", "my-first-os"])
+ .output()
+ .unwrap();
+ assert_success(&output);
+ assert!(fs::metadata("my-first-os").is_ok());
+ fs::remove_dir_all("my-first-os");
+}
|
[
"1135"
] |
0.6
|
6414111cc57b42db2bae1a0c8b01b85c3830a3b3
|
OSDK should support creating crate with `-` in its name
As discovered by #1133, `cargo osdk new --kernel my-first-os` will panic due to `my-first-os` contains `-`.
Since `cargo new my-first-os` is allowed, we should fix the problem to keep osdk consistent with cargo.
|
asterinas__asterinas-1138
| 1,138
|
diff --git a/osdk/src/commands/new/mod.rs b/osdk/src/commands/new/mod.rs
--- a/osdk/src/commands/new/mod.rs
+++ b/osdk/src/commands/new/mod.rs
@@ -163,18 +163,14 @@ fn get_manifest_path<'a>(cargo_metadata: &'a serde_json::Value, crate_name: &str
fn get_src_path<'a>(cargo_metadata: &'a serde_json::Value, crate_name: &str) -> &'a str {
let metadata = get_package_metadata(cargo_metadata, crate_name);
let targets = metadata.get("targets").unwrap().as_array().unwrap();
-
- for target in targets {
- let name = target.get("name").unwrap().as_str().unwrap();
- if name != crate_name {
- continue;
- }
-
- let src_path = target.get("src_path").unwrap();
- return src_path.as_str().unwrap();
- }
-
- panic!("the crate name does not match with any target");
+ assert!(
+ targets.len() == 1,
+ "there must be one and only one target generated"
+ );
+
+ let target = &targets[0];
+ let src_path = target.get("src_path").unwrap();
+ return src_path.as_str().unwrap();
}
fn get_workspace_root(cargo_metadata: &serde_json::Value) -> &str {
diff --git a/osdk/src/commands/new/mod.rs b/osdk/src/commands/new/mod.rs
--- a/osdk/src/commands/new/mod.rs
+++ b/osdk/src/commands/new/mod.rs
@@ -163,18 +163,14 @@ fn get_manifest_path<'a>(cargo_metadata: &'a serde_json::Value, crate_name: &str
fn get_src_path<'a>(cargo_metadata: &'a serde_json::Value, crate_name: &str) -> &'a str {
let metadata = get_package_metadata(cargo_metadata, crate_name);
let targets = metadata.get("targets").unwrap().as_array().unwrap();
-
- for target in targets {
- let name = target.get("name").unwrap().as_str().unwrap();
- if name != crate_name {
- continue;
- }
-
- let src_path = target.get("src_path").unwrap();
- return src_path.as_str().unwrap();
- }
-
- panic!("the crate name does not match with any target");
+ assert!(
+ targets.len() == 1,
+ "there must be one and only one target generated"
+ );
+
+ let target = &targets[0];
+ let src_path = target.get("src_path").unwrap();
+ return src_path.as_str().unwrap();
}
fn get_workspace_root(cargo_metadata: &serde_json::Value) -> &str {
diff --git a/osdk/tests/cli/mod.rs b/osdk/tests/cli/mod.rs
--- a/osdk/tests/cli/mod.rs
+++ b/osdk/tests/cli/mod.rs
@@ -1,5 +1,7 @@
// SPDX-License-Identifier: MPL-2.0
+use std::fs;
+
use crate::util::*;
#[test]
diff --git a/osdk/tests/cli/mod.rs b/osdk/tests/cli/mod.rs
--- a/osdk/tests/cli/mod.rs
+++ b/osdk/tests/cli/mod.rs
@@ -50,3 +52,13 @@ fn cli_clippy_help_message() {
assert_success(&output);
assert_stdout_contains_msg(&output, "cargo osdk clippy");
}
+
+#[test]
+fn cli_new_crate_with_hyphen() {
+ let output = cargo_osdk(&["new", "--kernel", "my-first-os"])
+ .output()
+ .unwrap();
+ assert_success(&output);
+ assert!(fs::metadata("my-first-os").is_ok());
+ fs::remove_dir_all("my-first-os");
+}
|
2024-08-08T01:38:09Z
|
562e64437584279783f244edba10b512beddc81d
|
|
asterinas/asterinas
|
diff --git a/kernel/aster-nix/src/process/process/mod.rs b/kernel/aster-nix/src/process/process/mod.rs
--- a/kernel/aster-nix/src/process/process/mod.rs
+++ b/kernel/aster-nix/src/process/process/mod.rs
@@ -636,15 +645,6 @@ impl Process {
}
}
-pub fn current() -> Arc<Process> {
- let current_thread = current_thread!();
- if let Some(posix_thread) = current_thread.as_posix_thread() {
- posix_thread.process()
- } else {
- panic!("[Internal error]The current thread does not belong to a process");
- }
-}
-
#[cfg(ktest)]
mod test {
diff --git a/kernel/aster-nix/src/thread/mod.rs b/kernel/aster-nix/src/thread/mod.rs
--- a/kernel/aster-nix/src/thread/mod.rs
+++ b/kernel/aster-nix/src/thread/mod.rs
@@ -50,13 +50,12 @@ impl Thread {
}
}
- /// Returns the current thread, or `None` if the current task is not associated with a thread.
+ /// Returns the current thread.
///
- /// Except for unit tests, all tasks should be associated with threads. This method is useful
- /// when writing code that can be called directly by unit tests. If this isn't the case,
- /// consider using [`current_thread!`] instead.
+ /// This function returns `None` if the current task is not associated with
+ /// a thread, or if called within the bootstrap context.
pub fn current() -> Option<Arc<Self>> {
- Task::current()
+ Task::current()?
.data()
.downcast_ref::<Weak<Thread>>()?
.upgrade()
diff --git a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
--- a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
+++ b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
@@ -72,7 +72,7 @@ fn create_user_space(program: &[u8]) -> UserSpace {
fn create_user_task(user_space: Arc<UserSpace>) -> Arc<Task> {
fn user_task() {
- let current = Task::current();
+ let current = Task::current().unwrap();
// Switching between user-kernel space is
// performed via the UserMode abstraction.
let mut user_mode = {
diff --git a/ostd/libs/ostd-test/src/lib.rs b/ostd/libs/ostd-test/src/lib.rs
--- a/ostd/libs/ostd-test/src/lib.rs
+++ b/ostd/libs/ostd-test/src/lib.rs
@@ -103,6 +103,7 @@ pub struct PanicInfo {
pub file: String,
pub line: usize,
pub col: usize,
+ pub resolve_panic: fn(),
}
impl core::fmt::Display for PanicInfo {
diff --git a/ostd/libs/ostd-test/src/lib.rs b/ostd/libs/ostd-test/src/lib.rs
--- a/ostd/libs/ostd-test/src/lib.rs
+++ b/ostd/libs/ostd-test/src/lib.rs
@@ -174,6 +175,7 @@ impl KtestItem {
Ok(()) => Err(KtestError::ShouldPanicButNoPanic),
Err(e) => match e.downcast::<PanicInfo>() {
Ok(s) => {
+ (s.resolve_panic)();
if let Some(expected) = self.should_panic.1 {
if s.message == expected {
Ok(())
diff --git a/ostd/src/cpu/cpu_local.rs /dev/null
--- a/ostd/src/cpu/cpu_local.rs
+++ /dev/null
@@ -1,340 +0,0 @@
-// SPDX-License-Identifier: MPL-2.0
-
-//! CPU local storage.
-//!
-//! This module provides a mechanism to define CPU-local objects.
-//!
-//! This is acheived by placing the CPU-local objects in a special section
-//! `.cpu_local`. The bootstrap processor (BSP) uses the objects linked in this
-//! section, and these objects are copied to dynamically allocated local
-//! storage of each application processors (AP) during the initialization
-//! process.
-//!
-//! Such a mechanism exploits the fact that constant values of non-[`Copy`]
-//! types can be bitwise copied. For example, a [`Option<T>`] object, though
-//! being not [`Copy`], have a constant constructor [`Option::None`] that
-//! produces a value that can be bitwise copied to create a new instance.
-//! [`alloc::sync::Arc`] however, don't have such a constructor, and thus cannot
-//! be directly used as a CPU-local object. Wrapping it in a type that has a
-//! constant constructor, like [`Option<T>`], can make it CPU-local.
-
-use alloc::vec::Vec;
-use core::ops::Deref;
-
-use align_ext::AlignExt;
-
-use crate::{
- arch, cpu,
- mm::{
- paddr_to_vaddr,
- page::{self, meta::KernelMeta, ContPages},
- PAGE_SIZE,
- },
- trap::{disable_local, DisabledLocalIrqGuard},
-};
-
-/// Defines a CPU-local variable.
-///
-/// # Example
-///
-/// ```rust
-/// use crate::cpu_local;
-/// use core::cell::RefCell;
-///
-/// cpu_local! {
-/// static FOO: RefCell<u32> = RefCell::new(1);
-///
-/// #[allow(unused)]
-/// pub static BAR: RefCell<f32> = RefCell::new(1.0);
-/// }
-///
-/// println!("FOO VAL: {:?}", *FOO.borrow());
-/// ```
-#[macro_export]
-macro_rules! cpu_local {
- ($( $(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; )*) => {
- $(
- #[link_section = ".cpu_local"]
- $(#[$attr])* $vis static $name: $crate::CpuLocal<$t> = {
- let val = $init;
- // SAFETY: The CPU local variable instantiated is statically
- // stored in the special `.cpu_local` section.
- unsafe {
- $crate::CpuLocal::__new(val)
- }
- };
- )*
- };
-}
-
-/// CPU-local objects.
-///
-/// A CPU-local object only gives you immutable references to the underlying value.
-/// To mutate the value, one can use atomic values (e.g., [`AtomicU32`]) or internally mutable
-/// objects (e.g., [`RefCell`]).
-///
-/// [`AtomicU32`]: core::sync::atomic::AtomicU32
-/// [`RefCell`]: core::cell::RefCell
-pub struct CpuLocal<T>(T);
-
-// SAFETY: At any given time, only one task can access the inner value T
-// of a cpu-local variable even if `T` is not `Sync`.
-unsafe impl<T> Sync for CpuLocal<T> {}
-
-// Prevent valid instances of CpuLocal from being copied to any memory
-// area outside the .cpu_local section.
-impl<T> !Copy for CpuLocal<T> {}
-impl<T> !Clone for CpuLocal<T> {}
-
-// In general, it does not make any sense to send instances of CpuLocal to
-// other tasks as they should live on other CPUs to make sending useful.
-impl<T> !Send for CpuLocal<T> {}
-
-// A check to ensure that the CPU-local object is never accessed before the
-// initialization for all CPUs.
-#[cfg(debug_assertions)]
-use core::sync::atomic::{AtomicBool, Ordering};
-#[cfg(debug_assertions)]
-static IS_INITIALIZED: AtomicBool = AtomicBool::new(false);
-
-impl<T> CpuLocal<T> {
- /// Initialize a CPU-local object.
- ///
- /// Please do not call this function directly. Instead, use the
- /// `cpu_local!` macro.
- ///
- /// # Safety
- ///
- /// The caller should ensure that the object initialized by this
- /// function resides in the `.cpu_local` section. Otherwise the
- /// behavior is undefined.
- #[doc(hidden)]
- pub const unsafe fn __new(val: T) -> Self {
- Self(val)
- }
-
- /// Get access to the underlying value with IRQs disabled.
- ///
- /// By this method, you can borrow a reference to the underlying value
- /// even if `T` is not `Sync`. Because that it is per-CPU and IRQs are
- /// disabled, no other running task can access it.
- pub fn borrow_irq_disabled(&self) -> CpuLocalDerefGuard<'_, T> {
- CpuLocalDerefGuard {
- cpu_local: self,
- _guard: disable_local(),
- }
- }
-
- /// Get access to the underlying value through a raw pointer.
- ///
- /// This function calculates the virtual address of the CPU-local object based on the per-
- /// cpu base address and the offset in the BSP.
- fn get(&self) -> *const T {
- // CPU-local objects should be initialized before being accessed. It should be ensured
- // by the implementation of OSTD initialization.
- #[cfg(debug_assertions)]
- debug_assert!(IS_INITIALIZED.load(Ordering::Relaxed));
-
- let offset = {
- let bsp_va = self as *const _ as usize;
- let bsp_base = __cpu_local_start as usize;
- // The implementation should ensure that the CPU-local object resides in the `.cpu_local`.
- debug_assert!(bsp_va + core::mem::size_of::<T>() <= __cpu_local_end as usize);
-
- bsp_va - bsp_base as usize
- };
-
- let local_base = arch::cpu::local::get_base() as usize;
- let local_va = local_base + offset;
-
- // A sanity check about the alignment.
- debug_assert_eq!(local_va % core::mem::align_of::<T>(), 0);
-
- local_va as *mut T
- }
-}
-
-// Considering a preemptive kernel, a CPU-local object may be dereferenced
-// when another task tries to access it. So, we need to ensure that `T` is
-// `Sync` before allowing it to be dereferenced.
-impl<T: Sync> Deref for CpuLocal<T> {
- type Target = T;
-
- fn deref(&self) -> &Self::Target {
- // SAFETY: it should be properly initialized before accesses.
- // And we do not create a mutable reference over it. It is
- // `Sync` so it can be referenced from this task.
- unsafe { &*self.get() }
- }
-}
-
-/// A guard for accessing the CPU-local object.
-///
-/// It ensures that the CPU-local object is accessed with IRQs
-/// disabled. It is created by [`CpuLocal::borrow_irq_disabled`].
-/// Do not hold this guard for a long time.
-#[must_use]
-pub struct CpuLocalDerefGuard<'a, T> {
- cpu_local: &'a CpuLocal<T>,
- _guard: DisabledLocalIrqGuard,
-}
-
-impl<T> Deref for CpuLocalDerefGuard<'_, T> {
- type Target = T;
-
- fn deref(&self) -> &Self::Target {
- // SAFETY: it should be properly initialized before accesses.
- // And we do not create a mutable reference over it. The IRQs
- // are disabled so it can be referenced from this task.
- unsafe { &*self.cpu_local.get() }
- }
-}
-
-/// Sets the base address of the CPU-local storage for the bootstrap processor.
-///
-/// It should be called early to let [`crate::task::disable_preempt`] work,
-/// which needs to update a CPU-local preempt lock count. Otherwise it may
-/// panic when calling [`crate::task::disable_preempt`].
-///
-/// # Safety
-///
-/// It should be called only once and only on the BSP.
-pub(crate) unsafe fn early_init_bsp_local_base() {
- let start_base_va = __cpu_local_start as usize as u64;
- // SAFETY: The base to be set is the start of the `.cpu_local` section,
- // where accessing the CPU-local objects have defined behaviors.
- unsafe {
- arch::cpu::local::set_base(start_base_va);
- }
-}
-
-/// The BSP initializes the CPU-local areas for APs. Here we use a
-/// non-disabling preempt version of lock because the [`crate::sync`]
-/// version needs `cpu_local` to work. Preemption and interrupts are
-/// disabled in this phase so it is safe to use this lock.
-static CPU_LOCAL_STORAGES: spin::RwLock<Vec<ContPages<KernelMeta>>> = spin::RwLock::new(Vec::new());
-
-/// Initializes the CPU local data for the bootstrap processor (BSP).
-///
-/// # Safety
-///
-/// This function can only called on the BSP, for once.
-///
-/// It must be guaranteed that the BSP will not access local data before
-/// this function being called, otherwise copying non-constant values
-/// will result in pretty bad undefined behavior.
-pub unsafe fn init_on_bsp() {
- let bsp_base_va = __cpu_local_start as usize;
- let bsp_end_va = __cpu_local_end as usize;
-
- let num_cpus = super::num_cpus();
-
- let mut cpu_local_storages = CPU_LOCAL_STORAGES.write();
- for cpu_i in 1..num_cpus {
- let ap_pages = {
- let nbytes = (bsp_end_va - bsp_base_va).align_up(PAGE_SIZE);
- page::allocator::alloc_contiguous(nbytes, |_| KernelMeta::default()).unwrap()
- };
- let ap_pages_ptr = paddr_to_vaddr(ap_pages.start_paddr()) as *mut u8;
-
- // SAFETY: The BSP has not initialized the CPU-local area, so the objects in
- // in the `.cpu_local` section can be bitwise bulk copied to the AP's local
- // storage. The destination memory is allocated so it is valid to write to.
- unsafe {
- core::ptr::copy_nonoverlapping(
- bsp_base_va as *const u8,
- ap_pages_ptr,
- bsp_end_va - bsp_base_va,
- );
- }
-
- // SAFETY: the first 4 bytes is reserved for storing CPU ID.
- unsafe {
- (ap_pages_ptr as *mut u32).write(cpu_i);
- }
-
- // SAFETY: the second 4 bytes is reserved for storing the preemt count.
- unsafe {
- (ap_pages_ptr as *mut u32).add(1).write(0);
- }
-
- cpu_local_storages.push(ap_pages);
- }
-
- // Write the CPU ID of BSP to the first 4 bytes of the CPU-local area.
- let bsp_cpu_id_ptr = bsp_base_va as *mut u32;
- // SAFETY: the first 4 bytes is reserved for storing CPU ID.
- unsafe {
- bsp_cpu_id_ptr.write(0);
- }
-
- cpu::local::set_base(bsp_base_va as u64);
-
- #[cfg(debug_assertions)]
- IS_INITIALIZED.store(true, Ordering::Relaxed);
-}
-
-/// Initializes the CPU local data for the application processor (AP).
-///
-/// # Safety
-///
-/// This function can only called on the AP.
-pub unsafe fn init_on_ap(cpu_id: u32) {
- let rlock = CPU_LOCAL_STORAGES.read();
- let ap_pages = rlock.get(cpu_id as usize - 1).unwrap();
-
- let ap_pages_ptr = paddr_to_vaddr(ap_pages.start_paddr()) as *mut u32;
-
- debug_assert_eq!(
- cpu_id,
- // SAFETY: the CPU ID is stored at the beginning of the CPU local area.
- unsafe { ap_pages_ptr.read() }
- );
-
- // SAFETY: the memory will be dedicated to the AP. And we are on the AP.
- unsafe {
- cpu::local::set_base(ap_pages_ptr as u64);
- }
-}
-
-// These symbols are provided by the linker script.
-extern "C" {
- fn __cpu_local_start();
- fn __cpu_local_end();
-}
-
-#[cfg(ktest)]
-mod test {
- use core::{
- cell::RefCell,
- sync::atomic::{AtomicU8, Ordering},
- };
-
- use ostd_macros::ktest;
-
- use super::*;
-
- #[ktest]
- fn test_cpu_local() {
- cpu_local! {
- static FOO: RefCell<usize> = RefCell::new(1);
- static BAR: AtomicU8 = AtomicU8::new(3);
- }
- for _ in 0..10 {
- let foo_guard = FOO.borrow_irq_disabled();
- assert_eq!(*foo_guard.borrow(), 1);
- *foo_guard.borrow_mut() = 2;
- drop(foo_guard);
- for _ in 0..10 {
- assert_eq!(BAR.load(Ordering::Relaxed), 3);
- BAR.store(4, Ordering::Relaxed);
- assert_eq!(BAR.load(Ordering::Relaxed), 4);
- BAR.store(3, Ordering::Relaxed);
- }
- let foo_guard = FOO.borrow_irq_disabled();
- assert_eq!(*foo_guard.borrow(), 2);
- *foo_guard.borrow_mut() = 1;
- drop(foo_guard);
- }
- }
-}
diff --git /dev/null b/ostd/src/cpu/local/mod.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/cpu/local/mod.rs
@@ -0,0 +1,246 @@
+// SPDX-License-Identifier: MPL-2.0
+
+//! CPU local storage.
+//!
+//! This module provides a mechanism to define CPU-local objects, by the macro
+//! [`crate::cpu_local!`].
+//!
+//! Such a mechanism exploits the fact that constant values of non-[`Copy`]
+//! types can be bitwise copied. For example, a [`Option<T>`] object, though
+//! being not [`Copy`], have a constant constructor [`Option::None`] that
+//! produces a value that can be bitwise copied to create a new instance.
+//! [`alloc::sync::Arc`] however, don't have such a constructor, and thus cannot
+//! be directly used as a CPU-local object. Wrapping it in a type that has a
+//! constant constructor, like [`Option<T>`], can make it CPU-local.
+//!
+//! # Implementation
+//!
+//! These APIs are implemented by placing the CPU-local objects in a special
+//! section `.cpu_local`. The bootstrap processor (BSP) uses the objects linked
+//! in this section, and these objects are copied to dynamically allocated
+//! local storage of each application processors (AP) during the initialization
+//! process.
+
+// This module also, provide CPU-local cell objects that have inner mutability.
+//
+// The difference between CPU-local objects (defined by [`crate::cpu_local!`])
+// and CPU-local cell objects (defined by [`crate::cpu_local_cell!`]) is that
+// the CPU-local objects can be shared across CPUs. While through a CPU-local
+// cell object you can only access the value on the current CPU, therefore
+// enabling inner mutability without locks.
+//
+// The cell-variant is currently not a public API because that it is rather
+// hard to be used without introducing races. But it is useful for OSTD's
+// internal implementation.
+
+mod cell;
+mod cpu_local;
+
+pub(crate) mod single_instr;
+
+use alloc::vec::Vec;
+
+use align_ext::AlignExt;
+pub(crate) use cell::{cpu_local_cell, CpuLocalCell};
+pub use cpu_local::{CpuLocal, CpuLocalDerefGuard};
+
+use crate::{
+ arch,
+ mm::{
+ paddr_to_vaddr,
+ page::{self, meta::KernelMeta, ContPages},
+ PAGE_SIZE,
+ },
+};
+
+// These symbols are provided by the linker script.
+extern "C" {
+ fn __cpu_local_start();
+ fn __cpu_local_end();
+}
+
+cpu_local_cell! {
+ /// The count of the preempt lock.
+ ///
+ /// We need to access the preemption count before we can copy the section
+ /// for application processors. So, the preemption count is not copied from
+ /// bootstrap processor's section as the initialization. Instead it is
+ /// initialized to zero for application processors.
+ pub(crate) static PREEMPT_LOCK_COUNT: u32 = 0;
+}
+
+/// Sets the base address of the CPU-local storage for the bootstrap processor.
+///
+/// It should be called early to let [`crate::task::disable_preempt`] work,
+/// which needs to update a CPU-local preempt lock count. Otherwise it may
+/// panic when calling [`crate::task::disable_preempt`].
+///
+/// # Safety
+///
+/// It should be called only once and only on the BSP.
+pub(crate) unsafe fn early_init_bsp_local_base() {
+ let start_base_va = __cpu_local_start as usize as u64;
+
+ // SAFETY: The base to be set is the start of the `.cpu_local` section,
+ // where accessing the CPU-local objects have defined behaviors.
+ unsafe {
+ arch::cpu::local::set_base(start_base_va);
+ }
+}
+
+/// The BSP initializes the CPU-local areas for APs. Here we use a
+/// non-disabling preempt version of lock because the [`crate::sync`]
+/// version needs `cpu_local` to work. Preemption and interrupts are
+/// disabled in this phase so it is safe to use this lock.
+static CPU_LOCAL_STORAGES: spin::RwLock<Vec<ContPages<KernelMeta>>> = spin::RwLock::new(Vec::new());
+
+/// Initializes the CPU local data for the bootstrap processor (BSP).
+///
+/// # Safety
+///
+/// This function can only called on the BSP, for once.
+///
+/// It must be guaranteed that the BSP will not access local data before
+/// this function being called, otherwise copying non-constant values
+/// will result in pretty bad undefined behavior.
+pub unsafe fn init_on_bsp() {
+ let bsp_base_va = __cpu_local_start as usize;
+ let bsp_end_va = __cpu_local_end as usize;
+
+ let num_cpus = super::num_cpus();
+
+ let mut cpu_local_storages = CPU_LOCAL_STORAGES.write();
+ for cpu_i in 1..num_cpus {
+ let ap_pages = {
+ let nbytes = (bsp_end_va - bsp_base_va).align_up(PAGE_SIZE);
+ page::allocator::alloc_contiguous(nbytes, |_| KernelMeta::default()).unwrap()
+ };
+ let ap_pages_ptr = paddr_to_vaddr(ap_pages.start_paddr()) as *mut u8;
+
+ // SAFETY: The BSP has not initialized the CPU-local area, so the objects in
+ // in the `.cpu_local` section can be bitwise bulk copied to the AP's local
+ // storage. The destination memory is allocated so it is valid to write to.
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ bsp_base_va as *const u8,
+ ap_pages_ptr,
+ bsp_end_va - bsp_base_va,
+ );
+ }
+
+ // SAFETY: bytes `0:4` are reserved for storing CPU ID.
+ unsafe {
+ (ap_pages_ptr as *mut u32).write(cpu_i);
+ }
+
+ // SAFETY: the `PREEMPT_LOCK_COUNT` may be dirty on the BSP, so we need
+ // to ensure that it is initialized to zero for APs. The safety
+ // requirements are met since the static is defined in the `.cpu_local`
+ // section and the pointer to that static is the offset in the CPU-
+ // local area. It is a `usize` so it is safe to be overwritten.
+ unsafe {
+ let preempt_count_ptr = &PREEMPT_LOCK_COUNT as *const _ as usize;
+ let preempt_count_offset = preempt_count_ptr - __cpu_local_start as usize;
+ let ap_preempt_count_ptr = ap_pages_ptr.add(preempt_count_offset) as *mut usize;
+ ap_preempt_count_ptr.write(0);
+ }
+
+ // SAFETY: bytes `8:16` are reserved for storing the pointer to the
+ // current task. We initialize it to null.
+ unsafe {
+ (ap_pages_ptr as *mut u64).add(1).write(0);
+ }
+
+ cpu_local_storages.push(ap_pages);
+ }
+
+ // Write the CPU ID of BSP to the first 4 bytes of the CPU-local area.
+ let bsp_cpu_id_ptr = bsp_base_va as *mut u32;
+ // SAFETY: the first 4 bytes is reserved for storing CPU ID.
+ unsafe {
+ bsp_cpu_id_ptr.write(0);
+ }
+
+ arch::cpu::local::set_base(bsp_base_va as u64);
+
+ has_init::set_true();
+}
+
+/// Initializes the CPU local data for the application processor (AP).
+///
+/// # Safety
+///
+/// This function can only called on the AP.
+pub unsafe fn init_on_ap(cpu_id: u32) {
+ let rlock = CPU_LOCAL_STORAGES.read();
+ let ap_pages = rlock.get(cpu_id as usize - 1).unwrap();
+
+ let ap_pages_ptr = paddr_to_vaddr(ap_pages.start_paddr()) as *mut u32;
+
+ debug_assert_eq!(
+ cpu_id,
+ // SAFETY: the CPU ID is stored at the beginning of the CPU local area.
+ unsafe { ap_pages_ptr.read() }
+ );
+
+ // SAFETY: the memory will be dedicated to the AP. And we are on the AP.
+ unsafe {
+ arch::cpu::local::set_base(ap_pages_ptr as u64);
+ }
+}
+
+mod has_init {
+ //! This module is used to detect the programming error of using the CPU-local
+ //! mechanism before it is initialized. Such bugs have been found before and we
+ //! do not want to repeat this error again. This module is only incurs runtime
+ //! overhead if debug assertions are enabled.
+ cfg_if::cfg_if! {
+ if #[cfg(debug_assertions)] {
+ use core::sync::atomic::{AtomicBool, Ordering};
+
+ static IS_INITIALIZED: AtomicBool = AtomicBool::new(false);
+
+ pub fn assert_true() {
+ debug_assert!(IS_INITIALIZED.load(Ordering::Relaxed));
+ }
+
+ pub fn set_true() {
+ IS_INITIALIZED.store(true, Ordering::Relaxed);
+ }
+ } else {
+ pub fn assert_true() {}
+
+ pub fn set_true() {}
+ }
+ }
+}
+
+#[cfg(ktest)]
+mod test {
+ use core::cell::RefCell;
+
+ use ostd_macros::ktest;
+
+ #[ktest]
+ fn test_cpu_local() {
+ crate::cpu_local! {
+ static FOO: RefCell<usize> = RefCell::new(1);
+ }
+ let foo_guard = FOO.borrow_irq_disabled();
+ assert_eq!(*foo_guard.borrow(), 1);
+ *foo_guard.borrow_mut() = 2;
+ assert_eq!(*foo_guard.borrow(), 2);
+ drop(foo_guard);
+ }
+
+ #[ktest]
+ fn test_cpu_local_cell() {
+ crate::cpu_local_cell! {
+ static BAR: usize = 3;
+ }
+ let _guard = crate::trap::disable_local();
+ assert_eq!(BAR.load(), 3);
+ BAR.store(4);
+ assert_eq!(BAR.load(), 4);
+ }
+}
diff --git a/ostd/src/panicking.rs b/ostd/src/panicking.rs
--- a/ostd/src/panicking.rs
+++ b/ostd/src/panicking.rs
@@ -17,12 +17,24 @@ use unwinding::abi::{
_Unwind_GetGR, _Unwind_GetIP,
};
+cpu_local_cell! {
+ static IN_PANIC: bool = false;
+}
+
/// The panic handler must be defined in the binary crate or in the crate that the binary
/// crate explicity declares by `extern crate`. We cannot let the base crate depend on OSTD
/// due to prismatic dependencies. That's why we export this symbol and state the
/// panic handler in the binary crate.
#[export_name = "__aster_panic_handler"]
pub fn panic_handler(info: &core::panic::PanicInfo) -> ! {
+ let _irq_guard = crate::trap::disable_local();
+
+ if IN_PANIC.load() {
+ early_println!("{}", info);
+ early_println!("The panic handler panicked when processing the above panic. Aborting.");
+ abort();
+ }
+
// If in ktest, we would like to catch the panics and resume the test.
#[cfg(ktest)]
{
diff --git a/ostd/src/prelude.rs b/ostd/src/prelude.rs
--- a/ostd/src/prelude.rs
+++ b/ostd/src/prelude.rs
@@ -8,7 +8,6 @@
pub type Result<T> = core::result::Result<T, crate::error::Error>;
pub(crate) use alloc::{boxed::Box, sync::Arc, vec::Vec};
-pub(crate) use core::any::Any;
#[cfg(ktest)]
pub use ostd_macros::ktest;
|
[
"1106"
] |
0.6
|
d04111079cb8edf03d9a58b2bd88d4af4b11543a
|
Lockless mutability for current task data.
**This is currently a work-in-progress RFC**
<!-- Thank you for taking the time to propose a new idea or significant change. Please provide a comprehensive overview of the concepts and motivations at play. -->
### Summary
<!-- Briefly summarize the idea, change, or feature you are proposing. What is it about, and what does it aim to achieve? -->
This RFC plans to introduce a mechanism for implementing lock-less inner mutability of task data that would be only accessible through the current task.
### Context and Problem Statement
<!-- Describe the problem or inadequacy of the current situation/state that your proposal is addressing. This is a key aspect of putting your RFC into context. -->
In `aster-nix`, there would be a hell lot of inner mutability patterns using `Mutex` or `SpinLock` in the thread structures, such as `SigMask`, `SigStack` and `sig_context`, etc. They are all implemented with locks. However, they should only be accessed through the current thread. There would be no syncing required. Modifying them from non-current threads should be illegal. Locks are too heavy-weighted for such kind of inner mutability patterns.
Also, for shared thread/task data, we access them using `current!` in thread/task contexts. These operations would also require fetching the task from a `cpu_local!` object that incurs heavy type-checking and interrupt/preempt blocking operations. Such jobs can be ignored when the caller is definitely in the current task's contexts. As #1105 points out, even the most simple system call `getpid` would access such task exclusive variables many times. Current implementation would require multiple locking operations and IRQ/preempt guarding operations. Many cycles are wasted doing so.
We currently only have per-task data storage that is shared (the implementer should provide `Send + Sync` types). Most of the data that don't need to be shared are also stored here, which would require a lock for inner mutability. In this RFC, I would like to introduce a new kind of data in the `ostd::Task` that is exclusive (not shared, no need to be `Send + Sync`). It would offer a chance to implement the above mentioned per-task storage without locks, boosting the performance by a lot.
### Proposal
Currently we access them via `current!()`, which would return a reference over the current task and it's corresponding data. The data is defined within a structure (either `PosixThread` or `KernelThread` currently).
In `aster-nix`, most code are running in the context of a task (other code runs in interrupt contexts). So the code would only have one replica of task local exclusive data that is accessible. Such data would only be accessed by the code in the corresponding task context also. Such kind of data should be safely mutably accessed. OSTD should provide a way to define task-context-global per-task mutable variables that are not visible in interrupt contexts. By doing so, many of the data specific to a task can be implemented lock-less.
<!-- Clearly and comprehensively describe your proposal including high-level technical specifics, any new interfaces or APIs, and how it should integrate into the existing system. -->
#### Task entry point
The optimal solution would let the task function receive references to the task data as arguments. Then all the functions that requires the data of the current task would like to receive arguments like so. This is the requirement of a function that should be used as a task entry point:
```rust
/// The entrypoint function of a task takes 4 arguments:
/// 1. the mutable task context,
/// 2. the shared task context,
/// 3. the reference to the mutable per-task data,
/// 4. and the reference to the per-task data.
pub trait TaskFn =
Fn(&mut MutTaskInfo, &SharedTaskInfo, &mut dyn Any, &(dyn Any + Send + Sync)) + 'static;
```
An example of usage:
```rust
// In `aster-nix`
use ostd::task::{MutTaskInfo, Priority, SharedTaskInfo};
use crate::thread::{
MutKernelThreadInfo, MutThreadInfo, SharedKernelThreadInfo, SharedThreadInfo, ThreadExt,
};
fn init_thread(
task_ctx_mut: &mut MutTaskInfo,
task_ctx: &SharedTaskInfo,
thread_ctx_mut: &mut MutThreadInfo,
thread_ctx: &SharedThreadInfo,
kthread_ctx_mut: &mut MutKernelThreadInfo,
kthread_ctx: &SharedKernelThreadInfo,
) {
println!(
"[kernel] Spawn init thread, tid = {}",
thread_ctx.tid
);
let initproc = Process::spawn_user_process(
karg.get_initproc_path().unwrap(),
karg.get_initproc_argv().to_vec(),
karg.get_initproc_envp().to_vec(),
)
.expect("Run init process failed.");
// Wait till initproc become zombie.
while !initproc.is_zombie() {
// We don't have preemptive scheduler now.
// The long running init thread should yield its own execution to allow other tasks to go on.
task_ctx_mut.yield_now();
}
}
#[controlled]
pub fn run_first_process() -> ! {
let _thread = thread::new_kernel(init_thread, Priority::normal(), CpuSet::new_full());
}
```
Such approach can eliminate the need of neither `current!` nor `current_thread!`, but introduces verbose parameters for the functions. This approach would be implemented by #1108 .
### Motivation and Rationale
<!-- Elaborate on why this proposal is important. Provide justifications for why it should be considered and what benefits it brings. Include use cases, user stories, and pain points it intends to solve. -->
### Detailed Design
<!-- Dive into the nitty-gritty details of your proposal. Discuss possible implementation strategies, potential issues, and how the proposal would alter workflows, behaviors, or structures. Include pseudocode, diagrams, or mock-ups if possible. -->
### Alternatives Considered
<!-- Detail any alternative solutions or features you've considered. Why were they discarded in favor of this proposal? -->
#### Context markers
Of course, the easiest way to block IRQ code from accessing task exclusive local data is to have a global state `IN_INTERRUPT_CONTEXT` and check for this state every time when accessing the task exclusive local variables. This would incur some (but not much) runtime overhead. Such overhead can be eliminated by static analysis, which we would encourage.
There would be 3 kind of contexts: the bootstrap context, the task context and the interrupt context. So the code would have $2^3=8$ types of possibilities to run in different contexts. But there are only 4 types that are significant:
1. Utility code that could run in all 3 kind of contexts;
2. Bootstrap code that only runs in the bootstrap context;
3. The IRQ handler that would only run in the interrupt context;
4. Task code that would only run in the task context.
Other code can be regarded as the type 1., since we do not know where would it run (for example, the page table cursor methods).
Code must be written in functions (except for some really low level bootstrap code, which are all in OSTD). So we can mark functions with the above types, and check if type 1./2./3. functions accessed task local exclusive global variables.
Here are the rules for function types:
- All functions that may call 2. should be 2., the root of type 2. function is `ostd::main` and `ostd::ap_entry`;
- all functions that may call 3. should be 3., the root of type 3. functions are send to `IrqLine::on_active`;
- all functions that may call 4. should be 4., the root of type 4. functions are send to `TaskOptions`;
- if a function can be call with multiple types of functions, it is type 1.
In this alternative, two tools will be introduced:
1. A procedural macro crate `code_context` (re-exported by OSTD) that provides function attributes `#[code_context::task]`, `#[code_context::interrupt]`, `#[code_context::boot]`. If not specified, the function is type 1.;
2. A tools that uses rustc to check the above rules ([an example](https://github.com/heinzelotto/rust-callgraph/tree/master)). OSDK would run this tool before compilation to reject unsound code.
### Additional Information and Resources
<!-- Offer any additional information, context, links, or resources that stakeholders might find helpful for understanding the proposal. -->
### Open Questions
<!-- List any questions that you have that might need further discussion. This can include areas where you are seeking feedback or require input to finalize decisions. -->
### Future Possibilities
<!-- If your RFC is likely to lead to subsequent changes, provide a brief outline of what those might be and how your proposal may lay the groundwork for them. -->
<!-- We appreciate your effort in contributing to the evolution of our system and look forward to reviewing and discussing your ideas! -->
|
asterinas__asterinas-1125
| 1,125
|
diff --git a/kernel/aster-nix/src/prelude.rs b/kernel/aster-nix/src/prelude.rs
--- a/kernel/aster-nix/src/prelude.rs
+++ b/kernel/aster-nix/src/prelude.rs
@@ -26,7 +26,7 @@ pub(crate) use ostd::{
#[macro_export]
macro_rules! current {
() => {
- $crate::process::current()
+ $crate::process::Process::current().unwrap()
};
}
diff --git a/kernel/aster-nix/src/prelude.rs b/kernel/aster-nix/src/prelude.rs
--- a/kernel/aster-nix/src/prelude.rs
+++ b/kernel/aster-nix/src/prelude.rs
@@ -26,7 +26,7 @@ pub(crate) use ostd::{
#[macro_export]
macro_rules! current {
() => {
- $crate::process::current()
+ $crate::process::Process::current().unwrap()
};
}
diff --git a/kernel/aster-nix/src/process/mod.rs b/kernel/aster-nix/src/process/mod.rs
--- a/kernel/aster-nix/src/process/mod.rs
+++ b/kernel/aster-nix/src/process/mod.rs
@@ -23,8 +23,7 @@ pub use credentials::{credentials, credentials_mut, Credentials, Gid, Uid};
pub use exit::do_exit_group;
pub use kill::{kill, kill_all, kill_group, tgkill};
pub use process::{
- current, ExitCode, JobControl, Pgid, Pid, Process, ProcessBuilder, ProcessGroup, Session, Sid,
- Terminal,
+ ExitCode, JobControl, Pgid, Pid, Process, ProcessBuilder, ProcessGroup, Session, Sid, Terminal,
};
pub use process_filter::ProcessFilter;
pub use process_vm::{MAX_ARGV_NUMBER, MAX_ARG_LEN, MAX_ENVP_NUMBER, MAX_ENV_LEN};
diff --git a/kernel/aster-nix/src/process/mod.rs b/kernel/aster-nix/src/process/mod.rs
--- a/kernel/aster-nix/src/process/mod.rs
+++ b/kernel/aster-nix/src/process/mod.rs
@@ -23,8 +23,7 @@ pub use credentials::{credentials, credentials_mut, Credentials, Gid, Uid};
pub use exit::do_exit_group;
pub use kill::{kill, kill_all, kill_group, tgkill};
pub use process::{
- current, ExitCode, JobControl, Pgid, Pid, Process, ProcessBuilder, ProcessGroup, Session, Sid,
- Terminal,
+ ExitCode, JobControl, Pgid, Pid, Process, ProcessBuilder, ProcessGroup, Session, Sid, Terminal,
};
pub use process_filter::ProcessFilter;
pub use process_vm::{MAX_ARGV_NUMBER, MAX_ARG_LEN, MAX_ENVP_NUMBER, MAX_ENV_LEN};
diff --git a/kernel/aster-nix/src/process/process/mod.rs b/kernel/aster-nix/src/process/process/mod.rs
--- a/kernel/aster-nix/src/process/process/mod.rs
+++ b/kernel/aster-nix/src/process/process/mod.rs
@@ -103,6 +103,15 @@ pub struct Process {
}
impl Process {
+ /// Returns the current process.
+ ///
+ /// It returns `None` if:
+ /// - the function is called in the bootstrap context;
+ /// - or if the current task is not associated with a process.
+ pub fn current() -> Option<Arc<Process>> {
+ Some(Thread::current()?.as_posix_thread()?.process())
+ }
+
#[allow(clippy::too_many_arguments)]
fn new(
pid: Pid,
diff --git a/kernel/aster-nix/src/process/process/mod.rs b/kernel/aster-nix/src/process/process/mod.rs
--- a/kernel/aster-nix/src/process/process/mod.rs
+++ b/kernel/aster-nix/src/process/process/mod.rs
@@ -103,6 +103,15 @@ pub struct Process {
}
impl Process {
+ /// Returns the current process.
+ ///
+ /// It returns `None` if:
+ /// - the function is called in the bootstrap context;
+ /// - or if the current task is not associated with a process.
+ pub fn current() -> Option<Arc<Process>> {
+ Some(Thread::current()?.as_posix_thread()?.process())
+ }
+
#[allow(clippy::too_many_arguments)]
fn new(
pid: Pid,
diff --git a/kernel/aster-nix/src/process/process/mod.rs b/kernel/aster-nix/src/process/process/mod.rs
--- a/kernel/aster-nix/src/process/process/mod.rs
+++ b/kernel/aster-nix/src/process/process/mod.rs
@@ -636,15 +645,6 @@ impl Process {
}
}
-pub fn current() -> Arc<Process> {
- let current_thread = current_thread!();
- if let Some(posix_thread) = current_thread.as_posix_thread() {
- posix_thread.process()
- } else {
- panic!("[Internal error]The current thread does not belong to a process");
- }
-}
-
#[cfg(ktest)]
mod test {
diff --git a/kernel/aster-nix/src/taskless.rs b/kernel/aster-nix/src/taskless.rs
--- a/kernel/aster-nix/src/taskless.rs
+++ b/kernel/aster-nix/src/taskless.rs
@@ -1,7 +1,5 @@
// SPDX-License-Identifier: MPL-2.0
-#![allow(dead_code)]
-
use alloc::{boxed::Box, sync::Arc};
use core::{
cell::RefCell,
diff --git a/kernel/aster-nix/src/taskless.rs b/kernel/aster-nix/src/taskless.rs
--- a/kernel/aster-nix/src/taskless.rs
+++ b/kernel/aster-nix/src/taskless.rs
@@ -1,7 +1,5 @@
// SPDX-License-Identifier: MPL-2.0
-#![allow(dead_code)]
-
use alloc::{boxed::Box, sync::Arc};
use core::{
cell::RefCell,
diff --git a/kernel/aster-nix/src/taskless.rs b/kernel/aster-nix/src/taskless.rs
--- a/kernel/aster-nix/src/taskless.rs
+++ b/kernel/aster-nix/src/taskless.rs
@@ -10,7 +8,7 @@ use core::{
};
use intrusive_collections::{intrusive_adapter, LinkedList, LinkedListAtomicLink};
-use ostd::{cpu_local, trap::SoftIrqLine, CpuLocal};
+use ostd::{cpu::local::CpuLocal, cpu_local, trap::SoftIrqLine};
use crate::softirq_id::{TASKLESS_SOFTIRQ_ID, TASKLESS_URGENT_SOFTIRQ_ID};
diff --git a/kernel/aster-nix/src/taskless.rs b/kernel/aster-nix/src/taskless.rs
--- a/kernel/aster-nix/src/taskless.rs
+++ b/kernel/aster-nix/src/taskless.rs
@@ -10,7 +8,7 @@ use core::{
};
use intrusive_collections::{intrusive_adapter, LinkedList, LinkedListAtomicLink};
-use ostd::{cpu_local, trap::SoftIrqLine, CpuLocal};
+use ostd::{cpu::local::CpuLocal, cpu_local, trap::SoftIrqLine};
use crate::softirq_id::{TASKLESS_SOFTIRQ_ID, TASKLESS_URGENT_SOFTIRQ_ID};
diff --git a/kernel/aster-nix/src/thread/mod.rs b/kernel/aster-nix/src/thread/mod.rs
--- a/kernel/aster-nix/src/thread/mod.rs
+++ b/kernel/aster-nix/src/thread/mod.rs
@@ -50,13 +50,12 @@ impl Thread {
}
}
- /// Returns the current thread, or `None` if the current task is not associated with a thread.
+ /// Returns the current thread.
///
- /// Except for unit tests, all tasks should be associated with threads. This method is useful
- /// when writing code that can be called directly by unit tests. If this isn't the case,
- /// consider using [`current_thread!`] instead.
+ /// This function returns `None` if the current task is not associated with
+ /// a thread, or if called within the bootstrap context.
pub fn current() -> Option<Arc<Self>> {
- Task::current()
+ Task::current()?
.data()
.downcast_ref::<Weak<Thread>>()?
.upgrade()
diff --git a/kernel/aster-nix/src/util/mod.rs b/kernel/aster-nix/src/util/mod.rs
--- a/kernel/aster-nix/src/util/mod.rs
+++ b/kernel/aster-nix/src/util/mod.rs
@@ -5,7 +5,7 @@ use core::mem;
use aster_rights::Full;
use ostd::{
mm::{KernelSpace, VmIo, VmReader, VmWriter},
- task::current_task,
+ task::Task,
};
use crate::{prelude::*, vm::vmar::Vmar};
diff --git a/kernel/aster-nix/src/util/mod.rs b/kernel/aster-nix/src/util/mod.rs
--- a/kernel/aster-nix/src/util/mod.rs
+++ b/kernel/aster-nix/src/util/mod.rs
@@ -5,7 +5,7 @@ use core::mem;
use aster_rights::Full;
use ostd::{
mm::{KernelSpace, VmIo, VmReader, VmWriter},
- task::current_task,
+ task::Task,
};
use crate::{prelude::*, vm::vmar::Vmar};
diff --git a/kernel/aster-nix/src/util/mod.rs b/kernel/aster-nix/src/util/mod.rs
--- a/kernel/aster-nix/src/util/mod.rs
+++ b/kernel/aster-nix/src/util/mod.rs
@@ -34,14 +34,8 @@ pub fn read_bytes_from_user(src: Vaddr, dest: &mut VmWriter<'_>) -> Result<()> {
check_vaddr(src)?;
}
- let current_task = current_task().ok_or(Error::with_message(
- Errno::EFAULT,
- "the current task is missing",
- ))?;
- let user_space = current_task.user_space().ok_or(Error::with_message(
- Errno::EFAULT,
- "the user space is missing",
- ))?;
+ let current_task = Task::current().unwrap();
+ let user_space = current_task.user_space().unwrap();
let mut user_reader = user_space.vm_space().reader(src, copy_len)?;
user_reader.read_fallible(dest).map_err(|err| err.0)?;
diff --git a/kernel/aster-nix/src/util/mod.rs b/kernel/aster-nix/src/util/mod.rs
--- a/kernel/aster-nix/src/util/mod.rs
+++ b/kernel/aster-nix/src/util/mod.rs
@@ -34,14 +34,8 @@ pub fn read_bytes_from_user(src: Vaddr, dest: &mut VmWriter<'_>) -> Result<()> {
check_vaddr(src)?;
}
- let current_task = current_task().ok_or(Error::with_message(
- Errno::EFAULT,
- "the current task is missing",
- ))?;
- let user_space = current_task.user_space().ok_or(Error::with_message(
- Errno::EFAULT,
- "the user space is missing",
- ))?;
+ let current_task = Task::current().unwrap();
+ let user_space = current_task.user_space().unwrap();
let mut user_reader = user_space.vm_space().reader(src, copy_len)?;
user_reader.read_fallible(dest).map_err(|err| err.0)?;
diff --git a/kernel/aster-nix/src/util/mod.rs b/kernel/aster-nix/src/util/mod.rs
--- a/kernel/aster-nix/src/util/mod.rs
+++ b/kernel/aster-nix/src/util/mod.rs
@@ -54,14 +48,8 @@ pub fn read_val_from_user<T: Pod>(src: Vaddr) -> Result<T> {
check_vaddr(src)?;
}
- let current_task = current_task().ok_or(Error::with_message(
- Errno::EFAULT,
- "the current task is missing",
- ))?;
- let user_space = current_task.user_space().ok_or(Error::with_message(
- Errno::EFAULT,
- "the user space is missing",
- ))?;
+ let current_task = Task::current().unwrap();
+ let user_space = current_task.user_space().unwrap();
let mut user_reader = user_space
.vm_space()
diff --git a/kernel/aster-nix/src/util/mod.rs b/kernel/aster-nix/src/util/mod.rs
--- a/kernel/aster-nix/src/util/mod.rs
+++ b/kernel/aster-nix/src/util/mod.rs
@@ -54,14 +48,8 @@ pub fn read_val_from_user<T: Pod>(src: Vaddr) -> Result<T> {
check_vaddr(src)?;
}
- let current_task = current_task().ok_or(Error::with_message(
- Errno::EFAULT,
- "the current task is missing",
- ))?;
- let user_space = current_task.user_space().ok_or(Error::with_message(
- Errno::EFAULT,
- "the user space is missing",
- ))?;
+ let current_task = Task::current().unwrap();
+ let user_space = current_task.user_space().unwrap();
let mut user_reader = user_space
.vm_space()
diff --git a/kernel/aster-nix/src/util/mod.rs b/kernel/aster-nix/src/util/mod.rs
--- a/kernel/aster-nix/src/util/mod.rs
+++ b/kernel/aster-nix/src/util/mod.rs
@@ -88,14 +76,8 @@ pub fn write_bytes_to_user(dest: Vaddr, src: &mut VmReader<'_, KernelSpace>) ->
check_vaddr(dest)?;
}
- let current_task = current_task().ok_or(Error::with_message(
- Errno::EFAULT,
- "the current task is missing",
- ))?;
- let user_space = current_task.user_space().ok_or(Error::with_message(
- Errno::EFAULT,
- "the user space is missing",
- ))?;
+ let current_task = Task::current().unwrap();
+ let user_space = current_task.user_space().unwrap();
let mut user_writer = user_space.vm_space().writer(dest, copy_len)?;
user_writer.write_fallible(src).map_err(|err| err.0)?;
diff --git a/kernel/aster-nix/src/util/mod.rs b/kernel/aster-nix/src/util/mod.rs
--- a/kernel/aster-nix/src/util/mod.rs
+++ b/kernel/aster-nix/src/util/mod.rs
@@ -88,14 +76,8 @@ pub fn write_bytes_to_user(dest: Vaddr, src: &mut VmReader<'_, KernelSpace>) ->
check_vaddr(dest)?;
}
- let current_task = current_task().ok_or(Error::with_message(
- Errno::EFAULT,
- "the current task is missing",
- ))?;
- let user_space = current_task.user_space().ok_or(Error::with_message(
- Errno::EFAULT,
- "the user space is missing",
- ))?;
+ let current_task = Task::current().unwrap();
+ let user_space = current_task.user_space().unwrap();
let mut user_writer = user_space.vm_space().writer(dest, copy_len)?;
user_writer.write_fallible(src).map_err(|err| err.0)?;
diff --git a/kernel/aster-nix/src/util/mod.rs b/kernel/aster-nix/src/util/mod.rs
--- a/kernel/aster-nix/src/util/mod.rs
+++ b/kernel/aster-nix/src/util/mod.rs
@@ -108,14 +90,8 @@ pub fn write_val_to_user<T: Pod>(dest: Vaddr, val: &T) -> Result<()> {
check_vaddr(dest)?;
}
- let current_task = current_task().ok_or(Error::with_message(
- Errno::EFAULT,
- "the current task is missing",
- ))?;
- let user_space = current_task.user_space().ok_or(Error::with_message(
- Errno::EFAULT,
- "the user space is missing",
- ))?;
+ let current_task = Task::current().unwrap();
+ let user_space = current_task.user_space().unwrap();
let mut user_writer = user_space
.vm_space()
diff --git a/kernel/aster-nix/src/util/mod.rs b/kernel/aster-nix/src/util/mod.rs
--- a/kernel/aster-nix/src/util/mod.rs
+++ b/kernel/aster-nix/src/util/mod.rs
@@ -108,14 +90,8 @@ pub fn write_val_to_user<T: Pod>(dest: Vaddr, val: &T) -> Result<()> {
check_vaddr(dest)?;
}
- let current_task = current_task().ok_or(Error::with_message(
- Errno::EFAULT,
- "the current task is missing",
- ))?;
- let user_space = current_task.user_space().ok_or(Error::with_message(
- Errno::EFAULT,
- "the user space is missing",
- ))?;
+ let current_task = Task::current().unwrap();
+ let user_space = current_task.user_space().unwrap();
let mut user_writer = user_space
.vm_space()
diff --git a/osdk/src/base_crate/x86_64.ld.template b/osdk/src/base_crate/x86_64.ld.template
--- a/osdk/src/base_crate/x86_64.ld.template
+++ b/osdk/src/base_crate/x86_64.ld.template
@@ -122,13 +122,7 @@ SECTIONS
# These 4 bytes are used to store the CPU ID.
. += 4;
-
- # These 4 bytes are used to store the number of preemption locks held.
- # The reason is stated in the Rust documentation of
- # [`ostd::task::processor::PreemptInfo`].
- __cpu_local_preempt_lock_count = . - __cpu_local_start;
- . += 4;
-
+
KEEP(*(SORT(.cpu_local)))
__cpu_local_end = .;
}
diff --git a/osdk/src/base_crate/x86_64.ld.template b/osdk/src/base_crate/x86_64.ld.template
--- a/osdk/src/base_crate/x86_64.ld.template
+++ b/osdk/src/base_crate/x86_64.ld.template
@@ -122,13 +122,7 @@ SECTIONS
# These 4 bytes are used to store the CPU ID.
. += 4;
-
- # These 4 bytes are used to store the number of preemption locks held.
- # The reason is stated in the Rust documentation of
- # [`ostd::task::processor::PreemptInfo`].
- __cpu_local_preempt_lock_count = . - __cpu_local_start;
- . += 4;
-
+
KEEP(*(SORT(.cpu_local)))
__cpu_local_end = .;
}
diff --git a/osdk/src/util.rs b/osdk/src/util.rs
--- a/osdk/src/util.rs
+++ b/osdk/src/util.rs
@@ -230,7 +230,7 @@ pub fn trace_panic_from_log(qemu_log: File, bin_path: PathBuf) {
.spawn()
.unwrap();
for line in lines.into_iter().rev() {
- if line.contains("printing stack trace:") {
+ if line.contains("Printing stack trace:") {
println!("[OSDK] The kernel seems panicked. Parsing stack trace for source lines:");
trace_exists = true;
}
diff --git a/osdk/src/util.rs b/osdk/src/util.rs
--- a/osdk/src/util.rs
+++ b/osdk/src/util.rs
@@ -230,7 +230,7 @@ pub fn trace_panic_from_log(qemu_log: File, bin_path: PathBuf) {
.spawn()
.unwrap();
for line in lines.into_iter().rev() {
- if line.contains("printing stack trace:") {
+ if line.contains("Printing stack trace:") {
println!("[OSDK] The kernel seems panicked. Parsing stack trace for source lines:");
trace_exists = true;
}
diff --git a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
--- a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
+++ b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
@@ -72,7 +72,7 @@ fn create_user_space(program: &[u8]) -> UserSpace {
fn create_user_task(user_space: Arc<UserSpace>) -> Arc<Task> {
fn user_task() {
- let current = Task::current();
+ let current = Task::current().unwrap();
// Switching between user-kernel space is
// performed via the UserMode abstraction.
let mut user_mode = {
diff --git a/ostd/libs/ostd-test/src/lib.rs b/ostd/libs/ostd-test/src/lib.rs
--- a/ostd/libs/ostd-test/src/lib.rs
+++ b/ostd/libs/ostd-test/src/lib.rs
@@ -103,6 +103,7 @@ pub struct PanicInfo {
pub file: String,
pub line: usize,
pub col: usize,
+ pub resolve_panic: fn(),
}
impl core::fmt::Display for PanicInfo {
diff --git a/ostd/libs/ostd-test/src/lib.rs b/ostd/libs/ostd-test/src/lib.rs
--- a/ostd/libs/ostd-test/src/lib.rs
+++ b/ostd/libs/ostd-test/src/lib.rs
@@ -174,6 +175,7 @@ impl KtestItem {
Ok(()) => Err(KtestError::ShouldPanicButNoPanic),
Err(e) => match e.downcast::<PanicInfo>() {
Ok(s) => {
+ (s.resolve_panic)();
if let Some(expected) = self.should_panic.1 {
if s.message == expected {
Ok(())
diff --git a/ostd/src/arch/x86/cpu/local.rs b/ostd/src/arch/x86/cpu/local.rs
--- a/ostd/src/arch/x86/cpu/local.rs
+++ b/ostd/src/arch/x86/cpu/local.rs
@@ -23,65 +23,205 @@ pub(crate) fn get_base() -> u64 {
FS::read_base().as_u64()
}
-pub mod preempt_lock_count {
- //! We need to increment/decrement the per-CPU preemption lock count using
- //! a single instruction. This requirement is stated by
- //! [`crate::task::processor::PreemptInfo`].
-
- /// The GDT ensures that the FS segment is initialized to zero on boot.
- /// This assertion checks that the base address has been set.
- macro_rules! debug_assert_initialized {
- () => {
- // The compiler may think that [`super::get_base`] has side effects
- // so it may not be optimized out. We make sure that it will be
- // conditionally compiled only in debug builds.
- #[cfg(debug_assertions)]
- debug_assert_ne!(super::get_base(), 0);
- };
- }
+use crate::cpu::local::single_instr::{
+ SingleInstructionAddAssign, SingleInstructionBitAndAssign, SingleInstructionBitOrAssign,
+ SingleInstructionBitXorAssign, SingleInstructionLoad, SingleInstructionStore,
+ SingleInstructionSubAssign,
+};
- /// Increments the per-CPU preemption lock count using one instruction.
- pub(crate) fn inc() {
- debug_assert_initialized!();
+/// The GDT ensures that the FS segment is initialized to zero on boot.
+/// This assertion checks that the base address has been set.
+macro_rules! debug_assert_initialized {
+ () => {
+ // The compiler may think that [`super::get_base`] has side effects
+ // so it may not be optimized out. We make sure that it will be
+ // conditionally compiled only in debug builds.
+ #[cfg(debug_assertions)]
+ debug_assert_ne!(get_base(), 0);
+ };
+}
+
+macro_rules! impl_numeric_single_instruction_for {
+ ($([$typ: ty, $inout_type: ident, $register_format: expr])*) => {$(
+
+ impl SingleInstructionAddAssign<$typ> for $typ {
+ unsafe fn add_assign(offset: *mut Self, val: Self) {
+ debug_assert_initialized!();
- // SAFETY: The inline assembly increments the lock count in one
- // instruction without side effects.
- unsafe {
- core::arch::asm!(
- "add dword ptr fs:[__cpu_local_preempt_lock_count], 1",
- options(nostack),
- );
+ core::arch::asm!(
+ concat!("add fs:[{0}], {1", $register_format, "}"),
+ in(reg) offset,
+ in($inout_type) val,
+ options(nostack),
+ );
+ }
}
- }
- /// Decrements the per-CPU preemption lock count using one instruction.
- pub(crate) fn dec() {
- debug_assert_initialized!();
+ impl SingleInstructionSubAssign<$typ> for $typ {
+ unsafe fn sub_assign(offset: *mut Self, val: Self) {
+ debug_assert_initialized!();
+
+ core::arch::asm!(
+ concat!("sub fs:[{0}], {1", $register_format, "}"),
+ in(reg) offset,
+ in($inout_type) val,
+ options(nostack),
+ );
+ }
+ }
+
+ impl SingleInstructionBitAndAssign<$typ> for $typ {
+ unsafe fn bitand_assign(offset: *mut Self, val: Self) {
+ debug_assert_initialized!();
+
+ core::arch::asm!(
+ concat!("and fs:[{0}], {1", $register_format, "}"),
+ in(reg) offset,
+ in($inout_type) val,
+ options(nostack),
+ );
+ }
+ }
+
+ impl SingleInstructionBitOrAssign<$typ> for $typ {
+ unsafe fn bitor_assign(offset: *mut Self, val: Self) {
+ debug_assert_initialized!();
+
+ core::arch::asm!(
+ concat!("or fs:[{0}], {1", $register_format, "}"),
+ in(reg) offset,
+ in($inout_type) val,
+ options(nostack),
+ );
+ }
+ }
+
+ impl SingleInstructionBitXorAssign<$typ> for $typ {
+ unsafe fn bitxor_assign(offset: *mut Self, val: Self) {
+ debug_assert_initialized!();
+
+ core::arch::asm!(
+ concat!("xor fs:[{0}], {1", $register_format, "}"),
+ in(reg) offset,
+ in($inout_type) val,
+ options(nostack),
+ );
+ }
+ }
+
+ impl SingleInstructionLoad for $typ {
+ unsafe fn load(offset: *const Self) -> Self {
+ debug_assert_initialized!();
+
+ let val: Self;
+ core::arch::asm!(
+ concat!("mov {0", $register_format, "}, fs:[{1}]"),
+ out($inout_type) val,
+ in(reg) offset,
+ options(nostack, readonly),
+ );
+ val
+ }
+ }
+
+ impl SingleInstructionStore for $typ {
+ unsafe fn store(offset: *mut Self, val: Self) {
+ debug_assert_initialized!();
+
+ core::arch::asm!(
+ concat!("mov fs:[{0}], {1", $register_format, "}"),
+ in(reg) offset,
+ in($inout_type) val,
+ options(nostack),
+ );
+ }
+ }
+
+ )*};
+}
+
+impl_numeric_single_instruction_for!(
+ [u64, reg, ":r"]
+ [usize, reg, ":r"]
+ [u32, reg, ":e"]
+ [u16, reg, ":x"]
+ [u8, reg_byte, ""]
+ [i64, reg, ":r"]
+ [isize, reg, ":r"]
+ [i32, reg, ":e"]
+ [i16, reg, ":x"]
+ [i8, reg_byte, ""]
+);
+
+macro_rules! impl_generic_single_instruction_for {
+ ($([<$gen_type:ident $(, $more_gen_type:ident)*>, $typ:ty])*) => {$(
+
+ impl<$gen_type $(, $more_gen_type)*> SingleInstructionLoad for $typ {
+ unsafe fn load(offset: *const Self) -> Self {
+ debug_assert_initialized!();
+
+ let val: Self;
+ core::arch::asm!(
+ concat!("mov {0}, fs:[{1}]"),
+ out(reg) val,
+ in(reg) offset,
+ options(nostack, readonly),
+ );
+ val
+ }
+ }
+
+ impl<$gen_type $(, $more_gen_type)*> SingleInstructionStore for $typ {
+ unsafe fn store(offset: *mut Self, val: Self) {
+ debug_assert_initialized!();
- // SAFETY: The inline assembly decrements the lock count in one
- // instruction without side effects.
- unsafe {
- core::arch::asm!(
- "sub dword ptr fs:[__cpu_local_preempt_lock_count], 1",
- options(nostack),
- );
+ core::arch::asm!(
+ concat!("mov fs:[{0}], {1}"),
+ in(reg) offset,
+ in(reg) val,
+ options(nostack),
+ );
+ }
}
+ )*}
+}
+
+impl_generic_single_instruction_for!(
+ [<T>, *const T]
+ [<T>, *mut T]
+ [<T, R>, fn(T) -> R]
+);
+
+// In this module, booleans are represented by the least significant bit of a
+// `u8` type. Other bits must be zero. This definition is compatible with the
+// Rust reference: <https://doc.rust-lang.org/reference/types/boolean.html>.
+
+impl SingleInstructionLoad for bool {
+ unsafe fn load(offset: *const Self) -> Self {
+ debug_assert_initialized!();
+
+ let val: u8;
+ core::arch::asm!(
+ "mov {0}, fs:[{1}]",
+ out(reg_byte) val,
+ in(reg) offset,
+ options(nostack, readonly),
+ );
+ debug_assert!(val == 1 || val == 0);
+ val == 1
}
+}
- /// Gets the per-CPU preemption lock count using one instruction.
- pub(crate) fn get() -> u32 {
+impl SingleInstructionStore for bool {
+ unsafe fn store(offset: *mut Self, val: Self) {
debug_assert_initialized!();
- let count: u32;
- // SAFETY: The inline assembly reads the lock count in one instruction
- // without side effects.
- unsafe {
- core::arch::asm!(
- "mov {0:e}, fs:[__cpu_local_preempt_lock_count]",
- out(reg) count,
- options(nostack, readonly),
- );
- }
- count
+ let val: u8 = if val { 1 } else { 0 };
+ core::arch::asm!(
+ "mov fs:[{0}], {1}",
+ in(reg) offset,
+ in(reg_byte) val,
+ options(nostack),
+ );
}
}
diff --git a/ostd/src/arch/x86/cpu/local.rs b/ostd/src/arch/x86/cpu/local.rs
--- a/ostd/src/arch/x86/cpu/local.rs
+++ b/ostd/src/arch/x86/cpu/local.rs
@@ -23,65 +23,205 @@ pub(crate) fn get_base() -> u64 {
FS::read_base().as_u64()
}
-pub mod preempt_lock_count {
- //! We need to increment/decrement the per-CPU preemption lock count using
- //! a single instruction. This requirement is stated by
- //! [`crate::task::processor::PreemptInfo`].
-
- /// The GDT ensures that the FS segment is initialized to zero on boot.
- /// This assertion checks that the base address has been set.
- macro_rules! debug_assert_initialized {
- () => {
- // The compiler may think that [`super::get_base`] has side effects
- // so it may not be optimized out. We make sure that it will be
- // conditionally compiled only in debug builds.
- #[cfg(debug_assertions)]
- debug_assert_ne!(super::get_base(), 0);
- };
- }
+use crate::cpu::local::single_instr::{
+ SingleInstructionAddAssign, SingleInstructionBitAndAssign, SingleInstructionBitOrAssign,
+ SingleInstructionBitXorAssign, SingleInstructionLoad, SingleInstructionStore,
+ SingleInstructionSubAssign,
+};
- /// Increments the per-CPU preemption lock count using one instruction.
- pub(crate) fn inc() {
- debug_assert_initialized!();
+/// The GDT ensures that the FS segment is initialized to zero on boot.
+/// This assertion checks that the base address has been set.
+macro_rules! debug_assert_initialized {
+ () => {
+ // The compiler may think that [`super::get_base`] has side effects
+ // so it may not be optimized out. We make sure that it will be
+ // conditionally compiled only in debug builds.
+ #[cfg(debug_assertions)]
+ debug_assert_ne!(get_base(), 0);
+ };
+}
+
+macro_rules! impl_numeric_single_instruction_for {
+ ($([$typ: ty, $inout_type: ident, $register_format: expr])*) => {$(
+
+ impl SingleInstructionAddAssign<$typ> for $typ {
+ unsafe fn add_assign(offset: *mut Self, val: Self) {
+ debug_assert_initialized!();
- // SAFETY: The inline assembly increments the lock count in one
- // instruction without side effects.
- unsafe {
- core::arch::asm!(
- "add dword ptr fs:[__cpu_local_preempt_lock_count], 1",
- options(nostack),
- );
+ core::arch::asm!(
+ concat!("add fs:[{0}], {1", $register_format, "}"),
+ in(reg) offset,
+ in($inout_type) val,
+ options(nostack),
+ );
+ }
}
- }
- /// Decrements the per-CPU preemption lock count using one instruction.
- pub(crate) fn dec() {
- debug_assert_initialized!();
+ impl SingleInstructionSubAssign<$typ> for $typ {
+ unsafe fn sub_assign(offset: *mut Self, val: Self) {
+ debug_assert_initialized!();
+
+ core::arch::asm!(
+ concat!("sub fs:[{0}], {1", $register_format, "}"),
+ in(reg) offset,
+ in($inout_type) val,
+ options(nostack),
+ );
+ }
+ }
+
+ impl SingleInstructionBitAndAssign<$typ> for $typ {
+ unsafe fn bitand_assign(offset: *mut Self, val: Self) {
+ debug_assert_initialized!();
+
+ core::arch::asm!(
+ concat!("and fs:[{0}], {1", $register_format, "}"),
+ in(reg) offset,
+ in($inout_type) val,
+ options(nostack),
+ );
+ }
+ }
+
+ impl SingleInstructionBitOrAssign<$typ> for $typ {
+ unsafe fn bitor_assign(offset: *mut Self, val: Self) {
+ debug_assert_initialized!();
+
+ core::arch::asm!(
+ concat!("or fs:[{0}], {1", $register_format, "}"),
+ in(reg) offset,
+ in($inout_type) val,
+ options(nostack),
+ );
+ }
+ }
+
+ impl SingleInstructionBitXorAssign<$typ> for $typ {
+ unsafe fn bitxor_assign(offset: *mut Self, val: Self) {
+ debug_assert_initialized!();
+
+ core::arch::asm!(
+ concat!("xor fs:[{0}], {1", $register_format, "}"),
+ in(reg) offset,
+ in($inout_type) val,
+ options(nostack),
+ );
+ }
+ }
+
+ impl SingleInstructionLoad for $typ {
+ unsafe fn load(offset: *const Self) -> Self {
+ debug_assert_initialized!();
+
+ let val: Self;
+ core::arch::asm!(
+ concat!("mov {0", $register_format, "}, fs:[{1}]"),
+ out($inout_type) val,
+ in(reg) offset,
+ options(nostack, readonly),
+ );
+ val
+ }
+ }
+
+ impl SingleInstructionStore for $typ {
+ unsafe fn store(offset: *mut Self, val: Self) {
+ debug_assert_initialized!();
+
+ core::arch::asm!(
+ concat!("mov fs:[{0}], {1", $register_format, "}"),
+ in(reg) offset,
+ in($inout_type) val,
+ options(nostack),
+ );
+ }
+ }
+
+ )*};
+}
+
+impl_numeric_single_instruction_for!(
+ [u64, reg, ":r"]
+ [usize, reg, ":r"]
+ [u32, reg, ":e"]
+ [u16, reg, ":x"]
+ [u8, reg_byte, ""]
+ [i64, reg, ":r"]
+ [isize, reg, ":r"]
+ [i32, reg, ":e"]
+ [i16, reg, ":x"]
+ [i8, reg_byte, ""]
+);
+
+macro_rules! impl_generic_single_instruction_for {
+ ($([<$gen_type:ident $(, $more_gen_type:ident)*>, $typ:ty])*) => {$(
+
+ impl<$gen_type $(, $more_gen_type)*> SingleInstructionLoad for $typ {
+ unsafe fn load(offset: *const Self) -> Self {
+ debug_assert_initialized!();
+
+ let val: Self;
+ core::arch::asm!(
+ concat!("mov {0}, fs:[{1}]"),
+ out(reg) val,
+ in(reg) offset,
+ options(nostack, readonly),
+ );
+ val
+ }
+ }
+
+ impl<$gen_type $(, $more_gen_type)*> SingleInstructionStore for $typ {
+ unsafe fn store(offset: *mut Self, val: Self) {
+ debug_assert_initialized!();
- // SAFETY: The inline assembly decrements the lock count in one
- // instruction without side effects.
- unsafe {
- core::arch::asm!(
- "sub dword ptr fs:[__cpu_local_preempt_lock_count], 1",
- options(nostack),
- );
+ core::arch::asm!(
+ concat!("mov fs:[{0}], {1}"),
+ in(reg) offset,
+ in(reg) val,
+ options(nostack),
+ );
+ }
}
+ )*}
+}
+
+impl_generic_single_instruction_for!(
+ [<T>, *const T]
+ [<T>, *mut T]
+ [<T, R>, fn(T) -> R]
+);
+
+// In this module, booleans are represented by the least significant bit of a
+// `u8` type. Other bits must be zero. This definition is compatible with the
+// Rust reference: <https://doc.rust-lang.org/reference/types/boolean.html>.
+
+impl SingleInstructionLoad for bool {
+ unsafe fn load(offset: *const Self) -> Self {
+ debug_assert_initialized!();
+
+ let val: u8;
+ core::arch::asm!(
+ "mov {0}, fs:[{1}]",
+ out(reg_byte) val,
+ in(reg) offset,
+ options(nostack, readonly),
+ );
+ debug_assert!(val == 1 || val == 0);
+ val == 1
}
+}
- /// Gets the per-CPU preemption lock count using one instruction.
- pub(crate) fn get() -> u32 {
+impl SingleInstructionStore for bool {
+ unsafe fn store(offset: *mut Self, val: Self) {
debug_assert_initialized!();
- let count: u32;
- // SAFETY: The inline assembly reads the lock count in one instruction
- // without side effects.
- unsafe {
- core::arch::asm!(
- "mov {0:e}, fs:[__cpu_local_preempt_lock_count]",
- out(reg) count,
- options(nostack, readonly),
- );
- }
- count
+ let val: u8 = if val { 1 } else { 0 };
+ core::arch::asm!(
+ "mov fs:[{0}], {1}",
+ in(reg) offset,
+ in(reg_byte) val,
+ options(nostack),
+ );
}
}
diff --git a/ostd/src/arch/x86/mod.rs b/ostd/src/arch/x86/mod.rs
--- a/ostd/src/arch/x86/mod.rs
+++ b/ostd/src/arch/x86/mod.rs
@@ -73,7 +73,7 @@ pub(crate) fn init_on_bsp() {
// SAFETY: no CPU local objects have been accessed by this far. And
// we are on the BSP.
- unsafe { crate::cpu::cpu_local::init_on_bsp() };
+ unsafe { crate::cpu::local::init_on_bsp() };
crate::boot::smp::boot_all_aps();
diff --git a/ostd/src/arch/x86/mod.rs b/ostd/src/arch/x86/mod.rs
--- a/ostd/src/arch/x86/mod.rs
+++ b/ostd/src/arch/x86/mod.rs
@@ -73,7 +73,7 @@ pub(crate) fn init_on_bsp() {
// SAFETY: no CPU local objects have been accessed by this far. And
// we are on the BSP.
- unsafe { crate::cpu::cpu_local::init_on_bsp() };
+ unsafe { crate::cpu::local::init_on_bsp() };
crate::boot::smp::boot_all_aps();
diff --git a/ostd/src/arch/x86/trap.rs b/ostd/src/arch/x86/trap.rs
--- a/ostd/src/arch/x86/trap.rs
+++ b/ostd/src/arch/x86/trap.rs
@@ -2,8 +2,6 @@
//! Handles trap.
-use core::sync::atomic::{AtomicBool, Ordering};
-
use align_ext::AlignExt;
use log::debug;
#[cfg(feature = "intel_tdx")]
diff --git a/ostd/src/arch/x86/trap.rs b/ostd/src/arch/x86/trap.rs
--- a/ostd/src/arch/x86/trap.rs
+++ b/ostd/src/arch/x86/trap.rs
@@ -2,8 +2,6 @@
//! Handles trap.
-use core::sync::atomic::{AtomicBool, Ordering};
-
use align_ext::AlignExt;
use log::debug;
#[cfg(feature = "intel_tdx")]
diff --git a/ostd/src/arch/x86/trap.rs b/ostd/src/arch/x86/trap.rs
--- a/ostd/src/arch/x86/trap.rs
+++ b/ostd/src/arch/x86/trap.rs
@@ -15,25 +13,25 @@ use super::ex_table::ExTable;
use crate::arch::{cpu::VIRTUALIZATION_EXCEPTION, tdx_guest::handle_virtual_exception};
use crate::{
cpu::{CpuException, CpuExceptionInfo, PageFaultErrorCode, PAGE_FAULT},
- cpu_local,
+ cpu_local_cell,
mm::{
kspace::{KERNEL_PAGE_TABLE, LINEAR_MAPPING_BASE_VADDR, LINEAR_MAPPING_VADDR_RANGE},
page_prop::{CachePolicy, PageProperty},
PageFlags, PrivilegedPageFlags as PrivFlags, MAX_USERSPACE_VADDR, PAGE_SIZE,
},
- task::current_task,
+ task::Task,
trap::call_irq_callback_functions,
};
-cpu_local! {
- static IS_KERNEL_INTERRUPTED: AtomicBool = AtomicBool::new(false);
+cpu_local_cell! {
+ static IS_KERNEL_INTERRUPTED: bool = false;
}
/// Returns true if this function is called within the context of an IRQ handler
/// and the IRQ occurs while the CPU is executing in the kernel mode.
/// Otherwise, it returns false.
pub fn is_kernel_interrupted() -> bool {
- IS_KERNEL_INTERRUPTED.load(Ordering::Acquire)
+ IS_KERNEL_INTERRUPTED.load()
}
/// Only from kernel
diff --git a/ostd/src/arch/x86/trap.rs b/ostd/src/arch/x86/trap.rs
--- a/ostd/src/arch/x86/trap.rs
+++ b/ostd/src/arch/x86/trap.rs
@@ -15,25 +13,25 @@ use super::ex_table::ExTable;
use crate::arch::{cpu::VIRTUALIZATION_EXCEPTION, tdx_guest::handle_virtual_exception};
use crate::{
cpu::{CpuException, CpuExceptionInfo, PageFaultErrorCode, PAGE_FAULT},
- cpu_local,
+ cpu_local_cell,
mm::{
kspace::{KERNEL_PAGE_TABLE, LINEAR_MAPPING_BASE_VADDR, LINEAR_MAPPING_VADDR_RANGE},
page_prop::{CachePolicy, PageProperty},
PageFlags, PrivilegedPageFlags as PrivFlags, MAX_USERSPACE_VADDR, PAGE_SIZE,
},
- task::current_task,
+ task::Task,
trap::call_irq_callback_functions,
};
-cpu_local! {
- static IS_KERNEL_INTERRUPTED: AtomicBool = AtomicBool::new(false);
+cpu_local_cell! {
+ static IS_KERNEL_INTERRUPTED: bool = false;
}
/// Returns true if this function is called within the context of an IRQ handler
/// and the IRQ occurs while the CPU is executing in the kernel mode.
/// Otherwise, it returns false.
pub fn is_kernel_interrupted() -> bool {
- IS_KERNEL_INTERRUPTED.load(Ordering::Acquire)
+ IS_KERNEL_INTERRUPTED.load()
}
/// Only from kernel
diff --git a/ostd/src/arch/x86/trap.rs b/ostd/src/arch/x86/trap.rs
--- a/ostd/src/arch/x86/trap.rs
+++ b/ostd/src/arch/x86/trap.rs
@@ -64,15 +62,15 @@ extern "sysv64" fn trap_handler(f: &mut TrapFrame) {
}
}
} else {
- IS_KERNEL_INTERRUPTED.store(true, Ordering::Release);
+ IS_KERNEL_INTERRUPTED.store(true);
call_irq_callback_functions(f, f.trap_num);
- IS_KERNEL_INTERRUPTED.store(false, Ordering::Release);
+ IS_KERNEL_INTERRUPTED.store(false);
}
}
/// Handles page fault from user space.
fn handle_user_page_fault(f: &mut TrapFrame, page_fault_addr: u64) {
- let current_task = current_task().unwrap();
+ let current_task = Task::current().unwrap();
let user_space = current_task
.user_space()
.expect("the user space is missing when a page fault from the user happens.");
diff --git a/ostd/src/arch/x86/trap.rs b/ostd/src/arch/x86/trap.rs
--- a/ostd/src/arch/x86/trap.rs
+++ b/ostd/src/arch/x86/trap.rs
@@ -64,15 +62,15 @@ extern "sysv64" fn trap_handler(f: &mut TrapFrame) {
}
}
} else {
- IS_KERNEL_INTERRUPTED.store(true, Ordering::Release);
+ IS_KERNEL_INTERRUPTED.store(true);
call_irq_callback_functions(f, f.trap_num);
- IS_KERNEL_INTERRUPTED.store(false, Ordering::Release);
+ IS_KERNEL_INTERRUPTED.store(false);
}
}
/// Handles page fault from user space.
fn handle_user_page_fault(f: &mut TrapFrame, page_fault_addr: u64) {
- let current_task = current_task().unwrap();
+ let current_task = Task::current().unwrap();
let user_space = current_task
.user_space()
.expect("the user space is missing when a page fault from the user happens.");
diff --git a/ostd/src/boot/smp.rs b/ostd/src/boot/smp.rs
--- a/ostd/src/boot/smp.rs
+++ b/ostd/src/boot/smp.rs
@@ -115,7 +115,7 @@ fn ap_early_entry(local_apic_id: u32) -> ! {
// SAFETY: we are on the AP.
unsafe {
- cpu::cpu_local::init_on_ap(local_apic_id);
+ cpu::local::init_on_ap(local_apic_id);
}
trap::init();
diff --git a/ostd/src/boot/smp.rs b/ostd/src/boot/smp.rs
--- a/ostd/src/boot/smp.rs
+++ b/ostd/src/boot/smp.rs
@@ -115,7 +115,7 @@ fn ap_early_entry(local_apic_id: u32) -> ! {
// SAFETY: we are on the AP.
unsafe {
- cpu::cpu_local::init_on_ap(local_apic_id);
+ cpu::local::init_on_ap(local_apic_id);
}
trap::init();
diff --git a/ostd/src/cpu/cpu_local.rs /dev/null
--- a/ostd/src/cpu/cpu_local.rs
+++ /dev/null
@@ -1,340 +0,0 @@
-// SPDX-License-Identifier: MPL-2.0
-
-//! CPU local storage.
-//!
-//! This module provides a mechanism to define CPU-local objects.
-//!
-//! This is acheived by placing the CPU-local objects in a special section
-//! `.cpu_local`. The bootstrap processor (BSP) uses the objects linked in this
-//! section, and these objects are copied to dynamically allocated local
-//! storage of each application processors (AP) during the initialization
-//! process.
-//!
-//! Such a mechanism exploits the fact that constant values of non-[`Copy`]
-//! types can be bitwise copied. For example, a [`Option<T>`] object, though
-//! being not [`Copy`], have a constant constructor [`Option::None`] that
-//! produces a value that can be bitwise copied to create a new instance.
-//! [`alloc::sync::Arc`] however, don't have such a constructor, and thus cannot
-//! be directly used as a CPU-local object. Wrapping it in a type that has a
-//! constant constructor, like [`Option<T>`], can make it CPU-local.
-
-use alloc::vec::Vec;
-use core::ops::Deref;
-
-use align_ext::AlignExt;
-
-use crate::{
- arch, cpu,
- mm::{
- paddr_to_vaddr,
- page::{self, meta::KernelMeta, ContPages},
- PAGE_SIZE,
- },
- trap::{disable_local, DisabledLocalIrqGuard},
-};
-
-/// Defines a CPU-local variable.
-///
-/// # Example
-///
-/// ```rust
-/// use crate::cpu_local;
-/// use core::cell::RefCell;
-///
-/// cpu_local! {
-/// static FOO: RefCell<u32> = RefCell::new(1);
-///
-/// #[allow(unused)]
-/// pub static BAR: RefCell<f32> = RefCell::new(1.0);
-/// }
-///
-/// println!("FOO VAL: {:?}", *FOO.borrow());
-/// ```
-#[macro_export]
-macro_rules! cpu_local {
- ($( $(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; )*) => {
- $(
- #[link_section = ".cpu_local"]
- $(#[$attr])* $vis static $name: $crate::CpuLocal<$t> = {
- let val = $init;
- // SAFETY: The CPU local variable instantiated is statically
- // stored in the special `.cpu_local` section.
- unsafe {
- $crate::CpuLocal::__new(val)
- }
- };
- )*
- };
-}
-
-/// CPU-local objects.
-///
-/// A CPU-local object only gives you immutable references to the underlying value.
-/// To mutate the value, one can use atomic values (e.g., [`AtomicU32`]) or internally mutable
-/// objects (e.g., [`RefCell`]).
-///
-/// [`AtomicU32`]: core::sync::atomic::AtomicU32
-/// [`RefCell`]: core::cell::RefCell
-pub struct CpuLocal<T>(T);
-
-// SAFETY: At any given time, only one task can access the inner value T
-// of a cpu-local variable even if `T` is not `Sync`.
-unsafe impl<T> Sync for CpuLocal<T> {}
-
-// Prevent valid instances of CpuLocal from being copied to any memory
-// area outside the .cpu_local section.
-impl<T> !Copy for CpuLocal<T> {}
-impl<T> !Clone for CpuLocal<T> {}
-
-// In general, it does not make any sense to send instances of CpuLocal to
-// other tasks as they should live on other CPUs to make sending useful.
-impl<T> !Send for CpuLocal<T> {}
-
-// A check to ensure that the CPU-local object is never accessed before the
-// initialization for all CPUs.
-#[cfg(debug_assertions)]
-use core::sync::atomic::{AtomicBool, Ordering};
-#[cfg(debug_assertions)]
-static IS_INITIALIZED: AtomicBool = AtomicBool::new(false);
-
-impl<T> CpuLocal<T> {
- /// Initialize a CPU-local object.
- ///
- /// Please do not call this function directly. Instead, use the
- /// `cpu_local!` macro.
- ///
- /// # Safety
- ///
- /// The caller should ensure that the object initialized by this
- /// function resides in the `.cpu_local` section. Otherwise the
- /// behavior is undefined.
- #[doc(hidden)]
- pub const unsafe fn __new(val: T) -> Self {
- Self(val)
- }
-
- /// Get access to the underlying value with IRQs disabled.
- ///
- /// By this method, you can borrow a reference to the underlying value
- /// even if `T` is not `Sync`. Because that it is per-CPU and IRQs are
- /// disabled, no other running task can access it.
- pub fn borrow_irq_disabled(&self) -> CpuLocalDerefGuard<'_, T> {
- CpuLocalDerefGuard {
- cpu_local: self,
- _guard: disable_local(),
- }
- }
-
- /// Get access to the underlying value through a raw pointer.
- ///
- /// This function calculates the virtual address of the CPU-local object based on the per-
- /// cpu base address and the offset in the BSP.
- fn get(&self) -> *const T {
- // CPU-local objects should be initialized before being accessed. It should be ensured
- // by the implementation of OSTD initialization.
- #[cfg(debug_assertions)]
- debug_assert!(IS_INITIALIZED.load(Ordering::Relaxed));
-
- let offset = {
- let bsp_va = self as *const _ as usize;
- let bsp_base = __cpu_local_start as usize;
- // The implementation should ensure that the CPU-local object resides in the `.cpu_local`.
- debug_assert!(bsp_va + core::mem::size_of::<T>() <= __cpu_local_end as usize);
-
- bsp_va - bsp_base as usize
- };
-
- let local_base = arch::cpu::local::get_base() as usize;
- let local_va = local_base + offset;
-
- // A sanity check about the alignment.
- debug_assert_eq!(local_va % core::mem::align_of::<T>(), 0);
-
- local_va as *mut T
- }
-}
-
-// Considering a preemptive kernel, a CPU-local object may be dereferenced
-// when another task tries to access it. So, we need to ensure that `T` is
-// `Sync` before allowing it to be dereferenced.
-impl<T: Sync> Deref for CpuLocal<T> {
- type Target = T;
-
- fn deref(&self) -> &Self::Target {
- // SAFETY: it should be properly initialized before accesses.
- // And we do not create a mutable reference over it. It is
- // `Sync` so it can be referenced from this task.
- unsafe { &*self.get() }
- }
-}
-
-/// A guard for accessing the CPU-local object.
-///
-/// It ensures that the CPU-local object is accessed with IRQs
-/// disabled. It is created by [`CpuLocal::borrow_irq_disabled`].
-/// Do not hold this guard for a long time.
-#[must_use]
-pub struct CpuLocalDerefGuard<'a, T> {
- cpu_local: &'a CpuLocal<T>,
- _guard: DisabledLocalIrqGuard,
-}
-
-impl<T> Deref for CpuLocalDerefGuard<'_, T> {
- type Target = T;
-
- fn deref(&self) -> &Self::Target {
- // SAFETY: it should be properly initialized before accesses.
- // And we do not create a mutable reference over it. The IRQs
- // are disabled so it can be referenced from this task.
- unsafe { &*self.cpu_local.get() }
- }
-}
-
-/// Sets the base address of the CPU-local storage for the bootstrap processor.
-///
-/// It should be called early to let [`crate::task::disable_preempt`] work,
-/// which needs to update a CPU-local preempt lock count. Otherwise it may
-/// panic when calling [`crate::task::disable_preempt`].
-///
-/// # Safety
-///
-/// It should be called only once and only on the BSP.
-pub(crate) unsafe fn early_init_bsp_local_base() {
- let start_base_va = __cpu_local_start as usize as u64;
- // SAFETY: The base to be set is the start of the `.cpu_local` section,
- // where accessing the CPU-local objects have defined behaviors.
- unsafe {
- arch::cpu::local::set_base(start_base_va);
- }
-}
-
-/// The BSP initializes the CPU-local areas for APs. Here we use a
-/// non-disabling preempt version of lock because the [`crate::sync`]
-/// version needs `cpu_local` to work. Preemption and interrupts are
-/// disabled in this phase so it is safe to use this lock.
-static CPU_LOCAL_STORAGES: spin::RwLock<Vec<ContPages<KernelMeta>>> = spin::RwLock::new(Vec::new());
-
-/// Initializes the CPU local data for the bootstrap processor (BSP).
-///
-/// # Safety
-///
-/// This function can only called on the BSP, for once.
-///
-/// It must be guaranteed that the BSP will not access local data before
-/// this function being called, otherwise copying non-constant values
-/// will result in pretty bad undefined behavior.
-pub unsafe fn init_on_bsp() {
- let bsp_base_va = __cpu_local_start as usize;
- let bsp_end_va = __cpu_local_end as usize;
-
- let num_cpus = super::num_cpus();
-
- let mut cpu_local_storages = CPU_LOCAL_STORAGES.write();
- for cpu_i in 1..num_cpus {
- let ap_pages = {
- let nbytes = (bsp_end_va - bsp_base_va).align_up(PAGE_SIZE);
- page::allocator::alloc_contiguous(nbytes, |_| KernelMeta::default()).unwrap()
- };
- let ap_pages_ptr = paddr_to_vaddr(ap_pages.start_paddr()) as *mut u8;
-
- // SAFETY: The BSP has not initialized the CPU-local area, so the objects in
- // in the `.cpu_local` section can be bitwise bulk copied to the AP's local
- // storage. The destination memory is allocated so it is valid to write to.
- unsafe {
- core::ptr::copy_nonoverlapping(
- bsp_base_va as *const u8,
- ap_pages_ptr,
- bsp_end_va - bsp_base_va,
- );
- }
-
- // SAFETY: the first 4 bytes is reserved for storing CPU ID.
- unsafe {
- (ap_pages_ptr as *mut u32).write(cpu_i);
- }
-
- // SAFETY: the second 4 bytes is reserved for storing the preemt count.
- unsafe {
- (ap_pages_ptr as *mut u32).add(1).write(0);
- }
-
- cpu_local_storages.push(ap_pages);
- }
-
- // Write the CPU ID of BSP to the first 4 bytes of the CPU-local area.
- let bsp_cpu_id_ptr = bsp_base_va as *mut u32;
- // SAFETY: the first 4 bytes is reserved for storing CPU ID.
- unsafe {
- bsp_cpu_id_ptr.write(0);
- }
-
- cpu::local::set_base(bsp_base_va as u64);
-
- #[cfg(debug_assertions)]
- IS_INITIALIZED.store(true, Ordering::Relaxed);
-}
-
-/// Initializes the CPU local data for the application processor (AP).
-///
-/// # Safety
-///
-/// This function can only called on the AP.
-pub unsafe fn init_on_ap(cpu_id: u32) {
- let rlock = CPU_LOCAL_STORAGES.read();
- let ap_pages = rlock.get(cpu_id as usize - 1).unwrap();
-
- let ap_pages_ptr = paddr_to_vaddr(ap_pages.start_paddr()) as *mut u32;
-
- debug_assert_eq!(
- cpu_id,
- // SAFETY: the CPU ID is stored at the beginning of the CPU local area.
- unsafe { ap_pages_ptr.read() }
- );
-
- // SAFETY: the memory will be dedicated to the AP. And we are on the AP.
- unsafe {
- cpu::local::set_base(ap_pages_ptr as u64);
- }
-}
-
-// These symbols are provided by the linker script.
-extern "C" {
- fn __cpu_local_start();
- fn __cpu_local_end();
-}
-
-#[cfg(ktest)]
-mod test {
- use core::{
- cell::RefCell,
- sync::atomic::{AtomicU8, Ordering},
- };
-
- use ostd_macros::ktest;
-
- use super::*;
-
- #[ktest]
- fn test_cpu_local() {
- cpu_local! {
- static FOO: RefCell<usize> = RefCell::new(1);
- static BAR: AtomicU8 = AtomicU8::new(3);
- }
- for _ in 0..10 {
- let foo_guard = FOO.borrow_irq_disabled();
- assert_eq!(*foo_guard.borrow(), 1);
- *foo_guard.borrow_mut() = 2;
- drop(foo_guard);
- for _ in 0..10 {
- assert_eq!(BAR.load(Ordering::Relaxed), 3);
- BAR.store(4, Ordering::Relaxed);
- assert_eq!(BAR.load(Ordering::Relaxed), 4);
- BAR.store(3, Ordering::Relaxed);
- }
- let foo_guard = FOO.borrow_irq_disabled();
- assert_eq!(*foo_guard.borrow(), 2);
- *foo_guard.borrow_mut() = 1;
- drop(foo_guard);
- }
- }
-}
diff --git /dev/null b/ostd/src/cpu/local/cell.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/cpu/local/cell.rs
@@ -0,0 +1,247 @@
+// SPDX-License-Identifier: MPL-2.0
+
+//! The implementaion of CPU-local variables that have inner mutability.
+
+use core::cell::UnsafeCell;
+
+use super::{__cpu_local_end, __cpu_local_start, single_instr::*};
+use crate::arch;
+
+/// Defines an inner-mutable CPU-local variable.
+///
+/// The accessors of the CPU-local variables are defined with [`CpuLocalCell`].
+///
+/// It should be noted that if the interrupts or preemption is enabled, two
+/// operations on the same CPU-local cell variable may access different objects
+/// since the task may live on different CPUs.
+///
+/// # Example
+///
+/// ```rust
+/// use ostd::cpu_local_cell;
+///
+/// cpu_local_cell! {
+/// static FOO: u32 = 1;
+/// pub static BAR: *const usize = core::ptr::null();
+/// }
+///
+/// fn not_an_atomic_function() {
+/// let bar_var: usize = 1;
+/// BAR.store(&bar_var as *const _);
+/// // Note that the value of `BAR` here doesn't nessarily equal to the address
+/// // of `bar_var`, since the task may be preempted and moved to another CPU.
+/// // You can avoid this by disabling interrupts (and preemption, if needed).
+/// println!("BAR VAL: {:?}", BAR.load());
+///
+/// let _irq_guard = ostd::trap::disable_local_irq();
+/// println!("1st FOO VAL: {:?}", FOO.load());
+/// // No suprises here, the two accesses must result in the same value.
+/// println!("2nd FOO VAL: {:?}", FOO.load());
+/// }
+/// ```
+macro_rules! cpu_local_cell {
+ ($( $(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; )*) => {
+ $(
+ #[link_section = ".cpu_local"]
+ $(#[$attr])* $vis static $name: $crate::cpu::local::CpuLocalCell<$t> = {
+ let val = $init;
+ // SAFETY: The CPU local variable instantiated is statically
+ // stored in the special `.cpu_local` section.
+ unsafe {
+ $crate::cpu::local::CpuLocalCell::__new(val)
+ }
+ };
+ )*
+ };
+}
+
+pub(crate) use cpu_local_cell;
+
+/// Inner mutable CPU-local objects.
+///
+/// CPU-local cell objects are only accessible from the current CPU. When
+/// accessing an underlying object using the same `CpuLocalCell` instance, the
+/// actually accessed object is always on the current CPU. So in a preemptive
+/// kernel task, the operated object may change if interrupts are enabled.
+///
+/// The inner mutability is provided by single instruction operations, and the
+/// CPU-local cell objects will not ever be shared between CPUs. So it is safe
+/// to modify the inner value without any locks.
+///
+/// You should only create the CPU-local cell object using the macro
+/// [`cpu_local_cell!`].
+///
+/// For the difference between [`super::CpuLocal`] and [`CpuLocalCell`], see
+/// [`super`].
+pub struct CpuLocalCell<T: 'static>(UnsafeCell<T>);
+
+impl<T: 'static> CpuLocalCell<T> {
+ /// Initialize a CPU-local object.
+ ///
+ /// Please do not call this function directly. Instead, use the
+ /// `cpu_local!` macro.
+ ///
+ /// # Safety
+ ///
+ /// The caller should ensure that the object initialized by this
+ /// function resides in the `.cpu_local` section. Otherwise the
+ /// behavior is undefined.
+ #[doc(hidden)]
+ pub const unsafe fn __new(val: T) -> Self {
+ Self(UnsafeCell::new(val))
+ }
+
+ /// Get access to the underlying value through a raw pointer.
+ ///
+ /// This function calculates the virtual address of the CPU-local object
+ /// based on the CPU-local base address and the offset in the BSP.
+ ///
+ /// # Safety
+ ///
+ /// The caller should ensure that within the entire execution of this
+ /// function, no interrupt or preemption can occur. Otherwise, the
+ /// returned pointer may points to the variable in another CPU.
+ pub unsafe fn as_ptr_mut(&'static self) -> *mut T {
+ super::has_init::assert_true();
+
+ let offset = {
+ let bsp_va = self as *const _ as usize;
+ let bsp_base = __cpu_local_start as usize;
+ // The implementation should ensure that the CPU-local object resides in the `.cpu_local`.
+ debug_assert!(bsp_va + core::mem::size_of::<T>() <= __cpu_local_end as usize);
+
+ bsp_va - bsp_base as usize
+ };
+
+ let local_base = arch::cpu::local::get_base() as usize;
+ let local_va = local_base + offset;
+
+ // A sanity check about the alignment.
+ debug_assert_eq!(local_va % core::mem::align_of::<T>(), 0);
+
+ local_va as *mut T
+ }
+}
+
+// SAFETY: At any given time, only one task can access the inner value T
+// of a cpu-local variable even if `T` is not `Sync`.
+unsafe impl<T: 'static> Sync for CpuLocalCell<T> {}
+
+// Prevent valid instances of CpuLocalCell from being copied to any memory
+// area outside the `.cpu_local` section.
+impl<T: 'static> !Copy for CpuLocalCell<T> {}
+impl<T: 'static> !Clone for CpuLocalCell<T> {}
+
+// In general, it does not make any sense to send instances of CpuLocalCell to
+// other tasks as they should live on other CPUs to make sending useful.
+impl<T: 'static> !Send for CpuLocalCell<T> {}
+
+// Accessors for the per-CPU objects whose type implements the single-
+// instruction operations.
+
+impl<T: 'static + SingleInstructionAddAssign<T>> CpuLocalCell<T> {
+ /// Adds a value to the per-CPU object in a single instruction.
+ ///
+ /// This operation wraps on overflow/underflow.
+ ///
+ /// Note that this memory operation will not be elided or reordered by the
+ /// compiler since it is a black-box.
+ pub fn add_assign(&'static self, rhs: T) {
+ let offset = self as *const _ as usize - __cpu_local_start as usize;
+ // SAFETY: The CPU-local object is defined in the `.cpu_local` section,
+ // so the pointer to the object is valid. And the reference is never shared.
+ unsafe {
+ T::add_assign(offset as *mut T, rhs);
+ }
+ }
+}
+
+impl<T: 'static + SingleInstructionSubAssign<T>> CpuLocalCell<T> {
+ /// Subtracts a value to the per-CPU object in a single instruction.
+ ///
+ /// This operation wraps on overflow/underflow.
+ ///
+ /// Note that this memory operation will not be elided or reordered by the
+ /// compiler since it is a black-box.
+ pub fn sub_assign(&'static self, rhs: T) {
+ let offset = self as *const _ as usize - __cpu_local_start as usize;
+ // SAFETY: The CPU-local object is defined in the `.cpu_local` section,
+ // so the pointer to the object is valid. And the reference is never shared.
+ unsafe {
+ T::sub_assign(offset as *mut T, rhs);
+ }
+ }
+}
+
+impl<T: 'static + SingleInstructionBitAndAssign<T>> CpuLocalCell<T> {
+ /// Bitwise ANDs a value to the per-CPU object in a single instruction.
+ ///
+ /// Note that this memory operation will not be elided or reordered by the
+ /// compiler since it is a black-box.
+ pub fn bitand_assign(&'static self, rhs: T) {
+ let offset = self as *const _ as usize - __cpu_local_start as usize;
+ // SAFETY: The CPU-local object is defined in the `.cpu_local` section,
+ // so the pointer to the object is valid. And the reference is never shared.
+ unsafe {
+ T::bitand_assign(offset as *mut T, rhs);
+ }
+ }
+}
+
+impl<T: 'static + SingleInstructionBitOrAssign<T>> CpuLocalCell<T> {
+ /// Bitwise ORs a value to the per-CPU object in a single instruction.
+ ///
+ /// Note that this memory operation will not be elided or reordered by the
+ /// compiler since it is a black-box.
+ pub fn bitor_assign(&'static self, rhs: T) {
+ let offset = self as *const _ as usize - __cpu_local_start as usize;
+ // SAFETY: The CPU-local object is defined in the `.cpu_local` section,
+ // so the pointer to the object is valid. And the reference is never shared.
+ unsafe {
+ T::bitor_assign(offset as *mut T, rhs);
+ }
+ }
+}
+
+impl<T: 'static + SingleInstructionBitXorAssign<T>> CpuLocalCell<T> {
+ /// Bitwise XORs a value to the per-CPU object in a single instruction.
+ ///
+ /// Note that this memory operation will not be elided or reordered by the
+ /// compiler since it is a black-box.
+ pub fn bitxor_assign(&'static self, rhs: T) {
+ let offset = self as *const _ as usize - __cpu_local_start as usize;
+ // SAFETY: The CPU-local object is defined in the `.cpu_local` section,
+ // so the pointer to the object is valid. And the reference is never shared.
+ unsafe {
+ T::bitxor_assign(offset as *mut T, rhs);
+ }
+ }
+}
+
+impl<T: 'static + SingleInstructionLoad> CpuLocalCell<T> {
+ /// Gets the value of the per-CPU object in a single instruction.
+ ///
+ /// Note that this memory operation will not be elided or reordered by the
+ /// compiler since it is a black-box.
+ pub fn load(&'static self) -> T {
+ let offset = self as *const _ as usize - __cpu_local_start as usize;
+ // SAFETY: The CPU-local object is defined in the `.cpu_local` section,
+ // so the pointer to the object is valid.
+ unsafe { T::load(offset as *const T) }
+ }
+}
+
+impl<T: 'static + SingleInstructionStore> CpuLocalCell<T> {
+ /// Writes a value to the per-CPU object in a single instruction.
+ ///
+ /// Note that this memory operation will not be elided or reordered by the
+ /// compiler since it is a black-box.
+ pub fn store(&'static self, val: T) {
+ let offset = self as *const _ as usize - __cpu_local_start as usize;
+ // SAFETY: The CPU-local object is defined in the `.cpu_local` section,
+ // so the pointer to the object is valid. And the reference is never shared.
+ unsafe {
+ T::store(offset as *mut T, val);
+ }
+ }
+}
diff --git /dev/null b/ostd/src/cpu/local/cell.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/cpu/local/cell.rs
@@ -0,0 +1,247 @@
+// SPDX-License-Identifier: MPL-2.0
+
+//! The implementaion of CPU-local variables that have inner mutability.
+
+use core::cell::UnsafeCell;
+
+use super::{__cpu_local_end, __cpu_local_start, single_instr::*};
+use crate::arch;
+
+/// Defines an inner-mutable CPU-local variable.
+///
+/// The accessors of the CPU-local variables are defined with [`CpuLocalCell`].
+///
+/// It should be noted that if the interrupts or preemption is enabled, two
+/// operations on the same CPU-local cell variable may access different objects
+/// since the task may live on different CPUs.
+///
+/// # Example
+///
+/// ```rust
+/// use ostd::cpu_local_cell;
+///
+/// cpu_local_cell! {
+/// static FOO: u32 = 1;
+/// pub static BAR: *const usize = core::ptr::null();
+/// }
+///
+/// fn not_an_atomic_function() {
+/// let bar_var: usize = 1;
+/// BAR.store(&bar_var as *const _);
+/// // Note that the value of `BAR` here doesn't nessarily equal to the address
+/// // of `bar_var`, since the task may be preempted and moved to another CPU.
+/// // You can avoid this by disabling interrupts (and preemption, if needed).
+/// println!("BAR VAL: {:?}", BAR.load());
+///
+/// let _irq_guard = ostd::trap::disable_local_irq();
+/// println!("1st FOO VAL: {:?}", FOO.load());
+/// // No suprises here, the two accesses must result in the same value.
+/// println!("2nd FOO VAL: {:?}", FOO.load());
+/// }
+/// ```
+macro_rules! cpu_local_cell {
+ ($( $(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; )*) => {
+ $(
+ #[link_section = ".cpu_local"]
+ $(#[$attr])* $vis static $name: $crate::cpu::local::CpuLocalCell<$t> = {
+ let val = $init;
+ // SAFETY: The CPU local variable instantiated is statically
+ // stored in the special `.cpu_local` section.
+ unsafe {
+ $crate::cpu::local::CpuLocalCell::__new(val)
+ }
+ };
+ )*
+ };
+}
+
+pub(crate) use cpu_local_cell;
+
+/// Inner mutable CPU-local objects.
+///
+/// CPU-local cell objects are only accessible from the current CPU. When
+/// accessing an underlying object using the same `CpuLocalCell` instance, the
+/// actually accessed object is always on the current CPU. So in a preemptive
+/// kernel task, the operated object may change if interrupts are enabled.
+///
+/// The inner mutability is provided by single instruction operations, and the
+/// CPU-local cell objects will not ever be shared between CPUs. So it is safe
+/// to modify the inner value without any locks.
+///
+/// You should only create the CPU-local cell object using the macro
+/// [`cpu_local_cell!`].
+///
+/// For the difference between [`super::CpuLocal`] and [`CpuLocalCell`], see
+/// [`super`].
+pub struct CpuLocalCell<T: 'static>(UnsafeCell<T>);
+
+impl<T: 'static> CpuLocalCell<T> {
+ /// Initialize a CPU-local object.
+ ///
+ /// Please do not call this function directly. Instead, use the
+ /// `cpu_local!` macro.
+ ///
+ /// # Safety
+ ///
+ /// The caller should ensure that the object initialized by this
+ /// function resides in the `.cpu_local` section. Otherwise the
+ /// behavior is undefined.
+ #[doc(hidden)]
+ pub const unsafe fn __new(val: T) -> Self {
+ Self(UnsafeCell::new(val))
+ }
+
+ /// Get access to the underlying value through a raw pointer.
+ ///
+ /// This function calculates the virtual address of the CPU-local object
+ /// based on the CPU-local base address and the offset in the BSP.
+ ///
+ /// # Safety
+ ///
+ /// The caller should ensure that within the entire execution of this
+ /// function, no interrupt or preemption can occur. Otherwise, the
+ /// returned pointer may points to the variable in another CPU.
+ pub unsafe fn as_ptr_mut(&'static self) -> *mut T {
+ super::has_init::assert_true();
+
+ let offset = {
+ let bsp_va = self as *const _ as usize;
+ let bsp_base = __cpu_local_start as usize;
+ // The implementation should ensure that the CPU-local object resides in the `.cpu_local`.
+ debug_assert!(bsp_va + core::mem::size_of::<T>() <= __cpu_local_end as usize);
+
+ bsp_va - bsp_base as usize
+ };
+
+ let local_base = arch::cpu::local::get_base() as usize;
+ let local_va = local_base + offset;
+
+ // A sanity check about the alignment.
+ debug_assert_eq!(local_va % core::mem::align_of::<T>(), 0);
+
+ local_va as *mut T
+ }
+}
+
+// SAFETY: At any given time, only one task can access the inner value T
+// of a cpu-local variable even if `T` is not `Sync`.
+unsafe impl<T: 'static> Sync for CpuLocalCell<T> {}
+
+// Prevent valid instances of CpuLocalCell from being copied to any memory
+// area outside the `.cpu_local` section.
+impl<T: 'static> !Copy for CpuLocalCell<T> {}
+impl<T: 'static> !Clone for CpuLocalCell<T> {}
+
+// In general, it does not make any sense to send instances of CpuLocalCell to
+// other tasks as they should live on other CPUs to make sending useful.
+impl<T: 'static> !Send for CpuLocalCell<T> {}
+
+// Accessors for the per-CPU objects whose type implements the single-
+// instruction operations.
+
+impl<T: 'static + SingleInstructionAddAssign<T>> CpuLocalCell<T> {
+ /// Adds a value to the per-CPU object in a single instruction.
+ ///
+ /// This operation wraps on overflow/underflow.
+ ///
+ /// Note that this memory operation will not be elided or reordered by the
+ /// compiler since it is a black-box.
+ pub fn add_assign(&'static self, rhs: T) {
+ let offset = self as *const _ as usize - __cpu_local_start as usize;
+ // SAFETY: The CPU-local object is defined in the `.cpu_local` section,
+ // so the pointer to the object is valid. And the reference is never shared.
+ unsafe {
+ T::add_assign(offset as *mut T, rhs);
+ }
+ }
+}
+
+impl<T: 'static + SingleInstructionSubAssign<T>> CpuLocalCell<T> {
+ /// Subtracts a value to the per-CPU object in a single instruction.
+ ///
+ /// This operation wraps on overflow/underflow.
+ ///
+ /// Note that this memory operation will not be elided or reordered by the
+ /// compiler since it is a black-box.
+ pub fn sub_assign(&'static self, rhs: T) {
+ let offset = self as *const _ as usize - __cpu_local_start as usize;
+ // SAFETY: The CPU-local object is defined in the `.cpu_local` section,
+ // so the pointer to the object is valid. And the reference is never shared.
+ unsafe {
+ T::sub_assign(offset as *mut T, rhs);
+ }
+ }
+}
+
+impl<T: 'static + SingleInstructionBitAndAssign<T>> CpuLocalCell<T> {
+ /// Bitwise ANDs a value to the per-CPU object in a single instruction.
+ ///
+ /// Note that this memory operation will not be elided or reordered by the
+ /// compiler since it is a black-box.
+ pub fn bitand_assign(&'static self, rhs: T) {
+ let offset = self as *const _ as usize - __cpu_local_start as usize;
+ // SAFETY: The CPU-local object is defined in the `.cpu_local` section,
+ // so the pointer to the object is valid. And the reference is never shared.
+ unsafe {
+ T::bitand_assign(offset as *mut T, rhs);
+ }
+ }
+}
+
+impl<T: 'static + SingleInstructionBitOrAssign<T>> CpuLocalCell<T> {
+ /// Bitwise ORs a value to the per-CPU object in a single instruction.
+ ///
+ /// Note that this memory operation will not be elided or reordered by the
+ /// compiler since it is a black-box.
+ pub fn bitor_assign(&'static self, rhs: T) {
+ let offset = self as *const _ as usize - __cpu_local_start as usize;
+ // SAFETY: The CPU-local object is defined in the `.cpu_local` section,
+ // so the pointer to the object is valid. And the reference is never shared.
+ unsafe {
+ T::bitor_assign(offset as *mut T, rhs);
+ }
+ }
+}
+
+impl<T: 'static + SingleInstructionBitXorAssign<T>> CpuLocalCell<T> {
+ /// Bitwise XORs a value to the per-CPU object in a single instruction.
+ ///
+ /// Note that this memory operation will not be elided or reordered by the
+ /// compiler since it is a black-box.
+ pub fn bitxor_assign(&'static self, rhs: T) {
+ let offset = self as *const _ as usize - __cpu_local_start as usize;
+ // SAFETY: The CPU-local object is defined in the `.cpu_local` section,
+ // so the pointer to the object is valid. And the reference is never shared.
+ unsafe {
+ T::bitxor_assign(offset as *mut T, rhs);
+ }
+ }
+}
+
+impl<T: 'static + SingleInstructionLoad> CpuLocalCell<T> {
+ /// Gets the value of the per-CPU object in a single instruction.
+ ///
+ /// Note that this memory operation will not be elided or reordered by the
+ /// compiler since it is a black-box.
+ pub fn load(&'static self) -> T {
+ let offset = self as *const _ as usize - __cpu_local_start as usize;
+ // SAFETY: The CPU-local object is defined in the `.cpu_local` section,
+ // so the pointer to the object is valid.
+ unsafe { T::load(offset as *const T) }
+ }
+}
+
+impl<T: 'static + SingleInstructionStore> CpuLocalCell<T> {
+ /// Writes a value to the per-CPU object in a single instruction.
+ ///
+ /// Note that this memory operation will not be elided or reordered by the
+ /// compiler since it is a black-box.
+ pub fn store(&'static self, val: T) {
+ let offset = self as *const _ as usize - __cpu_local_start as usize;
+ // SAFETY: The CPU-local object is defined in the `.cpu_local` section,
+ // so the pointer to the object is valid. And the reference is never shared.
+ unsafe {
+ T::store(offset as *mut T, val);
+ }
+ }
+}
diff --git /dev/null b/ostd/src/cpu/local/cpu_local.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/cpu/local/cpu_local.rs
@@ -0,0 +1,210 @@
+// SPDX-License-Identifier: MPL-2.0
+
+//! The CPU-local variable implementation.
+
+use core::{marker::Sync, ops::Deref};
+
+use super::{__cpu_local_end, __cpu_local_start};
+use crate::{
+ arch,
+ trap::{self, DisabledLocalIrqGuard},
+};
+
+/// Defines a CPU-local variable.
+///
+/// The accessors of the CPU-local variables are defined with [`CpuLocal`].
+///
+/// You can get the reference to the inner object by calling [`deref`]. But
+/// it is worth noting that the object is always the one in the original core
+/// when the reference is created. Use [`CpuLocal::borrow_irq_disabled`] if
+/// this is not expected, or if the inner type can't be shared across CPUs.
+///
+/// # Example
+///
+/// ```rust
+/// use ostd::{cpu_local, sync::SpinLock};
+/// use core::sync::atomic::{AtomicU32, Ordering};
+///
+/// cpu_local! {
+/// static FOO: AtomicU32 = AtomicU32::new(1);
+/// pub static BAR: SpinLock<usize> = SpinLock::new(2);
+/// }
+///
+/// fn not_an_atomic_function() {
+/// let ref_of_foo = FOO.deref();
+/// // Note that the value of `FOO` here doesn't necessarily equal to the value
+/// // of `FOO` of exactly the __current__ CPU. Since that task may be preempted
+/// // and moved to another CPU since `ref_of_foo` is created.
+/// let val_of_foo = ref_of_foo.load(Ordering::Relaxed);
+/// println!("FOO VAL: {}", val_of_foo);
+///
+/// let bar_guard = BAR.lock_irq_disabled();
+/// // Here the value of `BAR` is always the one in the __current__ CPU since
+/// // interrupts are disabled and we do not explicitly yield execution here.
+/// let val_of_bar = *bar_guard;
+/// println!("BAR VAL: {}", val_of_bar);
+/// }
+/// ```
+#[macro_export]
+macro_rules! cpu_local {
+ ($( $(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; )*) => {
+ $(
+ #[link_section = ".cpu_local"]
+ $(#[$attr])* $vis static $name: $crate::cpu::local::CpuLocal<$t> = {
+ let val = $init;
+ // SAFETY: The per-CPU variable instantiated is statically
+ // stored in the special `.cpu_local` section.
+ unsafe {
+ $crate::cpu::local::CpuLocal::__new(val)
+ }
+ };
+ )*
+ };
+}
+
+/// CPU-local objects.
+///
+/// CPU-local objects are instanciated once per CPU core. They can be shared to
+/// other cores. In the context of a preemptible kernel task, when holding the
+/// reference to the inner object, the object is always the one in the original
+/// core (when the reference is created), no matter which core the code is
+/// currently running on.
+///
+/// For the difference between [`CpuLocal`] and [`super::CpuLocalCell`], see
+/// [`super`].
+pub struct CpuLocal<T: 'static>(T);
+
+impl<T: 'static> CpuLocal<T> {
+ /// Creates a new CPU-local object.
+ ///
+ /// Please do not call this function directly. Instead, use the
+ /// `cpu_local!` macro.
+ ///
+ /// # Safety
+ ///
+ /// The caller should ensure that the object initialized by this
+ /// function resides in the `.cpu_local` section. Otherwise the
+ /// behavior is undefined.
+ #[doc(hidden)]
+ pub const unsafe fn __new(val: T) -> Self {
+ Self(val)
+ }
+
+ /// Get access to the underlying value with IRQs disabled.
+ ///
+ /// By this method, you can borrow a reference to the underlying value
+ /// even if `T` is not `Sync`. Because that it is per-CPU and IRQs are
+ /// disabled, no other running tasks can access it.
+ pub fn borrow_irq_disabled(&'static self) -> CpuLocalDerefGuard<'_, T> {
+ CpuLocalDerefGuard {
+ cpu_local: self,
+ _guard: InnerGuard::Created(trap::disable_local()),
+ }
+ }
+
+ /// Get access to the underlying value with a provided guard.
+ ///
+ /// Similar to [`CpuLocal::borrow_irq_disabled`], but you can provide
+ /// a guard to disable IRQs if you already have one.
+ pub fn borrow_with<'a>(
+ &'static self,
+ guard: &'a DisabledLocalIrqGuard,
+ ) -> CpuLocalDerefGuard<'a, T> {
+ CpuLocalDerefGuard {
+ cpu_local: self,
+ _guard: InnerGuard::Provided(guard),
+ }
+ }
+
+ /// Get access to the underlying value through a raw pointer.
+ ///
+ /// This function calculates the virtual address of the CPU-local object
+ /// based on the CPU-local base address and the offset in the BSP.
+ ///
+ /// # Safety
+ ///
+ /// The caller must ensure that the reference to `self` is static.
+ unsafe fn as_ptr(&self) -> *const T {
+ super::has_init::assert_true();
+
+ let offset = {
+ let bsp_va = self as *const _ as usize;
+ let bsp_base = __cpu_local_start as usize;
+ // The implementation should ensure that the CPU-local object resides in the `.cpu_local`.
+ debug_assert!(bsp_va + core::mem::size_of::<T>() <= __cpu_local_end as usize);
+
+ bsp_va - bsp_base as usize
+ };
+
+ let local_base = arch::cpu::local::get_base() as usize;
+ let local_va = local_base + offset;
+
+ // A sanity check about the alignment.
+ debug_assert_eq!(local_va % core::mem::align_of::<T>(), 0);
+
+ local_va as *mut T
+ }
+}
+
+// SAFETY: At any given time, only one task can access the inner value `T` of a
+// CPU-local variable if `T` is not `Sync`. We guarentee it by disabling the
+// reference to the inner value, or turning off preemptions when creating
+// the reference.
+unsafe impl<T: 'static> Sync for CpuLocal<T> {}
+
+// Prevent valid instances of `CpuLocal` from being copied to any memory areas
+// outside the `.cpu_local` section.
+impl<T: 'static> !Copy for CpuLocal<T> {}
+impl<T: 'static> !Clone for CpuLocal<T> {}
+
+// In general, it does not make any sense to send instances of `CpuLocal` to
+// other tasks as they should live on other CPUs to make sending useful.
+impl<T: 'static> !Send for CpuLocal<T> {}
+
+// For `Sync` types, we can create a reference over the inner type and allow
+// it to be shared across CPUs. So it is sound to provide a `Deref`
+// implementation. However it is up to the caller if sharing is desired.
+impl<T: 'static + Sync> Deref for CpuLocal<T> {
+ type Target = T;
+
+ /// Note that the reference to the inner object remains to the same object
+ /// accessed on the original CPU where the reference is created. If this
+ /// is not expected, turn off preemptions.
+ fn deref(&self) -> &Self::Target {
+ // SAFETY: it should be properly initialized before accesses.
+ // And we do not create a mutable reference over it. It is
+ // `Sync` so it can be referenced from this task. Here dereferencing
+ // from non-static instances is not feasible since no one can create
+ // a non-static instance of `CpuLocal`.
+ unsafe { &*self.as_ptr() }
+ }
+}
+
+/// A guard for accessing the CPU-local object.
+///
+/// It ensures that the CPU-local object is accessed with IRQs disabled.
+/// It is created by [`CpuLocal::borrow_irq_disabled`] or
+/// [`CpuLocal::borrow_with`]. Do not hold this guard for a longtime.
+#[must_use]
+pub struct CpuLocalDerefGuard<'a, T: 'static> {
+ cpu_local: &'static CpuLocal<T>,
+ _guard: InnerGuard<'a>,
+}
+
+enum InnerGuard<'a> {
+ #[allow(dead_code)]
+ Created(DisabledLocalIrqGuard),
+ #[allow(dead_code)]
+ Provided(&'a DisabledLocalIrqGuard),
+}
+
+impl<T: 'static> Deref for CpuLocalDerefGuard<'_, T> {
+ type Target = T;
+
+ fn deref(&self) -> &Self::Target {
+ // SAFETY: it should be properly initialized before accesses.
+ // And we do not create a mutable reference over it. The IRQs
+ // are disabled so it can only be referenced from this task.
+ unsafe { &*self.cpu_local.as_ptr() }
+ }
+}
diff --git /dev/null b/ostd/src/cpu/local/cpu_local.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/cpu/local/cpu_local.rs
@@ -0,0 +1,210 @@
+// SPDX-License-Identifier: MPL-2.0
+
+//! The CPU-local variable implementation.
+
+use core::{marker::Sync, ops::Deref};
+
+use super::{__cpu_local_end, __cpu_local_start};
+use crate::{
+ arch,
+ trap::{self, DisabledLocalIrqGuard},
+};
+
+/// Defines a CPU-local variable.
+///
+/// The accessors of the CPU-local variables are defined with [`CpuLocal`].
+///
+/// You can get the reference to the inner object by calling [`deref`]. But
+/// it is worth noting that the object is always the one in the original core
+/// when the reference is created. Use [`CpuLocal::borrow_irq_disabled`] if
+/// this is not expected, or if the inner type can't be shared across CPUs.
+///
+/// # Example
+///
+/// ```rust
+/// use ostd::{cpu_local, sync::SpinLock};
+/// use core::sync::atomic::{AtomicU32, Ordering};
+///
+/// cpu_local! {
+/// static FOO: AtomicU32 = AtomicU32::new(1);
+/// pub static BAR: SpinLock<usize> = SpinLock::new(2);
+/// }
+///
+/// fn not_an_atomic_function() {
+/// let ref_of_foo = FOO.deref();
+/// // Note that the value of `FOO` here doesn't necessarily equal to the value
+/// // of `FOO` of exactly the __current__ CPU. Since that task may be preempted
+/// // and moved to another CPU since `ref_of_foo` is created.
+/// let val_of_foo = ref_of_foo.load(Ordering::Relaxed);
+/// println!("FOO VAL: {}", val_of_foo);
+///
+/// let bar_guard = BAR.lock_irq_disabled();
+/// // Here the value of `BAR` is always the one in the __current__ CPU since
+/// // interrupts are disabled and we do not explicitly yield execution here.
+/// let val_of_bar = *bar_guard;
+/// println!("BAR VAL: {}", val_of_bar);
+/// }
+/// ```
+#[macro_export]
+macro_rules! cpu_local {
+ ($( $(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; )*) => {
+ $(
+ #[link_section = ".cpu_local"]
+ $(#[$attr])* $vis static $name: $crate::cpu::local::CpuLocal<$t> = {
+ let val = $init;
+ // SAFETY: The per-CPU variable instantiated is statically
+ // stored in the special `.cpu_local` section.
+ unsafe {
+ $crate::cpu::local::CpuLocal::__new(val)
+ }
+ };
+ )*
+ };
+}
+
+/// CPU-local objects.
+///
+/// CPU-local objects are instanciated once per CPU core. They can be shared to
+/// other cores. In the context of a preemptible kernel task, when holding the
+/// reference to the inner object, the object is always the one in the original
+/// core (when the reference is created), no matter which core the code is
+/// currently running on.
+///
+/// For the difference between [`CpuLocal`] and [`super::CpuLocalCell`], see
+/// [`super`].
+pub struct CpuLocal<T: 'static>(T);
+
+impl<T: 'static> CpuLocal<T> {
+ /// Creates a new CPU-local object.
+ ///
+ /// Please do not call this function directly. Instead, use the
+ /// `cpu_local!` macro.
+ ///
+ /// # Safety
+ ///
+ /// The caller should ensure that the object initialized by this
+ /// function resides in the `.cpu_local` section. Otherwise the
+ /// behavior is undefined.
+ #[doc(hidden)]
+ pub const unsafe fn __new(val: T) -> Self {
+ Self(val)
+ }
+
+ /// Get access to the underlying value with IRQs disabled.
+ ///
+ /// By this method, you can borrow a reference to the underlying value
+ /// even if `T` is not `Sync`. Because that it is per-CPU and IRQs are
+ /// disabled, no other running tasks can access it.
+ pub fn borrow_irq_disabled(&'static self) -> CpuLocalDerefGuard<'_, T> {
+ CpuLocalDerefGuard {
+ cpu_local: self,
+ _guard: InnerGuard::Created(trap::disable_local()),
+ }
+ }
+
+ /// Get access to the underlying value with a provided guard.
+ ///
+ /// Similar to [`CpuLocal::borrow_irq_disabled`], but you can provide
+ /// a guard to disable IRQs if you already have one.
+ pub fn borrow_with<'a>(
+ &'static self,
+ guard: &'a DisabledLocalIrqGuard,
+ ) -> CpuLocalDerefGuard<'a, T> {
+ CpuLocalDerefGuard {
+ cpu_local: self,
+ _guard: InnerGuard::Provided(guard),
+ }
+ }
+
+ /// Get access to the underlying value through a raw pointer.
+ ///
+ /// This function calculates the virtual address of the CPU-local object
+ /// based on the CPU-local base address and the offset in the BSP.
+ ///
+ /// # Safety
+ ///
+ /// The caller must ensure that the reference to `self` is static.
+ unsafe fn as_ptr(&self) -> *const T {
+ super::has_init::assert_true();
+
+ let offset = {
+ let bsp_va = self as *const _ as usize;
+ let bsp_base = __cpu_local_start as usize;
+ // The implementation should ensure that the CPU-local object resides in the `.cpu_local`.
+ debug_assert!(bsp_va + core::mem::size_of::<T>() <= __cpu_local_end as usize);
+
+ bsp_va - bsp_base as usize
+ };
+
+ let local_base = arch::cpu::local::get_base() as usize;
+ let local_va = local_base + offset;
+
+ // A sanity check about the alignment.
+ debug_assert_eq!(local_va % core::mem::align_of::<T>(), 0);
+
+ local_va as *mut T
+ }
+}
+
+// SAFETY: At any given time, only one task can access the inner value `T` of a
+// CPU-local variable if `T` is not `Sync`. We guarentee it by disabling the
+// reference to the inner value, or turning off preemptions when creating
+// the reference.
+unsafe impl<T: 'static> Sync for CpuLocal<T> {}
+
+// Prevent valid instances of `CpuLocal` from being copied to any memory areas
+// outside the `.cpu_local` section.
+impl<T: 'static> !Copy for CpuLocal<T> {}
+impl<T: 'static> !Clone for CpuLocal<T> {}
+
+// In general, it does not make any sense to send instances of `CpuLocal` to
+// other tasks as they should live on other CPUs to make sending useful.
+impl<T: 'static> !Send for CpuLocal<T> {}
+
+// For `Sync` types, we can create a reference over the inner type and allow
+// it to be shared across CPUs. So it is sound to provide a `Deref`
+// implementation. However it is up to the caller if sharing is desired.
+impl<T: 'static + Sync> Deref for CpuLocal<T> {
+ type Target = T;
+
+ /// Note that the reference to the inner object remains to the same object
+ /// accessed on the original CPU where the reference is created. If this
+ /// is not expected, turn off preemptions.
+ fn deref(&self) -> &Self::Target {
+ // SAFETY: it should be properly initialized before accesses.
+ // And we do not create a mutable reference over it. It is
+ // `Sync` so it can be referenced from this task. Here dereferencing
+ // from non-static instances is not feasible since no one can create
+ // a non-static instance of `CpuLocal`.
+ unsafe { &*self.as_ptr() }
+ }
+}
+
+/// A guard for accessing the CPU-local object.
+///
+/// It ensures that the CPU-local object is accessed with IRQs disabled.
+/// It is created by [`CpuLocal::borrow_irq_disabled`] or
+/// [`CpuLocal::borrow_with`]. Do not hold this guard for a longtime.
+#[must_use]
+pub struct CpuLocalDerefGuard<'a, T: 'static> {
+ cpu_local: &'static CpuLocal<T>,
+ _guard: InnerGuard<'a>,
+}
+
+enum InnerGuard<'a> {
+ #[allow(dead_code)]
+ Created(DisabledLocalIrqGuard),
+ #[allow(dead_code)]
+ Provided(&'a DisabledLocalIrqGuard),
+}
+
+impl<T: 'static> Deref for CpuLocalDerefGuard<'_, T> {
+ type Target = T;
+
+ fn deref(&self) -> &Self::Target {
+ // SAFETY: it should be properly initialized before accesses.
+ // And we do not create a mutable reference over it. The IRQs
+ // are disabled so it can only be referenced from this task.
+ unsafe { &*self.cpu_local.as_ptr() }
+ }
+}
diff --git /dev/null b/ostd/src/cpu/local/mod.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/cpu/local/mod.rs
@@ -0,0 +1,246 @@
+// SPDX-License-Identifier: MPL-2.0
+
+//! CPU local storage.
+//!
+//! This module provides a mechanism to define CPU-local objects, by the macro
+//! [`crate::cpu_local!`].
+//!
+//! Such a mechanism exploits the fact that constant values of non-[`Copy`]
+//! types can be bitwise copied. For example, a [`Option<T>`] object, though
+//! being not [`Copy`], have a constant constructor [`Option::None`] that
+//! produces a value that can be bitwise copied to create a new instance.
+//! [`alloc::sync::Arc`] however, don't have such a constructor, and thus cannot
+//! be directly used as a CPU-local object. Wrapping it in a type that has a
+//! constant constructor, like [`Option<T>`], can make it CPU-local.
+//!
+//! # Implementation
+//!
+//! These APIs are implemented by placing the CPU-local objects in a special
+//! section `.cpu_local`. The bootstrap processor (BSP) uses the objects linked
+//! in this section, and these objects are copied to dynamically allocated
+//! local storage of each application processors (AP) during the initialization
+//! process.
+
+// This module also, provide CPU-local cell objects that have inner mutability.
+//
+// The difference between CPU-local objects (defined by [`crate::cpu_local!`])
+// and CPU-local cell objects (defined by [`crate::cpu_local_cell!`]) is that
+// the CPU-local objects can be shared across CPUs. While through a CPU-local
+// cell object you can only access the value on the current CPU, therefore
+// enabling inner mutability without locks.
+//
+// The cell-variant is currently not a public API because that it is rather
+// hard to be used without introducing races. But it is useful for OSTD's
+// internal implementation.
+
+mod cell;
+mod cpu_local;
+
+pub(crate) mod single_instr;
+
+use alloc::vec::Vec;
+
+use align_ext::AlignExt;
+pub(crate) use cell::{cpu_local_cell, CpuLocalCell};
+pub use cpu_local::{CpuLocal, CpuLocalDerefGuard};
+
+use crate::{
+ arch,
+ mm::{
+ paddr_to_vaddr,
+ page::{self, meta::KernelMeta, ContPages},
+ PAGE_SIZE,
+ },
+};
+
+// These symbols are provided by the linker script.
+extern "C" {
+ fn __cpu_local_start();
+ fn __cpu_local_end();
+}
+
+cpu_local_cell! {
+ /// The count of the preempt lock.
+ ///
+ /// We need to access the preemption count before we can copy the section
+ /// for application processors. So, the preemption count is not copied from
+ /// bootstrap processor's section as the initialization. Instead it is
+ /// initialized to zero for application processors.
+ pub(crate) static PREEMPT_LOCK_COUNT: u32 = 0;
+}
+
+/// Sets the base address of the CPU-local storage for the bootstrap processor.
+///
+/// It should be called early to let [`crate::task::disable_preempt`] work,
+/// which needs to update a CPU-local preempt lock count. Otherwise it may
+/// panic when calling [`crate::task::disable_preempt`].
+///
+/// # Safety
+///
+/// It should be called only once and only on the BSP.
+pub(crate) unsafe fn early_init_bsp_local_base() {
+ let start_base_va = __cpu_local_start as usize as u64;
+
+ // SAFETY: The base to be set is the start of the `.cpu_local` section,
+ // where accessing the CPU-local objects have defined behaviors.
+ unsafe {
+ arch::cpu::local::set_base(start_base_va);
+ }
+}
+
+/// The BSP initializes the CPU-local areas for APs. Here we use a
+/// non-disabling preempt version of lock because the [`crate::sync`]
+/// version needs `cpu_local` to work. Preemption and interrupts are
+/// disabled in this phase so it is safe to use this lock.
+static CPU_LOCAL_STORAGES: spin::RwLock<Vec<ContPages<KernelMeta>>> = spin::RwLock::new(Vec::new());
+
+/// Initializes the CPU local data for the bootstrap processor (BSP).
+///
+/// # Safety
+///
+/// This function can only called on the BSP, for once.
+///
+/// It must be guaranteed that the BSP will not access local data before
+/// this function being called, otherwise copying non-constant values
+/// will result in pretty bad undefined behavior.
+pub unsafe fn init_on_bsp() {
+ let bsp_base_va = __cpu_local_start as usize;
+ let bsp_end_va = __cpu_local_end as usize;
+
+ let num_cpus = super::num_cpus();
+
+ let mut cpu_local_storages = CPU_LOCAL_STORAGES.write();
+ for cpu_i in 1..num_cpus {
+ let ap_pages = {
+ let nbytes = (bsp_end_va - bsp_base_va).align_up(PAGE_SIZE);
+ page::allocator::alloc_contiguous(nbytes, |_| KernelMeta::default()).unwrap()
+ };
+ let ap_pages_ptr = paddr_to_vaddr(ap_pages.start_paddr()) as *mut u8;
+
+ // SAFETY: The BSP has not initialized the CPU-local area, so the objects in
+ // in the `.cpu_local` section can be bitwise bulk copied to the AP's local
+ // storage. The destination memory is allocated so it is valid to write to.
+ unsafe {
+ core::ptr::copy_nonoverlapping(
+ bsp_base_va as *const u8,
+ ap_pages_ptr,
+ bsp_end_va - bsp_base_va,
+ );
+ }
+
+ // SAFETY: bytes `0:4` are reserved for storing CPU ID.
+ unsafe {
+ (ap_pages_ptr as *mut u32).write(cpu_i);
+ }
+
+ // SAFETY: the `PREEMPT_LOCK_COUNT` may be dirty on the BSP, so we need
+ // to ensure that it is initialized to zero for APs. The safety
+ // requirements are met since the static is defined in the `.cpu_local`
+ // section and the pointer to that static is the offset in the CPU-
+ // local area. It is a `usize` so it is safe to be overwritten.
+ unsafe {
+ let preempt_count_ptr = &PREEMPT_LOCK_COUNT as *const _ as usize;
+ let preempt_count_offset = preempt_count_ptr - __cpu_local_start as usize;
+ let ap_preempt_count_ptr = ap_pages_ptr.add(preempt_count_offset) as *mut usize;
+ ap_preempt_count_ptr.write(0);
+ }
+
+ // SAFETY: bytes `8:16` are reserved for storing the pointer to the
+ // current task. We initialize it to null.
+ unsafe {
+ (ap_pages_ptr as *mut u64).add(1).write(0);
+ }
+
+ cpu_local_storages.push(ap_pages);
+ }
+
+ // Write the CPU ID of BSP to the first 4 bytes of the CPU-local area.
+ let bsp_cpu_id_ptr = bsp_base_va as *mut u32;
+ // SAFETY: the first 4 bytes is reserved for storing CPU ID.
+ unsafe {
+ bsp_cpu_id_ptr.write(0);
+ }
+
+ arch::cpu::local::set_base(bsp_base_va as u64);
+
+ has_init::set_true();
+}
+
+/// Initializes the CPU local data for the application processor (AP).
+///
+/// # Safety
+///
+/// This function can only called on the AP.
+pub unsafe fn init_on_ap(cpu_id: u32) {
+ let rlock = CPU_LOCAL_STORAGES.read();
+ let ap_pages = rlock.get(cpu_id as usize - 1).unwrap();
+
+ let ap_pages_ptr = paddr_to_vaddr(ap_pages.start_paddr()) as *mut u32;
+
+ debug_assert_eq!(
+ cpu_id,
+ // SAFETY: the CPU ID is stored at the beginning of the CPU local area.
+ unsafe { ap_pages_ptr.read() }
+ );
+
+ // SAFETY: the memory will be dedicated to the AP. And we are on the AP.
+ unsafe {
+ arch::cpu::local::set_base(ap_pages_ptr as u64);
+ }
+}
+
+mod has_init {
+ //! This module is used to detect the programming error of using the CPU-local
+ //! mechanism before it is initialized. Such bugs have been found before and we
+ //! do not want to repeat this error again. This module is only incurs runtime
+ //! overhead if debug assertions are enabled.
+ cfg_if::cfg_if! {
+ if #[cfg(debug_assertions)] {
+ use core::sync::atomic::{AtomicBool, Ordering};
+
+ static IS_INITIALIZED: AtomicBool = AtomicBool::new(false);
+
+ pub fn assert_true() {
+ debug_assert!(IS_INITIALIZED.load(Ordering::Relaxed));
+ }
+
+ pub fn set_true() {
+ IS_INITIALIZED.store(true, Ordering::Relaxed);
+ }
+ } else {
+ pub fn assert_true() {}
+
+ pub fn set_true() {}
+ }
+ }
+}
+
+#[cfg(ktest)]
+mod test {
+ use core::cell::RefCell;
+
+ use ostd_macros::ktest;
+
+ #[ktest]
+ fn test_cpu_local() {
+ crate::cpu_local! {
+ static FOO: RefCell<usize> = RefCell::new(1);
+ }
+ let foo_guard = FOO.borrow_irq_disabled();
+ assert_eq!(*foo_guard.borrow(), 1);
+ *foo_guard.borrow_mut() = 2;
+ assert_eq!(*foo_guard.borrow(), 2);
+ drop(foo_guard);
+ }
+
+ #[ktest]
+ fn test_cpu_local_cell() {
+ crate::cpu_local_cell! {
+ static BAR: usize = 3;
+ }
+ let _guard = crate::trap::disable_local();
+ assert_eq!(BAR.load(), 3);
+ BAR.store(4);
+ assert_eq!(BAR.load(), 4);
+ }
+}
diff --git /dev/null b/ostd/src/cpu/local/single_instr.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/cpu/local/single_instr.rs
@@ -0,0 +1,165 @@
+// SPDX-License-Identifier: MPL-2.0
+
+//! Extensions for CPU-local types that allows single-instruction operations.
+//!
+//! For some per-CPU objects, fetching or modifying the values of them can be
+//! done in a single instruction. Then we would avoid turning off interrupts
+//! when accessing them, which incurs non-trivial overhead.
+//!
+//! These traits are the architecture-specific interface for single-instruction
+//! operations. The architecture-specific module can implement these traits for
+//! common integer types. For architectures that don't support such single-
+//! instruction operations, we emulate a single-instruction implementation by
+//! disabling interruptions and preemptions.
+//!
+//! Currently we implement some of the [`core::ops`] operations. Bitwise shift
+//! implementations are missing. Also for less-fundamental types such as
+//! enumerations or boolean types, the caller can cast it themselves to the
+//! integer types, for which the operations are implemented.
+//!
+//! # Safety
+//!
+//! All operations in the provided traits are unsafe, and the caller should
+//! ensure that the offset is a valid pointer to a static [`CpuLocalCell`]
+//! object. The offset of the object is relative to the base address of the
+//! CPU-local storage. These operations are not atomic. Accessing the same
+//! address from multiple CPUs produces undefined behavior.
+//!
+//! [`CpuLocalCell`]: crate::cpu::local::CpuLocalCell
+
+/// An interface for architecture-specific single-instruction add operation.
+pub trait SingleInstructionAddAssign<Rhs = Self> {
+ /// Adds a value to the per-CPU object.
+ ///
+ /// This operation wraps on overflow.
+ ///
+ /// # Safety
+ ///
+ ///
+ unsafe fn add_assign(offset: *mut Self, rhs: Rhs);
+}
+
+impl<T: num_traits::WrappingAdd + Copy> SingleInstructionAddAssign<T> for T {
+ default unsafe fn add_assign(offset: *mut Self, rhs: T) {
+ let _guard = crate::trap::disable_local();
+ let base = crate::arch::cpu::local::get_base() as usize;
+ let addr = (base + offset as usize) as *mut Self;
+ addr.write(addr.read().wrapping_add(&rhs));
+ }
+}
+
+/// An interface for architecture-specific single-instruction subtract operation.
+pub trait SingleInstructionSubAssign<Rhs = Self> {
+ /// Subtracts a value to the per-CPU object.
+ ///
+ /// This operation wraps on overflow.
+ ///
+ /// # Safety
+ ///
+ /// Please refer to the module-level documentation of [`self`].
+ unsafe fn sub_assign(offset: *mut Self, rhs: Rhs);
+}
+
+impl<T: num_traits::WrappingSub + Copy> SingleInstructionSubAssign<T> for T {
+ default unsafe fn sub_assign(offset: *mut Self, rhs: T) {
+ let _guard = crate::trap::disable_local();
+ let base = crate::arch::cpu::local::get_base() as usize;
+ let addr = (base + offset as usize) as *mut Self;
+ addr.write(addr.read().wrapping_sub(&rhs));
+ }
+}
+
+/// An interface for architecture-specific single-instruction bitwise OR.
+pub trait SingleInstructionBitOrAssign<Rhs = Self> {
+ /// Bitwise ORs a value to the per-CPU object.
+ ///
+ /// # Safety
+ ///
+ /// Please refer to the module-level documentation of [`self`].
+ unsafe fn bitor_assign(offset: *mut Self, rhs: Rhs);
+}
+
+impl<T: core::ops::BitOr<Output = T> + Copy> SingleInstructionBitOrAssign<T> for T {
+ default unsafe fn bitor_assign(offset: *mut Self, rhs: T) {
+ let _guard = crate::trap::disable_local();
+ let base = crate::arch::cpu::local::get_base() as usize;
+ let addr = (base + offset as usize) as *mut Self;
+ addr.write(addr.read() | rhs);
+ }
+}
+
+/// An interface for architecture-specific single-instruction bitwise AND.
+pub trait SingleInstructionBitAndAssign<Rhs = Self> {
+ /// Bitwise ANDs a value to the per-CPU object.
+ ///
+ /// # Safety
+ ///
+ /// Please refer to the module-level documentation of [`self`].
+ unsafe fn bitand_assign(offset: *mut Self, rhs: Rhs);
+}
+
+impl<T: core::ops::BitAnd<Output = T> + Copy> SingleInstructionBitAndAssign<T> for T {
+ default unsafe fn bitand_assign(offset: *mut Self, rhs: T) {
+ let _guard = crate::trap::disable_local();
+ let base = crate::arch::cpu::local::get_base() as usize;
+ let addr = (base + offset as usize) as *mut Self;
+ addr.write(addr.read() & rhs);
+ }
+}
+
+/// An interface for architecture-specific single-instruction bitwise XOR.
+pub trait SingleInstructionBitXorAssign<Rhs = Self> {
+ /// Bitwise XORs a value to the per-CPU object.
+ ///
+ /// # Safety
+ ///
+ /// Please refer to the module-level documentation of [`self`].
+ unsafe fn bitxor_assign(offset: *mut Self, rhs: Rhs);
+}
+
+impl<T: core::ops::BitXor<Output = T> + Copy> SingleInstructionBitXorAssign<T> for T {
+ default unsafe fn bitxor_assign(offset: *mut Self, rhs: T) {
+ let _guard = crate::trap::disable_local();
+ let base = crate::arch::cpu::local::get_base() as usize;
+ let addr = (base + offset as usize) as *mut Self;
+ addr.write(addr.read() ^ rhs);
+ }
+}
+
+/// An interface for architecture-specific single-instruction get operation.
+pub trait SingleInstructionLoad {
+ /// Gets the value of the per-CPU object.
+ ///
+ /// # Safety
+ ///
+ /// Please refer to the module-level documentation of [`self`].
+ unsafe fn load(offset: *const Self) -> Self;
+}
+
+impl<T: Copy> SingleInstructionLoad for T {
+ default unsafe fn load(offset: *const Self) -> Self {
+ let _guard = crate::trap::disable_local();
+ let base = crate::arch::cpu::local::get_base() as usize;
+ let ptr = (base + offset as usize) as *const Self;
+ ptr.read()
+ }
+}
+
+/// An interface for architecture-specific single-instruction set operation.
+pub trait SingleInstructionStore {
+ /// Writes a value to the per-CPU object.
+ ///
+ /// # Safety
+ ///
+ /// Please refer to the module-level documentation of [`self`].
+ unsafe fn store(offset: *mut Self, val: Self);
+}
+
+impl<T: Copy> SingleInstructionStore for T {
+ default unsafe fn store(offset: *mut Self, val: Self) {
+ let _guard = crate::trap::disable_local();
+ let base = crate::arch::cpu::local::get_base() as usize;
+ let ptr = (base + offset as usize) as *mut Self;
+ ptr.write(val);
+ }
+}
diff --git /dev/null b/ostd/src/cpu/local/single_instr.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/cpu/local/single_instr.rs
@@ -0,0 +1,165 @@
+// SPDX-License-Identifier: MPL-2.0
+
+//! Extensions for CPU-local types that allows single-instruction operations.
+//!
+//! For some per-CPU objects, fetching or modifying the values of them can be
+//! done in a single instruction. Then we would avoid turning off interrupts
+//! when accessing them, which incurs non-trivial overhead.
+//!
+//! These traits are the architecture-specific interface for single-instruction
+//! operations. The architecture-specific module can implement these traits for
+//! common integer types. For architectures that don't support such single-
+//! instruction operations, we emulate a single-instruction implementation by
+//! disabling interruptions and preemptions.
+//!
+//! Currently we implement some of the [`core::ops`] operations. Bitwise shift
+//! implementations are missing. Also for less-fundamental types such as
+//! enumerations or boolean types, the caller can cast it themselves to the
+//! integer types, for which the operations are implemented.
+//!
+//! # Safety
+//!
+//! All operations in the provided traits are unsafe, and the caller should
+//! ensure that the offset is a valid pointer to a static [`CpuLocalCell`]
+//! object. The offset of the object is relative to the base address of the
+//! CPU-local storage. These operations are not atomic. Accessing the same
+//! address from multiple CPUs produces undefined behavior.
+//!
+//! [`CpuLocalCell`]: crate::cpu::local::CpuLocalCell
+
+/// An interface for architecture-specific single-instruction add operation.
+pub trait SingleInstructionAddAssign<Rhs = Self> {
+ /// Adds a value to the per-CPU object.
+ ///
+ /// This operation wraps on overflow.
+ ///
+ /// # Safety
+ ///
+ ///
+ unsafe fn add_assign(offset: *mut Self, rhs: Rhs);
+}
+
+impl<T: num_traits::WrappingAdd + Copy> SingleInstructionAddAssign<T> for T {
+ default unsafe fn add_assign(offset: *mut Self, rhs: T) {
+ let _guard = crate::trap::disable_local();
+ let base = crate::arch::cpu::local::get_base() as usize;
+ let addr = (base + offset as usize) as *mut Self;
+ addr.write(addr.read().wrapping_add(&rhs));
+ }
+}
+
+/// An interface for architecture-specific single-instruction subtract operation.
+pub trait SingleInstructionSubAssign<Rhs = Self> {
+ /// Subtracts a value to the per-CPU object.
+ ///
+ /// This operation wraps on overflow.
+ ///
+ /// # Safety
+ ///
+ /// Please refer to the module-level documentation of [`self`].
+ unsafe fn sub_assign(offset: *mut Self, rhs: Rhs);
+}
+
+impl<T: num_traits::WrappingSub + Copy> SingleInstructionSubAssign<T> for T {
+ default unsafe fn sub_assign(offset: *mut Self, rhs: T) {
+ let _guard = crate::trap::disable_local();
+ let base = crate::arch::cpu::local::get_base() as usize;
+ let addr = (base + offset as usize) as *mut Self;
+ addr.write(addr.read().wrapping_sub(&rhs));
+ }
+}
+
+/// An interface for architecture-specific single-instruction bitwise OR.
+pub trait SingleInstructionBitOrAssign<Rhs = Self> {
+ /// Bitwise ORs a value to the per-CPU object.
+ ///
+ /// # Safety
+ ///
+ /// Please refer to the module-level documentation of [`self`].
+ unsafe fn bitor_assign(offset: *mut Self, rhs: Rhs);
+}
+
+impl<T: core::ops::BitOr<Output = T> + Copy> SingleInstructionBitOrAssign<T> for T {
+ default unsafe fn bitor_assign(offset: *mut Self, rhs: T) {
+ let _guard = crate::trap::disable_local();
+ let base = crate::arch::cpu::local::get_base() as usize;
+ let addr = (base + offset as usize) as *mut Self;
+ addr.write(addr.read() | rhs);
+ }
+}
+
+/// An interface for architecture-specific single-instruction bitwise AND.
+pub trait SingleInstructionBitAndAssign<Rhs = Self> {
+ /// Bitwise ANDs a value to the per-CPU object.
+ ///
+ /// # Safety
+ ///
+ /// Please refer to the module-level documentation of [`self`].
+ unsafe fn bitand_assign(offset: *mut Self, rhs: Rhs);
+}
+
+impl<T: core::ops::BitAnd<Output = T> + Copy> SingleInstructionBitAndAssign<T> for T {
+ default unsafe fn bitand_assign(offset: *mut Self, rhs: T) {
+ let _guard = crate::trap::disable_local();
+ let base = crate::arch::cpu::local::get_base() as usize;
+ let addr = (base + offset as usize) as *mut Self;
+ addr.write(addr.read() & rhs);
+ }
+}
+
+/// An interface for architecture-specific single-instruction bitwise XOR.
+pub trait SingleInstructionBitXorAssign<Rhs = Self> {
+ /// Bitwise XORs a value to the per-CPU object.
+ ///
+ /// # Safety
+ ///
+ /// Please refer to the module-level documentation of [`self`].
+ unsafe fn bitxor_assign(offset: *mut Self, rhs: Rhs);
+}
+
+impl<T: core::ops::BitXor<Output = T> + Copy> SingleInstructionBitXorAssign<T> for T {
+ default unsafe fn bitxor_assign(offset: *mut Self, rhs: T) {
+ let _guard = crate::trap::disable_local();
+ let base = crate::arch::cpu::local::get_base() as usize;
+ let addr = (base + offset as usize) as *mut Self;
+ addr.write(addr.read() ^ rhs);
+ }
+}
+
+/// An interface for architecture-specific single-instruction get operation.
+pub trait SingleInstructionLoad {
+ /// Gets the value of the per-CPU object.
+ ///
+ /// # Safety
+ ///
+ /// Please refer to the module-level documentation of [`self`].
+ unsafe fn load(offset: *const Self) -> Self;
+}
+
+impl<T: Copy> SingleInstructionLoad for T {
+ default unsafe fn load(offset: *const Self) -> Self {
+ let _guard = crate::trap::disable_local();
+ let base = crate::arch::cpu::local::get_base() as usize;
+ let ptr = (base + offset as usize) as *const Self;
+ ptr.read()
+ }
+}
+
+/// An interface for architecture-specific single-instruction set operation.
+pub trait SingleInstructionStore {
+ /// Writes a value to the per-CPU object.
+ ///
+ /// # Safety
+ ///
+ /// Please refer to the module-level documentation of [`self`].
+ unsafe fn store(offset: *mut Self, val: Self);
+}
+
+impl<T: Copy> SingleInstructionStore for T {
+ default unsafe fn store(offset: *mut Self, val: Self) {
+ let _guard = crate::trap::disable_local();
+ let base = crate::arch::cpu::local::get_base() as usize;
+ let ptr = (base + offset as usize) as *mut Self;
+ ptr.write(val);
+ }
+}
diff --git a/ostd/src/cpu/mod.rs b/ostd/src/cpu/mod.rs
--- a/ostd/src/cpu/mod.rs
+++ b/ostd/src/cpu/mod.rs
@@ -2,7 +2,7 @@
//! CPU-related definitions.
-pub mod cpu_local;
+pub mod local;
cfg_if::cfg_if! {
if #[cfg(target_arch = "x86_64")]{
diff --git a/ostd/src/cpu/mod.rs b/ostd/src/cpu/mod.rs
--- a/ostd/src/cpu/mod.rs
+++ b/ostd/src/cpu/mod.rs
@@ -2,7 +2,7 @@
//! CPU-related definitions.
-pub mod cpu_local;
+pub mod local;
cfg_if::cfg_if! {
if #[cfg(target_arch = "x86_64")]{
diff --git a/ostd/src/cpu/mod.rs b/ostd/src/cpu/mod.rs
--- a/ostd/src/cpu/mod.rs
+++ b/ostd/src/cpu/mod.rs
@@ -18,7 +18,7 @@ use bitvec::{
slice::IterOnes,
};
-use crate::{arch::boot::smp::get_num_processors, cpu};
+use crate::arch::{self, boot::smp::get_num_processors};
/// The number of CPUs. Zero means uninitialized.
static NUM_CPUS: AtomicU32 = AtomicU32::new(0);
diff --git a/ostd/src/cpu/mod.rs b/ostd/src/cpu/mod.rs
--- a/ostd/src/cpu/mod.rs
+++ b/ostd/src/cpu/mod.rs
@@ -18,7 +18,7 @@ use bitvec::{
slice::IterOnes,
};
-use crate::{arch::boot::smp::get_num_processors, cpu};
+use crate::arch::{self, boot::smp::get_num_processors};
/// The number of CPUs. Zero means uninitialized.
static NUM_CPUS: AtomicU32 = AtomicU32::new(0);
diff --git a/ostd/src/cpu/mod.rs b/ostd/src/cpu/mod.rs
--- a/ostd/src/cpu/mod.rs
+++ b/ostd/src/cpu/mod.rs
@@ -47,7 +47,7 @@ pub fn num_cpus() -> u32 {
pub fn this_cpu() -> u32 {
// SAFETY: the cpu ID is stored at the beginning of the cpu local area, provided
// by the linker script.
- unsafe { (cpu::local::get_base() as usize as *mut u32).read() }
+ unsafe { (arch::cpu::local::get_base() as usize as *mut u32).read() }
}
/// A subset of all CPUs in the system.
diff --git a/ostd/src/cpu/mod.rs b/ostd/src/cpu/mod.rs
--- a/ostd/src/cpu/mod.rs
+++ b/ostd/src/cpu/mod.rs
@@ -47,7 +47,7 @@ pub fn num_cpus() -> u32 {
pub fn this_cpu() -> u32 {
// SAFETY: the cpu ID is stored at the beginning of the cpu local area, provided
// by the linker script.
- unsafe { (cpu::local::get_base() as usize as *mut u32).read() }
+ unsafe { (arch::cpu::local::get_base() as usize as *mut u32).read() }
}
/// A subset of all CPUs in the system.
diff --git a/ostd/src/lib.rs b/ostd/src/lib.rs
--- a/ostd/src/lib.rs
+++ b/ostd/src/lib.rs
@@ -11,6 +11,7 @@
#![feature(generic_const_exprs)]
#![feature(iter_from_coroutine)]
#![feature(let_chains)]
+#![feature(min_specialization)]
#![feature(negative_impls)]
#![feature(new_uninit)]
#![feature(panic_info_message)]
diff --git a/ostd/src/lib.rs b/ostd/src/lib.rs
--- a/ostd/src/lib.rs
+++ b/ostd/src/lib.rs
@@ -11,6 +11,7 @@
#![feature(generic_const_exprs)]
#![feature(iter_from_coroutine)]
#![feature(let_chains)]
+#![feature(min_specialization)]
#![feature(negative_impls)]
#![feature(new_uninit)]
#![feature(panic_info_message)]
diff --git a/ostd/src/lib.rs b/ostd/src/lib.rs
--- a/ostd/src/lib.rs
+++ b/ostd/src/lib.rs
@@ -46,7 +47,9 @@ pub mod user;
pub use ostd_macros::main;
pub use ostd_pod::Pod;
-pub use self::{cpu::cpu_local::CpuLocal, error::Error, prelude::Result};
+pub use self::{error::Error, prelude::Result};
+// [`CpuLocalCell`] is easy to be mis-used, so we don't expose it to the users.
+pub(crate) use crate::cpu::local::cpu_local_cell;
/// Initializes OSTD.
///
diff --git a/ostd/src/lib.rs b/ostd/src/lib.rs
--- a/ostd/src/lib.rs
+++ b/ostd/src/lib.rs
@@ -46,7 +47,9 @@ pub mod user;
pub use ostd_macros::main;
pub use ostd_pod::Pod;
-pub use self::{cpu::cpu_local::CpuLocal, error::Error, prelude::Result};
+pub use self::{error::Error, prelude::Result};
+// [`CpuLocalCell`] is easy to be mis-used, so we don't expose it to the users.
+pub(crate) use crate::cpu::local::cpu_local_cell;
/// Initializes OSTD.
///
diff --git a/ostd/src/lib.rs b/ostd/src/lib.rs
--- a/ostd/src/lib.rs
+++ b/ostd/src/lib.rs
@@ -64,7 +67,7 @@ pub fn init() {
arch::check_tdx_init();
// SAFETY: This function is called only once and only on the BSP.
- unsafe { cpu::cpu_local::early_init_bsp_local_base() };
+ unsafe { cpu::local::early_init_bsp_local_base() };
mm::heap_allocator::init();
diff --git a/ostd/src/lib.rs b/ostd/src/lib.rs
--- a/ostd/src/lib.rs
+++ b/ostd/src/lib.rs
@@ -64,7 +67,7 @@ pub fn init() {
arch::check_tdx_init();
// SAFETY: This function is called only once and only on the BSP.
- unsafe { cpu::cpu_local::early_init_bsp_local_base() };
+ unsafe { cpu::local::early_init_bsp_local_base() };
mm::heap_allocator::init();
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -48,6 +48,7 @@ use crate::{
/// A `VmSpace` can also attach a page fault handler, which will be invoked to
/// handle page faults generated from user space.
#[allow(clippy::type_complexity)]
+#[derive(Debug)]
pub struct VmSpace {
pt: PageTable<UserMode>,
page_fault_handler: Once<fn(&VmSpace, &CpuExceptionInfo) -> core::result::Result<(), ()>>,
diff --git a/ostd/src/mm/vm_space.rs b/ostd/src/mm/vm_space.rs
--- a/ostd/src/mm/vm_space.rs
+++ b/ostd/src/mm/vm_space.rs
@@ -48,6 +48,7 @@ use crate::{
/// A `VmSpace` can also attach a page fault handler, which will be invoked to
/// handle page faults generated from user space.
#[allow(clippy::type_complexity)]
+#[derive(Debug)]
pub struct VmSpace {
pt: PageTable<UserMode>,
page_fault_handler: Once<fn(&VmSpace, &CpuExceptionInfo) -> core::result::Result<(), ()>>,
diff --git a/ostd/src/panicking.rs b/ostd/src/panicking.rs
--- a/ostd/src/panicking.rs
+++ b/ostd/src/panicking.rs
@@ -6,7 +6,7 @@ use core::ffi::c_void;
use crate::{
arch::qemu::{exit_qemu, QemuExitCode},
- early_print, early_println,
+ cpu_local_cell, early_print, early_println,
};
extern crate cfg_if;
diff --git a/ostd/src/panicking.rs b/ostd/src/panicking.rs
--- a/ostd/src/panicking.rs
+++ b/ostd/src/panicking.rs
@@ -6,7 +6,7 @@ use core::ffi::c_void;
use crate::{
arch::qemu::{exit_qemu, QemuExitCode},
- early_print, early_println,
+ cpu_local_cell, early_print, early_println,
};
extern crate cfg_if;
diff --git a/ostd/src/panicking.rs b/ostd/src/panicking.rs
--- a/ostd/src/panicking.rs
+++ b/ostd/src/panicking.rs
@@ -17,12 +17,24 @@ use unwinding::abi::{
_Unwind_GetGR, _Unwind_GetIP,
};
+cpu_local_cell! {
+ static IN_PANIC: bool = false;
+}
+
/// The panic handler must be defined in the binary crate or in the crate that the binary
/// crate explicity declares by `extern crate`. We cannot let the base crate depend on OSTD
/// due to prismatic dependencies. That's why we export this symbol and state the
/// panic handler in the binary crate.
#[export_name = "__aster_panic_handler"]
pub fn panic_handler(info: &core::panic::PanicInfo) -> ! {
+ let _irq_guard = crate::trap::disable_local();
+
+ if IN_PANIC.load() {
+ early_println!("{}", info);
+ early_println!("The panic handler panicked when processing the above panic. Aborting.");
+ abort();
+ }
+
// If in ktest, we would like to catch the panics and resume the test.
#[cfg(ktest)]
{
diff --git a/ostd/src/panicking.rs b/ostd/src/panicking.rs
--- a/ostd/src/panicking.rs
+++ b/ostd/src/panicking.rs
@@ -35,12 +47,15 @@ pub fn panic_handler(info: &core::panic::PanicInfo) -> ! {
file: info.location().unwrap().file().to_string(),
line: info.location().unwrap().line() as usize,
col: info.location().unwrap().column() as usize,
+ resolve_panic: || {
+ IN_PANIC.store(false);
+ },
};
// Throw an exception and expecting it to be caught.
begin_panic(Box::new(throw_info.clone()));
}
early_println!("{}", info);
- early_println!("printing stack trace:");
+ early_println!("Printing stack trace:");
print_stack_trace();
abort();
}
diff --git a/ostd/src/panicking.rs b/ostd/src/panicking.rs
--- a/ostd/src/panicking.rs
+++ b/ostd/src/panicking.rs
@@ -35,12 +47,15 @@ pub fn panic_handler(info: &core::panic::PanicInfo) -> ! {
file: info.location().unwrap().file().to_string(),
line: info.location().unwrap().line() as usize,
col: info.location().unwrap().column() as usize,
+ resolve_panic: || {
+ IN_PANIC.store(false);
+ },
};
// Throw an exception and expecting it to be caught.
begin_panic(Box::new(throw_info.clone()));
}
early_println!("{}", info);
- early_println!("printing stack trace:");
+ early_println!("Printing stack trace:");
print_stack_trace();
abort();
}
diff --git a/ostd/src/prelude.rs b/ostd/src/prelude.rs
--- a/ostd/src/prelude.rs
+++ b/ostd/src/prelude.rs
@@ -8,7 +8,6 @@
pub type Result<T> = core::result::Result<T, crate::error::Error>;
pub(crate) use alloc::{boxed::Box, sync::Arc, vec::Vec};
-pub(crate) use core::any::Any;
#[cfg(ktest)]
pub use ostd_macros::ktest;
diff --git a/ostd/src/sync/wait.rs b/ostd/src/sync/wait.rs
--- a/ostd/src/sync/wait.rs
+++ b/ostd/src/sync/wait.rs
@@ -4,7 +4,7 @@ use alloc::{collections::VecDeque, sync::Arc};
use core::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use super::SpinLock;
-use crate::task::{add_task, current_task, schedule, Task, TaskStatus};
+use crate::task::{add_task, schedule, Task, TaskStatus};
// # Explanation on the memory orders
//
diff --git a/ostd/src/sync/wait.rs b/ostd/src/sync/wait.rs
--- a/ostd/src/sync/wait.rs
+++ b/ostd/src/sync/wait.rs
@@ -4,7 +4,7 @@ use alloc::{collections::VecDeque, sync::Arc};
use core::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use super::SpinLock;
-use crate::task::{add_task, current_task, schedule, Task, TaskStatus};
+use crate::task::{add_task, schedule, Task, TaskStatus};
// # Explanation on the memory orders
//
diff --git a/ostd/src/sync/wait.rs b/ostd/src/sync/wait.rs
--- a/ostd/src/sync/wait.rs
+++ b/ostd/src/sync/wait.rs
@@ -209,7 +209,7 @@ impl Waiter {
pub fn new_pair() -> (Self, Arc<Waker>) {
let waker = Arc::new(Waker {
has_woken: AtomicBool::new(false),
- task: current_task().unwrap(),
+ task: Task::current().unwrap(),
});
let waiter = Self {
waker: waker.clone(),
diff --git a/ostd/src/sync/wait.rs b/ostd/src/sync/wait.rs
--- a/ostd/src/sync/wait.rs
+++ b/ostd/src/sync/wait.rs
@@ -209,7 +209,7 @@ impl Waiter {
pub fn new_pair() -> (Self, Arc<Waker>) {
let waker = Arc::new(Waker {
has_woken: AtomicBool::new(false),
- task: current_task().unwrap(),
+ task: Task::current().unwrap(),
});
let waiter = Self {
waker: waker.clone(),
diff --git a/ostd/src/task/mod.rs b/ostd/src/task/mod.rs
--- a/ostd/src/task/mod.rs
+++ b/ostd/src/task/mod.rs
@@ -10,7 +10,7 @@ mod task;
pub use self::{
priority::Priority,
- processor::{current_task, disable_preempt, preempt, schedule, DisablePreemptGuard},
+ processor::{disable_preempt, preempt, schedule, DisablePreemptGuard},
scheduler::{add_task, set_scheduler, FifoScheduler, Scheduler},
task::{Task, TaskAdapter, TaskContextApi, TaskOptions, TaskStatus},
};
diff --git a/ostd/src/task/mod.rs b/ostd/src/task/mod.rs
--- a/ostd/src/task/mod.rs
+++ b/ostd/src/task/mod.rs
@@ -10,7 +10,7 @@ mod task;
pub use self::{
priority::Priority,
- processor::{current_task, disable_preempt, preempt, schedule, DisablePreemptGuard},
+ processor::{disable_preempt, preempt, schedule, DisablePreemptGuard},
scheduler::{add_task, set_scheduler, FifoScheduler, Scheduler},
task::{Task, TaskAdapter, TaskContextApi, TaskOptions, TaskStatus},
};
diff --git a/ostd/src/task/priority.rs b/ostd/src/task/priority.rs
--- a/ostd/src/task/priority.rs
+++ b/ostd/src/task/priority.rs
@@ -7,7 +7,7 @@ pub const REAL_TIME_TASK_PRIORITY: u16 = 100;
/// Similar to Linux, a larger value represents a lower priority,
/// with a range of 0 to 139. Priorities ranging from 0 to 99 are considered real-time,
/// while those ranging from 100 to 139 are considered normal.
-#[derive(Copy, Clone)]
+#[derive(Copy, Clone, Debug)]
pub struct Priority(u16);
impl Priority {
diff --git a/ostd/src/task/priority.rs b/ostd/src/task/priority.rs
--- a/ostd/src/task/priority.rs
+++ b/ostd/src/task/priority.rs
@@ -7,7 +7,7 @@ pub const REAL_TIME_TASK_PRIORITY: u16 = 100;
/// Similar to Linux, a larger value represents a lower priority,
/// with a range of 0 to 139. Priorities ranging from 0 to 99 are considered real-time,
/// while those ranging from 100 to 139 are considered normal.
-#[derive(Copy, Clone)]
+#[derive(Copy, Clone, Debug)]
pub struct Priority(u16);
impl Priority {
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -1,59 +1,40 @@
// SPDX-License-Identifier: MPL-2.0
use alloc::sync::Arc;
-use core::cell::RefCell;
use super::{
scheduler::{fetch_task, GLOBAL_SCHEDULER},
task::{context_switch, TaskContext},
Task, TaskStatus,
};
-use crate::{arch, cpu_local};
-
-pub struct Processor {
- current: Option<Arc<Task>>,
- /// A temporary variable used in [`switch_to_task`] to avoid dropping `current` while running
- /// as `current`.
- prev_task: Option<Arc<Task>>,
- idle_task_ctx: TaskContext,
+use crate::{cpu::local::PREEMPT_LOCK_COUNT, cpu_local_cell};
+
+cpu_local_cell! {
+ /// The `Arc<Task>` (casted by [`Arc::into_raw`]) that is the current task.
+ static CURRENT_TASK_PTR: *const Task = core::ptr::null();
+ /// The previous task on the processor before switching to the current task.
+ /// It is used for delayed resource release since it would be the current
+ /// task's job to recycle the previous resources.
+ static PREVIOUS_TASK_PTR: *const Task = core::ptr::null();
+ /// An unsafe cell to store the context of the bootstrap code.
+ static BOOTSTRAP_CONTEXT: TaskContext = TaskContext::new();
}
-impl Processor {
- pub const fn new() -> Self {
- Self {
- current: None,
- prev_task: None,
- idle_task_ctx: TaskContext::new(),
- }
- }
- fn get_idle_task_ctx_ptr(&mut self) -> *mut TaskContext {
- &mut self.idle_task_ctx as *mut _
- }
- pub fn take_current(&mut self) -> Option<Arc<Task>> {
- self.current.take()
- }
- pub fn current(&self) -> Option<Arc<Task>> {
- self.current.as_ref().map(Arc::clone)
- }
- pub fn set_current_task(&mut self, task: Arc<Task>) {
- self.current = Some(task.clone());
- }
-}
-
-cpu_local! {
- static PROCESSOR: RefCell<Processor> = RefCell::new(Processor::new());
-}
-
-/// Retrieves the current task running on the processor.
-pub fn current_task() -> Option<Arc<Task>> {
- PROCESSOR.borrow_irq_disabled().borrow().current()
-}
-
-pub(crate) fn get_idle_task_ctx_ptr() -> *mut TaskContext {
- PROCESSOR
- .borrow_irq_disabled()
- .borrow_mut()
- .get_idle_task_ctx_ptr()
+/// Retrieves a reference to the current task running on the processor.
+///
+/// It returns `None` if the function is called in the bootstrap context.
+pub(super) fn current_task() -> Option<Arc<Task>> {
+ let ptr = CURRENT_TASK_PTR.load();
+ if ptr.is_null() {
+ return None;
+ }
+ // SAFETY: The pointer is set by `switch_to_task` and is guaranteed to be
+ // built with `Arc::into_raw`.
+ let restored = unsafe { Arc::from_raw(ptr) };
+ // To let the `CURRENT_TASK_PTR` still own the task, we clone and forget it
+ // to increment the reference count.
+ let _ = core::mem::ManuallyDrop::new(restored.clone());
+ Some(restored)
}
/// Calls this function to switch to other task by using GLOBAL_SCHEDULER
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -1,59 +1,40 @@
// SPDX-License-Identifier: MPL-2.0
use alloc::sync::Arc;
-use core::cell::RefCell;
use super::{
scheduler::{fetch_task, GLOBAL_SCHEDULER},
task::{context_switch, TaskContext},
Task, TaskStatus,
};
-use crate::{arch, cpu_local};
-
-pub struct Processor {
- current: Option<Arc<Task>>,
- /// A temporary variable used in [`switch_to_task`] to avoid dropping `current` while running
- /// as `current`.
- prev_task: Option<Arc<Task>>,
- idle_task_ctx: TaskContext,
+use crate::{cpu::local::PREEMPT_LOCK_COUNT, cpu_local_cell};
+
+cpu_local_cell! {
+ /// The `Arc<Task>` (casted by [`Arc::into_raw`]) that is the current task.
+ static CURRENT_TASK_PTR: *const Task = core::ptr::null();
+ /// The previous task on the processor before switching to the current task.
+ /// It is used for delayed resource release since it would be the current
+ /// task's job to recycle the previous resources.
+ static PREVIOUS_TASK_PTR: *const Task = core::ptr::null();
+ /// An unsafe cell to store the context of the bootstrap code.
+ static BOOTSTRAP_CONTEXT: TaskContext = TaskContext::new();
}
-impl Processor {
- pub const fn new() -> Self {
- Self {
- current: None,
- prev_task: None,
- idle_task_ctx: TaskContext::new(),
- }
- }
- fn get_idle_task_ctx_ptr(&mut self) -> *mut TaskContext {
- &mut self.idle_task_ctx as *mut _
- }
- pub fn take_current(&mut self) -> Option<Arc<Task>> {
- self.current.take()
- }
- pub fn current(&self) -> Option<Arc<Task>> {
- self.current.as_ref().map(Arc::clone)
- }
- pub fn set_current_task(&mut self, task: Arc<Task>) {
- self.current = Some(task.clone());
- }
-}
-
-cpu_local! {
- static PROCESSOR: RefCell<Processor> = RefCell::new(Processor::new());
-}
-
-/// Retrieves the current task running on the processor.
-pub fn current_task() -> Option<Arc<Task>> {
- PROCESSOR.borrow_irq_disabled().borrow().current()
-}
-
-pub(crate) fn get_idle_task_ctx_ptr() -> *mut TaskContext {
- PROCESSOR
- .borrow_irq_disabled()
- .borrow_mut()
- .get_idle_task_ctx_ptr()
+/// Retrieves a reference to the current task running on the processor.
+///
+/// It returns `None` if the function is called in the bootstrap context.
+pub(super) fn current_task() -> Option<Arc<Task>> {
+ let ptr = CURRENT_TASK_PTR.load();
+ if ptr.is_null() {
+ return None;
+ }
+ // SAFETY: The pointer is set by `switch_to_task` and is guaranteed to be
+ // built with `Arc::into_raw`.
+ let restored = unsafe { Arc::from_raw(ptr) };
+ // To let the `CURRENT_TASK_PTR` still own the task, we clone and forget it
+ // to increment the reference count.
+ let _ = core::mem::ManuallyDrop::new(restored.clone());
+ Some(restored)
}
/// Calls this function to switch to other task by using GLOBAL_SCHEDULER
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -85,36 +66,48 @@ pub fn preempt(task: &Arc<Task>) {
/// Calls this function to switch to other task
///
-/// if current task is none, then it will use the default task context and it will not return to this function again
-///
-/// if current task status is exit, then it will not add to the scheduler
+/// If current task is none, then it will use the default task context and it
+/// will not return to this function again.
///
-/// before context switch, current task will switch to the next task
+/// If the current task's status not [`TaskStatus::Runnable`], it will not be
+/// added to the scheduler.
fn switch_to_task(next_task: Arc<Task>) {
- if !PREEMPT_COUNT.is_preemptive() {
+ let preemt_lock_count = PREEMPT_LOCK_COUNT.load();
+ if preemt_lock_count != 0 {
panic!(
"Calling schedule() while holding {} locks",
- PREEMPT_COUNT.num_locks()
+ preemt_lock_count
);
}
- let current_task_ctx_ptr = match current_task() {
- None => get_idle_task_ctx_ptr(),
- Some(current_task) => {
- let ctx_ptr = current_task.ctx().get();
+ let irq_guard = crate::trap::disable_local();
+
+ let current_task_ptr = CURRENT_TASK_PTR.load();
+
+ let current_task_ctx_ptr = if current_task_ptr.is_null() {
+ // SAFETY: Interrupts are disabled, so the pointer is safe to be fetched.
+ unsafe { BOOTSTRAP_CONTEXT.as_ptr_mut() }
+ } else {
+ // SAFETY: The pointer is not NULL and set as the current task.
+ let cur_task_arc = unsafe {
+ let restored = Arc::from_raw(current_task_ptr);
+ let _ = core::mem::ManuallyDrop::new(restored.clone());
+ restored
+ };
- let mut task_inner = current_task.inner_exclusive_access();
+ let ctx_ptr = cur_task_arc.ctx().get();
- debug_assert_ne!(task_inner.task_status, TaskStatus::Sleeping);
- if task_inner.task_status == TaskStatus::Runnable {
- drop(task_inner);
- GLOBAL_SCHEDULER.lock_irq_disabled().enqueue(current_task);
- } else if task_inner.task_status == TaskStatus::Sleepy {
- task_inner.task_status = TaskStatus::Sleeping;
- }
+ let mut task_inner = cur_task_arc.inner_exclusive_access();
- ctx_ptr
+ debug_assert_ne!(task_inner.task_status, TaskStatus::Sleeping);
+ if task_inner.task_status == TaskStatus::Runnable {
+ drop(task_inner);
+ GLOBAL_SCHEDULER.lock().enqueue(cur_task_arc);
+ } else if task_inner.task_status == TaskStatus::Sleepy {
+ task_inner.task_status = TaskStatus::Sleeping;
}
+
+ ctx_ptr
};
let next_task_ctx_ptr = next_task.ctx().get().cast_const();
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -85,36 +66,48 @@ pub fn preempt(task: &Arc<Task>) {
/// Calls this function to switch to other task
///
-/// if current task is none, then it will use the default task context and it will not return to this function again
-///
-/// if current task status is exit, then it will not add to the scheduler
+/// If current task is none, then it will use the default task context and it
+/// will not return to this function again.
///
-/// before context switch, current task will switch to the next task
+/// If the current task's status not [`TaskStatus::Runnable`], it will not be
+/// added to the scheduler.
fn switch_to_task(next_task: Arc<Task>) {
- if !PREEMPT_COUNT.is_preemptive() {
+ let preemt_lock_count = PREEMPT_LOCK_COUNT.load();
+ if preemt_lock_count != 0 {
panic!(
"Calling schedule() while holding {} locks",
- PREEMPT_COUNT.num_locks()
+ preemt_lock_count
);
}
- let current_task_ctx_ptr = match current_task() {
- None => get_idle_task_ctx_ptr(),
- Some(current_task) => {
- let ctx_ptr = current_task.ctx().get();
+ let irq_guard = crate::trap::disable_local();
+
+ let current_task_ptr = CURRENT_TASK_PTR.load();
+
+ let current_task_ctx_ptr = if current_task_ptr.is_null() {
+ // SAFETY: Interrupts are disabled, so the pointer is safe to be fetched.
+ unsafe { BOOTSTRAP_CONTEXT.as_ptr_mut() }
+ } else {
+ // SAFETY: The pointer is not NULL and set as the current task.
+ let cur_task_arc = unsafe {
+ let restored = Arc::from_raw(current_task_ptr);
+ let _ = core::mem::ManuallyDrop::new(restored.clone());
+ restored
+ };
- let mut task_inner = current_task.inner_exclusive_access();
+ let ctx_ptr = cur_task_arc.ctx().get();
- debug_assert_ne!(task_inner.task_status, TaskStatus::Sleeping);
- if task_inner.task_status == TaskStatus::Runnable {
- drop(task_inner);
- GLOBAL_SCHEDULER.lock_irq_disabled().enqueue(current_task);
- } else if task_inner.task_status == TaskStatus::Sleepy {
- task_inner.task_status = TaskStatus::Sleeping;
- }
+ let mut task_inner = cur_task_arc.inner_exclusive_access();
- ctx_ptr
+ debug_assert_ne!(task_inner.task_status, TaskStatus::Sleeping);
+ if task_inner.task_status == TaskStatus::Runnable {
+ drop(task_inner);
+ GLOBAL_SCHEDULER.lock().enqueue(cur_task_arc);
+ } else if task_inner.task_status == TaskStatus::Sleepy {
+ task_inner.task_status = TaskStatus::Sleeping;
}
+
+ ctx_ptr
};
let next_task_ctx_ptr = next_task.ctx().get().cast_const();
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -124,16 +117,21 @@ fn switch_to_task(next_task: Arc<Task>) {
}
// Change the current task to the next task.
- {
- let processor_guard = PROCESSOR.borrow_irq_disabled();
- let mut processor = processor_guard.borrow_mut();
-
- // We cannot directly overwrite `current` at this point. Since we are running as `current`,
- // we must avoid dropping `current`. Otherwise, the kernel stack may be unmapped, leading
- // to soundness problems.
- let old_current = processor.current.replace(next_task);
- processor.prev_task = old_current;
- }
+ //
+ // We cannot directly drop `current` at this point. Since we are running as
+ // `current`, we must avoid dropping `current`. Otherwise, the kernel stack
+ // may be unmapped, leading to instant failure.
+ let old_prev = PREVIOUS_TASK_PTR.load();
+ PREVIOUS_TASK_PTR.store(current_task_ptr);
+ CURRENT_TASK_PTR.store(Arc::into_raw(next_task));
+ // Drop the old-previously running task.
+ if !old_prev.is_null() {
+ // SAFETY: The pointer is set by `switch_to_task` and is guaranteed to be
+ // built with `Arc::into_raw`.
+ drop(unsafe { Arc::from_raw(old_prev) });
+ }
+
+ drop(irq_guard);
// SAFETY:
// 1. `ctx` is only used in `schedule()`. We have exclusive access to both the current task
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -124,16 +117,21 @@ fn switch_to_task(next_task: Arc<Task>) {
}
// Change the current task to the next task.
- {
- let processor_guard = PROCESSOR.borrow_irq_disabled();
- let mut processor = processor_guard.borrow_mut();
-
- // We cannot directly overwrite `current` at this point. Since we are running as `current`,
- // we must avoid dropping `current`. Otherwise, the kernel stack may be unmapped, leading
- // to soundness problems.
- let old_current = processor.current.replace(next_task);
- processor.prev_task = old_current;
- }
+ //
+ // We cannot directly drop `current` at this point. Since we are running as
+ // `current`, we must avoid dropping `current`. Otherwise, the kernel stack
+ // may be unmapped, leading to instant failure.
+ let old_prev = PREVIOUS_TASK_PTR.load();
+ PREVIOUS_TASK_PTR.store(current_task_ptr);
+ CURRENT_TASK_PTR.store(Arc::into_raw(next_task));
+ // Drop the old-previously running task.
+ if !old_prev.is_null() {
+ // SAFETY: The pointer is set by `switch_to_task` and is guaranteed to be
+ // built with `Arc::into_raw`.
+ drop(unsafe { Arc::from_raw(old_prev) });
+ }
+
+ drop(irq_guard);
// SAFETY:
// 1. `ctx` is only used in `schedule()`. We have exclusive access to both the current task
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -151,53 +149,6 @@ fn switch_to_task(next_task: Arc<Task>) {
// to the next task switching.
}
-static PREEMPT_COUNT: PreemptInfo = PreemptInfo::new();
-
-/// Currently, it only holds the number of preemption locks held by the
-/// current CPU. When it has a non-zero value, the CPU cannot call
-/// [`schedule()`].
-///
-/// For per-CPU preemption lock count, we cannot afford two non-atomic
-/// operations to increment and decrement the count. The [`crate::cpu_local`]
-/// implementation is free to read the base register and then calculate the
-/// address of the per-CPU variable using an additional instruction. Interrupts
-/// can happen between the address calculation and modification to that
-/// address. If the task is preempted to another CPU by this interrupt, the
-/// count of the original CPU will be mistakenly modified. To avoid this, we
-/// introduce [`crate::arch::cpu::local::preempt_lock_count`]. For x86_64 we
-/// can implement this using one instruction. In other less expressive
-/// architectures, we may need to disable interrupts.
-///
-/// Also, the preemption count is reserved in the `.cpu_local` section
-/// specified in the linker script. The reason is that we need to access the
-/// preemption count before we can copy the section for application processors.
-/// So, the preemption count is not copied from bootstrap processor's section
-/// as the initialization. Instead it is initialized to zero for application
-/// processors.
-struct PreemptInfo {}
-
-impl PreemptInfo {
- const fn new() -> Self {
- Self {}
- }
-
- fn increase_num_locks(&self) {
- arch::cpu::local::preempt_lock_count::inc();
- }
-
- fn decrease_num_locks(&self) {
- arch::cpu::local::preempt_lock_count::dec();
- }
-
- fn is_preemptive(&self) -> bool {
- arch::cpu::local::preempt_lock_count::get() == 0
- }
-
- fn num_locks(&self) -> usize {
- arch::cpu::local::preempt_lock_count::get() as usize
- }
-}
-
/// A guard for disable preempt.
#[clippy::has_significant_drop]
#[must_use]
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -151,53 +149,6 @@ fn switch_to_task(next_task: Arc<Task>) {
// to the next task switching.
}
-static PREEMPT_COUNT: PreemptInfo = PreemptInfo::new();
-
-/// Currently, it only holds the number of preemption locks held by the
-/// current CPU. When it has a non-zero value, the CPU cannot call
-/// [`schedule()`].
-///
-/// For per-CPU preemption lock count, we cannot afford two non-atomic
-/// operations to increment and decrement the count. The [`crate::cpu_local`]
-/// implementation is free to read the base register and then calculate the
-/// address of the per-CPU variable using an additional instruction. Interrupts
-/// can happen between the address calculation and modification to that
-/// address. If the task is preempted to another CPU by this interrupt, the
-/// count of the original CPU will be mistakenly modified. To avoid this, we
-/// introduce [`crate::arch::cpu::local::preempt_lock_count`]. For x86_64 we
-/// can implement this using one instruction. In other less expressive
-/// architectures, we may need to disable interrupts.
-///
-/// Also, the preemption count is reserved in the `.cpu_local` section
-/// specified in the linker script. The reason is that we need to access the
-/// preemption count before we can copy the section for application processors.
-/// So, the preemption count is not copied from bootstrap processor's section
-/// as the initialization. Instead it is initialized to zero for application
-/// processors.
-struct PreemptInfo {}
-
-impl PreemptInfo {
- const fn new() -> Self {
- Self {}
- }
-
- fn increase_num_locks(&self) {
- arch::cpu::local::preempt_lock_count::inc();
- }
-
- fn decrease_num_locks(&self) {
- arch::cpu::local::preempt_lock_count::dec();
- }
-
- fn is_preemptive(&self) -> bool {
- arch::cpu::local::preempt_lock_count::get() == 0
- }
-
- fn num_locks(&self) -> usize {
- arch::cpu::local::preempt_lock_count::get() as usize
- }
-}
-
/// A guard for disable preempt.
#[clippy::has_significant_drop]
#[must_use]
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -210,7 +161,7 @@ impl !Send for DisablePreemptGuard {}
impl DisablePreemptGuard {
fn new() -> Self {
- PREEMPT_COUNT.increase_num_locks();
+ PREEMPT_LOCK_COUNT.add_assign(1);
Self { _private: () }
}
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -210,7 +161,7 @@ impl !Send for DisablePreemptGuard {}
impl DisablePreemptGuard {
fn new() -> Self {
- PREEMPT_COUNT.increase_num_locks();
+ PREEMPT_LOCK_COUNT.add_assign(1);
Self { _private: () }
}
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -223,7 +174,7 @@ impl DisablePreemptGuard {
impl Drop for DisablePreemptGuard {
fn drop(&mut self) {
- PREEMPT_COUNT.decrease_num_locks();
+ PREEMPT_LOCK_COUNT.sub_assign(1);
}
}
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -223,7 +174,7 @@ impl DisablePreemptGuard {
impl Drop for DisablePreemptGuard {
fn drop(&mut self) {
- PREEMPT_COUNT.decrease_num_locks();
+ PREEMPT_LOCK_COUNT.sub_assign(1);
}
}
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task.rs
@@ -3,9 +3,9 @@
// FIXME: the `intrusive_adapter` macro will generate methods without docs.
// So we temporary allow missing_docs for this module.
#![allow(missing_docs)]
-#![allow(dead_code)]
-use core::cell::UnsafeCell;
+use alloc::{boxed::Box, sync::Arc};
+use core::{any::Any, cell::UnsafeCell};
use intrusive_collections::{intrusive_adapter, LinkedListAtomicLink};
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task.rs
@@ -3,9 +3,9 @@
// FIXME: the `intrusive_adapter` macro will generate methods without docs.
// So we temporary allow missing_docs for this module.
#![allow(missing_docs)]
-#![allow(dead_code)]
-use core::cell::UnsafeCell;
+use alloc::{boxed::Box, sync::Arc};
+use core::{any::Any, cell::UnsafeCell};
use intrusive_collections::{intrusive_adapter, LinkedListAtomicLink};
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task.rs
@@ -18,7 +18,7 @@ pub(crate) use crate::arch::task::{context_switch, TaskContext};
use crate::{
arch::mm::tlb_flush_addr_range,
cpu::CpuSet,
- mm::{kspace::KERNEL_PAGE_TABLE, FrameAllocOptions, PageFlags, Segment, PAGE_SIZE},
+ mm::{kspace::KERNEL_PAGE_TABLE, FrameAllocOptions, Paddr, PageFlags, Segment, PAGE_SIZE},
prelude::*,
sync::{SpinLock, SpinLockGuard},
user::UserSpace,
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task.rs
@@ -18,7 +18,7 @@ pub(crate) use crate::arch::task::{context_switch, TaskContext};
use crate::{
arch::mm::tlb_flush_addr_range,
cpu::CpuSet,
- mm::{kspace::KERNEL_PAGE_TABLE, FrameAllocOptions, PageFlags, Segment, PAGE_SIZE},
+ mm::{kspace::KERNEL_PAGE_TABLE, FrameAllocOptions, Paddr, PageFlags, Segment, PAGE_SIZE},
prelude::*,
sync::{SpinLock, SpinLockGuard},
user::UserSpace,
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task.rs
@@ -41,6 +41,7 @@ pub trait TaskContextApi {
fn stack_pointer(&self) -> usize;
}
+#[derive(Debug)]
pub struct KernelStack {
segment: Segment,
has_guard_page: bool,
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task.rs
@@ -41,6 +41,7 @@ pub trait TaskContextApi {
fn stack_pointer(&self) -> usize;
}
+#[derive(Debug)]
pub struct KernelStack {
segment: Segment,
has_guard_page: bool,
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task.rs
@@ -121,6 +122,7 @@ pub struct Task {
link: LinkedListAtomicLink,
priority: Priority,
// TODO: add multiprocessor support
+ #[allow(dead_code)]
cpu_affinity: CpuSet,
}
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task.rs
@@ -121,6 +122,7 @@ pub struct Task {
link: LinkedListAtomicLink,
priority: Priority,
// TODO: add multiprocessor support
+ #[allow(dead_code)]
cpu_affinity: CpuSet,
}
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task.rs
@@ -131,14 +133,17 @@ intrusive_adapter!(pub TaskAdapter = Arc<Task>: Task { link: LinkedListAtomicLin
// we have exclusive access to the field.
unsafe impl Sync for Task {}
+#[derive(Debug)]
pub(crate) struct TaskInner {
pub task_status: TaskStatus,
}
impl Task {
/// Gets the current task.
- pub fn current() -> Arc<Task> {
- current_task().unwrap()
+ ///
+ /// It returns `None` if the function is called in the bootstrap context.
+ pub fn current() -> Option<Arc<Task>> {
+ current_task()
}
/// Gets inner
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task.rs
@@ -131,14 +133,17 @@ intrusive_adapter!(pub TaskAdapter = Arc<Task>: Task { link: LinkedListAtomicLin
// we have exclusive access to the field.
unsafe impl Sync for Task {}
+#[derive(Debug)]
pub(crate) struct TaskInner {
pub task_status: TaskStatus,
}
impl Task {
/// Gets the current task.
- pub fn current() -> Arc<Task> {
- current_task().unwrap()
+ ///
+ /// It returns `None` if the function is called in the bootstrap context.
+ pub fn current() -> Option<Arc<Task>> {
+ current_task()
}
/// Gets inner
diff --git a/ostd/src/trap/handler.rs b/ostd/src/trap/handler.rs
--- a/ostd/src/trap/handler.rs
+++ b/ostd/src/trap/handler.rs
@@ -1,17 +1,15 @@
// SPDX-License-Identifier: MPL-2.0
-use core::sync::atomic::{AtomicBool, Ordering};
-
use trapframe::TrapFrame;
-use crate::{arch::irq::IRQ_LIST, cpu_local};
+use crate::{arch::irq::IRQ_LIST, cpu_local_cell};
pub(crate) fn call_irq_callback_functions(trap_frame: &TrapFrame, irq_number: usize) {
// For x86 CPUs, interrupts are not re-entrant. Local interrupts will be disabled when
// an interrupt handler is called (Unless interrupts are re-enabled in an interrupt handler).
//
// FIXME: For arch that supports re-entrant interrupts, we may need to record nested level here.
- IN_INTERRUPT_CONTEXT.store(true, Ordering::Release);
+ IN_INTERRUPT_CONTEXT.store(true);
let irq_line = IRQ_LIST.get().unwrap().get(irq_number).unwrap();
let callback_functions = irq_line.callback_list();
diff --git a/ostd/src/trap/handler.rs b/ostd/src/trap/handler.rs
--- a/ostd/src/trap/handler.rs
+++ b/ostd/src/trap/handler.rs
@@ -1,17 +1,15 @@
// SPDX-License-Identifier: MPL-2.0
-use core::sync::atomic::{AtomicBool, Ordering};
-
use trapframe::TrapFrame;
-use crate::{arch::irq::IRQ_LIST, cpu_local};
+use crate::{arch::irq::IRQ_LIST, cpu_local_cell};
pub(crate) fn call_irq_callback_functions(trap_frame: &TrapFrame, irq_number: usize) {
// For x86 CPUs, interrupts are not re-entrant. Local interrupts will be disabled when
// an interrupt handler is called (Unless interrupts are re-enabled in an interrupt handler).
//
// FIXME: For arch that supports re-entrant interrupts, we may need to record nested level here.
- IN_INTERRUPT_CONTEXT.store(true, Ordering::Release);
+ IN_INTERRUPT_CONTEXT.store(true);
let irq_line = IRQ_LIST.get().unwrap().get(irq_number).unwrap();
let callback_functions = irq_line.callback_list();
diff --git a/ostd/src/trap/handler.rs b/ostd/src/trap/handler.rs
--- a/ostd/src/trap/handler.rs
+++ b/ostd/src/trap/handler.rs
@@ -22,20 +20,17 @@ pub(crate) fn call_irq_callback_functions(trap_frame: &TrapFrame, irq_number: us
crate::arch::interrupts_ack(irq_number);
- IN_INTERRUPT_CONTEXT.store(false, Ordering::Release);
-
crate::arch::irq::enable_local();
crate::trap::softirq::process_pending();
+
+ IN_INTERRUPT_CONTEXT.store(false);
}
-cpu_local! {
- static IN_INTERRUPT_CONTEXT: AtomicBool = AtomicBool::new(false);
+cpu_local_cell! {
+ static IN_INTERRUPT_CONTEXT: bool = false;
}
/// Returns whether we are in the interrupt context.
-///
-/// FIXME: Here only hardware irq is taken into account. According to linux implementation, if
-/// we are in softirq context, or bottom half is disabled, this function also returns true.
pub fn in_interrupt_context() -> bool {
- IN_INTERRUPT_CONTEXT.load(Ordering::Acquire)
+ IN_INTERRUPT_CONTEXT.load()
}
diff --git a/ostd/src/trap/handler.rs b/ostd/src/trap/handler.rs
--- a/ostd/src/trap/handler.rs
+++ b/ostd/src/trap/handler.rs
@@ -22,20 +20,17 @@ pub(crate) fn call_irq_callback_functions(trap_frame: &TrapFrame, irq_number: us
crate::arch::interrupts_ack(irq_number);
- IN_INTERRUPT_CONTEXT.store(false, Ordering::Release);
-
crate::arch::irq::enable_local();
crate::trap::softirq::process_pending();
+
+ IN_INTERRUPT_CONTEXT.store(false);
}
-cpu_local! {
- static IN_INTERRUPT_CONTEXT: AtomicBool = AtomicBool::new(false);
+cpu_local_cell! {
+ static IN_INTERRUPT_CONTEXT: bool = false;
}
/// Returns whether we are in the interrupt context.
-///
-/// FIXME: Here only hardware irq is taken into account. According to linux implementation, if
-/// we are in softirq context, or bottom half is disabled, this function also returns true.
pub fn in_interrupt_context() -> bool {
- IN_INTERRUPT_CONTEXT.load(Ordering::Acquire)
+ IN_INTERRUPT_CONTEXT.load()
}
diff --git a/ostd/src/trap/softirq.rs b/ostd/src/trap/softirq.rs
--- a/ostd/src/trap/softirq.rs
+++ b/ostd/src/trap/softirq.rs
@@ -2,14 +2,12 @@
//! Software interrupt.
-#![allow(unused_variables)]
-
use alloc::boxed::Box;
-use core::sync::atomic::{AtomicBool, AtomicU8, Ordering};
+use core::sync::atomic::{AtomicU8, Ordering};
use spin::Once;
-use crate::{cpu_local, task::disable_preempt};
+use crate::{cpu_local_cell, task::disable_preempt};
/// A representation of a software interrupt (softirq) line.
///
diff --git a/ostd/src/trap/softirq.rs b/ostd/src/trap/softirq.rs
--- a/ostd/src/trap/softirq.rs
+++ b/ostd/src/trap/softirq.rs
@@ -2,14 +2,12 @@
//! Software interrupt.
-#![allow(unused_variables)]
-
use alloc::boxed::Box;
-use core::sync::atomic::{AtomicBool, AtomicU8, Ordering};
+use core::sync::atomic::{AtomicU8, Ordering};
use spin::Once;
-use crate::{cpu_local, task::disable_preempt};
+use crate::{cpu_local_cell, task::disable_preempt};
/// A representation of a software interrupt (softirq) line.
///
diff --git a/ostd/src/trap/softirq.rs b/ostd/src/trap/softirq.rs
--- a/ostd/src/trap/softirq.rs
+++ b/ostd/src/trap/softirq.rs
@@ -70,7 +68,7 @@ impl SoftIrqLine {
///
/// If this line is not enabled yet, the method has no effect.
pub fn raise(&self) {
- PENDING_MASK.fetch_or(1 << self.id, Ordering::Release);
+ PENDING_MASK.bitor_assign(1 << self.id);
}
/// Enables a softirq line by registering its callback.
diff --git a/ostd/src/trap/softirq.rs b/ostd/src/trap/softirq.rs
--- a/ostd/src/trap/softirq.rs
+++ b/ostd/src/trap/softirq.rs
@@ -70,7 +68,7 @@ impl SoftIrqLine {
///
/// If this line is not enabled yet, the method has no effect.
pub fn raise(&self) {
- PENDING_MASK.fetch_or(1 << self.id, Ordering::Release);
+ PENDING_MASK.bitor_assign(1 << self.id);
}
/// Enables a softirq line by registering its callback.
diff --git a/ostd/src/trap/softirq.rs b/ostd/src/trap/softirq.rs
--- a/ostd/src/trap/softirq.rs
+++ b/ostd/src/trap/softirq.rs
@@ -105,24 +103,24 @@ pub(super) fn init() {
static ENABLED_MASK: AtomicU8 = AtomicU8::new(0);
-cpu_local! {
- static PENDING_MASK: AtomicU8 = AtomicU8::new(0);
- static IS_ENABLED: AtomicBool = AtomicBool::new(true);
+cpu_local_cell! {
+ static PENDING_MASK: u8 = 0;
+ static IS_ENABLED: bool = true;
}
/// Enables softirq in current processor.
fn enable_softirq_local() {
- IS_ENABLED.store(true, Ordering::Release);
+ IS_ENABLED.store(true);
}
/// Disables softirq in current processor.
fn disable_softirq_local() {
- IS_ENABLED.store(false, Ordering::Release);
+ IS_ENABLED.store(false);
}
/// Checks whether the softirq is enabled in current processor.
fn is_softirq_enabled() -> bool {
- IS_ENABLED.load(Ordering::Acquire)
+ IS_ENABLED.load()
}
/// Processes pending softirqs.
diff --git a/ostd/src/trap/softirq.rs b/ostd/src/trap/softirq.rs
--- a/ostd/src/trap/softirq.rs
+++ b/ostd/src/trap/softirq.rs
@@ -105,24 +103,24 @@ pub(super) fn init() {
static ENABLED_MASK: AtomicU8 = AtomicU8::new(0);
-cpu_local! {
- static PENDING_MASK: AtomicU8 = AtomicU8::new(0);
- static IS_ENABLED: AtomicBool = AtomicBool::new(true);
+cpu_local_cell! {
+ static PENDING_MASK: u8 = 0;
+ static IS_ENABLED: bool = true;
}
/// Enables softirq in current processor.
fn enable_softirq_local() {
- IS_ENABLED.store(true, Ordering::Release);
+ IS_ENABLED.store(true);
}
/// Disables softirq in current processor.
fn disable_softirq_local() {
- IS_ENABLED.store(false, Ordering::Release);
+ IS_ENABLED.store(false);
}
/// Checks whether the softirq is enabled in current processor.
fn is_softirq_enabled() -> bool {
- IS_ENABLED.load(Ordering::Acquire)
+ IS_ENABLED.load()
}
/// Processes pending softirqs.
diff --git a/ostd/src/trap/softirq.rs b/ostd/src/trap/softirq.rs
--- a/ostd/src/trap/softirq.rs
+++ b/ostd/src/trap/softirq.rs
@@ -136,12 +134,13 @@ pub(crate) fn process_pending() {
return;
}
- let preempt_guard = disable_preempt();
+ let _preempt_guard = disable_preempt();
disable_softirq_local();
- for i in 0..SOFTIRQ_RUN_TIMES {
+ for _i in 0..SOFTIRQ_RUN_TIMES {
let mut action_mask = {
- let pending_mask = PENDING_MASK.fetch_and(0, Ordering::Acquire);
+ let pending_mask = PENDING_MASK.load();
+ PENDING_MASK.store(0);
pending_mask & ENABLED_MASK.load(Ordering::Acquire)
};
diff --git a/ostd/src/trap/softirq.rs b/ostd/src/trap/softirq.rs
--- a/ostd/src/trap/softirq.rs
+++ b/ostd/src/trap/softirq.rs
@@ -136,12 +134,13 @@ pub(crate) fn process_pending() {
return;
}
- let preempt_guard = disable_preempt();
+ let _preempt_guard = disable_preempt();
disable_softirq_local();
- for i in 0..SOFTIRQ_RUN_TIMES {
+ for _i in 0..SOFTIRQ_RUN_TIMES {
let mut action_mask = {
- let pending_mask = PENDING_MASK.fetch_and(0, Ordering::Acquire);
+ let pending_mask = PENDING_MASK.load();
+ PENDING_MASK.store(0);
pending_mask & ENABLED_MASK.load(Ordering::Acquire)
};
diff --git a/ostd/src/user.rs b/ostd/src/user.rs
--- a/ostd/src/user.rs
+++ b/ostd/src/user.rs
@@ -12,6 +12,7 @@ use crate::{cpu::UserContext, mm::VmSpace, prelude::*, task::Task};
///
/// Each user space has a VM address space and allows a task to execute in
/// user mode.
+#[derive(Debug)]
pub struct UserSpace {
/// vm space
vm_space: Arc<VmSpace>,
diff --git a/ostd/src/user.rs b/ostd/src/user.rs
--- a/ostd/src/user.rs
+++ b/ostd/src/user.rs
@@ -12,6 +12,7 @@ use crate::{cpu::UserContext, mm::VmSpace, prelude::*, task::Task};
///
/// Each user space has a VM address space and allows a task to execute in
/// user mode.
+#[derive(Debug)]
pub struct UserSpace {
/// vm space
vm_space: Arc<VmSpace>,
diff --git a/ostd/src/user.rs b/ostd/src/user.rs
--- a/ostd/src/user.rs
+++ b/ostd/src/user.rs
@@ -94,7 +95,7 @@ pub trait UserContextApi {
///
/// let current = Task::current();
/// let user_space = current.user_space()
-/// .expect("the current task is associated with a user space");
+/// .expect("the current task is not associated with a user space");
/// let mut user_mode = user_space.user_mode();
/// loop {
/// // Execute in the user space until some interesting events occur.
diff --git a/ostd/src/user.rs b/ostd/src/user.rs
--- a/ostd/src/user.rs
+++ b/ostd/src/user.rs
@@ -94,7 +95,7 @@ pub trait UserContextApi {
///
/// let current = Task::current();
/// let user_space = current.user_space()
-/// .expect("the current task is associated with a user space");
+/// .expect("the current task is not associated with a user space");
/// let mut user_mode = user_space.user_mode();
/// loop {
/// // Execute in the user space until some interesting events occur.
diff --git a/ostd/src/user.rs b/ostd/src/user.rs
--- a/ostd/src/user.rs
+++ b/ostd/src/user.rs
@@ -108,14 +109,14 @@ pub struct UserMode<'a> {
context: UserContext,
}
-// An instance of `UserMode` is bound to the current task. So it cannot be
+// An instance of `UserMode` is bound to the current task. So it cannot be [`Send`].
impl<'a> !Send for UserMode<'a> {}
impl<'a> UserMode<'a> {
/// Creates a new `UserMode`.
pub fn new(user_space: &'a Arc<UserSpace>) -> Self {
Self {
- current: Task::current(),
+ current: Task::current().unwrap(),
user_space,
context: user_space.init_ctx,
}
diff --git a/ostd/src/user.rs b/ostd/src/user.rs
--- a/ostd/src/user.rs
+++ b/ostd/src/user.rs
@@ -108,14 +109,14 @@ pub struct UserMode<'a> {
context: UserContext,
}
-// An instance of `UserMode` is bound to the current task. So it cannot be
+// An instance of `UserMode` is bound to the current task. So it cannot be [`Send`].
impl<'a> !Send for UserMode<'a> {}
impl<'a> UserMode<'a> {
/// Creates a new `UserMode`.
pub fn new(user_space: &'a Arc<UserSpace>) -> Self {
Self {
- current: Task::current(),
+ current: Task::current().unwrap(),
user_space,
context: user_space.init_ctx,
}
diff --git a/ostd/src/user.rs b/ostd/src/user.rs
--- a/ostd/src/user.rs
+++ b/ostd/src/user.rs
@@ -136,7 +137,7 @@ impl<'a> UserMode<'a> {
where
F: FnMut() -> bool,
{
- debug_assert!(Arc::ptr_eq(&self.current, &Task::current()));
+ debug_assert!(Arc::ptr_eq(&self.current, &Task::current().unwrap()));
self.context.execute(has_kernel_event)
}
diff --git a/ostd/src/user.rs b/ostd/src/user.rs
--- a/ostd/src/user.rs
+++ b/ostd/src/user.rs
@@ -136,7 +137,7 @@ impl<'a> UserMode<'a> {
where
F: FnMut() -> bool,
{
- debug_assert!(Arc::ptr_eq(&self.current, &Task::current()));
+ debug_assert!(Arc::ptr_eq(&self.current, &Task::current().unwrap()));
self.context.execute(has_kernel_event)
}
|
Let's say we have a function `foo` with `#[code_context::task]` attribute. How would this `foo` function "receive references to the task data as arguments"? What would the user code look like?
> ```rust
> /// The entrypoint function of a task takes 4 arguments:
> /// 1. the mutable task context,
> /// 2. the shared task context,
> /// 3. the reference to the mutable per-task data,
> /// 4. and the reference to the per-task data.
> pub trait TaskFn =
> Fn(&mut MutTaskInfo, &SharedTaskInfo, &mut dyn Any, &(dyn Any + Send + Sync)) + 'static;
> ```
Could you please change it to `FnOnce`?
https://github.com/asterinas/asterinas/blob/20a856b07fa8210fdd2d46d3feb5087004c27afb/kernel/aster-nix/src/fs/pipe.rs#L233-L235
|
2024-08-03T03:09:32Z
|
562e64437584279783f244edba10b512beddc81d
|
asterinas/asterinas
|
diff --git a/ostd/src/mm/dma/dma_coherent.rs b/ostd/src/mm/dma/dma_coherent.rs
--- a/ostd/src/mm/dma/dma_coherent.rs
+++ b/ostd/src/mm/dma/dma_coherent.rs
@@ -192,7 +211,7 @@ mod test {
use alloc::vec;
use super::*;
- use crate::{mm::FrameAllocOptions, prelude::*};
+ use crate::mm::FrameAllocOptions;
#[ktest]
fn map_with_coherent_device() {
|
[
"1089"
] |
0.6
|
aa84b31634b9c710e04b337c5d1b8fa207f8dbde
|
Syscall test at Ext2, MicroVM occasionally fails
<!-- Thank you for taking the time to report a bug. Your input is valuable to us.
Please replace all the <angle brackets> below with your own information. -->
### Describe the bug
<!-- A clear and concise description of what the bug is. -->
### To Reproduce
<!-- Steps to reproduce the behavior. Example:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error -->
In CI, the syscall test at Ext2, MicroVM randomly output bad characters and then hang without panicking. There are some runs that seemed irrelevant with the PR modification:
https://github.com/asterinas/asterinas/actions/runs/10053473151/job/27786308763?pr=1088
https://github.com/asterinas/asterinas/actions/runs/10021055466/job/27699299104
They would pass the syscall test at ramfs (linux boot, normal VM), and then fail at Ext2, MicroVM.
### Logs
<!-- If applicable, add log snippets or files to help explain and debug the problem. Please use code blocks (```) to format logs. -->
<!-- Once again, thank you for helping us improve our project! -->
The log would look like this:
```
[Bn �731ns] : p�b ����l ��� R<�����p�1����� protected range is not fully mappedp hk ��� "}
```
|
asterinas__asterinas-1112
| 1,112
|
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -398,6 +398,12 @@ dependencies = [
"toml",
]
+[[package]]
+name = "const-assert"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d8298db53081b3a951cadb6e0f4ebbe36def7bcb591a34676708d0d7ac87dd86"
+
[[package]]
name = "controlled"
version = "0.1.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -398,6 +398,12 @@ dependencies = [
"toml",
]
+[[package]]
+name = "const-assert"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d8298db53081b3a951cadb6e0f4ebbe36def7bcb591a34676708d0d7ac87dd86"
+
[[package]]
name = "controlled"
version = "0.1.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1070,6 +1076,7 @@ dependencies = [
"bitvec",
"buddy_system_allocator",
"cfg-if",
+ "const-assert",
"gimli 0.28.0",
"iced-x86",
"id-alloc",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1070,6 +1076,7 @@ dependencies = [
"bitvec",
"buddy_system_allocator",
"cfg-if",
+ "const-assert",
"gimli 0.28.0",
"iced-x86",
"id-alloc",
diff --git a/kernel/comps/virtio/src/queue.rs b/kernel/comps/virtio/src/queue.rs
--- a/kernel/comps/virtio/src/queue.rs
+++ b/kernel/comps/virtio/src/queue.rs
@@ -129,17 +129,21 @@ impl VirtQueue {
let mut desc = descs.get(i as usize).unwrap().clone();
let next_i = i + 1;
if next_i != size {
- field_ptr!(&desc, Descriptor, next).write(&next_i).unwrap();
+ field_ptr!(&desc, Descriptor, next)
+ .write_once(&next_i)
+ .unwrap();
desc.add(1);
descs.push(desc);
} else {
- field_ptr!(&desc, Descriptor, next).write(&(0u16)).unwrap();
+ field_ptr!(&desc, Descriptor, next)
+ .write_once(&(0u16))
+ .unwrap();
}
}
let notify = transport.get_notify_ptr(idx).unwrap();
field_ptr!(&avail_ring_ptr, AvailRing, flags)
- .write(&(0u16))
+ .write_once(&(0u16))
.unwrap();
Ok(VirtQueue {
descs,
diff --git a/kernel/comps/virtio/src/queue.rs b/kernel/comps/virtio/src/queue.rs
--- a/kernel/comps/virtio/src/queue.rs
+++ b/kernel/comps/virtio/src/queue.rs
@@ -129,17 +129,21 @@ impl VirtQueue {
let mut desc = descs.get(i as usize).unwrap().clone();
let next_i = i + 1;
if next_i != size {
- field_ptr!(&desc, Descriptor, next).write(&next_i).unwrap();
+ field_ptr!(&desc, Descriptor, next)
+ .write_once(&next_i)
+ .unwrap();
desc.add(1);
descs.push(desc);
} else {
- field_ptr!(&desc, Descriptor, next).write(&(0u16)).unwrap();
+ field_ptr!(&desc, Descriptor, next)
+ .write_once(&(0u16))
+ .unwrap();
}
}
let notify = transport.get_notify_ptr(idx).unwrap();
field_ptr!(&avail_ring_ptr, AvailRing, flags)
- .write(&(0u16))
+ .write_once(&(0u16))
.unwrap();
Ok(VirtQueue {
descs,
diff --git a/kernel/comps/virtio/src/queue.rs b/kernel/comps/virtio/src/queue.rs
--- a/kernel/comps/virtio/src/queue.rs
+++ b/kernel/comps/virtio/src/queue.rs
@@ -177,10 +181,10 @@ impl VirtQueue {
let desc = &self.descs[self.free_head as usize];
set_dma_buf(&desc.borrow_vm().restrict::<TRights![Write, Dup]>(), *input);
field_ptr!(desc, Descriptor, flags)
- .write(&DescFlags::NEXT)
+ .write_once(&DescFlags::NEXT)
.unwrap();
last = self.free_head;
- self.free_head = field_ptr!(desc, Descriptor, next).read().unwrap();
+ self.free_head = field_ptr!(desc, Descriptor, next).read_once().unwrap();
}
for output in outputs.iter() {
let desc = &mut self.descs[self.free_head as usize];
diff --git a/kernel/comps/virtio/src/queue.rs b/kernel/comps/virtio/src/queue.rs
--- a/kernel/comps/virtio/src/queue.rs
+++ b/kernel/comps/virtio/src/queue.rs
@@ -177,10 +181,10 @@ impl VirtQueue {
let desc = &self.descs[self.free_head as usize];
set_dma_buf(&desc.borrow_vm().restrict::<TRights![Write, Dup]>(), *input);
field_ptr!(desc, Descriptor, flags)
- .write(&DescFlags::NEXT)
+ .write_once(&DescFlags::NEXT)
.unwrap();
last = self.free_head;
- self.free_head = field_ptr!(desc, Descriptor, next).read().unwrap();
+ self.free_head = field_ptr!(desc, Descriptor, next).read_once().unwrap();
}
for output in outputs.iter() {
let desc = &mut self.descs[self.free_head as usize];
diff --git a/kernel/comps/virtio/src/queue.rs b/kernel/comps/virtio/src/queue.rs
--- a/kernel/comps/virtio/src/queue.rs
+++ b/kernel/comps/virtio/src/queue.rs
@@ -189,17 +193,19 @@ impl VirtQueue {
*output,
);
field_ptr!(desc, Descriptor, flags)
- .write(&(DescFlags::NEXT | DescFlags::WRITE))
+ .write_once(&(DescFlags::NEXT | DescFlags::WRITE))
.unwrap();
last = self.free_head;
- self.free_head = field_ptr!(desc, Descriptor, next).read().unwrap();
+ self.free_head = field_ptr!(desc, Descriptor, next).read_once().unwrap();
}
// set last_elem.next = NULL
{
let desc = &mut self.descs[last as usize];
- let mut flags: DescFlags = field_ptr!(desc, Descriptor, flags).read().unwrap();
+ let mut flags: DescFlags = field_ptr!(desc, Descriptor, flags).read_once().unwrap();
flags.remove(DescFlags::NEXT);
- field_ptr!(desc, Descriptor, flags).write(&flags).unwrap();
+ field_ptr!(desc, Descriptor, flags)
+ .write_once(&flags)
+ .unwrap();
}
self.num_used += (inputs.len() + outputs.len()) as u16;
diff --git a/kernel/comps/virtio/src/queue.rs b/kernel/comps/virtio/src/queue.rs
--- a/kernel/comps/virtio/src/queue.rs
+++ b/kernel/comps/virtio/src/queue.rs
@@ -189,17 +193,19 @@ impl VirtQueue {
*output,
);
field_ptr!(desc, Descriptor, flags)
- .write(&(DescFlags::NEXT | DescFlags::WRITE))
+ .write_once(&(DescFlags::NEXT | DescFlags::WRITE))
.unwrap();
last = self.free_head;
- self.free_head = field_ptr!(desc, Descriptor, next).read().unwrap();
+ self.free_head = field_ptr!(desc, Descriptor, next).read_once().unwrap();
}
// set last_elem.next = NULL
{
let desc = &mut self.descs[last as usize];
- let mut flags: DescFlags = field_ptr!(desc, Descriptor, flags).read().unwrap();
+ let mut flags: DescFlags = field_ptr!(desc, Descriptor, flags).read_once().unwrap();
flags.remove(DescFlags::NEXT);
- field_ptr!(desc, Descriptor, flags).write(&flags).unwrap();
+ field_ptr!(desc, Descriptor, flags)
+ .write_once(&flags)
+ .unwrap();
}
self.num_used += (inputs.len() + outputs.len()) as u16;
diff --git a/kernel/comps/virtio/src/queue.rs b/kernel/comps/virtio/src/queue.rs
--- a/kernel/comps/virtio/src/queue.rs
+++ b/kernel/comps/virtio/src/queue.rs
@@ -210,7 +216,7 @@ impl VirtQueue {
field_ptr!(&self.avail, AvailRing, ring);
let mut ring_slot_ptr = ring_ptr.cast::<u16>();
ring_slot_ptr.add(avail_slot as usize);
- ring_slot_ptr.write(&head).unwrap();
+ ring_slot_ptr.write_once(&head).unwrap();
}
// write barrier
fence(Ordering::SeqCst);
diff --git a/kernel/comps/virtio/src/queue.rs b/kernel/comps/virtio/src/queue.rs
--- a/kernel/comps/virtio/src/queue.rs
+++ b/kernel/comps/virtio/src/queue.rs
@@ -210,7 +216,7 @@ impl VirtQueue {
field_ptr!(&self.avail, AvailRing, ring);
let mut ring_slot_ptr = ring_ptr.cast::<u16>();
ring_slot_ptr.add(avail_slot as usize);
- ring_slot_ptr.write(&head).unwrap();
+ ring_slot_ptr.write_once(&head).unwrap();
}
// write barrier
fence(Ordering::SeqCst);
diff --git a/kernel/comps/virtio/src/queue.rs b/kernel/comps/virtio/src/queue.rs
--- a/kernel/comps/virtio/src/queue.rs
+++ b/kernel/comps/virtio/src/queue.rs
@@ -218,7 +224,7 @@ impl VirtQueue {
// increase head of avail ring
self.avail_idx = self.avail_idx.wrapping_add(1);
field_ptr!(&self.avail, AvailRing, idx)
- .write(&self.avail_idx)
+ .write_once(&self.avail_idx)
.unwrap();
fence(Ordering::SeqCst);
diff --git a/kernel/comps/virtio/src/queue.rs b/kernel/comps/virtio/src/queue.rs
--- a/kernel/comps/virtio/src/queue.rs
+++ b/kernel/comps/virtio/src/queue.rs
@@ -218,7 +224,7 @@ impl VirtQueue {
// increase head of avail ring
self.avail_idx = self.avail_idx.wrapping_add(1);
field_ptr!(&self.avail, AvailRing, idx)
- .write(&self.avail_idx)
+ .write_once(&self.avail_idx)
.unwrap();
fence(Ordering::SeqCst);
diff --git a/kernel/comps/virtio/src/queue.rs b/kernel/comps/virtio/src/queue.rs
--- a/kernel/comps/virtio/src/queue.rs
+++ b/kernel/comps/virtio/src/queue.rs
@@ -230,7 +236,7 @@ impl VirtQueue {
// read barrier
fence(Ordering::SeqCst);
- self.last_used_idx != field_ptr!(&self.used, UsedRing, idx).read().unwrap()
+ self.last_used_idx != field_ptr!(&self.used, UsedRing, idx).read_once().unwrap()
}
/// The number of free descriptors.
diff --git a/kernel/comps/virtio/src/queue.rs b/kernel/comps/virtio/src/queue.rs
--- a/kernel/comps/virtio/src/queue.rs
+++ b/kernel/comps/virtio/src/queue.rs
@@ -230,7 +236,7 @@ impl VirtQueue {
// read barrier
fence(Ordering::SeqCst);
- self.last_used_idx != field_ptr!(&self.used, UsedRing, idx).read().unwrap()
+ self.last_used_idx != field_ptr!(&self.used, UsedRing, idx).read_once().unwrap()
}
/// The number of free descriptors.
diff --git a/kernel/comps/virtio/src/queue.rs b/kernel/comps/virtio/src/queue.rs
--- a/kernel/comps/virtio/src/queue.rs
+++ b/kernel/comps/virtio/src/queue.rs
@@ -247,19 +253,23 @@ impl VirtQueue {
loop {
let desc = &mut self.descs[head as usize];
// Sets the buffer address and length to 0
- field_ptr!(desc, Descriptor, addr).write(&(0u64)).unwrap();
- field_ptr!(desc, Descriptor, len).write(&(0u32)).unwrap();
+ field_ptr!(desc, Descriptor, addr)
+ .write_once(&(0u64))
+ .unwrap();
+ field_ptr!(desc, Descriptor, len)
+ .write_once(&(0u32))
+ .unwrap();
self.num_used -= 1;
- let flags: DescFlags = field_ptr!(desc, Descriptor, flags).read().unwrap();
+ let flags: DescFlags = field_ptr!(desc, Descriptor, flags).read_once().unwrap();
if flags.contains(DescFlags::NEXT) {
field_ptr!(desc, Descriptor, flags)
- .write(&DescFlags::empty())
+ .write_once(&DescFlags::empty())
.unwrap();
- head = field_ptr!(desc, Descriptor, next).read().unwrap();
+ head = field_ptr!(desc, Descriptor, next).read_once().unwrap();
} else {
field_ptr!(desc, Descriptor, next)
- .write(&origin_free_head)
+ .write_once(&origin_free_head)
.unwrap();
break;
}
diff --git a/kernel/comps/virtio/src/queue.rs b/kernel/comps/virtio/src/queue.rs
--- a/kernel/comps/virtio/src/queue.rs
+++ b/kernel/comps/virtio/src/queue.rs
@@ -247,19 +253,23 @@ impl VirtQueue {
loop {
let desc = &mut self.descs[head as usize];
// Sets the buffer address and length to 0
- field_ptr!(desc, Descriptor, addr).write(&(0u64)).unwrap();
- field_ptr!(desc, Descriptor, len).write(&(0u32)).unwrap();
+ field_ptr!(desc, Descriptor, addr)
+ .write_once(&(0u64))
+ .unwrap();
+ field_ptr!(desc, Descriptor, len)
+ .write_once(&(0u32))
+ .unwrap();
self.num_used -= 1;
- let flags: DescFlags = field_ptr!(desc, Descriptor, flags).read().unwrap();
+ let flags: DescFlags = field_ptr!(desc, Descriptor, flags).read_once().unwrap();
if flags.contains(DescFlags::NEXT) {
field_ptr!(desc, Descriptor, flags)
- .write(&DescFlags::empty())
+ .write_once(&DescFlags::empty())
.unwrap();
- head = field_ptr!(desc, Descriptor, next).read().unwrap();
+ head = field_ptr!(desc, Descriptor, next).read_once().unwrap();
} else {
field_ptr!(desc, Descriptor, next)
- .write(&origin_free_head)
+ .write_once(&origin_free_head)
.unwrap();
break;
}
diff --git a/kernel/comps/virtio/src/queue.rs b/kernel/comps/virtio/src/queue.rs
--- a/kernel/comps/virtio/src/queue.rs
+++ b/kernel/comps/virtio/src/queue.rs
@@ -280,8 +290,8 @@ impl VirtQueue {
ptr.byte_add(offset_of!(UsedRing, ring) as usize + last_used_slot as usize * 8);
ptr.cast::<UsedElem>()
};
- let index = field_ptr!(&element_ptr, UsedElem, id).read().unwrap();
- let len = field_ptr!(&element_ptr, UsedElem, len).read().unwrap();
+ let index = field_ptr!(&element_ptr, UsedElem, id).read_once().unwrap();
+ let len = field_ptr!(&element_ptr, UsedElem, len).read_once().unwrap();
self.recycle_descriptors(index as u16);
self.last_used_idx = self.last_used_idx.wrapping_add(1);
diff --git a/kernel/comps/virtio/src/queue.rs b/kernel/comps/virtio/src/queue.rs
--- a/kernel/comps/virtio/src/queue.rs
+++ b/kernel/comps/virtio/src/queue.rs
@@ -280,8 +290,8 @@ impl VirtQueue {
ptr.byte_add(offset_of!(UsedRing, ring) as usize + last_used_slot as usize * 8);
ptr.cast::<UsedElem>()
};
- let index = field_ptr!(&element_ptr, UsedElem, id).read().unwrap();
- let len = field_ptr!(&element_ptr, UsedElem, len).read().unwrap();
+ let index = field_ptr!(&element_ptr, UsedElem, id).read_once().unwrap();
+ let len = field_ptr!(&element_ptr, UsedElem, len).read_once().unwrap();
self.recycle_descriptors(index as u16);
self.last_used_idx = self.last_used_idx.wrapping_add(1);
diff --git a/kernel/comps/virtio/src/queue.rs b/kernel/comps/virtio/src/queue.rs
--- a/kernel/comps/virtio/src/queue.rs
+++ b/kernel/comps/virtio/src/queue.rs
@@ -304,8 +314,8 @@ impl VirtQueue {
ptr.byte_add(offset_of!(UsedRing, ring) as usize + last_used_slot as usize * 8);
ptr.cast::<UsedElem>()
};
- let index = field_ptr!(&element_ptr, UsedElem, id).read().unwrap();
- let len = field_ptr!(&element_ptr, UsedElem, len).read().unwrap();
+ let index = field_ptr!(&element_ptr, UsedElem, id).read_once().unwrap();
+ let len = field_ptr!(&element_ptr, UsedElem, len).read_once().unwrap();
if index as u16 != token {
return Err(QueueError::WrongToken);
diff --git a/kernel/comps/virtio/src/queue.rs b/kernel/comps/virtio/src/queue.rs
--- a/kernel/comps/virtio/src/queue.rs
+++ b/kernel/comps/virtio/src/queue.rs
@@ -304,8 +314,8 @@ impl VirtQueue {
ptr.byte_add(offset_of!(UsedRing, ring) as usize + last_used_slot as usize * 8);
ptr.cast::<UsedElem>()
};
- let index = field_ptr!(&element_ptr, UsedElem, id).read().unwrap();
- let len = field_ptr!(&element_ptr, UsedElem, len).read().unwrap();
+ let index = field_ptr!(&element_ptr, UsedElem, id).read_once().unwrap();
+ let len = field_ptr!(&element_ptr, UsedElem, len).read_once().unwrap();
if index as u16 != token {
return Err(QueueError::WrongToken);
diff --git a/kernel/comps/virtio/src/queue.rs b/kernel/comps/virtio/src/queue.rs
--- a/kernel/comps/virtio/src/queue.rs
+++ b/kernel/comps/virtio/src/queue.rs
@@ -326,7 +336,7 @@ impl VirtQueue {
pub fn should_notify(&self) -> bool {
// read barrier
fence(Ordering::SeqCst);
- let flags = field_ptr!(&self.used, UsedRing, flags).read().unwrap();
+ let flags = field_ptr!(&self.used, UsedRing, flags).read_once().unwrap();
flags & 0x0001u16 == 0u16
}
diff --git a/kernel/comps/virtio/src/queue.rs b/kernel/comps/virtio/src/queue.rs
--- a/kernel/comps/virtio/src/queue.rs
+++ b/kernel/comps/virtio/src/queue.rs
@@ -326,7 +336,7 @@ impl VirtQueue {
pub fn should_notify(&self) -> bool {
// read barrier
fence(Ordering::SeqCst);
- let flags = field_ptr!(&self.used, UsedRing, flags).read().unwrap();
+ let flags = field_ptr!(&self.used, UsedRing, flags).read_once().unwrap();
flags & 0x0001u16 == 0u16
}
diff --git a/kernel/comps/virtio/src/queue.rs b/kernel/comps/virtio/src/queue.rs
--- a/kernel/comps/virtio/src/queue.rs
+++ b/kernel/comps/virtio/src/queue.rs
@@ -353,10 +363,10 @@ fn set_dma_buf<T: DmaBuf>(desc_ptr: &DescriptorPtr, buf: &T) {
debug_assert_ne!(buf.len(), 0);
let daddr = buf.daddr();
field_ptr!(desc_ptr, Descriptor, addr)
- .write(&(daddr as u64))
+ .write_once(&(daddr as u64))
.unwrap();
field_ptr!(desc_ptr, Descriptor, len)
- .write(&(buf.len() as u32))
+ .write_once(&(buf.len() as u32))
.unwrap();
}
diff --git a/kernel/comps/virtio/src/queue.rs b/kernel/comps/virtio/src/queue.rs
--- a/kernel/comps/virtio/src/queue.rs
+++ b/kernel/comps/virtio/src/queue.rs
@@ -353,10 +363,10 @@ fn set_dma_buf<T: DmaBuf>(desc_ptr: &DescriptorPtr, buf: &T) {
debug_assert_ne!(buf.len(), 0);
let daddr = buf.daddr();
field_ptr!(desc_ptr, Descriptor, addr)
- .write(&(daddr as u64))
+ .write_once(&(daddr as u64))
.unwrap();
field_ptr!(desc_ptr, Descriptor, len)
- .write(&(buf.len() as u32))
+ .write_once(&(buf.len() as u32))
.unwrap();
}
diff --git a/kernel/libs/aster-util/src/safe_ptr.rs b/kernel/libs/aster-util/src/safe_ptr.rs
--- a/kernel/libs/aster-util/src/safe_ptr.rs
+++ b/kernel/libs/aster-util/src/safe_ptr.rs
@@ -7,7 +7,7 @@ use aster_rights_proc::require;
use inherit_methods_macro::inherit_methods;
pub use ostd::Pod;
use ostd::{
- mm::{Daddr, DmaStream, HasDaddr, HasPaddr, Paddr, VmIo},
+ mm::{Daddr, DmaStream, HasDaddr, HasPaddr, Paddr, PodOnce, VmIo, VmIoOnce},
Result,
};
pub use typeflags_util::SetContain;
diff --git a/kernel/libs/aster-util/src/safe_ptr.rs b/kernel/libs/aster-util/src/safe_ptr.rs
--- a/kernel/libs/aster-util/src/safe_ptr.rs
+++ b/kernel/libs/aster-util/src/safe_ptr.rs
@@ -7,7 +7,7 @@ use aster_rights_proc::require;
use inherit_methods_macro::inherit_methods;
pub use ostd::Pod;
use ostd::{
- mm::{Daddr, DmaStream, HasDaddr, HasPaddr, Paddr, VmIo},
+ mm::{Daddr, DmaStream, HasDaddr, HasPaddr, Paddr, PodOnce, VmIo, VmIoOnce},
Result,
};
pub use typeflags_util::SetContain;
diff --git a/kernel/libs/aster-util/src/safe_ptr.rs b/kernel/libs/aster-util/src/safe_ptr.rs
--- a/kernel/libs/aster-util/src/safe_ptr.rs
+++ b/kernel/libs/aster-util/src/safe_ptr.rs
@@ -324,6 +324,28 @@ impl<T: Pod, M: VmIo, R: TRights> SafePtr<T, M, TRightSet<R>> {
}
}
+impl<T: PodOnce, M: VmIoOnce, R: TRights> SafePtr<T, M, TRightSet<R>> {
+ /// Reads the value from the pointer using one non-tearing instruction.
+ ///
+ /// # Access rights
+ ///
+ /// This method requires the `Read` right.
+ #[require(R > Read)]
+ pub fn read_once(&self) -> Result<T> {
+ self.vm_obj.read_once(self.offset)
+ }
+
+ /// Overwrites the value at the pointer using one non-tearing instruction.
+ ///
+ /// # Access rights
+ ///
+ /// This method requires the `Write` right.
+ #[require(R > Write)]
+ pub fn write_once(&self, val: &T) -> Result<()> {
+ self.vm_obj.write_once(self.offset, val)
+ }
+}
+
impl<T, M: HasDaddr, R> HasDaddr for SafePtr<T, M, R> {
fn daddr(&self) -> Daddr {
self.offset + self.vm_obj.daddr()
diff --git a/kernel/libs/aster-util/src/safe_ptr.rs b/kernel/libs/aster-util/src/safe_ptr.rs
--- a/kernel/libs/aster-util/src/safe_ptr.rs
+++ b/kernel/libs/aster-util/src/safe_ptr.rs
@@ -324,6 +324,28 @@ impl<T: Pod, M: VmIo, R: TRights> SafePtr<T, M, TRightSet<R>> {
}
}
+impl<T: PodOnce, M: VmIoOnce, R: TRights> SafePtr<T, M, TRightSet<R>> {
+ /// Reads the value from the pointer using one non-tearing instruction.
+ ///
+ /// # Access rights
+ ///
+ /// This method requires the `Read` right.
+ #[require(R > Read)]
+ pub fn read_once(&self) -> Result<T> {
+ self.vm_obj.read_once(self.offset)
+ }
+
+ /// Overwrites the value at the pointer using one non-tearing instruction.
+ ///
+ /// # Access rights
+ ///
+ /// This method requires the `Write` right.
+ #[require(R > Write)]
+ pub fn write_once(&self, val: &T) -> Result<()> {
+ self.vm_obj.write_once(self.offset, val)
+ }
+}
+
impl<T, M: HasDaddr, R> HasDaddr for SafePtr<T, M, R> {
fn daddr(&self) -> Daddr {
self.offset + self.vm_obj.daddr()
diff --git a/ostd/Cargo.toml b/ostd/Cargo.toml
--- a/ostd/Cargo.toml
+++ b/ostd/Cargo.toml
@@ -22,6 +22,7 @@ buddy_system_allocator = "0.9.0"
bitflags = "1.3"
bitvec = { version = "1.0", default-features = false, features = ["alloc"] }
cfg-if = "1.0"
+const-assert = "1.0"
gimli = { version = "0.28", default-features = false, features = ["read-core"] }
id-alloc = { path = "libs/id-alloc", version = "0.1.0" }
inherit-methods-macro = { git = "https://github.com/asterinas/inherit-methods-macro", rev = "98f7e3e", version = "0.1.0" }
diff --git a/ostd/Cargo.toml b/ostd/Cargo.toml
--- a/ostd/Cargo.toml
+++ b/ostd/Cargo.toml
@@ -22,6 +22,7 @@ buddy_system_allocator = "0.9.0"
bitflags = "1.3"
bitvec = { version = "1.0", default-features = false, features = ["alloc"] }
cfg-if = "1.0"
+const-assert = "1.0"
gimli = { version = "0.28", default-features = false, features = ["read-core"] }
id-alloc = { path = "libs/id-alloc", version = "0.1.0" }
inherit-methods-macro = { git = "https://github.com/asterinas/inherit-methods-macro", rev = "98f7e3e", version = "0.1.0" }
diff --git a/ostd/src/mm/dma/dma_coherent.rs b/ostd/src/mm/dma/dma_coherent.rs
--- a/ostd/src/mm/dma/dma_coherent.rs
+++ b/ostd/src/mm/dma/dma_coherent.rs
@@ -13,10 +13,12 @@ use crate::{
arch::{iommu, mm::tlb_flush_addr_range},
mm::{
dma::{dma_type, Daddr, DmaType},
+ io::VmIoOnce,
kspace::{paddr_to_vaddr, KERNEL_PAGE_TABLE},
page_prop::CachePolicy,
- HasPaddr, Paddr, Segment, VmIo, VmReader, VmWriter, PAGE_SIZE,
+ HasPaddr, Paddr, PodOnce, Segment, VmIo, VmReader, VmWriter, PAGE_SIZE,
},
+ prelude::*,
};
/// A coherent (or consistent) DMA mapping,
diff --git a/ostd/src/mm/dma/dma_coherent.rs b/ostd/src/mm/dma/dma_coherent.rs
--- a/ostd/src/mm/dma/dma_coherent.rs
+++ b/ostd/src/mm/dma/dma_coherent.rs
@@ -13,10 +13,12 @@ use crate::{
arch::{iommu, mm::tlb_flush_addr_range},
mm::{
dma::{dma_type, Daddr, DmaType},
+ io::VmIoOnce,
kspace::{paddr_to_vaddr, KERNEL_PAGE_TABLE},
page_prop::CachePolicy,
- HasPaddr, Paddr, Segment, VmIo, VmReader, VmWriter, PAGE_SIZE,
+ HasPaddr, Paddr, PodOnce, Segment, VmIo, VmReader, VmWriter, PAGE_SIZE,
},
+ prelude::*,
};
/// A coherent (or consistent) DMA mapping,
diff --git a/ostd/src/mm/dma/dma_coherent.rs b/ostd/src/mm/dma/dma_coherent.rs
--- a/ostd/src/mm/dma/dma_coherent.rs
+++ b/ostd/src/mm/dma/dma_coherent.rs
@@ -47,7 +49,10 @@ impl DmaCoherent {
///
/// The method fails if any part of the given `vm_segment`
/// already belongs to a DMA mapping.
- pub fn map(vm_segment: Segment, is_cache_coherent: bool) -> Result<Self, DmaError> {
+ pub fn map(
+ vm_segment: Segment,
+ is_cache_coherent: bool,
+ ) -> core::result::Result<Self, DmaError> {
let frame_count = vm_segment.nframes();
let start_paddr = vm_segment.start_paddr();
if !check_and_insert_dma_mapping(start_paddr, frame_count) {
diff --git a/ostd/src/mm/dma/dma_coherent.rs b/ostd/src/mm/dma/dma_coherent.rs
--- a/ostd/src/mm/dma/dma_coherent.rs
+++ b/ostd/src/mm/dma/dma_coherent.rs
@@ -47,7 +49,10 @@ impl DmaCoherent {
///
/// The method fails if any part of the given `vm_segment`
/// already belongs to a DMA mapping.
- pub fn map(vm_segment: Segment, is_cache_coherent: bool) -> Result<Self, DmaError> {
+ pub fn map(
+ vm_segment: Segment,
+ is_cache_coherent: bool,
+ ) -> core::result::Result<Self, DmaError> {
let frame_count = vm_segment.nframes();
let start_paddr = vm_segment.start_paddr();
if !check_and_insert_dma_mapping(start_paddr, frame_count) {
diff --git a/ostd/src/mm/dma/dma_coherent.rs b/ostd/src/mm/dma/dma_coherent.rs
--- a/ostd/src/mm/dma/dma_coherent.rs
+++ b/ostd/src/mm/dma/dma_coherent.rs
@@ -160,15 +165,29 @@ impl Drop for DmaCoherentInner {
}
impl VmIo for DmaCoherent {
- fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> crate::prelude::Result<()> {
+ fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> Result<()> {
self.inner.vm_segment.read_bytes(offset, buf)
}
- fn write_bytes(&self, offset: usize, buf: &[u8]) -> crate::prelude::Result<()> {
+ fn write_bytes(&self, offset: usize, buf: &[u8]) -> Result<()> {
self.inner.vm_segment.write_bytes(offset, buf)
}
}
+impl VmIoOnce for DmaCoherent {
+ fn read_once<T: PodOnce>(&self, offset: usize) -> Result<T> {
+ self.inner.vm_segment.reader().skip(offset).read_once()
+ }
+
+ fn write_once<T: PodOnce>(&self, offset: usize, new_val: &T) -> Result<()> {
+ self.inner
+ .vm_segment
+ .writer()
+ .skip(offset)
+ .write_once(new_val)
+ }
+}
+
impl<'a> DmaCoherent {
/// Returns a reader to read data from it.
pub fn reader(&'a self) -> VmReader<'a> {
diff --git a/ostd/src/mm/dma/dma_coherent.rs b/ostd/src/mm/dma/dma_coherent.rs
--- a/ostd/src/mm/dma/dma_coherent.rs
+++ b/ostd/src/mm/dma/dma_coherent.rs
@@ -160,15 +165,29 @@ impl Drop for DmaCoherentInner {
}
impl VmIo for DmaCoherent {
- fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> crate::prelude::Result<()> {
+ fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> Result<()> {
self.inner.vm_segment.read_bytes(offset, buf)
}
- fn write_bytes(&self, offset: usize, buf: &[u8]) -> crate::prelude::Result<()> {
+ fn write_bytes(&self, offset: usize, buf: &[u8]) -> Result<()> {
self.inner.vm_segment.write_bytes(offset, buf)
}
}
+impl VmIoOnce for DmaCoherent {
+ fn read_once<T: PodOnce>(&self, offset: usize) -> Result<T> {
+ self.inner.vm_segment.reader().skip(offset).read_once()
+ }
+
+ fn write_once<T: PodOnce>(&self, offset: usize, new_val: &T) -> Result<()> {
+ self.inner
+ .vm_segment
+ .writer()
+ .skip(offset)
+ .write_once(new_val)
+ }
+}
+
impl<'a> DmaCoherent {
/// Returns a reader to read data from it.
pub fn reader(&'a self) -> VmReader<'a> {
diff --git a/ostd/src/mm/dma/dma_coherent.rs b/ostd/src/mm/dma/dma_coherent.rs
--- a/ostd/src/mm/dma/dma_coherent.rs
+++ b/ostd/src/mm/dma/dma_coherent.rs
@@ -192,7 +211,7 @@ mod test {
use alloc::vec;
use super::*;
- use crate::{mm::FrameAllocOptions, prelude::*};
+ use crate::mm::FrameAllocOptions;
#[ktest]
fn map_with_coherent_device() {
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -5,6 +5,7 @@
use core::marker::PhantomData;
use align_ext::AlignExt;
+use const_assert::{Assert, IsTrue};
use inherit_methods_macro::inherit_methods;
use crate::{
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -5,6 +5,7 @@
use core::marker::PhantomData;
use align_ext::AlignExt;
+use const_assert::{Assert, IsTrue};
use inherit_methods_macro::inherit_methods;
use crate::{
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -155,7 +156,28 @@ pub trait VmIo: Send + Sync {
}
}
-macro_rules! impl_vmio_pointer {
+/// A trait that enables reading/writing data from/to a VM object using one non-tearing memory
+/// load/store.
+///
+/// See also [`VmIo`], which enables reading/writing data from/to a VM object without the guarantee
+/// of using one non-tearing memory load/store.
+pub trait VmIoOnce {
+ /// Reads a value of the `PodOnce` type at the specified offset using one non-tearing memory
+ /// load.
+ ///
+ /// Except that the offset is specified explicitly, the semantics of this method is the same as
+ /// [`VmReader::read_once`].
+ fn read_once<T: PodOnce>(&self, offset: usize) -> Result<T>;
+
+ /// Writes a value of the `PodOnce` type at the specified offset using one non-tearing memory
+ /// store.
+ ///
+ /// Except that the offset is specified explicitly, the semantics of this method is the same as
+ /// [`VmWriter::write_once`].
+ fn write_once<T: PodOnce>(&self, offset: usize, new_val: &T) -> Result<()>;
+}
+
+macro_rules! impl_vm_io_pointer {
($typ:ty,$from:tt) => {
#[inherit_methods(from = $from)]
impl<T: VmIo> VmIo for $typ {
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -155,7 +156,28 @@ pub trait VmIo: Send + Sync {
}
}
-macro_rules! impl_vmio_pointer {
+/// A trait that enables reading/writing data from/to a VM object using one non-tearing memory
+/// load/store.
+///
+/// See also [`VmIo`], which enables reading/writing data from/to a VM object without the guarantee
+/// of using one non-tearing memory load/store.
+pub trait VmIoOnce {
+ /// Reads a value of the `PodOnce` type at the specified offset using one non-tearing memory
+ /// load.
+ ///
+ /// Except that the offset is specified explicitly, the semantics of this method is the same as
+ /// [`VmReader::read_once`].
+ fn read_once<T: PodOnce>(&self, offset: usize) -> Result<T>;
+
+ /// Writes a value of the `PodOnce` type at the specified offset using one non-tearing memory
+ /// store.
+ ///
+ /// Except that the offset is specified explicitly, the semantics of this method is the same as
+ /// [`VmWriter::write_once`].
+ fn write_once<T: PodOnce>(&self, offset: usize, new_val: &T) -> Result<()>;
+}
+
+macro_rules! impl_vm_io_pointer {
($typ:ty,$from:tt) => {
#[inherit_methods(from = $from)]
impl<T: VmIo> VmIo for $typ {
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -169,10 +191,25 @@ macro_rules! impl_vmio_pointer {
};
}
-impl_vmio_pointer!(&T, "(**self)");
-impl_vmio_pointer!(&mut T, "(**self)");
-impl_vmio_pointer!(Box<T>, "(**self)");
-impl_vmio_pointer!(Arc<T>, "(**self)");
+impl_vm_io_pointer!(&T, "(**self)");
+impl_vm_io_pointer!(&mut T, "(**self)");
+impl_vm_io_pointer!(Box<T>, "(**self)");
+impl_vm_io_pointer!(Arc<T>, "(**self)");
+
+macro_rules! impl_vm_io_once_pointer {
+ ($typ:ty,$from:tt) => {
+ #[inherit_methods(from = $from)]
+ impl<T: VmIoOnce> VmIoOnce for $typ {
+ fn read_once<F: PodOnce>(&self, offset: usize) -> Result<F>;
+ fn write_once<F: PodOnce>(&self, offset: usize, new_val: &F) -> Result<()>;
+ }
+ };
+}
+
+impl_vm_io_once_pointer!(&T, "(**self)");
+impl_vm_io_once_pointer!(&mut T, "(**self)");
+impl_vm_io_once_pointer!(Box<T>, "(**self)");
+impl_vm_io_once_pointer!(Arc<T>, "(**self)");
/// A marker structure used for [`VmReader`] and [`VmWriter`],
/// representing their operated memory scope is in user space.
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -169,10 +191,25 @@ macro_rules! impl_vmio_pointer {
};
}
-impl_vmio_pointer!(&T, "(**self)");
-impl_vmio_pointer!(&mut T, "(**self)");
-impl_vmio_pointer!(Box<T>, "(**self)");
-impl_vmio_pointer!(Arc<T>, "(**self)");
+impl_vm_io_pointer!(&T, "(**self)");
+impl_vm_io_pointer!(&mut T, "(**self)");
+impl_vm_io_pointer!(Box<T>, "(**self)");
+impl_vm_io_pointer!(Arc<T>, "(**self)");
+
+macro_rules! impl_vm_io_once_pointer {
+ ($typ:ty,$from:tt) => {
+ #[inherit_methods(from = $from)]
+ impl<T: VmIoOnce> VmIoOnce for $typ {
+ fn read_once<F: PodOnce>(&self, offset: usize) -> Result<F>;
+ fn write_once<F: PodOnce>(&self, offset: usize, new_val: &F) -> Result<()>;
+ }
+ };
+}
+
+impl_vm_io_once_pointer!(&T, "(**self)");
+impl_vm_io_once_pointer!(&mut T, "(**self)");
+impl_vm_io_once_pointer!(Box<T>, "(**self)");
+impl_vm_io_once_pointer!(Arc<T>, "(**self)");
/// A marker structure used for [`VmReader`] and [`VmWriter`],
/// representing their operated memory scope is in user space.
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -391,6 +428,34 @@ impl<'a> VmReader<'a, KernelSpace> {
self.read(&mut writer);
Ok(val)
}
+
+ /// Reads a value of the `PodOnce` type using one non-tearing memory load.
+ ///
+ /// If the length of the `PodOnce` type exceeds `self.remain()`, this method will return `Err`.
+ ///
+ /// This method will not compile if the `Pod` type is too large for the current architecture
+ /// and the operation must be tear into multiple memory loads.
+ ///
+ /// # Panics
+ ///
+ /// This method will panic if the current position of the reader does not meet the alignment
+ /// requirements of type `T`.
+ pub fn read_once<T: PodOnce>(&mut self) -> Result<T> {
+ if self.remain() < core::mem::size_of::<T>() {
+ return Err(Error::InvalidArgs);
+ }
+
+ let cursor = self.cursor.cast::<T>();
+ assert!(cursor.is_aligned());
+
+ // SAFETY: We have checked that the number of bytes remaining is at least the size of `T`
+ // and that the cursor is properly aligned with respect to the type `T`. All other safety
+ // requirements are the same as for `Self::read`.
+ let val = unsafe { cursor.read_volatile() };
+ self.cursor = unsafe { self.cursor.add(core::mem::size_of::<T>()) };
+
+ Ok(val)
+ }
}
impl<'a> VmReader<'a, UserSpace> {
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -391,6 +428,34 @@ impl<'a> VmReader<'a, KernelSpace> {
self.read(&mut writer);
Ok(val)
}
+
+ /// Reads a value of the `PodOnce` type using one non-tearing memory load.
+ ///
+ /// If the length of the `PodOnce` type exceeds `self.remain()`, this method will return `Err`.
+ ///
+ /// This method will not compile if the `Pod` type is too large for the current architecture
+ /// and the operation must be tear into multiple memory loads.
+ ///
+ /// # Panics
+ ///
+ /// This method will panic if the current position of the reader does not meet the alignment
+ /// requirements of type `T`.
+ pub fn read_once<T: PodOnce>(&mut self) -> Result<T> {
+ if self.remain() < core::mem::size_of::<T>() {
+ return Err(Error::InvalidArgs);
+ }
+
+ let cursor = self.cursor.cast::<T>();
+ assert!(cursor.is_aligned());
+
+ // SAFETY: We have checked that the number of bytes remaining is at least the size of `T`
+ // and that the cursor is properly aligned with respect to the type `T`. All other safety
+ // requirements are the same as for `Self::read`.
+ let val = unsafe { cursor.read_volatile() };
+ self.cursor = unsafe { self.cursor.add(core::mem::size_of::<T>()) };
+
+ Ok(val)
+ }
}
impl<'a> VmReader<'a, UserSpace> {
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -461,7 +526,7 @@ impl<'a, Space> VmReader<'a, Space> {
/// Skips the first `nbytes` bytes of data.
/// The length of remaining data is decreased accordingly.
///
- /// # Panic
+ /// # Panics
///
/// If `nbytes` is greater than `self.remain()`, then the method panics.
pub fn skip(mut self, nbytes: usize) -> Self {
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -461,7 +526,7 @@ impl<'a, Space> VmReader<'a, Space> {
/// Skips the first `nbytes` bytes of data.
/// The length of remaining data is decreased accordingly.
///
- /// # Panic
+ /// # Panics
///
/// If `nbytes` is greater than `self.remain()`, then the method panics.
pub fn skip(mut self, nbytes: usize) -> Self {
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -553,11 +618,36 @@ impl<'a> VmWriter<'a, KernelSpace> {
Ok(())
}
+ /// Writes a value of the `PodOnce` type using one non-tearing memory store.
+ ///
+ /// If the length of the `PodOnce` type exceeds `self.remain()`, this method will return `Err`.
+ ///
+ /// # Panics
+ ///
+ /// This method will panic if the current position of the writer does not meet the alignment
+ /// requirements of type `T`.
+ pub fn write_once<T: PodOnce>(&mut self, new_val: &T) -> Result<()> {
+ if self.avail() < core::mem::size_of::<T>() {
+ return Err(Error::InvalidArgs);
+ }
+
+ let cursor = self.cursor.cast::<T>();
+ assert!(cursor.is_aligned());
+
+ // SAFETY: We have checked that the number of bytes remaining is at least the size of `T`
+ // and that the cursor is properly aligned with respect to the type `T`. All other safety
+ // requirements are the same as for `Self::writer`.
+ unsafe { cursor.cast::<T>().write_volatile(*new_val) };
+ self.cursor = unsafe { self.cursor.add(core::mem::size_of::<T>()) };
+
+ Ok(())
+ }
+
/// Fills the available space by repeating `value`.
///
/// Returns the number of values written.
///
- /// # Panic
+ /// # Panics
///
/// The size of the available space must be a multiple of the size of `value`.
/// Otherwise, the method would panic.
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -553,11 +618,36 @@ impl<'a> VmWriter<'a, KernelSpace> {
Ok(())
}
+ /// Writes a value of the `PodOnce` type using one non-tearing memory store.
+ ///
+ /// If the length of the `PodOnce` type exceeds `self.remain()`, this method will return `Err`.
+ ///
+ /// # Panics
+ ///
+ /// This method will panic if the current position of the writer does not meet the alignment
+ /// requirements of type `T`.
+ pub fn write_once<T: PodOnce>(&mut self, new_val: &T) -> Result<()> {
+ if self.avail() < core::mem::size_of::<T>() {
+ return Err(Error::InvalidArgs);
+ }
+
+ let cursor = self.cursor.cast::<T>();
+ assert!(cursor.is_aligned());
+
+ // SAFETY: We have checked that the number of bytes remaining is at least the size of `T`
+ // and that the cursor is properly aligned with respect to the type `T`. All other safety
+ // requirements are the same as for `Self::writer`.
+ unsafe { cursor.cast::<T>().write_volatile(*new_val) };
+ self.cursor = unsafe { self.cursor.add(core::mem::size_of::<T>()) };
+
+ Ok(())
+ }
+
/// Fills the available space by repeating `value`.
///
/// Returns the number of values written.
///
- /// # Panic
+ /// # Panics
///
/// The size of the available space must be a multiple of the size of `value`.
/// Otherwise, the method would panic.
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -574,7 +664,7 @@ impl<'a> VmWriter<'a, KernelSpace> {
// hence the `add` operation and `write` operation are valid and will only manipulate
// the memory managed by this writer.
unsafe {
- (self.cursor as *mut T).add(i).write(value);
+ (self.cursor as *mut T).add(i).write_volatile(value);
}
}
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -574,7 +664,7 @@ impl<'a> VmWriter<'a, KernelSpace> {
// hence the `add` operation and `write` operation are valid and will only manipulate
// the memory managed by this writer.
unsafe {
- (self.cursor as *mut T).add(i).write(value);
+ (self.cursor as *mut T).add(i).write_volatile(value);
}
}
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -650,7 +740,7 @@ impl<'a, Space> VmWriter<'a, Space> {
/// Skips the first `nbytes` bytes of data.
/// The length of available space is decreased accordingly.
///
- /// # Panic
+ /// # Panics
///
/// If `nbytes` is greater than `self.avail()`, then the method panics.
pub fn skip(mut self, nbytes: usize) -> Self {
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -650,7 +740,7 @@ impl<'a, Space> VmWriter<'a, Space> {
/// Skips the first `nbytes` bytes of data.
/// The length of available space is decreased accordingly.
///
- /// # Panic
+ /// # Panics
///
/// If `nbytes` is greater than `self.avail()`, then the method panics.
pub fn skip(mut self, nbytes: usize) -> Self {
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -672,3 +762,23 @@ impl<'a> From<&'a mut [u8]> for VmWriter<'a> {
unsafe { Self::from_kernel_space(slice.as_mut_ptr(), slice.len()) }
}
}
+
+/// A marker trait for POD types that can be read or written with one instruction.
+///
+/// We currently rely on this trait to ensure that the memory operation created by
+/// `ptr::read_volatile` and `ptr::write_volatile` doesn't tear. However, the Rust documentation
+/// makes no such guarantee, and even the wording in the LLVM LangRef is ambiguous.
+///
+/// At this point, we can only _hope_ that this doesn't break in future versions of the Rust or
+/// LLVM compilers. However, this is unlikely to happen in practice, since the Linux kernel also
+/// uses "volatile" semantics to implement `READ_ONCE`/`WRITE_ONCE`.
+pub trait PodOnce: Pod {}
+
+impl<T: Pod> PodOnce for T where Assert<{ is_pod_once::<T>() }>: IsTrue {}
+
+#[cfg(target_arch = "x86_64")]
+const fn is_pod_once<T: Pod>() -> bool {
+ let size = size_of::<T>();
+
+ size == 1 || size == 2 || size == 4 || size == 8
+}
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -672,3 +762,23 @@ impl<'a> From<&'a mut [u8]> for VmWriter<'a> {
unsafe { Self::from_kernel_space(slice.as_mut_ptr(), slice.len()) }
}
}
+
+/// A marker trait for POD types that can be read or written with one instruction.
+///
+/// We currently rely on this trait to ensure that the memory operation created by
+/// `ptr::read_volatile` and `ptr::write_volatile` doesn't tear. However, the Rust documentation
+/// makes no such guarantee, and even the wording in the LLVM LangRef is ambiguous.
+///
+/// At this point, we can only _hope_ that this doesn't break in future versions of the Rust or
+/// LLVM compilers. However, this is unlikely to happen in practice, since the Linux kernel also
+/// uses "volatile" semantics to implement `READ_ONCE`/`WRITE_ONCE`.
+pub trait PodOnce: Pod {}
+
+impl<T: Pod> PodOnce for T where Assert<{ is_pod_once::<T>() }>: IsTrue {}
+
+#[cfg(target_arch = "x86_64")]
+const fn is_pod_once<T: Pod>() -> bool {
+ let size = size_of::<T>();
+
+ size == 1 || size == 2 || size == 4 || size == 8
+}
diff --git a/ostd/src/mm/mod.rs b/ostd/src/mm/mod.rs
--- a/ostd/src/mm/mod.rs
+++ b/ostd/src/mm/mod.rs
@@ -28,7 +28,7 @@ use spin::Once;
pub use self::{
dma::{Daddr, DmaCoherent, DmaDirection, DmaStream, DmaStreamSlice, HasDaddr},
frame::{options::FrameAllocOptions, Frame, Segment},
- io::{KernelSpace, UserSpace, VmIo, VmReader, VmWriter},
+ io::{KernelSpace, PodOnce, UserSpace, VmIo, VmIoOnce, VmReader, VmWriter},
page_prop::{CachePolicy, PageFlags, PageProperty},
vm_space::VmSpace,
};
diff --git a/ostd/src/mm/mod.rs b/ostd/src/mm/mod.rs
--- a/ostd/src/mm/mod.rs
+++ b/ostd/src/mm/mod.rs
@@ -28,7 +28,7 @@ use spin::Once;
pub use self::{
dma::{Daddr, DmaCoherent, DmaDirection, DmaStream, DmaStreamSlice, HasDaddr},
frame::{options::FrameAllocOptions, Frame, Segment},
- io::{KernelSpace, UserSpace, VmIo, VmReader, VmWriter},
+ io::{KernelSpace, PodOnce, UserSpace, VmIo, VmIoOnce, VmReader, VmWriter},
page_prop::{CachePolicy, PageFlags, PageProperty},
vm_space::VmSpace,
};
|
Another example:
https://github.com/asterinas/asterinas/actions/runs/10104476344/job/27943517035?pr=1030
I found it being reproducible (randomly) locally. And it has nothing to do with Ext2. It seems to be a problem with MicroVM.
It is really easy to reproduce but once you need to debug (via printing or gdb), it is really hard to reproduce. It seems that it occurs lesser if the system is running more slowly (LOL).
I GDBed it with KVM on (can't use breakpoints but can backtrace), I found that it hangs here:
```
(gdb) bt
#0 ostd::sync::spin::SpinLock<core::option::Option<core::mem::manually_drop::ManuallyDrop<ostd::mm::page_table::boot_pt::BootPageTable<ostd::arch::x86::mm::PageTableEntry, ostd::arch::x86::mm::PagingConsts>>>>::acquire_lock<core::option::Option<core::mem::manually_drop::ManuallyDrop<ostd::mm::page_table::boot_pt::BootPageTable<ostd::arch::x86::mm::PageTableEntry, ostd::arch::x86::mm::PagingConsts>>>> (
self=0xffffffff8836e370 <_ZN4ostd2mm14heap_allocator14HEAP_ALLOCATOR17he1684604edc78901E.llvm.13890399637656761890+8>) at src/sync/spin.rs:111
#1 ostd::sync::spin::SpinLock<core::option::Option<core::mem::manually_drop::ManuallyDrop<ostd::mm::page_table::boot_pt::BootPageTable<ostd::arch::x86::mm::PageTableEntry, ostd::arch::x86::mm::PagingConsts>>>>::lock<core::option::Option<core::mem::manually_drop::ManuallyDrop<ostd::mm::page_table::boot_pt::BootPageTable<ostd::arch::x86::mm::PageTableEntry, ostd::arch::x86::mm::PagingConsts>>>> (
self=0xffffffff8836e370 <_ZN4ostd2mm14heap_allocator14HEAP_ALLOCATOR17he1684604edc78901E.llvm.13890399637656761890+8>) at src/sync/spin.rs:74
#2 0xffffffff882765bd in ostd::mm::heap_allocator::{impl#1}::alloc<32> (self=<optimized out>, layout=...) at src/mm/heap_allocator.rs:71
#3 0xffffffff88049bf7 in ostd::mm::heap_allocator::_::__rust_alloc (size=4, align=1) at /root/asterinas/ostd/src/mm/heap_allocator.rs:22
#4 alloc::alloc::alloc (layout=...) at src/alloc.rs:100
#5 alloc::alloc::Global::alloc_impl (layout=..., zeroed=false, self=<optimized out>) at src/alloc.rs:183
#6 alloc::alloc::{impl#1}::allocate (layout=..., self=<optimized out>) at src/alloc.rs:243
#7 alloc::raw_vec::RawVec<u8, alloc::alloc::Global>::try_allocate_in<u8, alloc::alloc::Global> (capacity=4, init=alloc::raw_vec::AllocInit::Uninitialized, alloc=...) at src/raw_vec.rs:230
#8 alloc::raw_vec::RawVec<u8, alloc::alloc::Global>::with_capacity_in<u8, alloc::alloc::Global> (capacity=<optimized out>) at src/raw_vec.rs:158
#9 alloc::vec::Vec<u8, alloc::alloc::Global>::with_capacity_in<u8, alloc::alloc::Global> (capacity=<optimized out>) at src/vec/mod.rs:699
#10 alloc::vec::Vec<u8, alloc::alloc::Global>::with_capacity<u8> (capacity=<optimized out>) at src/vec/mod.rs:481
#11 alloc::string::String::with_capacity () at src/string.rs:492
#12 alloc::fmt::format::format_inner (args=...) at src/fmt.rs:632
#13 0xffffffff8826174f in alloc::fmt::format::{closure#0} () at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/fmt.rs:639
#14 core::option::Option<&str>::map_or_else<&str, alloc::string::String, alloc::fmt::format::{closure_env#0}, fn(&str) -> alloc::string::String> (self=..., default=..., f=<optimized out>)
at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/option.rs:1207
#15 alloc::fmt::format (args=...) at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/fmt.rs:639
#16 ostd::logger::{impl#0}::log (self=<optimized out>, record=0xffff8000ba93d858) at src/logger.rs:37
#17 0xffffffff880e2859 in log::__private_api::log_impl (args=..., level=log::Level::Error, kvs=...) at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/log-0.4.22/src/__private_api.rs:61
#18 log::__private_api::log<()> (args=<error reading variable: Cannot access memory at address 0x20>, target_module_path_and_loc=<optimized out>,
args=<error reading variable: Cannot access memory at address 0x20>, target_module_path_and_loc=<optimized out>)
at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/log-0.4.22/src/__private_api.rs:72
#19 aster_nix::thread::exception::handle_page_fault (vm_space=<optimized out>, trap_info=<optimized out>) at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/log-0.4.22/src/macros.rs:49
#20 0xffffffff8827db32 in ostd::mm::vm_space::VmSpace::handle_page_fault (self=0xffffffff8836e370 <_ZN4ostd2mm14heap_allocator14HEAP_ALLOCATOR17he1684604edc78901E.llvm.13890399637656761890+8>,
info=0xffff8000ba93da00) at src/mm/vm_space.rs:109
#21 ostd::arch::x86::trap::handle_user_page_fault (f=0xffff8000ba93dae0, page_fault_addr=7) at src/arch/x86/trap.rs:86
#22 ostd::arch::x86::trap::trap_handler (f=0xffff8000ba93dae0) at src/arch/x86/trap.rs:54
#23 0xffffffff8829911a in __from_kernel ()
#24 0x0000000000000008 in ?? ()
#25 0x0000000000000000 in ?? ()
```
https://github.com/asterinas/asterinas/issues/1085
It seemed, not reliable
Ok, the previous backtrace I offered is definitely resulted by a kernel mode page fault. After restoring the trapframe in GDB I had a backtrace at the state which the page fault happened:
```
(gdb) bt
#0 core::sync::atomic::atomic_compare_exchange<u8> (dst=0x40, old=0, new=1, success=core::sync::atomic::Ordering::Acquire, failure=core::sync::atomic::Ordering::Relaxed)
at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/sync/atomic.rs:3373
#1 core::sync::atomic::AtomicBool::compare_exchange (self=0x40, current=false, new=true, success=core::sync::atomic::Ordering::Acquire, failure=core::sync::atomic::Ordering::Relaxed)
at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/sync/atomic.rs:811
#2 ostd::sync::spin::SpinLock<core::option::Option<core::mem::manually_drop::ManuallyDrop<ostd::mm::page_table::boot_pt::BootPageTable<ostd::arch::x86::mm::PageTableEntry, ostd::arch::x86::mm::PagingCon:
#3 ostd::sync::spin::SpinLock<core::option::Option<core::mem::manually_drop::ManuallyDrop<ostd::mm::page_table::boot_pt::BootPageTable<ostd::arch::x86::mm::PageTableEntry, ostd::arch::x86::mm::PagingCon
self=0x40) at src/sync/spin.rs:111
#4 ostd::sync::spin::SpinLock<core::option::Option<core::mem::manually_drop::ManuallyDrop<ostd::mm::page_table::boot_pt::BootPageTable<ostd::arch::x86::mm::PageTableEntry, ostd::arch::x86::mm::PagingCon
self=0x40) at src/sync/spin.rs:74
#5 0xffffffff88275edd in ostd::mm::heap_allocator::{impl#1}::alloc<32> (self=<optimized out>, layout=...) at src/mm/heap_allocator.rs:71
#6 0xffffffff88049bf7 in ostd::mm::heap_allocator::_::__rust_alloc (size=4, align=1) at /root/asterinas/ostd/src/mm/heap_allocator.rs:22
#7 alloc::alloc::alloc (layout=...) at src/alloc.rs:100
#8 alloc::alloc::Global::alloc_impl (layout=..., zeroed=false, self=<optimized out>) at src/alloc.rs:183
#9 alloc::alloc::{impl#1}::allocate (layout=..., self=<optimized out>) at src/alloc.rs:243
#10 alloc::raw_vec::RawVec<u8, alloc::alloc::Global>::try_allocate_in<u8, alloc::alloc::Global> (capacity=4, init=alloc::raw_vec::AllocInit::Uninitialized, alloc=...) at src/raw_vec.rs:230
#11 alloc::raw_vec::RawVec<u8, alloc::alloc::Global>::with_capacity_in<u8, alloc::alloc::Global> (capacity=<optimized out>) at src/raw_vec.rs:158
#12 alloc::vec::Vec<u8, alloc::alloc::Global>::with_capacity_in<u8, alloc::alloc::Global> (capacity=<optimized out>) at src/vec/mod.rs:699
#13 alloc::vec::Vec<u8, alloc::alloc::Global>::with_capacity<u8> (capacity=<optimized out>) at src/vec/mod.rs:481
#14 alloc::string::String::with_capacity () at src/string.rs:492
#15 alloc::fmt::format::format_inner (args=...) at src/fmt.rs:632
#16 0xffffffff8826106f in alloc::fmt::format::{closure#0} () at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/fmt.rs:639
#17 core::option::Option<&str>::map_or_else<&str, alloc::string::String, alloc::fmt::format::{closure_env#0}, fn(&str) -> alloc::string::String> (self=..., default=..., f=<optimized out>)
at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/option.rs:1207
#18 alloc::fmt::format (args=...) at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/fmt.rs:639
#19 ostd::logger::{impl#0}::log (self=<optimized out>, record=0xffff8000ba93dbd8) at src/logger.rs:37
#20 0xffffffff881234d9 in log::__private_api::log_impl (args=..., level=log::Level::Error, kvs=...) at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/log-0.4.22/src/__private_api.rs:61
#21 log::__private_api::log<()> (args=<error reading variable: Cannot access memory at address 0x20>, target_module_path_and_loc=<optimized out>,
args=<error reading variable: Cannot access memory at address 0x20>, target_module_path_and_loc=<optimized out>)
at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/log-0.4.22/src/__private_api.rs:72
#22 aster_nix::thread::exception::handle_page_fault (vm_space=<optimized out>, trap_info=<optimized out>) at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/log-0.4.22/src/macros.rs:49
#23 0xffffffff8827617b in buddy_system_allocator::linked_list::{impl#5}::next (self=<optimized out>)
at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/buddy_system_allocator-0.9.1/src/linked_list.rs:137
#24 buddy_system_allocator::Heap<32>::dealloc<32> (ptr=..., layout=..., self=<optimized out>) at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/buddy_system_allocator-0.9.1/src/lib.rs:164
#25 ostd::mm::heap_allocator::{impl#1}::dealloc<32> (self=<optimized out>, ptr=<optimized out>, layout=...) at src/mm/heap_allocator.rs:90
#26 0x080000000000001f in ?? ()
#27 0xffffffff883086b9 in ?? ()
#28 0x0000000000000007 in ?? ()
#29 0xffff8000ba93ddc8 in ?? ()
#30 0xffff80000c389008 in ?? ()
#31 0x0000000000000002 in ?? ()
#32 0x0000000000000000 in ?? ()
```
After user space NULL pointers are checked, I attempted to backtraced the first page fault which leads to a lockout. Here's the stack:
```
(gdb) bt
#0 0xffffffff8825e56b in buddy_system_allocator::linked_list::{impl#5}::next (self=<optimized out>)
at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/buddy_system_allocator-0.9.1/src/linked_list.rs:137
#1 buddy_system_allocator::Heap<32>::dealloc<32> (ptr=..., layout=..., self=<optimized out>) at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/buddy_system_allocator-0.9.1/src/lib.rs:164
#2 ostd::mm::heap_allocator::{impl#1}::dealloc<32> (self=<optimized out>, ptr=<optimized out>, layout=...) at src/mm/heap_allocator.rs:90
#3 0x0000000000000020 in ?? ()
#4 0x0000000000000040 in ?? ()
#5 0x0000000000000001 in ?? ()
#6 0xffffffff8825253b in core::alloc::global::GlobalAlloc::realloc<ostd::mm::heap_allocator::LockedHeapWithRescue<32>> (ptr=0xffff80000c8b1460, layout=..., new_size=18446603336431669952,
self=<optimized out>) at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/alloc/global.rs:271
#7 ostd::mm::heap_allocator::_::__rust_realloc (ptr=0xffff80000c8b1460, size=0, align=18446603339351457464, new_size=18446603336431669952) at src/mm/heap_allocator.rs:22
#8 alloc::alloc::realloc () at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/alloc.rs:138
#9 alloc::alloc::Global::grow_impl (ptr=..., old_layout=..., new_layout=..., zeroed=false, self=<optimized out>)
at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/alloc.rs:215
#10 alloc::alloc::{impl#1}::grow (ptr=..., old_layout=..., new_layout=..., self=<optimized out>)
at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/alloc.rs:268
#11 alloc::raw_vec::finish_grow<alloc::alloc::Global> (new_layout=..., current_memory=..., alloc=<optimized out>)
at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/raw_vec.rs:570
#12 0xffffffff88252628 in alloc::raw_vec::RawVec<u8, alloc::alloc::Global>::grow_amortized<u8, alloc::alloc::Global> (len=<optimized out>, additional=<optimized out>, self=<optimized out>)
at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/raw_vec.rs:485
#13 alloc::raw_vec::{impl#2}::reserve::do_reserve_and_handle<u8, alloc::alloc::Global> (slf=0xffff8000ba93fff0, len=<optimized out>, additional=<optimized out>)
at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/raw_vec.rs:349
#14 0xffffffff882722d2 in alloc::raw_vec::RawVec<u8, alloc::alloc::Global>::reserve<u8, alloc::alloc::Global> (self=<optimized out>, len=<optimized out>, additional=<optimized out>)
at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/raw_vec.rs:355
#15 alloc::vec::Vec<u8, alloc::alloc::Global>::reserve<u8, alloc::alloc::Global> (self=0xffff8000ba93fff0, additional=1)
at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/vec/mod.rs:972
#16 alloc::vec::Vec<u8, alloc::alloc::Global>::append_elements<u8, alloc::alloc::Global> (self=0xffff8000ba93fff0, other=...)
at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/vec/mod.rs:2145
#17 alloc::vec::spec_extend::{impl#4}::spec_extend<u8, alloc::alloc::Global> (self=0xffff8000ba93fff0, iterator=...)
at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/vec/spec_extend.rs:55
#18 alloc::vec::Vec<u8, alloc::alloc::Global>::extend_from_slice<u8, alloc::alloc::Global> (self=0xffff8000ba93fff0, other=...)
at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/vec/mod.rs:2591
#19 alloc::string::String::push_str () at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/string.rs:1067
#20 alloc::string::{impl#58}::write_str (self=0xffff8000ba93fff0, s=...) at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/string.rs:2921
#21 0xffffffff88228d7f in core::fmt::num::imp::fmt_u64 (n=<optimized out>, is_nonnegative=true, f=<optimized out>) at src/fmt/num.rs:278
#22 core::fmt::num::imp::{impl#7}::fmt (self=<optimized out>, f=0x20) at src/fmt/num.rs:324
#23 0xffffffff8822453c in core::fmt::rt::Argument::fmt (self=0xffff8000ba940118, f=0xffff8000ba93ff68) at src/fmt/rt.rs:165
#24 core::fmt::write (output=..., args=...) at src/fmt/mod.rs:1168
#25 0xffffffff88273238 in core::fmt::Formatter::write_fmt (fmt=..., self=<optimized out>)
at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/fmt/mod.rs:1640
#26 core::panic::panic_info::{impl#3}::fmt (self=0xffff8000ba9400b8, formatter=<optimized out>)
at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/panic/panic_info.rs:180
#27 alloc::string::{impl#32}::to_string<core::panic::panic_info::PanicMessage> (self=0xffff8000ba9400b8)
at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/string.rs:2562
#28 ostd::panicking::panic_handler (info=0xffff8000ba9400b8) at src/panicking.rs:33
#29 0xffffffff8821c946 in asterinas_osdk_bin::panic (info=0x20) at src/main.rs:11
#30 0xffffffff8822c3bf in core::panicking::panic_fmt (fmt=...) at src/panicking.rs:74
#31 0xffffffff8822c5ef in core::panicking::panic_bounds_check (index=57088, len=2) at src/panicking.rs:276
#32 0xffffffff881f38b5 in core::slice::index::{impl#2}::index_mut<aster_util::safe_ptr::SafePtr<aster_virtio::queue::Descriptor, ostd::mm::dma::dma_coherent::DmaCoherent, aster_rights::TRightSet<typeflags_util::set::Cons<aster_rights::Signal, typeflags_util::set::Cons<aster_rights::Exec, typeflags_util::set::Cons<aster_rights::Write, typeflags_util::set::Cons<aster_rights::Read, typeflags_util::set::Cons<aster_rights::Dup, typeflags_util::set::Nil>>>>>>>> (self=57088, slice=...)
at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/slice/index.rs:298
#33 core::slice::index::{impl#1}::index_mut<aster_util::safe_ptr::SafePtr<aster_virtio::queue::Descriptor, ostd::mm::dma::dma_coherent::DmaCoherent, aster_rights::TRightSet<typeflags_util::set::Cons<ast--Type <RET> for more, q to quit, c to continue without paging--
er_rights::Signal, typeflags_util::set::Cons<aster_rights::Exec, typeflags_util::set::Cons<aster_rights::Write, typeflags_util::set::Cons<aster_rights::Read, typeflags_util::set::Cons<aster_rights::Dup, typeflags_util::set::Nil>>>>>>>, usize> (self=..., index=<optimized out>)
at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/slice/index.rs:27
#34 alloc::vec::{impl#14}::index_mut<aster_util::safe_ptr::SafePtr<aster_virtio::queue::Descriptor, ostd::mm::dma::dma_coherent::DmaCoherent, aster_rights::TRightSet<typeflags_util::set::Cons<aster_rights::Signal, typeflags_util::set::Cons<aster_rights::Exec, typeflags_util::set::Cons<aster_rights::Write, typeflags_util::set::Cons<aster_rights::Read, typeflags_util::set::Cons<aster_rights::Dup, typeflags_util::set::Nil>>>>>>>, usize, alloc::alloc::Global> (index=57088, self=<optimized out>)
at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/vec/mod.rs:2917
#35 aster_virtio::queue::VirtQueue::recycle_descriptors (self=<optimized out>, head=<optimized out>) at src/queue.rs:248
#36 0xffffffff881f3b90 in aster_virtio::queue::VirtQueue::pop_used (self=0xffffffff88469258 <ostd::mm::heap_allocator::HEAP_SPACE+1032710>) at src/queue.rs:286
#37 0xffffffff8821a0df in aster_virtio::device::console::device::ConsoleDevice::handle_recv_irq (self=0xffffffff88469210 <ostd::mm::heap_allocator::HEAP_SPACE+1032638>)
at src/device/console/device.rs:134
#38 aster_virtio::device::console::device::{impl#2}::init::{closure#0} () at src/device/console/device.rs:115
#39 0xffffffff8821a4ca in alloc::boxed::{impl#50}::call<(&trapframe::arch::trap::TrapFrame), (dyn core::ops::function::Fn<(&trapframe::arch::trap::TrapFrame), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=<optimized out>, args=...) at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2076
#40 aster_virtio::transport::mmio::multiplex::{impl#0}::new::{closure#0} (trap_frame=0xffff8000ba940510) at src/transport/mmio/multiplex.rs:56
#41 0xffffffff88256e0a in alloc::boxed::{impl#50}::call<(&trapframe::arch::trap::TrapFrame), (dyn core::ops::function::Fn<(&trapframe::arch::trap::TrapFrame), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=<optimized out>, args=...) at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2076
#42 ostd::arch::x86::irq::CallbackElement::call (self=<optimized out>, element=0xffff8000ba940510) at src/arch/x86/irq.rs:68
#43 ostd::trap::handler::call_irq_callback_functions (trap_frame=0xffff8000ba940510, irq_number=38) at src/trap/handler.rs:19
#44 0xffffffff88255c03 in ostd::arch::x86::trap::trap_handler (f=0x20) at src/arch/x86/trap.rs:68
#45 0xffffffff882966de in __from_kernel ()
#46 0x0000000000000000 in ?? ()
```
A further dig:
```
0xffffffff8825e565 <_ZN108_$LT$ostd..mm..heap_allocator..LockedHeapWithRescue$LT$_$GT$$u20$as$u20$core..alloc..global..GlobalAlloc$GT$7dealloc17hac09483596a107acE+245>: mov %r15,%r10
0xffffffff8825e568 <_ZN108_$LT$ostd..mm..heap_allocator..LockedHeapWithRescue$LT$_$GT$$u20$as$u20$core..alloc..global..GlobalAlloc$GT$7dealloc17hac09483596a107acE+248>: mov %rsi,%r15
=> 0xffffffff8825e56b <_ZN108_$LT$ostd..mm..heap_allocator..LockedHeapWithRescue$LT$_$GT$$u20$as$u20$core..alloc..global..GlobalAlloc$GT$7dealloc17hac09483596a107acE+251>: mov (%rsi),%r11
```
The PF happened at `0xffffffff8825e56b`, but in the trapframe, `$rsi=0xe0`, `$r15=0xe0`, `r10=0xffff80000c8b92a0`, which absolutely makes no sense.
I've noticed that the issue is connected to the heap allocator. As a result, I think it could be the same problem as issue #1085. Can you try making the changes described in the `Additional context`? However, I'm not sure if this will solve the problem.
Update: The problem described in #1085 does not seem to be related to PF, and may not be the same issue.
The root cause is:
```
panicked at /root/asterinas/kernel/comps/virtio/src/queue.rs:248:39:
index out of bounds: the len is 2 but the index is 768
```
It only happens randomly in MicroVM.
Such a panic results in a failing heap allocation, which in turn causes the kernel to hang.
@sdww0 Do you have ideas about why the virtio queue driver failed?
> The root cause is:
>
> ```
> panicked at /root/asterinas/kernel/comps/virtio/src/queue.rs:248:39:
> index out of bounds: the len is 2 but the index is 768
> ```
>
> It only happens randomly in MicroVM.
>
> Such a panic results in a failing heap allocation, which in turn causes the kernel to hang.
>
> @sdww0 Do you have ideas about why the virtio queue driver failed?
The only device that set the queue size to 2 is the console device. I think it is the [send function](https://github.com/asterinas/asterinas/blob/main/kernel/comps/virtio/src/device/console/device.rs#L34) cause this problem when calling `pop_used` (Since Github CI receive no input):
```rust
impl AnyConsoleDevice for ConsoleDevice {
fn send(&self, value: &[u8]) {
let mut transmit_queue = self.transmit_queue.lock_irq_disabled();
let mut reader = VmReader::from(value);
while reader.remain() > 0 {
let mut writer = self.send_buffer.writer().unwrap();
let len = writer.write(&mut reader);
self.send_buffer.sync(0..len).unwrap();
let slice = DmaStreamSlice::new(&self.send_buffer, 0, len);
transmit_queue.add_dma_buf(&[&slice], &[]).unwrap();
if transmit_queue.should_notify() {
transmit_queue.notify();
}
while !transmit_queue.can_pop() {
spin_loop();
}
transmit_queue.pop_used().unwrap();
}
}
fn register_callback(&self, callback: &'static ConsoleCallback) {
self.callbacks.write_irq_disabled().push(callback);
}
}
```
`send` -> `pop_used` -> `recycle_descriptor` -> `panic`
> `send` -> `pop_used` -> `recycle_descriptor` -> `panic`
The call chain should be `handle_recv_irq` -> `pop_used` -> `recycle_descriptor` -> `panic`. The call chain can be discovered in https://github.com/asterinas/asterinas/issues/1089#issuecomment-2253719767, which is the backtrace in one failure case.
Here is another CI failure after https://github.com/asterinas/asterinas/pull/1103:
https://github.com/asterinas/asterinas/actions/runs/10146669825/job/28055276772?pr=1109
> panicked at /__w/asterinas/asterinas/kernel/comps/virtio/src/queue.rs:248:39:
index out of bounds: the len is 2 but the index is 512
printing stack trace:
Unfortunately, the stack traces are still not available.
https://github.com/asterinas/asterinas/actions/runs/10155075478/job/28081230243
Yes the CI reproduced the error. Reopening.
I checked the assembly code and suspect that https://github.com/asterinas/asterinas/pull/1112 will fix the root cause. At least I can no longer reproduce the problem locally.
|
2024-07-30T04:20:46Z
|
562e64437584279783f244edba10b512beddc81d
|
asterinas/asterinas
|
diff --git a/ostd/src/panicking.rs b/ostd/src/panicking.rs
--- a/ostd/src/panicking.rs
+++ b/ostd/src/panicking.rs
@@ -29,17 +23,22 @@ use unwinding::{
/// panic handler in the binary crate.
#[export_name = "__aster_panic_handler"]
pub fn panic_handler(info: &core::panic::PanicInfo) -> ! {
- let throw_info = ostd_test::PanicInfo {
- message: info.message().to_string(),
- file: info.location().unwrap().file().to_string(),
- line: info.location().unwrap().line() as usize,
- col: info.location().unwrap().column() as usize,
- };
- // Throw an exception and expecting it to be caught.
- begin_panic(Box::new(throw_info.clone()));
- // If the exception is not caught (e.g. by ktest) and resumed,
- // then print the information and abort.
- error!("Uncaught panic!");
+ // If in ktest, we would like to catch the panics and resume the test.
+ #[cfg(ktest)]
+ {
+ use alloc::{boxed::Box, string::ToString};
+
+ use unwinding::panic::begin_panic;
+
+ let throw_info = ostd_test::PanicInfo {
+ message: info.message().to_string(),
+ file: info.location().unwrap().file().to_string(),
+ line: info.location().unwrap().line() as usize,
+ col: info.location().unwrap().column() as usize,
+ };
+ // Throw an exception and expecting it to be caught.
+ begin_panic(Box::new(throw_info.clone()));
+ }
early_println!("{}", info);
early_println!("printing stack trace:");
print_stack_trace();
|
[
"1089"
] |
0.6
|
e83e1fc01ba38ad2a405d7d710ec7258fb664f60
|
Syscall test at Ext2, MicroVM occasionally fails
<!-- Thank you for taking the time to report a bug. Your input is valuable to us.
Please replace all the <angle brackets> below with your own information. -->
### Describe the bug
<!-- A clear and concise description of what the bug is. -->
### To Reproduce
<!-- Steps to reproduce the behavior. Example:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error -->
In CI, the syscall test at Ext2, MicroVM randomly output bad characters and then hang without panicking. There are some runs that seemed irrelevant with the PR modification:
https://github.com/asterinas/asterinas/actions/runs/10053473151/job/27786308763?pr=1088
https://github.com/asterinas/asterinas/actions/runs/10021055466/job/27699299104
They would pass the syscall test at ramfs (linux boot, normal VM), and then fail at Ext2, MicroVM.
### Logs
<!-- If applicable, add log snippets or files to help explain and debug the problem. Please use code blocks (```) to format logs. -->
<!-- Once again, thank you for helping us improve our project! -->
The log would look like this:
```
[Bn �731ns] : p�b ����l ��� R<�����p�1����� protected range is not fully mappedp hk ��� "}
```
|
asterinas__asterinas-1103
| 1,103
|
diff --git a/docs/src/kernel/advanced-instructions.md b/docs/src/kernel/advanced-instructions.md
--- a/docs/src/kernel/advanced-instructions.md
+++ b/docs/src/kernel/advanced-instructions.md
@@ -93,3 +93,6 @@ Your previous launch configs will be restored after the server is down.
Press `F5`(Run and Debug) to start a debug session via VS Code.
Click `Continue`(or, press `F5`) at the fisrt break to resume the paused server instance,
then it will continue until reaching your first breakpoint.
+
+Note that if debugging with KVM enabled, you must use hardware assisted breakpoints. See "hbreak" in
+[the GDB manual](https://ftp.gnu.org/old-gnu/Manuals/gdb/html_node/gdb_28.html) for details.
diff --git a/docs/src/kernel/advanced-instructions.md b/docs/src/kernel/advanced-instructions.md
--- a/docs/src/kernel/advanced-instructions.md
+++ b/docs/src/kernel/advanced-instructions.md
@@ -93,3 +93,6 @@ Your previous launch configs will be restored after the server is down.
Press `F5`(Run and Debug) to start a debug session via VS Code.
Click `Continue`(or, press `F5`) at the fisrt break to resume the paused server instance,
then it will continue until reaching your first breakpoint.
+
+Note that if debugging with KVM enabled, you must use hardware assisted breakpoints. See "hbreak" in
+[the GDB manual](https://ftp.gnu.org/old-gnu/Manuals/gdb/html_node/gdb_28.html) for details.
diff --git a/kernel/aster-nix/src/syscall/read.rs b/kernel/aster-nix/src/syscall/read.rs
--- a/kernel/aster-nix/src/syscall/read.rs
+++ b/kernel/aster-nix/src/syscall/read.rs
@@ -1,5 +1,7 @@
// SPDX-License-Identifier: MPL-2.0
+use core::cmp::min;
+
use super::SyscallReturn;
use crate::{fs::file_table::FileDesc, prelude::*, util::write_bytes_to_user};
diff --git a/kernel/aster-nix/src/syscall/read.rs b/kernel/aster-nix/src/syscall/read.rs
--- a/kernel/aster-nix/src/syscall/read.rs
+++ b/kernel/aster-nix/src/syscall/read.rs
@@ -1,5 +1,7 @@
// SPDX-License-Identifier: MPL-2.0
+use core::cmp::min;
+
use super::SyscallReturn;
use crate::{fs::file_table::FileDesc, prelude::*, util::write_bytes_to_user};
diff --git a/kernel/aster-nix/src/syscall/read.rs b/kernel/aster-nix/src/syscall/read.rs
--- a/kernel/aster-nix/src/syscall/read.rs
+++ b/kernel/aster-nix/src/syscall/read.rs
@@ -15,8 +17,20 @@ pub fn sys_read(fd: FileDesc, user_buf_addr: Vaddr, buf_len: usize) -> Result<Sy
file_table.get_file(fd)?.clone()
};
- let mut read_buf = vec![0u8; buf_len];
- let read_len = file.read(&mut read_buf)?;
- write_bytes_to_user(user_buf_addr, &mut VmReader::from(read_buf.as_slice()))?;
+ // According to <https://man7.org/linux/man-pages/man2/read.2.html>, if
+ // the user specified an empty buffer, we should detect errors by checking
+ // the file discriptor. If no errors detected, return 0 successfully.
+ let read_len = if buf_len != 0 {
+ let mut read_buf = vec![0u8; buf_len];
+ let read_len = file.read(&mut read_buf)?;
+ write_bytes_to_user(
+ user_buf_addr,
+ &mut VmReader::from(&read_buf[..min(read_len, buf_len)]),
+ )?;
+ read_len
+ } else {
+ file.read(&mut [])?
+ };
+
Ok(SyscallReturn::Return(read_len as _))
}
diff --git a/kernel/aster-nix/src/syscall/read.rs b/kernel/aster-nix/src/syscall/read.rs
--- a/kernel/aster-nix/src/syscall/read.rs
+++ b/kernel/aster-nix/src/syscall/read.rs
@@ -15,8 +17,20 @@ pub fn sys_read(fd: FileDesc, user_buf_addr: Vaddr, buf_len: usize) -> Result<Sy
file_table.get_file(fd)?.clone()
};
- let mut read_buf = vec![0u8; buf_len];
- let read_len = file.read(&mut read_buf)?;
- write_bytes_to_user(user_buf_addr, &mut VmReader::from(read_buf.as_slice()))?;
+ // According to <https://man7.org/linux/man-pages/man2/read.2.html>, if
+ // the user specified an empty buffer, we should detect errors by checking
+ // the file discriptor. If no errors detected, return 0 successfully.
+ let read_len = if buf_len != 0 {
+ let mut read_buf = vec![0u8; buf_len];
+ let read_len = file.read(&mut read_buf)?;
+ write_bytes_to_user(
+ user_buf_addr,
+ &mut VmReader::from(&read_buf[..min(read_len, buf_len)]),
+ )?;
+ read_len
+ } else {
+ file.read(&mut [])?
+ };
+
Ok(SyscallReturn::Return(read_len as _))
}
diff --git a/kernel/aster-nix/src/syscall/write.rs b/kernel/aster-nix/src/syscall/write.rs
--- a/kernel/aster-nix/src/syscall/write.rs
+++ b/kernel/aster-nix/src/syscall/write.rs
@@ -20,9 +20,17 @@ pub fn sys_write(fd: FileDesc, user_buf_ptr: Vaddr, user_buf_len: usize) -> Resu
file_table.get_file(fd)?.clone()
};
- let mut buffer = vec![0u8; user_buf_len];
- read_bytes_from_user(user_buf_ptr, &mut VmWriter::from(buffer.as_mut_slice()))?;
- debug!("write content = {:?}", buffer);
- let write_len = file.write(&buffer)?;
+ // According to <https://man7.org/linux/man-pages/man2/write.2.html>, if
+ // the user specified an empty buffer, we should detect errors by checking
+ // the file discriptor. If no errors detected, return 0 successfully.
+ let write_len = if user_buf_len != 0 {
+ let mut buffer = vec![0u8; user_buf_len];
+ read_bytes_from_user(user_buf_ptr, &mut VmWriter::from(buffer.as_mut_slice()))?;
+ debug!("write content = {:?}", buffer);
+ file.write(&buffer)?
+ } else {
+ file.write(&[])?
+ };
+
Ok(SyscallReturn::Return(write_len as _))
}
diff --git a/kernel/aster-nix/src/syscall/write.rs b/kernel/aster-nix/src/syscall/write.rs
--- a/kernel/aster-nix/src/syscall/write.rs
+++ b/kernel/aster-nix/src/syscall/write.rs
@@ -20,9 +20,17 @@ pub fn sys_write(fd: FileDesc, user_buf_ptr: Vaddr, user_buf_len: usize) -> Resu
file_table.get_file(fd)?.clone()
};
- let mut buffer = vec![0u8; user_buf_len];
- read_bytes_from_user(user_buf_ptr, &mut VmWriter::from(buffer.as_mut_slice()))?;
- debug!("write content = {:?}", buffer);
- let write_len = file.write(&buffer)?;
+ // According to <https://man7.org/linux/man-pages/man2/write.2.html>, if
+ // the user specified an empty buffer, we should detect errors by checking
+ // the file discriptor. If no errors detected, return 0 successfully.
+ let write_len = if user_buf_len != 0 {
+ let mut buffer = vec![0u8; user_buf_len];
+ read_bytes_from_user(user_buf_ptr, &mut VmWriter::from(buffer.as_mut_slice()))?;
+ debug!("write content = {:?}", buffer);
+ file.write(&buffer)?
+ } else {
+ file.write(&[])?
+ };
+
Ok(SyscallReturn::Return(write_len as _))
}
diff --git a/kernel/aster-nix/src/util/mod.rs b/kernel/aster-nix/src/util/mod.rs
--- a/kernel/aster-nix/src/util/mod.rs
+++ b/kernel/aster-nix/src/util/mod.rs
@@ -15,15 +15,25 @@ pub mod random;
pub use iovec::{copy_iovs_from_user, IoVec};
-/// Reads bytes into the `dest` `VmWriter`
-/// from the user space of the current process.
+/// Reads bytes into the destination `VmWriter` from the user space of the
+/// current process.
///
-/// If the reading is completely successful, returns `Ok`.
-/// Otherwise, returns `Err`.
+/// If the reading is completely successful, returns `Ok`. Otherwise, it
+/// returns `Err`.
+///
+/// If the destination `VmWriter` (`dest`) is empty, this function still
+/// checks if the current task and user space are available. If they are,
+/// it returns `Ok`.
///
/// TODO: this API can be discarded and replaced with the API of `VmReader`
/// after replacing all related `buf` usages.
pub fn read_bytes_from_user(src: Vaddr, dest: &mut VmWriter<'_>) -> Result<()> {
+ let copy_len = dest.avail();
+
+ if copy_len > 0 {
+ check_vaddr(src)?;
+ }
+
let current_task = current_task().ok_or(Error::with_message(
Errno::EFAULT,
"the current task is missing",
diff --git a/kernel/aster-nix/src/util/mod.rs b/kernel/aster-nix/src/util/mod.rs
--- a/kernel/aster-nix/src/util/mod.rs
+++ b/kernel/aster-nix/src/util/mod.rs
@@ -15,15 +15,25 @@ pub mod random;
pub use iovec::{copy_iovs_from_user, IoVec};
-/// Reads bytes into the `dest` `VmWriter`
-/// from the user space of the current process.
+/// Reads bytes into the destination `VmWriter` from the user space of the
+/// current process.
///
-/// If the reading is completely successful, returns `Ok`.
-/// Otherwise, returns `Err`.
+/// If the reading is completely successful, returns `Ok`. Otherwise, it
+/// returns `Err`.
+///
+/// If the destination `VmWriter` (`dest`) is empty, this function still
+/// checks if the current task and user space are available. If they are,
+/// it returns `Ok`.
///
/// TODO: this API can be discarded and replaced with the API of `VmReader`
/// after replacing all related `buf` usages.
pub fn read_bytes_from_user(src: Vaddr, dest: &mut VmWriter<'_>) -> Result<()> {
+ let copy_len = dest.avail();
+
+ if copy_len > 0 {
+ check_vaddr(src)?;
+ }
+
let current_task = current_task().ok_or(Error::with_message(
Errno::EFAULT,
"the current task is missing",
diff --git a/kernel/aster-nix/src/util/mod.rs b/kernel/aster-nix/src/util/mod.rs
--- a/kernel/aster-nix/src/util/mod.rs
+++ b/kernel/aster-nix/src/util/mod.rs
@@ -32,16 +42,18 @@ pub fn read_bytes_from_user(src: Vaddr, dest: &mut VmWriter<'_>) -> Result<()> {
Errno::EFAULT,
"the user space is missing",
))?;
- let copy_len = dest.avail();
let mut user_reader = user_space.vm_space().reader(src, copy_len)?;
user_reader.read_fallible(dest).map_err(|err| err.0)?;
Ok(())
}
-/// Reads a value of `Pod` type
-/// from the user space of the current process.
+/// Reads a value typed `Pod` from the user space of the current process.
pub fn read_val_from_user<T: Pod>(src: Vaddr) -> Result<T> {
+ if core::mem::size_of::<T>() > 0 {
+ check_vaddr(src)?;
+ }
+
let current_task = current_task().ok_or(Error::with_message(
Errno::EFAULT,
"the current task is missing",
diff --git a/kernel/aster-nix/src/util/mod.rs b/kernel/aster-nix/src/util/mod.rs
--- a/kernel/aster-nix/src/util/mod.rs
+++ b/kernel/aster-nix/src/util/mod.rs
@@ -32,16 +42,18 @@ pub fn read_bytes_from_user(src: Vaddr, dest: &mut VmWriter<'_>) -> Result<()> {
Errno::EFAULT,
"the user space is missing",
))?;
- let copy_len = dest.avail();
let mut user_reader = user_space.vm_space().reader(src, copy_len)?;
user_reader.read_fallible(dest).map_err(|err| err.0)?;
Ok(())
}
-/// Reads a value of `Pod` type
-/// from the user space of the current process.
+/// Reads a value typed `Pod` from the user space of the current process.
pub fn read_val_from_user<T: Pod>(src: Vaddr) -> Result<T> {
+ if core::mem::size_of::<T>() > 0 {
+ check_vaddr(src)?;
+ }
+
let current_task = current_task().ok_or(Error::with_message(
Errno::EFAULT,
"the current task is missing",
diff --git a/kernel/aster-nix/src/util/mod.rs b/kernel/aster-nix/src/util/mod.rs
--- a/kernel/aster-nix/src/util/mod.rs
+++ b/kernel/aster-nix/src/util/mod.rs
@@ -57,15 +69,25 @@ pub fn read_val_from_user<T: Pod>(src: Vaddr) -> Result<T> {
Ok(user_reader.read_val()?)
}
-/// Writes bytes from the `src` `VmReader`
-/// to the user space of the current process.
+/// Writes bytes from the source `VmReader` to the user space of the current
+/// process.
+///
+/// If the writing is completely successful, returns `Ok`. Otherwise, it
+/// returns `Err`.
///
-/// If the writing is completely successful, returns `Ok`,
-/// Otherwise, returns `Err`.
+/// If the source `VmReader` (`src`) is empty, this function still checks if
+/// the current task and user space are available. If they are, it returns
+/// `Ok`.
///
/// TODO: this API can be discarded and replaced with the API of `VmWriter`
/// after replacing all related `buf` usages.
pub fn write_bytes_to_user(dest: Vaddr, src: &mut VmReader<'_, KernelSpace>) -> Result<()> {
+ let copy_len = src.remain();
+
+ if copy_len > 0 {
+ check_vaddr(dest)?;
+ }
+
let current_task = current_task().ok_or(Error::with_message(
Errno::EFAULT,
"the current task is missing",
diff --git a/kernel/aster-nix/src/util/mod.rs b/kernel/aster-nix/src/util/mod.rs
--- a/kernel/aster-nix/src/util/mod.rs
+++ b/kernel/aster-nix/src/util/mod.rs
@@ -57,15 +69,25 @@ pub fn read_val_from_user<T: Pod>(src: Vaddr) -> Result<T> {
Ok(user_reader.read_val()?)
}
-/// Writes bytes from the `src` `VmReader`
-/// to the user space of the current process.
+/// Writes bytes from the source `VmReader` to the user space of the current
+/// process.
+///
+/// If the writing is completely successful, returns `Ok`. Otherwise, it
+/// returns `Err`.
///
-/// If the writing is completely successful, returns `Ok`,
-/// Otherwise, returns `Err`.
+/// If the source `VmReader` (`src`) is empty, this function still checks if
+/// the current task and user space are available. If they are, it returns
+/// `Ok`.
///
/// TODO: this API can be discarded and replaced with the API of `VmWriter`
/// after replacing all related `buf` usages.
pub fn write_bytes_to_user(dest: Vaddr, src: &mut VmReader<'_, KernelSpace>) -> Result<()> {
+ let copy_len = src.remain();
+
+ if copy_len > 0 {
+ check_vaddr(dest)?;
+ }
+
let current_task = current_task().ok_or(Error::with_message(
Errno::EFAULT,
"the current task is missing",
diff --git a/kernel/aster-nix/src/util/mod.rs b/kernel/aster-nix/src/util/mod.rs
--- a/kernel/aster-nix/src/util/mod.rs
+++ b/kernel/aster-nix/src/util/mod.rs
@@ -74,7 +96,6 @@ pub fn write_bytes_to_user(dest: Vaddr, src: &mut VmReader<'_, KernelSpace>) ->
Errno::EFAULT,
"the user space is missing",
))?;
- let copy_len = src.remain();
let mut user_writer = user_space.vm_space().writer(dest, copy_len)?;
user_writer.write_fallible(src).map_err(|err| err.0)?;
diff --git a/kernel/aster-nix/src/util/mod.rs b/kernel/aster-nix/src/util/mod.rs
--- a/kernel/aster-nix/src/util/mod.rs
+++ b/kernel/aster-nix/src/util/mod.rs
@@ -74,7 +96,6 @@ pub fn write_bytes_to_user(dest: Vaddr, src: &mut VmReader<'_, KernelSpace>) ->
Errno::EFAULT,
"the user space is missing",
))?;
- let copy_len = src.remain();
let mut user_writer = user_space.vm_space().writer(dest, copy_len)?;
user_writer.write_fallible(src).map_err(|err| err.0)?;
diff --git a/kernel/aster-nix/src/util/mod.rs b/kernel/aster-nix/src/util/mod.rs
--- a/kernel/aster-nix/src/util/mod.rs
+++ b/kernel/aster-nix/src/util/mod.rs
@@ -83,6 +104,10 @@ pub fn write_bytes_to_user(dest: Vaddr, src: &mut VmReader<'_, KernelSpace>) ->
/// Writes `val` to the user space of the current process.
pub fn write_val_to_user<T: Pod>(dest: Vaddr, val: &T) -> Result<()> {
+ if core::mem::size_of::<T>() > 0 {
+ check_vaddr(dest)?;
+ }
+
let current_task = current_task().ok_or(Error::with_message(
Errno::EFAULT,
"the current task is missing",
diff --git a/kernel/aster-nix/src/util/mod.rs b/kernel/aster-nix/src/util/mod.rs
--- a/kernel/aster-nix/src/util/mod.rs
+++ b/kernel/aster-nix/src/util/mod.rs
@@ -83,6 +104,10 @@ pub fn write_bytes_to_user(dest: Vaddr, src: &mut VmReader<'_, KernelSpace>) ->
/// Writes `val` to the user space of the current process.
pub fn write_val_to_user<T: Pod>(dest: Vaddr, val: &T) -> Result<()> {
+ if core::mem::size_of::<T>() > 0 {
+ check_vaddr(dest)?;
+ }
+
let current_task = current_task().ok_or(Error::with_message(
Errno::EFAULT,
"the current task is missing",
diff --git a/kernel/aster-nix/src/util/mod.rs b/kernel/aster-nix/src/util/mod.rs
--- a/kernel/aster-nix/src/util/mod.rs
+++ b/kernel/aster-nix/src/util/mod.rs
@@ -107,6 +132,10 @@ pub fn write_val_to_user<T: Pod>(dest: Vaddr, val: &T) -> Result<()> {
/// The original Linux implementation can be found at:
/// <https://elixir.bootlin.com/linux/v6.0.9/source/lib/strncpy_from_user.c#L28>
pub fn read_cstring_from_user(addr: Vaddr, max_len: usize) -> Result<CString> {
+ if max_len > 0 {
+ check_vaddr(addr)?;
+ }
+
let current = current!();
let vmar = current.root_vmar();
read_cstring_from_vmar(vmar, addr, max_len)
diff --git a/kernel/aster-nix/src/util/mod.rs b/kernel/aster-nix/src/util/mod.rs
--- a/kernel/aster-nix/src/util/mod.rs
+++ b/kernel/aster-nix/src/util/mod.rs
@@ -107,6 +132,10 @@ pub fn write_val_to_user<T: Pod>(dest: Vaddr, val: &T) -> Result<()> {
/// The original Linux implementation can be found at:
/// <https://elixir.bootlin.com/linux/v6.0.9/source/lib/strncpy_from_user.c#L28>
pub fn read_cstring_from_user(addr: Vaddr, max_len: usize) -> Result<CString> {
+ if max_len > 0 {
+ check_vaddr(addr)?;
+ }
+
let current = current!();
let vmar = current.root_vmar();
read_cstring_from_vmar(vmar, addr, max_len)
diff --git a/kernel/aster-nix/src/util/mod.rs b/kernel/aster-nix/src/util/mod.rs
--- a/kernel/aster-nix/src/util/mod.rs
+++ b/kernel/aster-nix/src/util/mod.rs
@@ -114,6 +143,10 @@ pub fn read_cstring_from_user(addr: Vaddr, max_len: usize) -> Result<CString> {
/// Read CString from `vmar`. If possible, use `read_cstring_from_user` instead.
pub fn read_cstring_from_vmar(vmar: &Vmar<Full>, addr: Vaddr, max_len: usize) -> Result<CString> {
+ if max_len > 0 {
+ check_vaddr(addr)?;
+ }
+
let mut buffer: Vec<u8> = Vec::with_capacity(max_len);
let mut cur_addr = addr;
diff --git a/kernel/aster-nix/src/util/mod.rs b/kernel/aster-nix/src/util/mod.rs
--- a/kernel/aster-nix/src/util/mod.rs
+++ b/kernel/aster-nix/src/util/mod.rs
@@ -114,6 +143,10 @@ pub fn read_cstring_from_user(addr: Vaddr, max_len: usize) -> Result<CString> {
/// Read CString from `vmar`. If possible, use `read_cstring_from_user` instead.
pub fn read_cstring_from_vmar(vmar: &Vmar<Full>, addr: Vaddr, max_len: usize) -> Result<CString> {
+ if max_len > 0 {
+ check_vaddr(addr)?;
+ }
+
let mut buffer: Vec<u8> = Vec::with_capacity(max_len);
let mut cur_addr = addr;
diff --git a/kernel/aster-nix/src/util/mod.rs b/kernel/aster-nix/src/util/mod.rs
--- a/kernel/aster-nix/src/util/mod.rs
+++ b/kernel/aster-nix/src/util/mod.rs
@@ -175,3 +208,24 @@ const fn has_zero(value: usize) -> bool {
value.wrapping_sub(ONE_BITS) & !value & HIGH_BITS != 0
}
+
+/// Check if the user space pointer is below the lowest userspace address.
+///
+/// If a pointer is below the lowest userspace address, it is likely to be a
+/// NULL pointer. Reading from or writing to a NULL pointer should trigger a
+/// segmentation fault.
+///
+/// If it is not checked here, a kernel page fault will happen and we would
+/// deny the access in the page fault handler either. It may save a page fault
+/// in some occasions. More importantly, double page faults may not be handled
+/// quite well on some platforms.
+fn check_vaddr(va: Vaddr) -> Result<()> {
+ if va < crate::vm::vmar::ROOT_VMAR_LOWEST_ADDR {
+ Err(Error::with_message(
+ Errno::EFAULT,
+ "Bad user space pointer specified",
+ ))
+ } else {
+ Ok(())
+ }
+}
diff --git a/kernel/aster-nix/src/util/mod.rs b/kernel/aster-nix/src/util/mod.rs
--- a/kernel/aster-nix/src/util/mod.rs
+++ b/kernel/aster-nix/src/util/mod.rs
@@ -175,3 +208,24 @@ const fn has_zero(value: usize) -> bool {
value.wrapping_sub(ONE_BITS) & !value & HIGH_BITS != 0
}
+
+/// Check if the user space pointer is below the lowest userspace address.
+///
+/// If a pointer is below the lowest userspace address, it is likely to be a
+/// NULL pointer. Reading from or writing to a NULL pointer should trigger a
+/// segmentation fault.
+///
+/// If it is not checked here, a kernel page fault will happen and we would
+/// deny the access in the page fault handler either. It may save a page fault
+/// in some occasions. More importantly, double page faults may not be handled
+/// quite well on some platforms.
+fn check_vaddr(va: Vaddr) -> Result<()> {
+ if va < crate::vm::vmar::ROOT_VMAR_LOWEST_ADDR {
+ Err(Error::with_message(
+ Errno::EFAULT,
+ "Bad user space pointer specified",
+ ))
+ } else {
+ Ok(())
+ }
+}
diff --git a/kernel/aster-nix/src/vm/vmar/mod.rs b/kernel/aster-nix/src/vm/vmar/mod.rs
--- a/kernel/aster-nix/src/vm/vmar/mod.rs
+++ b/kernel/aster-nix/src/vm/vmar/mod.rs
@@ -123,7 +123,7 @@ impl VmarInner {
}
}
-const ROOT_VMAR_LOWEST_ADDR: Vaddr = 0x001_0000; // 64 KiB is the Linux configurable default
+pub const ROOT_VMAR_LOWEST_ADDR: Vaddr = 0x001_0000; // 64 KiB is the Linux configurable default
const ROOT_VMAR_CAP_ADDR: Vaddr = MAX_USERSPACE_VADDR;
impl Interval<usize> for Arc<Vmar_> {
diff --git a/kernel/aster-nix/src/vm/vmar/mod.rs b/kernel/aster-nix/src/vm/vmar/mod.rs
--- a/kernel/aster-nix/src/vm/vmar/mod.rs
+++ b/kernel/aster-nix/src/vm/vmar/mod.rs
@@ -123,7 +123,7 @@ impl VmarInner {
}
}
-const ROOT_VMAR_LOWEST_ADDR: Vaddr = 0x001_0000; // 64 KiB is the Linux configurable default
+pub const ROOT_VMAR_LOWEST_ADDR: Vaddr = 0x001_0000; // 64 KiB is the Linux configurable default
const ROOT_VMAR_CAP_ADDR: Vaddr = MAX_USERSPACE_VADDR;
impl Interval<usize> for Arc<Vmar_> {
diff --git a/osdk/src/commands/run.rs b/osdk/src/commands/run.rs
--- a/osdk/src/commands/run.rs
+++ b/osdk/src/commands/run.rs
@@ -3,7 +3,7 @@
use super::{build::create_base_and_cached_build, util::DEFAULT_TARGET_RELPATH};
use crate::{
cli::GdbServerArgs,
- config::{scheme::ActionChoice, unix_args::split_to_kv_array, Config},
+ config::{scheme::ActionChoice, Config},
util::{get_current_crate_info, get_target_directory},
};
diff --git a/osdk/src/commands/run.rs b/osdk/src/commands/run.rs
--- a/osdk/src/commands/run.rs
+++ b/osdk/src/commands/run.rs
@@ -3,7 +3,7 @@
use super::{build::create_base_and_cached_build, util::DEFAULT_TARGET_RELPATH};
use crate::{
cli::GdbServerArgs,
- config::{scheme::ActionChoice, unix_args::split_to_kv_array, Config},
+ config::{scheme::ActionChoice, Config},
util::{get_current_crate_info, get_target_directory},
};
diff --git a/osdk/src/commands/run.rs b/osdk/src/commands/run.rs
--- a/osdk/src/commands/run.rs
+++ b/osdk/src/commands/run.rs
@@ -41,20 +41,6 @@ pub fn execute_run_command(config: &Config, gdb_server_args: &GdbServerArgs) {
};
config.run.qemu.args += &qemu_gdb_args;
- // FIXME: Disable KVM from QEMU args in debug mode.
- // Currently, the QEMU GDB server does not work properly with KVM enabled.
- let mut splitted = split_to_kv_array(&config.run.qemu.args);
- let args_num = splitted.len();
- splitted.retain(|x| !x.contains("kvm"));
- if splitted.len() != args_num {
- println!(
- "[WARNING] KVM is forced to be disabled in GDB server currently. \
- Options related with KVM are ignored."
- );
- }
-
- config.run.qemu.args = splitted.join(" ");
-
// Ensure debug info added when debugging in the release profile.
if config.run.build.profile.contains("release") {
config
diff --git a/osdk/src/commands/run.rs b/osdk/src/commands/run.rs
--- a/osdk/src/commands/run.rs
+++ b/osdk/src/commands/run.rs
@@ -41,20 +41,6 @@ pub fn execute_run_command(config: &Config, gdb_server_args: &GdbServerArgs) {
};
config.run.qemu.args += &qemu_gdb_args;
- // FIXME: Disable KVM from QEMU args in debug mode.
- // Currently, the QEMU GDB server does not work properly with KVM enabled.
- let mut splitted = split_to_kv_array(&config.run.qemu.args);
- let args_num = splitted.len();
- splitted.retain(|x| !x.contains("kvm"));
- if splitted.len() != args_num {
- println!(
- "[WARNING] KVM is forced to be disabled in GDB server currently. \
- Options related with KVM are ignored."
- );
- }
-
- config.run.qemu.args = splitted.join(" ");
-
// Ensure debug info added when debugging in the release profile.
if config.run.build.profile.contains("release") {
config
diff --git a/ostd/src/panicking.rs b/ostd/src/panicking.rs
--- a/ostd/src/panicking.rs
+++ b/ostd/src/panicking.rs
@@ -2,11 +2,8 @@
//! Panic support.
-use alloc::{boxed::Box, string::ToString};
use core::ffi::c_void;
-use log::error;
-
use crate::{
arch::qemu::{exit_qemu, QemuExitCode},
early_print, early_println,
diff --git a/ostd/src/panicking.rs b/ostd/src/panicking.rs
--- a/ostd/src/panicking.rs
+++ b/ostd/src/panicking.rs
@@ -2,11 +2,8 @@
//! Panic support.
-use alloc::{boxed::Box, string::ToString};
use core::ffi::c_void;
-use log::error;
-
use crate::{
arch::qemu::{exit_qemu, QemuExitCode},
early_print, early_println,
diff --git a/ostd/src/panicking.rs b/ostd/src/panicking.rs
--- a/ostd/src/panicking.rs
+++ b/ostd/src/panicking.rs
@@ -15,12 +12,9 @@ use crate::{
extern crate cfg_if;
extern crate gimli;
use gimli::Register;
-use unwinding::{
- abi::{
- UnwindContext, UnwindReasonCode, _Unwind_Backtrace, _Unwind_FindEnclosingFunction,
- _Unwind_GetGR, _Unwind_GetIP,
- },
- panic::begin_panic,
+use unwinding::abi::{
+ UnwindContext, UnwindReasonCode, _Unwind_Backtrace, _Unwind_FindEnclosingFunction,
+ _Unwind_GetGR, _Unwind_GetIP,
};
/// The panic handler must be defined in the binary crate or in the crate that the binary
diff --git a/ostd/src/panicking.rs b/ostd/src/panicking.rs
--- a/ostd/src/panicking.rs
+++ b/ostd/src/panicking.rs
@@ -15,12 +12,9 @@ use crate::{
extern crate cfg_if;
extern crate gimli;
use gimli::Register;
-use unwinding::{
- abi::{
- UnwindContext, UnwindReasonCode, _Unwind_Backtrace, _Unwind_FindEnclosingFunction,
- _Unwind_GetGR, _Unwind_GetIP,
- },
- panic::begin_panic,
+use unwinding::abi::{
+ UnwindContext, UnwindReasonCode, _Unwind_Backtrace, _Unwind_FindEnclosingFunction,
+ _Unwind_GetGR, _Unwind_GetIP,
};
/// The panic handler must be defined in the binary crate or in the crate that the binary
diff --git a/ostd/src/panicking.rs b/ostd/src/panicking.rs
--- a/ostd/src/panicking.rs
+++ b/ostd/src/panicking.rs
@@ -29,17 +23,22 @@ use unwinding::{
/// panic handler in the binary crate.
#[export_name = "__aster_panic_handler"]
pub fn panic_handler(info: &core::panic::PanicInfo) -> ! {
- let throw_info = ostd_test::PanicInfo {
- message: info.message().to_string(),
- file: info.location().unwrap().file().to_string(),
- line: info.location().unwrap().line() as usize,
- col: info.location().unwrap().column() as usize,
- };
- // Throw an exception and expecting it to be caught.
- begin_panic(Box::new(throw_info.clone()));
- // If the exception is not caught (e.g. by ktest) and resumed,
- // then print the information and abort.
- error!("Uncaught panic!");
+ // If in ktest, we would like to catch the panics and resume the test.
+ #[cfg(ktest)]
+ {
+ use alloc::{boxed::Box, string::ToString};
+
+ use unwinding::panic::begin_panic;
+
+ let throw_info = ostd_test::PanicInfo {
+ message: info.message().to_string(),
+ file: info.location().unwrap().file().to_string(),
+ line: info.location().unwrap().line() as usize,
+ col: info.location().unwrap().column() as usize,
+ };
+ // Throw an exception and expecting it to be caught.
+ begin_panic(Box::new(throw_info.clone()));
+ }
early_println!("{}", info);
early_println!("printing stack trace:");
print_stack_trace();
|
Another example:
https://github.com/asterinas/asterinas/actions/runs/10104476344/job/27943517035?pr=1030
I found it being reproducible (randomly) locally. And it has nothing to do with Ext2. It seems to be a problem with MicroVM.
It is really easy to reproduce but once you need to debug (via printing or gdb), it is really hard to reproduce. It seems that it occurs lesser if the system is running more slowly (LOL).
I GDBed it with KVM on (can't use breakpoints but can backtrace), I found that it hangs here:
```
(gdb) bt
#0 ostd::sync::spin::SpinLock<core::option::Option<core::mem::manually_drop::ManuallyDrop<ostd::mm::page_table::boot_pt::BootPageTable<ostd::arch::x86::mm::PageTableEntry, ostd::arch::x86::mm::PagingConsts>>>>::acquire_lock<core::option::Option<core::mem::manually_drop::ManuallyDrop<ostd::mm::page_table::boot_pt::BootPageTable<ostd::arch::x86::mm::PageTableEntry, ostd::arch::x86::mm::PagingConsts>>>> (
self=0xffffffff8836e370 <_ZN4ostd2mm14heap_allocator14HEAP_ALLOCATOR17he1684604edc78901E.llvm.13890399637656761890+8>) at src/sync/spin.rs:111
#1 ostd::sync::spin::SpinLock<core::option::Option<core::mem::manually_drop::ManuallyDrop<ostd::mm::page_table::boot_pt::BootPageTable<ostd::arch::x86::mm::PageTableEntry, ostd::arch::x86::mm::PagingConsts>>>>::lock<core::option::Option<core::mem::manually_drop::ManuallyDrop<ostd::mm::page_table::boot_pt::BootPageTable<ostd::arch::x86::mm::PageTableEntry, ostd::arch::x86::mm::PagingConsts>>>> (
self=0xffffffff8836e370 <_ZN4ostd2mm14heap_allocator14HEAP_ALLOCATOR17he1684604edc78901E.llvm.13890399637656761890+8>) at src/sync/spin.rs:74
#2 0xffffffff882765bd in ostd::mm::heap_allocator::{impl#1}::alloc<32> (self=<optimized out>, layout=...) at src/mm/heap_allocator.rs:71
#3 0xffffffff88049bf7 in ostd::mm::heap_allocator::_::__rust_alloc (size=4, align=1) at /root/asterinas/ostd/src/mm/heap_allocator.rs:22
#4 alloc::alloc::alloc (layout=...) at src/alloc.rs:100
#5 alloc::alloc::Global::alloc_impl (layout=..., zeroed=false, self=<optimized out>) at src/alloc.rs:183
#6 alloc::alloc::{impl#1}::allocate (layout=..., self=<optimized out>) at src/alloc.rs:243
#7 alloc::raw_vec::RawVec<u8, alloc::alloc::Global>::try_allocate_in<u8, alloc::alloc::Global> (capacity=4, init=alloc::raw_vec::AllocInit::Uninitialized, alloc=...) at src/raw_vec.rs:230
#8 alloc::raw_vec::RawVec<u8, alloc::alloc::Global>::with_capacity_in<u8, alloc::alloc::Global> (capacity=<optimized out>) at src/raw_vec.rs:158
#9 alloc::vec::Vec<u8, alloc::alloc::Global>::with_capacity_in<u8, alloc::alloc::Global> (capacity=<optimized out>) at src/vec/mod.rs:699
#10 alloc::vec::Vec<u8, alloc::alloc::Global>::with_capacity<u8> (capacity=<optimized out>) at src/vec/mod.rs:481
#11 alloc::string::String::with_capacity () at src/string.rs:492
#12 alloc::fmt::format::format_inner (args=...) at src/fmt.rs:632
#13 0xffffffff8826174f in alloc::fmt::format::{closure#0} () at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/fmt.rs:639
#14 core::option::Option<&str>::map_or_else<&str, alloc::string::String, alloc::fmt::format::{closure_env#0}, fn(&str) -> alloc::string::String> (self=..., default=..., f=<optimized out>)
at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/option.rs:1207
#15 alloc::fmt::format (args=...) at /root/.rustup/toolchains/nightly-2024-06-20-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/fmt.rs:639
#16 ostd::logger::{impl#0}::log (self=<optimized out>, record=0xffff8000ba93d858) at src/logger.rs:37
#17 0xffffffff880e2859 in log::__private_api::log_impl (args=..., level=log::Level::Error, kvs=...) at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/log-0.4.22/src/__private_api.rs:61
#18 log::__private_api::log<()> (args=<error reading variable: Cannot access memory at address 0x20>, target_module_path_and_loc=<optimized out>,
args=<error reading variable: Cannot access memory at address 0x20>, target_module_path_and_loc=<optimized out>)
at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/log-0.4.22/src/__private_api.rs:72
#19 aster_nix::thread::exception::handle_page_fault (vm_space=<optimized out>, trap_info=<optimized out>) at /root/.cargo/registry/src/index.crates.io-6f17d22bba15001f/log-0.4.22/src/macros.rs:49
#20 0xffffffff8827db32 in ostd::mm::vm_space::VmSpace::handle_page_fault (self=0xffffffff8836e370 <_ZN4ostd2mm14heap_allocator14HEAP_ALLOCATOR17he1684604edc78901E.llvm.13890399637656761890+8>,
info=0xffff8000ba93da00) at src/mm/vm_space.rs:109
#21 ostd::arch::x86::trap::handle_user_page_fault (f=0xffff8000ba93dae0, page_fault_addr=7) at src/arch/x86/trap.rs:86
#22 ostd::arch::x86::trap::trap_handler (f=0xffff8000ba93dae0) at src/arch/x86/trap.rs:54
#23 0xffffffff8829911a in __from_kernel ()
#24 0x0000000000000008 in ?? ()
#25 0x0000000000000000 in ?? ()
```
https://github.com/asterinas/asterinas/issues/1085
It seemed, not reliable
|
2024-07-26T11:09:27Z
|
562e64437584279783f244edba10b512beddc81d
|
asterinas/asterinas
|
diff --git a/test/apps/network/listen_backlog.c b/test/apps/network/listen_backlog.c
--- a/test/apps/network/listen_backlog.c
+++ b/test/apps/network/listen_backlog.c
@@ -131,7 +131,7 @@ int main(void)
for (backlog = 0; backlog <= MAX_TEST_BACKLOG; ++backlog) {
// Avoid "bind: Address already in use"
- addr.sin_port = htons(8080 + backlog);
+ addr.sin_port = htons(10000 + backlog);
err = test_listen_backlog(&addr, backlog);
if (err != 0)
diff --git a/test/apps/network/send_buf_full.c b/test/apps/network/send_buf_full.c
--- a/test/apps/network/send_buf_full.c
+++ b/test/apps/network/send_buf_full.c
@@ -265,7 +265,7 @@ int main(void)
struct sockaddr_in addr;
addr.sin_family = AF_INET;
- addr.sin_port = htons(8080);
+ addr.sin_port = htons(9999);
if (inet_aton("127.0.0.1", &addr.sin_addr) < 0) {
fprintf(stderr, "inet_aton cannot parse 127.0.0.1\n");
return -1;
diff --git a/test/apps/network/tcp_err.c b/test/apps/network/tcp_err.c
--- a/test/apps/network/tcp_err.c
+++ b/test/apps/network/tcp_err.c
@@ -338,26 +338,23 @@ FN_TEST(sendmsg_and_recvmsg)
// Send two message and receive two message
- // This test is commented out due to a known issue:
- // See <https://github.com/asterinas/asterinas/issues/819>
-
- // iov[0].iov_base = message;
- // iov[0].iov_len = strlen(message);
- // msg.msg_iovlen = 1;
- // TEST_RES(sendmsg(sk_accepted, &msg, 0), _ret == strlen(message));
- // TEST_RES(sendmsg(sk_accepted, &msg, 0), _ret == strlen(message));
-
- // char first_buffer[BUFFER_SIZE] = { 0 };
- // char second_buffer[BUFFER_SIZE] = { 0 };
- // iov[0].iov_base = first_buffer;
- // iov[0].iov_len = BUFFER_SIZE;
- // iov[1].iov_base = second_buffer;
- // iov[1].iov_len = BUFFER_SIZE;
- // msg.msg_iovlen = 2;
-
- // // Ensure two messages are prepared for receiving
- // sleep(1);
-
- // TEST_RES(recvmsg(sk_connected, &msg, 0), _ret == strlen(message) * 2);
+ iov[0].iov_base = message;
+ iov[0].iov_len = strlen(message);
+ msg.msg_iovlen = 1;
+ TEST_RES(sendmsg(sk_accepted, &msg, 0), _ret == strlen(message));
+ TEST_RES(sendmsg(sk_accepted, &msg, 0), _ret == strlen(message));
+
+ char first_buffer[BUFFER_SIZE] = { 0 };
+ char second_buffer[BUFFER_SIZE] = { 0 };
+ iov[0].iov_base = first_buffer;
+ iov[0].iov_len = BUFFER_SIZE;
+ iov[1].iov_base = second_buffer;
+ iov[1].iov_len = BUFFER_SIZE;
+ msg.msg_iovlen = 2;
+
+ // Ensure two messages are prepared for receiving
+ sleep(1);
+
+ TEST_RES(recvmsg(sk_connected, &msg, 0), _ret == strlen(message) * 2);
}
END_TEST()
|
[
"819"
] |
0.6
|
e83e1fc01ba38ad2a405d7d710ec7258fb664f60
|
Polling ifaces may not ensure packets be transmitted
The problem occurs when I trying to send two messages to the same TCP socket, and trying to receive the two messages at once.
```C
TEST_RES(sendmsg(sk_accepted, &msg, 0), _ret == strlen(message));
TEST_RES(sendmsg(sk_accepted, &msg, 0), _ret == strlen(message));
// Ensure two messages are ready for receiving
sleep(1);
TEST_RES(recvmsg(sk_connected, &msg, 0), _ret == strlen(message) * 2);
```
The test program always succeeds when running on Linux.
However, when running on Asterinas, `sk_connected` can only accept the first message.
The problem disappears when I running in set log level as TRACE. So it may be some problems with timeout.......
# Possible solution
This problem may be related to the [nagle-enabled feature](https://docs.rs/smoltcp/latest/smoltcp/socket/tcp/struct.Socket.html#method.set_nagle_enabled), which disables small packets to be transmitted. If set `nagle-enabled` as false, the problem will also disappear.
But totally disabling this feature may affect performance. This feature is same as the `TCP_NODELAY` option in Linux, but Linux keeps this option on by default.
|
asterinas__asterinas-1098
| 1,098
|
diff --git a/kernel/aster-nix/src/net/iface/any_socket.rs b/kernel/aster-nix/src/net/iface/any_socket.rs
--- a/kernel/aster-nix/src/net/iface/any_socket.rs
+++ b/kernel/aster-nix/src/net/iface/any_socket.rs
@@ -59,14 +59,7 @@ impl AnyUnboundSocket {
}
}
-pub struct AnyBoundSocket {
- iface: Arc<dyn Iface>,
- handle: smoltcp::iface::SocketHandle,
- port: u16,
- socket_family: SocketFamily,
- observer: RwLock<Weak<dyn Observer<()>>>,
- weak_self: Weak<Self>,
-}
+pub struct AnyBoundSocket(Arc<AnyBoundSocketInner>);
impl AnyBoundSocket {
pub(super) fn new(
diff --git a/kernel/aster-nix/src/net/iface/any_socket.rs b/kernel/aster-nix/src/net/iface/any_socket.rs
--- a/kernel/aster-nix/src/net/iface/any_socket.rs
+++ b/kernel/aster-nix/src/net/iface/any_socket.rs
@@ -59,14 +59,7 @@ impl AnyUnboundSocket {
}
}
-pub struct AnyBoundSocket {
- iface: Arc<dyn Iface>,
- handle: smoltcp::iface::SocketHandle,
- port: u16,
- socket_family: SocketFamily,
- observer: RwLock<Weak<dyn Observer<()>>>,
- weak_self: Weak<Self>,
-}
+pub struct AnyBoundSocket(Arc<AnyBoundSocketInner>);
impl AnyBoundSocket {
pub(super) fn new(
diff --git a/kernel/aster-nix/src/net/iface/any_socket.rs b/kernel/aster-nix/src/net/iface/any_socket.rs
--- a/kernel/aster-nix/src/net/iface/any_socket.rs
+++ b/kernel/aster-nix/src/net/iface/any_socket.rs
@@ -75,21 +68,18 @@ impl AnyBoundSocket {
port: u16,
socket_family: SocketFamily,
observer: Weak<dyn Observer<()>>,
- ) -> Arc<Self> {
- Arc::new_cyclic(|weak_self| Self {
+ ) -> Self {
+ Self(Arc::new(AnyBoundSocketInner {
iface,
handle,
port,
socket_family,
observer: RwLock::new(observer),
- weak_self: weak_self.clone(),
- })
+ }))
}
- pub(super) fn on_iface_events(&self) {
- if let Some(observer) = Weak::upgrade(&*self.observer.read()) {
- observer.on_events(&())
- }
+ pub(super) fn inner(&self) -> &Arc<AnyBoundSocketInner> {
+ &self.0
}
/// Set the observer whose `on_events` will be called when certain iface events happen. After
diff --git a/kernel/aster-nix/src/net/iface/any_socket.rs b/kernel/aster-nix/src/net/iface/any_socket.rs
--- a/kernel/aster-nix/src/net/iface/any_socket.rs
+++ b/kernel/aster-nix/src/net/iface/any_socket.rs
@@ -75,21 +68,18 @@ impl AnyBoundSocket {
port: u16,
socket_family: SocketFamily,
observer: Weak<dyn Observer<()>>,
- ) -> Arc<Self> {
- Arc::new_cyclic(|weak_self| Self {
+ ) -> Self {
+ Self(Arc::new(AnyBoundSocketInner {
iface,
handle,
port,
socket_family,
observer: RwLock::new(observer),
- weak_self: weak_self.clone(),
- })
+ }))
}
- pub(super) fn on_iface_events(&self) {
- if let Some(observer) = Weak::upgrade(&*self.observer.read()) {
- observer.on_events(&())
- }
+ pub(super) fn inner(&self) -> &Arc<AnyBoundSocketInner> {
+ &self.0
}
/// Set the observer whose `on_events` will be called when certain iface events happen. After
diff --git a/kernel/aster-nix/src/net/iface/any_socket.rs b/kernel/aster-nix/src/net/iface/any_socket.rs
--- a/kernel/aster-nix/src/net/iface/any_socket.rs
+++ b/kernel/aster-nix/src/net/iface/any_socket.rs
@@ -99,34 +89,32 @@ impl AnyBoundSocket {
/// that the old observer will never be called after the setting. Users should be aware of this
/// and proactively handle the race conditions if necessary.
pub fn set_observer(&self, handler: Weak<dyn Observer<()>>) {
- *self.observer.write() = handler;
+ *self.0.observer.write() = handler;
- self.on_iface_events();
+ self.0.on_iface_events();
}
pub fn local_endpoint(&self) -> Option<IpEndpoint> {
let ip_addr = {
- let ipv4_addr = self.iface.ipv4_addr()?;
+ let ipv4_addr = self.0.iface.ipv4_addr()?;
IpAddress::Ipv4(ipv4_addr)
};
- Some(IpEndpoint::new(ip_addr, self.port))
+ Some(IpEndpoint::new(ip_addr, self.0.port))
}
pub fn raw_with<T: smoltcp::socket::AnySocket<'static>, R, F: FnMut(&mut T) -> R>(
&self,
- mut f: F,
+ f: F,
) -> R {
- let mut sockets = self.iface.sockets();
- let socket = sockets.get_mut::<T>(self.handle);
- f(socket)
+ self.0.raw_with(f)
}
/// Try to connect to a remote endpoint. Tcp socket only.
pub fn do_connect(&self, remote_endpoint: IpEndpoint) -> Result<()> {
- let mut sockets = self.iface.sockets();
- let socket = sockets.get_mut::<RawTcpSocket>(self.handle);
- let port = self.port;
- let mut iface_inner = self.iface.iface_inner();
+ let mut sockets = self.0.iface.sockets();
+ let socket = sockets.get_mut::<RawTcpSocket>(self.0.handle);
+ let port = self.0.port;
+ let mut iface_inner = self.0.iface.iface_inner();
let cx = iface_inner.context();
socket
.connect(cx, remote_endpoint, port)
diff --git a/kernel/aster-nix/src/net/iface/any_socket.rs b/kernel/aster-nix/src/net/iface/any_socket.rs
--- a/kernel/aster-nix/src/net/iface/any_socket.rs
+++ b/kernel/aster-nix/src/net/iface/any_socket.rs
@@ -99,34 +89,32 @@ impl AnyBoundSocket {
/// that the old observer will never be called after the setting. Users should be aware of this
/// and proactively handle the race conditions if necessary.
pub fn set_observer(&self, handler: Weak<dyn Observer<()>>) {
- *self.observer.write() = handler;
+ *self.0.observer.write() = handler;
- self.on_iface_events();
+ self.0.on_iface_events();
}
pub fn local_endpoint(&self) -> Option<IpEndpoint> {
let ip_addr = {
- let ipv4_addr = self.iface.ipv4_addr()?;
+ let ipv4_addr = self.0.iface.ipv4_addr()?;
IpAddress::Ipv4(ipv4_addr)
};
- Some(IpEndpoint::new(ip_addr, self.port))
+ Some(IpEndpoint::new(ip_addr, self.0.port))
}
pub fn raw_with<T: smoltcp::socket::AnySocket<'static>, R, F: FnMut(&mut T) -> R>(
&self,
- mut f: F,
+ f: F,
) -> R {
- let mut sockets = self.iface.sockets();
- let socket = sockets.get_mut::<T>(self.handle);
- f(socket)
+ self.0.raw_with(f)
}
/// Try to connect to a remote endpoint. Tcp socket only.
pub fn do_connect(&self, remote_endpoint: IpEndpoint) -> Result<()> {
- let mut sockets = self.iface.sockets();
- let socket = sockets.get_mut::<RawTcpSocket>(self.handle);
- let port = self.port;
- let mut iface_inner = self.iface.iface_inner();
+ let mut sockets = self.0.iface.sockets();
+ let socket = sockets.get_mut::<RawTcpSocket>(self.0.handle);
+ let port = self.0.port;
+ let mut iface_inner = self.0.iface.iface_inner();
let cx = iface_inner.context();
socket
.connect(cx, remote_endpoint, port)
diff --git a/kernel/aster-nix/src/net/iface/any_socket.rs b/kernel/aster-nix/src/net/iface/any_socket.rs
--- a/kernel/aster-nix/src/net/iface/any_socket.rs
+++ b/kernel/aster-nix/src/net/iface/any_socket.rs
@@ -135,28 +123,84 @@ impl AnyBoundSocket {
}
pub fn iface(&self) -> &Arc<dyn Iface> {
- &self.iface
+ &self.0.iface
}
+}
- pub(super) fn weak_ref(&self) -> Weak<Self> {
- self.weak_self.clone()
+impl Drop for AnyBoundSocket {
+ fn drop(&mut self) {
+ if self.0.start_closing() {
+ self.0.iface.common().remove_bound_socket_now(&self.0);
+ } else {
+ self.0
+ .iface
+ .common()
+ .remove_bound_socket_when_closed(&self.0);
+ }
}
+}
- fn close(&self) {
+pub(super) struct AnyBoundSocketInner {
+ iface: Arc<dyn Iface>,
+ handle: smoltcp::iface::SocketHandle,
+ port: u16,
+ socket_family: SocketFamily,
+ observer: RwLock<Weak<dyn Observer<()>>>,
+}
+
+impl AnyBoundSocketInner {
+ pub(super) fn on_iface_events(&self) {
+ if let Some(observer) = Weak::upgrade(&*self.observer.read()) {
+ observer.on_events(&())
+ }
+ }
+
+ pub(super) fn is_closed(&self) -> bool {
+ match self.socket_family {
+ SocketFamily::Tcp => self.raw_with(|socket: &mut RawTcpSocket| {
+ socket.state() == smoltcp::socket::tcp::State::Closed
+ }),
+ SocketFamily::Udp => true,
+ }
+ }
+
+ /// Starts closing the socket and returns whether the socket is closed.
+ ///
+ /// For sockets that can be closed immediately, such as UDP sockets and TCP listening sockets,
+ /// this method will always return `true`.
+ ///
+ /// For other sockets, such as TCP connected sockets, they cannot be closed immediately because
+ /// we at least need to send the FIN packet and wait for the remote end to send an ACK packet.
+ /// In this case, this method will return `false` and [`Self::is_closed`] can be used to
+ /// determine if the closing process is complete.
+ fn start_closing(&self) -> bool {
match self.socket_family {
- SocketFamily::Tcp => self.raw_with(|socket: &mut RawTcpSocket| socket.close()),
- SocketFamily::Udp => self.raw_with(|socket: &mut RawUdpSocket| socket.close()),
+ SocketFamily::Tcp => self.raw_with(|socket: &mut RawTcpSocket| {
+ socket.close();
+ socket.state() == smoltcp::socket::tcp::State::Closed
+ }),
+ SocketFamily::Udp => {
+ self.raw_with(|socket: &mut RawUdpSocket| socket.close());
+ true
+ }
}
}
+
+ pub fn raw_with<T: smoltcp::socket::AnySocket<'static>, R, F: FnMut(&mut T) -> R>(
+ &self,
+ mut f: F,
+ ) -> R {
+ let mut sockets = self.iface.sockets();
+ let socket = sockets.get_mut::<T>(self.handle);
+ f(socket)
+ }
}
-impl Drop for AnyBoundSocket {
+impl Drop for AnyBoundSocketInner {
fn drop(&mut self) {
- self.close();
- self.iface.poll();
- self.iface.common().remove_socket(self.handle);
- self.iface.common().release_port(self.port);
- self.iface.common().remove_bound_socket(self.weak_ref());
+ let iface_common = self.iface.common();
+ iface_common.remove_socket(self.handle);
+ iface_common.release_port(self.port);
}
}
diff --git a/kernel/aster-nix/src/net/iface/any_socket.rs b/kernel/aster-nix/src/net/iface/any_socket.rs
--- a/kernel/aster-nix/src/net/iface/any_socket.rs
+++ b/kernel/aster-nix/src/net/iface/any_socket.rs
@@ -135,28 +123,84 @@ impl AnyBoundSocket {
}
pub fn iface(&self) -> &Arc<dyn Iface> {
- &self.iface
+ &self.0.iface
}
+}
- pub(super) fn weak_ref(&self) -> Weak<Self> {
- self.weak_self.clone()
+impl Drop for AnyBoundSocket {
+ fn drop(&mut self) {
+ if self.0.start_closing() {
+ self.0.iface.common().remove_bound_socket_now(&self.0);
+ } else {
+ self.0
+ .iface
+ .common()
+ .remove_bound_socket_when_closed(&self.0);
+ }
}
+}
- fn close(&self) {
+pub(super) struct AnyBoundSocketInner {
+ iface: Arc<dyn Iface>,
+ handle: smoltcp::iface::SocketHandle,
+ port: u16,
+ socket_family: SocketFamily,
+ observer: RwLock<Weak<dyn Observer<()>>>,
+}
+
+impl AnyBoundSocketInner {
+ pub(super) fn on_iface_events(&self) {
+ if let Some(observer) = Weak::upgrade(&*self.observer.read()) {
+ observer.on_events(&())
+ }
+ }
+
+ pub(super) fn is_closed(&self) -> bool {
+ match self.socket_family {
+ SocketFamily::Tcp => self.raw_with(|socket: &mut RawTcpSocket| {
+ socket.state() == smoltcp::socket::tcp::State::Closed
+ }),
+ SocketFamily::Udp => true,
+ }
+ }
+
+ /// Starts closing the socket and returns whether the socket is closed.
+ ///
+ /// For sockets that can be closed immediately, such as UDP sockets and TCP listening sockets,
+ /// this method will always return `true`.
+ ///
+ /// For other sockets, such as TCP connected sockets, they cannot be closed immediately because
+ /// we at least need to send the FIN packet and wait for the remote end to send an ACK packet.
+ /// In this case, this method will return `false` and [`Self::is_closed`] can be used to
+ /// determine if the closing process is complete.
+ fn start_closing(&self) -> bool {
match self.socket_family {
- SocketFamily::Tcp => self.raw_with(|socket: &mut RawTcpSocket| socket.close()),
- SocketFamily::Udp => self.raw_with(|socket: &mut RawUdpSocket| socket.close()),
+ SocketFamily::Tcp => self.raw_with(|socket: &mut RawTcpSocket| {
+ socket.close();
+ socket.state() == smoltcp::socket::tcp::State::Closed
+ }),
+ SocketFamily::Udp => {
+ self.raw_with(|socket: &mut RawUdpSocket| socket.close());
+ true
+ }
}
}
+
+ pub fn raw_with<T: smoltcp::socket::AnySocket<'static>, R, F: FnMut(&mut T) -> R>(
+ &self,
+ mut f: F,
+ ) -> R {
+ let mut sockets = self.iface.sockets();
+ let socket = sockets.get_mut::<T>(self.handle);
+ f(socket)
+ }
}
-impl Drop for AnyBoundSocket {
+impl Drop for AnyBoundSocketInner {
fn drop(&mut self) {
- self.close();
- self.iface.poll();
- self.iface.common().remove_socket(self.handle);
- self.iface.common().release_port(self.port);
- self.iface.common().remove_bound_socket(self.weak_ref());
+ let iface_common = self.iface.common();
+ iface_common.remove_socket(self.handle);
+ iface_common.release_port(self.port);
}
}
diff --git a/kernel/aster-nix/src/net/iface/common.rs b/kernel/aster-nix/src/net/iface/common.rs
--- a/kernel/aster-nix/src/net/iface/common.rs
+++ b/kernel/aster-nix/src/net/iface/common.rs
@@ -3,7 +3,7 @@
use alloc::collections::btree_map::Entry;
use core::sync::atomic::{AtomicU64, Ordering};
-use keyable_arc::KeyableWeak;
+use keyable_arc::KeyableArc;
use ostd::sync::WaitQueue;
use smoltcp::{
iface::{SocketHandle, SocketSet},
diff --git a/kernel/aster-nix/src/net/iface/common.rs b/kernel/aster-nix/src/net/iface/common.rs
--- a/kernel/aster-nix/src/net/iface/common.rs
+++ b/kernel/aster-nix/src/net/iface/common.rs
@@ -3,7 +3,7 @@
use alloc::collections::btree_map::Entry;
use core::sync::atomic::{AtomicU64, Ordering};
-use keyable_arc::KeyableWeak;
+use keyable_arc::KeyableArc;
use ostd::sync::WaitQueue;
use smoltcp::{
iface::{SocketHandle, SocketSet},
diff --git a/kernel/aster-nix/src/net/iface/common.rs b/kernel/aster-nix/src/net/iface/common.rs
--- a/kernel/aster-nix/src/net/iface/common.rs
+++ b/kernel/aster-nix/src/net/iface/common.rs
@@ -12,10 +12,10 @@ use smoltcp::{
};
use super::{
- any_socket::{AnyBoundSocket, AnyRawSocket, AnyUnboundSocket, SocketFamily},
+ any_socket::{AnyBoundSocketInner, AnyRawSocket, AnyUnboundSocket, SocketFamily},
time::get_network_timestamp,
util::BindPortConfig,
- Iface, Ipv4Address,
+ AnyBoundSocket, Iface, Ipv4Address,
};
use crate::prelude::*;
diff --git a/kernel/aster-nix/src/net/iface/common.rs b/kernel/aster-nix/src/net/iface/common.rs
--- a/kernel/aster-nix/src/net/iface/common.rs
+++ b/kernel/aster-nix/src/net/iface/common.rs
@@ -12,10 +12,10 @@ use smoltcp::{
};
use super::{
- any_socket::{AnyBoundSocket, AnyRawSocket, AnyUnboundSocket, SocketFamily},
+ any_socket::{AnyBoundSocketInner, AnyRawSocket, AnyUnboundSocket, SocketFamily},
time::get_network_timestamp,
util::BindPortConfig,
- Iface, Ipv4Address,
+ AnyBoundSocket, Iface, Ipv4Address,
};
use crate::prelude::*;
diff --git a/kernel/aster-nix/src/net/iface/common.rs b/kernel/aster-nix/src/net/iface/common.rs
--- a/kernel/aster-nix/src/net/iface/common.rs
+++ b/kernel/aster-nix/src/net/iface/common.rs
@@ -25,7 +25,8 @@ pub struct IfaceCommon {
used_ports: RwLock<BTreeMap<u16, usize>>,
/// The time should do next poll. We stores the total milliseconds since system boots up.
next_poll_at_ms: AtomicU64,
- bound_sockets: RwLock<BTreeSet<KeyableWeak<AnyBoundSocket>>>,
+ bound_sockets: RwLock<BTreeSet<KeyableArc<AnyBoundSocketInner>>>,
+ closing_sockets: SpinLock<BTreeSet<KeyableArc<AnyBoundSocketInner>>>,
/// The wait queue that background polling thread will sleep on
polling_wait_queue: WaitQueue,
}
diff --git a/kernel/aster-nix/src/net/iface/common.rs b/kernel/aster-nix/src/net/iface/common.rs
--- a/kernel/aster-nix/src/net/iface/common.rs
+++ b/kernel/aster-nix/src/net/iface/common.rs
@@ -25,7 +25,8 @@ pub struct IfaceCommon {
used_ports: RwLock<BTreeMap<u16, usize>>,
/// The time should do next poll. We stores the total milliseconds since system boots up.
next_poll_at_ms: AtomicU64,
- bound_sockets: RwLock<BTreeSet<KeyableWeak<AnyBoundSocket>>>,
+ bound_sockets: RwLock<BTreeSet<KeyableArc<AnyBoundSocketInner>>>,
+ closing_sockets: SpinLock<BTreeSet<KeyableArc<AnyBoundSocketInner>>>,
/// The wait queue that background polling thread will sleep on
polling_wait_queue: WaitQueue,
}
diff --git a/kernel/aster-nix/src/net/iface/common.rs b/kernel/aster-nix/src/net/iface/common.rs
--- a/kernel/aster-nix/src/net/iface/common.rs
+++ b/kernel/aster-nix/src/net/iface/common.rs
@@ -40,14 +41,21 @@ impl IfaceCommon {
used_ports: RwLock::new(used_ports),
next_poll_at_ms: AtomicU64::new(0),
bound_sockets: RwLock::new(BTreeSet::new()),
+ closing_sockets: SpinLock::new(BTreeSet::new()),
polling_wait_queue: WaitQueue::new(),
}
}
+ /// Acquires the lock to the interface.
+ ///
+ /// *Lock ordering:* [`Self::sockets`] first, [`Self::interface`] second.
pub(super) fn interface(&self) -> SpinLockGuard<smoltcp::iface::Interface> {
self.interface.lock_irq_disabled()
}
+ /// Acuqires the lock to the sockets.
+ ///
+ /// *Lock ordering:* [`Self::sockets`] first, [`Self::interface`] second.
pub(super) fn sockets(&self) -> SpinLockGuard<smoltcp::iface::SocketSet<'static>> {
self.sockets.lock_irq_disabled()
}
diff --git a/kernel/aster-nix/src/net/iface/common.rs b/kernel/aster-nix/src/net/iface/common.rs
--- a/kernel/aster-nix/src/net/iface/common.rs
+++ b/kernel/aster-nix/src/net/iface/common.rs
@@ -40,14 +41,21 @@ impl IfaceCommon {
used_ports: RwLock::new(used_ports),
next_poll_at_ms: AtomicU64::new(0),
bound_sockets: RwLock::new(BTreeSet::new()),
+ closing_sockets: SpinLock::new(BTreeSet::new()),
polling_wait_queue: WaitQueue::new(),
}
}
+ /// Acquires the lock to the interface.
+ ///
+ /// *Lock ordering:* [`Self::sockets`] first, [`Self::interface`] second.
pub(super) fn interface(&self) -> SpinLockGuard<smoltcp::iface::Interface> {
self.interface.lock_irq_disabled()
}
+ /// Acuqires the lock to the sockets.
+ ///
+ /// *Lock ordering:* [`Self::sockets`] first, [`Self::interface`] second.
pub(super) fn sockets(&self) -> SpinLockGuard<smoltcp::iface::SocketSet<'static>> {
self.sockets.lock_irq_disabled()
}
diff --git a/kernel/aster-nix/src/net/iface/common.rs b/kernel/aster-nix/src/net/iface/common.rs
--- a/kernel/aster-nix/src/net/iface/common.rs
+++ b/kernel/aster-nix/src/net/iface/common.rs
@@ -109,7 +117,7 @@ impl IfaceCommon {
iface: Arc<dyn Iface>,
socket: Box<AnyUnboundSocket>,
config: BindPortConfig,
- ) -> core::result::Result<Arc<AnyBoundSocket>, (Error, Box<AnyUnboundSocket>)> {
+ ) -> core::result::Result<AnyBoundSocket, (Error, Box<AnyUnboundSocket>)> {
let port = if let Some(port) = config.port() {
port
} else {
diff --git a/kernel/aster-nix/src/net/iface/common.rs b/kernel/aster-nix/src/net/iface/common.rs
--- a/kernel/aster-nix/src/net/iface/common.rs
+++ b/kernel/aster-nix/src/net/iface/common.rs
@@ -109,7 +117,7 @@ impl IfaceCommon {
iface: Arc<dyn Iface>,
socket: Box<AnyUnboundSocket>,
config: BindPortConfig,
- ) -> core::result::Result<Arc<AnyBoundSocket>, (Error, Box<AnyUnboundSocket>)> {
+ ) -> core::result::Result<AnyBoundSocket, (Error, Box<AnyUnboundSocket>)> {
let port = if let Some(port) = config.port() {
port
} else {
diff --git a/kernel/aster-nix/src/net/iface/common.rs b/kernel/aster-nix/src/net/iface/common.rs
--- a/kernel/aster-nix/src/net/iface/common.rs
+++ b/kernel/aster-nix/src/net/iface/common.rs
@@ -135,7 +143,7 @@ impl IfaceCommon {
),
};
let bound_socket = AnyBoundSocket::new(iface, handle, port, socket_family, observer);
- self.insert_bound_socket(&bound_socket).unwrap();
+ self.insert_bound_socket(bound_socket.inner());
Ok(bound_socket)
}
diff --git a/kernel/aster-nix/src/net/iface/common.rs b/kernel/aster-nix/src/net/iface/common.rs
--- a/kernel/aster-nix/src/net/iface/common.rs
+++ b/kernel/aster-nix/src/net/iface/common.rs
@@ -135,7 +143,7 @@ impl IfaceCommon {
),
};
let bound_socket = AnyBoundSocket::new(iface, handle, port, socket_family, observer);
- self.insert_bound_socket(&bound_socket).unwrap();
+ self.insert_bound_socket(bound_socket.inner());
Ok(bound_socket)
}
diff --git a/kernel/aster-nix/src/net/iface/common.rs b/kernel/aster-nix/src/net/iface/common.rs
--- a/kernel/aster-nix/src/net/iface/common.rs
+++ b/kernel/aster-nix/src/net/iface/common.rs
@@ -146,37 +154,60 @@ impl IfaceCommon {
}
pub(super) fn poll<D: Device + ?Sized>(&self, device: &mut D) {
+ let mut sockets = self.sockets.lock_irq_disabled();
let mut interface = self.interface.lock_irq_disabled();
+
let timestamp = get_network_timestamp();
- let has_events = {
- let mut sockets = self.sockets.lock_irq_disabled();
- interface.poll(timestamp, device, &mut sockets)
- // drop sockets here to avoid deadlock
- };
- if has_events {
- self.bound_sockets.read().iter().for_each(|bound_socket| {
- if let Some(bound_socket) = bound_socket.upgrade() {
- bound_socket.on_iface_events();
+ let (has_events, poll_at) = {
+ let mut has_events = false;
+ let mut poll_at;
+ loop {
+ has_events |= interface.poll(timestamp, device, &mut sockets);
+ poll_at = interface.poll_at(timestamp, &sockets);
+ let Some(instant) = poll_at else {
+ break;
+ };
+ if instant > timestamp {
+ break;
}
- });
- }
+ }
+ (has_events, poll_at)
+ };
+
+ // drop sockets here to avoid deadlock
+ drop(interface);
+ drop(sockets);
- let sockets = self.sockets.lock_irq_disabled();
- if let Some(instant) = interface.poll_at(timestamp, &sockets) {
- let old_instant = self.next_poll_at_ms.load(Ordering::Acquire);
+ if let Some(instant) = poll_at {
+ let old_instant = self.next_poll_at_ms.load(Ordering::Relaxed);
let new_instant = instant.total_millis() as u64;
self.next_poll_at_ms.store(new_instant, Ordering::Relaxed);
- if new_instant < old_instant {
+ if old_instant == 0 || new_instant < old_instant {
self.polling_wait_queue.wake_all();
}
} else {
self.next_poll_at_ms.store(0, Ordering::Relaxed);
}
+
+ if has_events {
+ // We never try to hold the write lock in the IRQ context, and we disable IRQ when
+ // holding the write lock. So we don't need to disable IRQ when holding the read lock.
+ self.bound_sockets.read().iter().for_each(|bound_socket| {
+ bound_socket.on_iface_events();
+ });
+
+ let closed_sockets = self
+ .closing_sockets
+ .lock_irq_disabled()
+ .extract_if(|closing_socket| closing_socket.is_closed())
+ .collect::<Vec<_>>();
+ drop(closed_sockets);
+ }
}
pub(super) fn next_poll_at_ms(&self) -> Option<u64> {
- let millis = self.next_poll_at_ms.load(Ordering::SeqCst);
+ let millis = self.next_poll_at_ms.load(Ordering::Relaxed);
if millis == 0 {
None
} else {
diff --git a/kernel/aster-nix/src/net/iface/common.rs b/kernel/aster-nix/src/net/iface/common.rs
--- a/kernel/aster-nix/src/net/iface/common.rs
+++ b/kernel/aster-nix/src/net/iface/common.rs
@@ -146,37 +154,60 @@ impl IfaceCommon {
}
pub(super) fn poll<D: Device + ?Sized>(&self, device: &mut D) {
+ let mut sockets = self.sockets.lock_irq_disabled();
let mut interface = self.interface.lock_irq_disabled();
+
let timestamp = get_network_timestamp();
- let has_events = {
- let mut sockets = self.sockets.lock_irq_disabled();
- interface.poll(timestamp, device, &mut sockets)
- // drop sockets here to avoid deadlock
- };
- if has_events {
- self.bound_sockets.read().iter().for_each(|bound_socket| {
- if let Some(bound_socket) = bound_socket.upgrade() {
- bound_socket.on_iface_events();
+ let (has_events, poll_at) = {
+ let mut has_events = false;
+ let mut poll_at;
+ loop {
+ has_events |= interface.poll(timestamp, device, &mut sockets);
+ poll_at = interface.poll_at(timestamp, &sockets);
+ let Some(instant) = poll_at else {
+ break;
+ };
+ if instant > timestamp {
+ break;
}
- });
- }
+ }
+ (has_events, poll_at)
+ };
+
+ // drop sockets here to avoid deadlock
+ drop(interface);
+ drop(sockets);
- let sockets = self.sockets.lock_irq_disabled();
- if let Some(instant) = interface.poll_at(timestamp, &sockets) {
- let old_instant = self.next_poll_at_ms.load(Ordering::Acquire);
+ if let Some(instant) = poll_at {
+ let old_instant = self.next_poll_at_ms.load(Ordering::Relaxed);
let new_instant = instant.total_millis() as u64;
self.next_poll_at_ms.store(new_instant, Ordering::Relaxed);
- if new_instant < old_instant {
+ if old_instant == 0 || new_instant < old_instant {
self.polling_wait_queue.wake_all();
}
} else {
self.next_poll_at_ms.store(0, Ordering::Relaxed);
}
+
+ if has_events {
+ // We never try to hold the write lock in the IRQ context, and we disable IRQ when
+ // holding the write lock. So we don't need to disable IRQ when holding the read lock.
+ self.bound_sockets.read().iter().for_each(|bound_socket| {
+ bound_socket.on_iface_events();
+ });
+
+ let closed_sockets = self
+ .closing_sockets
+ .lock_irq_disabled()
+ .extract_if(|closing_socket| closing_socket.is_closed())
+ .collect::<Vec<_>>();
+ drop(closed_sockets);
+ }
}
pub(super) fn next_poll_at_ms(&self) -> Option<u64> {
- let millis = self.next_poll_at_ms.load(Ordering::SeqCst);
+ let millis = self.next_poll_at_ms.load(Ordering::Relaxed);
if millis == 0 {
None
} else {
diff --git a/kernel/aster-nix/src/net/iface/common.rs b/kernel/aster-nix/src/net/iface/common.rs
--- a/kernel/aster-nix/src/net/iface/common.rs
+++ b/kernel/aster-nix/src/net/iface/common.rs
@@ -184,19 +215,44 @@ impl IfaceCommon {
}
}
- fn insert_bound_socket(&self, socket: &Arc<AnyBoundSocket>) -> Result<()> {
- let weak_ref = KeyableWeak::from(Arc::downgrade(socket));
- let mut bound_sockets = self.bound_sockets.write();
- if bound_sockets.contains(&weak_ref) {
- return_errno_with_message!(Errno::EINVAL, "the socket is already bound");
- }
- bound_sockets.insert(weak_ref);
- Ok(())
+ fn insert_bound_socket(&self, socket: &Arc<AnyBoundSocketInner>) {
+ let keyable_socket = KeyableArc::from(socket.clone());
+
+ let inserted = self
+ .bound_sockets
+ .write_irq_disabled()
+ .insert(keyable_socket);
+ assert!(inserted);
}
- pub(super) fn remove_bound_socket(&self, socket: Weak<AnyBoundSocket>) {
- let weak_ref = KeyableWeak::from(socket);
- self.bound_sockets.write().remove(&weak_ref);
+ pub(super) fn remove_bound_socket_now(&self, socket: &Arc<AnyBoundSocketInner>) {
+ let keyable_socket = KeyableArc::from(socket.clone());
+
+ let removed = self
+ .bound_sockets
+ .write_irq_disabled()
+ .remove(&keyable_socket);
+ assert!(removed);
+ }
+
+ pub(super) fn remove_bound_socket_when_closed(&self, socket: &Arc<AnyBoundSocketInner>) {
+ let keyable_socket = KeyableArc::from(socket.clone());
+
+ let removed = self
+ .bound_sockets
+ .write_irq_disabled()
+ .remove(&keyable_socket);
+ assert!(removed);
+
+ let mut closing_sockets = self.closing_sockets.lock_irq_disabled();
+
+ // Check `is_closed` after holding the lock to avoid race conditions.
+ if keyable_socket.is_closed() {
+ return;
+ }
+
+ let inserted = closing_sockets.insert(keyable_socket);
+ assert!(inserted);
}
}
diff --git a/kernel/aster-nix/src/net/iface/common.rs b/kernel/aster-nix/src/net/iface/common.rs
--- a/kernel/aster-nix/src/net/iface/common.rs
+++ b/kernel/aster-nix/src/net/iface/common.rs
@@ -184,19 +215,44 @@ impl IfaceCommon {
}
}
- fn insert_bound_socket(&self, socket: &Arc<AnyBoundSocket>) -> Result<()> {
- let weak_ref = KeyableWeak::from(Arc::downgrade(socket));
- let mut bound_sockets = self.bound_sockets.write();
- if bound_sockets.contains(&weak_ref) {
- return_errno_with_message!(Errno::EINVAL, "the socket is already bound");
- }
- bound_sockets.insert(weak_ref);
- Ok(())
+ fn insert_bound_socket(&self, socket: &Arc<AnyBoundSocketInner>) {
+ let keyable_socket = KeyableArc::from(socket.clone());
+
+ let inserted = self
+ .bound_sockets
+ .write_irq_disabled()
+ .insert(keyable_socket);
+ assert!(inserted);
}
- pub(super) fn remove_bound_socket(&self, socket: Weak<AnyBoundSocket>) {
- let weak_ref = KeyableWeak::from(socket);
- self.bound_sockets.write().remove(&weak_ref);
+ pub(super) fn remove_bound_socket_now(&self, socket: &Arc<AnyBoundSocketInner>) {
+ let keyable_socket = KeyableArc::from(socket.clone());
+
+ let removed = self
+ .bound_sockets
+ .write_irq_disabled()
+ .remove(&keyable_socket);
+ assert!(removed);
+ }
+
+ pub(super) fn remove_bound_socket_when_closed(&self, socket: &Arc<AnyBoundSocketInner>) {
+ let keyable_socket = KeyableArc::from(socket.clone());
+
+ let removed = self
+ .bound_sockets
+ .write_irq_disabled()
+ .remove(&keyable_socket);
+ assert!(removed);
+
+ let mut closing_sockets = self.closing_sockets.lock_irq_disabled();
+
+ // Check `is_closed` after holding the lock to avoid race conditions.
+ if keyable_socket.is_closed() {
+ return;
+ }
+
+ let inserted = closing_sockets.insert(keyable_socket);
+ assert!(inserted);
}
}
diff --git a/kernel/aster-nix/src/net/iface/mod.rs b/kernel/aster-nix/src/net/iface/mod.rs
--- a/kernel/aster-nix/src/net/iface/mod.rs
+++ b/kernel/aster-nix/src/net/iface/mod.rs
@@ -45,7 +45,7 @@ pub trait Iface: internal::IfaceInternal + Send + Sync {
&self,
socket: Box<AnyUnboundSocket>,
config: BindPortConfig,
- ) -> core::result::Result<Arc<AnyBoundSocket>, (Error, Box<AnyUnboundSocket>)> {
+ ) -> core::result::Result<AnyBoundSocket, (Error, Box<AnyUnboundSocket>)> {
let common = self.common();
common.bind_socket(self.arc_self(), socket, config)
}
diff --git a/kernel/aster-nix/src/net/iface/mod.rs b/kernel/aster-nix/src/net/iface/mod.rs
--- a/kernel/aster-nix/src/net/iface/mod.rs
+++ b/kernel/aster-nix/src/net/iface/mod.rs
@@ -45,7 +45,7 @@ pub trait Iface: internal::IfaceInternal + Send + Sync {
&self,
socket: Box<AnyUnboundSocket>,
config: BindPortConfig,
- ) -> core::result::Result<Arc<AnyBoundSocket>, (Error, Box<AnyUnboundSocket>)> {
+ ) -> core::result::Result<AnyBoundSocket, (Error, Box<AnyUnboundSocket>)> {
let common = self.common();
common.bind_socket(self.arc_self(), socket, config)
}
diff --git a/kernel/aster-nix/src/net/socket/ip/common.rs b/kernel/aster-nix/src/net/socket/ip/common.rs
--- a/kernel/aster-nix/src/net/socket/ip/common.rs
+++ b/kernel/aster-nix/src/net/socket/ip/common.rs
@@ -46,7 +46,7 @@ pub(super) fn bind_socket(
unbound_socket: Box<AnyUnboundSocket>,
endpoint: &IpEndpoint,
can_reuse: bool,
-) -> core::result::Result<Arc<AnyBoundSocket>, (Error, Box<AnyUnboundSocket>)> {
+) -> core::result::Result<AnyBoundSocket, (Error, Box<AnyUnboundSocket>)> {
let iface = match get_iface_to_bind(&endpoint.addr) {
Some(iface) => iface,
None => {
diff --git a/kernel/aster-nix/src/net/socket/ip/common.rs b/kernel/aster-nix/src/net/socket/ip/common.rs
--- a/kernel/aster-nix/src/net/socket/ip/common.rs
+++ b/kernel/aster-nix/src/net/socket/ip/common.rs
@@ -46,7 +46,7 @@ pub(super) fn bind_socket(
unbound_socket: Box<AnyUnboundSocket>,
endpoint: &IpEndpoint,
can_reuse: bool,
-) -> core::result::Result<Arc<AnyBoundSocket>, (Error, Box<AnyUnboundSocket>)> {
+) -> core::result::Result<AnyBoundSocket, (Error, Box<AnyUnboundSocket>)> {
let iface = match get_iface_to_bind(&endpoint.addr) {
Some(iface) => iface,
None => {
diff --git a/kernel/aster-nix/src/net/socket/ip/datagram/bound.rs b/kernel/aster-nix/src/net/socket/ip/datagram/bound.rs
--- a/kernel/aster-nix/src/net/socket/ip/datagram/bound.rs
+++ b/kernel/aster-nix/src/net/socket/ip/datagram/bound.rs
@@ -13,12 +13,12 @@ use crate::{
};
pub struct BoundDatagram {
- bound_socket: Arc<AnyBoundSocket>,
+ bound_socket: AnyBoundSocket,
remote_endpoint: Option<IpEndpoint>,
}
impl BoundDatagram {
- pub fn new(bound_socket: Arc<AnyBoundSocket>) -> Self {
+ pub fn new(bound_socket: AnyBoundSocket) -> Self {
Self {
bound_socket,
remote_endpoint: None,
diff --git a/kernel/aster-nix/src/net/socket/ip/datagram/bound.rs b/kernel/aster-nix/src/net/socket/ip/datagram/bound.rs
--- a/kernel/aster-nix/src/net/socket/ip/datagram/bound.rs
+++ b/kernel/aster-nix/src/net/socket/ip/datagram/bound.rs
@@ -13,12 +13,12 @@ use crate::{
};
pub struct BoundDatagram {
- bound_socket: Arc<AnyBoundSocket>,
+ bound_socket: AnyBoundSocket,
remote_endpoint: Option<IpEndpoint>,
}
impl BoundDatagram {
- pub fn new(bound_socket: Arc<AnyBoundSocket>) -> Self {
+ pub fn new(bound_socket: AnyBoundSocket) -> Self {
Self {
bound_socket,
remote_endpoint: None,
diff --git a/kernel/aster-nix/src/net/socket/ip/stream/connected.rs b/kernel/aster-nix/src/net/socket/ip/stream/connected.rs
--- a/kernel/aster-nix/src/net/socket/ip/stream/connected.rs
+++ b/kernel/aster-nix/src/net/socket/ip/stream/connected.rs
@@ -15,7 +15,7 @@ use crate::{
};
pub struct ConnectedStream {
- bound_socket: Arc<AnyBoundSocket>,
+ bound_socket: AnyBoundSocket,
remote_endpoint: IpEndpoint,
/// Indicates whether this connection is "new" in a `connect()` system call.
///
diff --git a/kernel/aster-nix/src/net/socket/ip/stream/connected.rs b/kernel/aster-nix/src/net/socket/ip/stream/connected.rs
--- a/kernel/aster-nix/src/net/socket/ip/stream/connected.rs
+++ b/kernel/aster-nix/src/net/socket/ip/stream/connected.rs
@@ -15,7 +15,7 @@ use crate::{
};
pub struct ConnectedStream {
- bound_socket: Arc<AnyBoundSocket>,
+ bound_socket: AnyBoundSocket,
remote_endpoint: IpEndpoint,
/// Indicates whether this connection is "new" in a `connect()` system call.
///
diff --git a/kernel/aster-nix/src/net/socket/ip/stream/connected.rs b/kernel/aster-nix/src/net/socket/ip/stream/connected.rs
--- a/kernel/aster-nix/src/net/socket/ip/stream/connected.rs
+++ b/kernel/aster-nix/src/net/socket/ip/stream/connected.rs
@@ -32,7 +32,7 @@ pub struct ConnectedStream {
impl ConnectedStream {
pub fn new(
- bound_socket: Arc<AnyBoundSocket>,
+ bound_socket: AnyBoundSocket,
remote_endpoint: IpEndpoint,
is_new_connection: bool,
) -> Self {
diff --git a/kernel/aster-nix/src/net/socket/ip/stream/connected.rs b/kernel/aster-nix/src/net/socket/ip/stream/connected.rs
--- a/kernel/aster-nix/src/net/socket/ip/stream/connected.rs
+++ b/kernel/aster-nix/src/net/socket/ip/stream/connected.rs
@@ -32,7 +32,7 @@ pub struct ConnectedStream {
impl ConnectedStream {
pub fn new(
- bound_socket: Arc<AnyBoundSocket>,
+ bound_socket: AnyBoundSocket,
remote_endpoint: IpEndpoint,
is_new_connection: bool,
) -> Self {
diff --git a/kernel/aster-nix/src/net/socket/ip/stream/connecting.rs b/kernel/aster-nix/src/net/socket/ip/stream/connecting.rs
--- a/kernel/aster-nix/src/net/socket/ip/stream/connecting.rs
+++ b/kernel/aster-nix/src/net/socket/ip/stream/connecting.rs
@@ -8,7 +8,7 @@ use crate::{
};
pub struct ConnectingStream {
- bound_socket: Arc<AnyBoundSocket>,
+ bound_socket: AnyBoundSocket,
remote_endpoint: IpEndpoint,
conn_result: RwLock<Option<ConnResult>>,
}
diff --git a/kernel/aster-nix/src/net/socket/ip/stream/connecting.rs b/kernel/aster-nix/src/net/socket/ip/stream/connecting.rs
--- a/kernel/aster-nix/src/net/socket/ip/stream/connecting.rs
+++ b/kernel/aster-nix/src/net/socket/ip/stream/connecting.rs
@@ -8,7 +8,7 @@ use crate::{
};
pub struct ConnectingStream {
- bound_socket: Arc<AnyBoundSocket>,
+ bound_socket: AnyBoundSocket,
remote_endpoint: IpEndpoint,
conn_result: RwLock<Option<ConnResult>>,
}
diff --git a/kernel/aster-nix/src/net/socket/ip/stream/connecting.rs b/kernel/aster-nix/src/net/socket/ip/stream/connecting.rs
--- a/kernel/aster-nix/src/net/socket/ip/stream/connecting.rs
+++ b/kernel/aster-nix/src/net/socket/ip/stream/connecting.rs
@@ -26,9 +26,9 @@ pub enum NonConnectedStream {
impl ConnectingStream {
pub fn new(
- bound_socket: Arc<AnyBoundSocket>,
+ bound_socket: AnyBoundSocket,
remote_endpoint: IpEndpoint,
- ) -> core::result::Result<Self, (Error, Arc<AnyBoundSocket>)> {
+ ) -> core::result::Result<Self, (Error, AnyBoundSocket)> {
if let Err(err) = bound_socket.do_connect(remote_endpoint) {
return Err((err, bound_socket));
}
diff --git a/kernel/aster-nix/src/net/socket/ip/stream/connecting.rs b/kernel/aster-nix/src/net/socket/ip/stream/connecting.rs
--- a/kernel/aster-nix/src/net/socket/ip/stream/connecting.rs
+++ b/kernel/aster-nix/src/net/socket/ip/stream/connecting.rs
@@ -26,9 +26,9 @@ pub enum NonConnectedStream {
impl ConnectingStream {
pub fn new(
- bound_socket: Arc<AnyBoundSocket>,
+ bound_socket: AnyBoundSocket,
remote_endpoint: IpEndpoint,
- ) -> core::result::Result<Self, (Error, Arc<AnyBoundSocket>)> {
+ ) -> core::result::Result<Self, (Error, AnyBoundSocket)> {
if let Err(err) = bound_socket.do_connect(remote_endpoint) {
return Err((err, bound_socket));
}
diff --git a/kernel/aster-nix/src/net/socket/ip/stream/init.rs b/kernel/aster-nix/src/net/socket/ip/stream/init.rs
--- a/kernel/aster-nix/src/net/socket/ip/stream/init.rs
+++ b/kernel/aster-nix/src/net/socket/ip/stream/init.rs
@@ -15,7 +15,7 @@ use crate::{
pub enum InitStream {
Unbound(Box<AnyUnboundSocket>),
- Bound(Arc<AnyBoundSocket>),
+ Bound(AnyBoundSocket),
}
impl InitStream {
diff --git a/kernel/aster-nix/src/net/socket/ip/stream/init.rs b/kernel/aster-nix/src/net/socket/ip/stream/init.rs
--- a/kernel/aster-nix/src/net/socket/ip/stream/init.rs
+++ b/kernel/aster-nix/src/net/socket/ip/stream/init.rs
@@ -15,7 +15,7 @@ use crate::{
pub enum InitStream {
Unbound(Box<AnyUnboundSocket>),
- Bound(Arc<AnyBoundSocket>),
+ Bound(AnyBoundSocket),
}
impl InitStream {
diff --git a/kernel/aster-nix/src/net/socket/ip/stream/init.rs b/kernel/aster-nix/src/net/socket/ip/stream/init.rs
--- a/kernel/aster-nix/src/net/socket/ip/stream/init.rs
+++ b/kernel/aster-nix/src/net/socket/ip/stream/init.rs
@@ -23,14 +23,14 @@ impl InitStream {
InitStream::Unbound(Box::new(AnyUnboundSocket::new_tcp(observer)))
}
- pub fn new_bound(bound_socket: Arc<AnyBoundSocket>) -> Self {
+ pub fn new_bound(bound_socket: AnyBoundSocket) -> Self {
InitStream::Bound(bound_socket)
}
pub fn bind(
self,
endpoint: &IpEndpoint,
- ) -> core::result::Result<Arc<AnyBoundSocket>, (Error, Self)> {
+ ) -> core::result::Result<AnyBoundSocket, (Error, Self)> {
let unbound_socket = match self {
InitStream::Unbound(unbound_socket) => unbound_socket,
InitStream::Bound(bound_socket) => {
diff --git a/kernel/aster-nix/src/net/socket/ip/stream/init.rs b/kernel/aster-nix/src/net/socket/ip/stream/init.rs
--- a/kernel/aster-nix/src/net/socket/ip/stream/init.rs
+++ b/kernel/aster-nix/src/net/socket/ip/stream/init.rs
@@ -23,14 +23,14 @@ impl InitStream {
InitStream::Unbound(Box::new(AnyUnboundSocket::new_tcp(observer)))
}
- pub fn new_bound(bound_socket: Arc<AnyBoundSocket>) -> Self {
+ pub fn new_bound(bound_socket: AnyBoundSocket) -> Self {
InitStream::Bound(bound_socket)
}
pub fn bind(
self,
endpoint: &IpEndpoint,
- ) -> core::result::Result<Arc<AnyBoundSocket>, (Error, Self)> {
+ ) -> core::result::Result<AnyBoundSocket, (Error, Self)> {
let unbound_socket = match self {
InitStream::Unbound(unbound_socket) => unbound_socket,
InitStream::Bound(bound_socket) => {
diff --git a/kernel/aster-nix/src/net/socket/ip/stream/init.rs b/kernel/aster-nix/src/net/socket/ip/stream/init.rs
--- a/kernel/aster-nix/src/net/socket/ip/stream/init.rs
+++ b/kernel/aster-nix/src/net/socket/ip/stream/init.rs
@@ -50,7 +50,7 @@ impl InitStream {
fn bind_to_ephemeral_endpoint(
self,
remote_endpoint: &IpEndpoint,
- ) -> core::result::Result<Arc<AnyBoundSocket>, (Error, Self)> {
+ ) -> core::result::Result<AnyBoundSocket, (Error, Self)> {
let endpoint = get_ephemeral_endpoint(remote_endpoint);
self.bind(&endpoint)
}
diff --git a/kernel/aster-nix/src/net/socket/ip/stream/init.rs b/kernel/aster-nix/src/net/socket/ip/stream/init.rs
--- a/kernel/aster-nix/src/net/socket/ip/stream/init.rs
+++ b/kernel/aster-nix/src/net/socket/ip/stream/init.rs
@@ -50,7 +50,7 @@ impl InitStream {
fn bind_to_ephemeral_endpoint(
self,
remote_endpoint: &IpEndpoint,
- ) -> core::result::Result<Arc<AnyBoundSocket>, (Error, Self)> {
+ ) -> core::result::Result<AnyBoundSocket, (Error, Self)> {
let endpoint = get_ephemeral_endpoint(remote_endpoint);
self.bind(&endpoint)
}
diff --git a/kernel/aster-nix/src/net/socket/ip/stream/listen.rs b/kernel/aster-nix/src/net/socket/ip/stream/listen.rs
--- a/kernel/aster-nix/src/net/socket/ip/stream/listen.rs
+++ b/kernel/aster-nix/src/net/socket/ip/stream/listen.rs
@@ -13,16 +13,16 @@ use crate::{
pub struct ListenStream {
backlog: usize,
/// A bound socket held to ensure the TCP port cannot be released
- bound_socket: Arc<AnyBoundSocket>,
+ bound_socket: AnyBoundSocket,
/// Backlog sockets listening at the local endpoint
backlog_sockets: RwLock<Vec<BacklogSocket>>,
}
impl ListenStream {
pub fn new(
- bound_socket: Arc<AnyBoundSocket>,
+ bound_socket: AnyBoundSocket,
backlog: usize,
- ) -> core::result::Result<Self, (Error, Arc<AnyBoundSocket>)> {
+ ) -> core::result::Result<Self, (Error, AnyBoundSocket)> {
let listen_stream = Self {
backlog,
bound_socket,
diff --git a/kernel/aster-nix/src/net/socket/ip/stream/listen.rs b/kernel/aster-nix/src/net/socket/ip/stream/listen.rs
--- a/kernel/aster-nix/src/net/socket/ip/stream/listen.rs
+++ b/kernel/aster-nix/src/net/socket/ip/stream/listen.rs
@@ -13,16 +13,16 @@ use crate::{
pub struct ListenStream {
backlog: usize,
/// A bound socket held to ensure the TCP port cannot be released
- bound_socket: Arc<AnyBoundSocket>,
+ bound_socket: AnyBoundSocket,
/// Backlog sockets listening at the local endpoint
backlog_sockets: RwLock<Vec<BacklogSocket>>,
}
impl ListenStream {
pub fn new(
- bound_socket: Arc<AnyBoundSocket>,
+ bound_socket: AnyBoundSocket,
backlog: usize,
- ) -> core::result::Result<Self, (Error, Arc<AnyBoundSocket>)> {
+ ) -> core::result::Result<Self, (Error, AnyBoundSocket)> {
let listen_stream = Self {
backlog,
bound_socket,
diff --git a/kernel/aster-nix/src/net/socket/ip/stream/listen.rs b/kernel/aster-nix/src/net/socket/ip/stream/listen.rs
--- a/kernel/aster-nix/src/net/socket/ip/stream/listen.rs
+++ b/kernel/aster-nix/src/net/socket/ip/stream/listen.rs
@@ -99,13 +99,13 @@ impl ListenStream {
}
struct BacklogSocket {
- bound_socket: Arc<AnyBoundSocket>,
+ bound_socket: AnyBoundSocket,
}
impl BacklogSocket {
// FIXME: All of the error codes below seem to have no Linux equivalents, and I see no reason
// why the error may occur. Perhaps it is better to call `unwrap()` directly?
- fn new(bound_socket: &Arc<AnyBoundSocket>) -> Result<Self> {
+ fn new(bound_socket: &AnyBoundSocket) -> Result<Self> {
let local_endpoint = bound_socket.local_endpoint().ok_or(Error::with_message(
Errno::EINVAL,
"the socket is not bound",
diff --git a/kernel/aster-nix/src/net/socket/ip/stream/listen.rs b/kernel/aster-nix/src/net/socket/ip/stream/listen.rs
--- a/kernel/aster-nix/src/net/socket/ip/stream/listen.rs
+++ b/kernel/aster-nix/src/net/socket/ip/stream/listen.rs
@@ -99,13 +99,13 @@ impl ListenStream {
}
struct BacklogSocket {
- bound_socket: Arc<AnyBoundSocket>,
+ bound_socket: AnyBoundSocket,
}
impl BacklogSocket {
// FIXME: All of the error codes below seem to have no Linux equivalents, and I see no reason
// why the error may occur. Perhaps it is better to call `unwrap()` directly?
- fn new(bound_socket: &Arc<AnyBoundSocket>) -> Result<Self> {
+ fn new(bound_socket: &AnyBoundSocket) -> Result<Self> {
let local_endpoint = bound_socket.local_endpoint().ok_or(Error::with_message(
Errno::EINVAL,
"the socket is not bound",
diff --git a/kernel/aster-nix/src/net/socket/ip/stream/listen.rs b/kernel/aster-nix/src/net/socket/ip/stream/listen.rs
--- a/kernel/aster-nix/src/net/socket/ip/stream/listen.rs
+++ b/kernel/aster-nix/src/net/socket/ip/stream/listen.rs
@@ -143,7 +143,7 @@ impl BacklogSocket {
.raw_with(|socket: &mut RawTcpSocket| socket.remote_endpoint())
}
- fn into_bound_socket(self) -> Arc<AnyBoundSocket> {
+ fn into_bound_socket(self) -> AnyBoundSocket {
self.bound_socket
}
}
diff --git a/kernel/aster-nix/src/net/socket/ip/stream/listen.rs b/kernel/aster-nix/src/net/socket/ip/stream/listen.rs
--- a/kernel/aster-nix/src/net/socket/ip/stream/listen.rs
+++ b/kernel/aster-nix/src/net/socket/ip/stream/listen.rs
@@ -143,7 +143,7 @@ impl BacklogSocket {
.raw_with(|socket: &mut RawTcpSocket| socket.remote_endpoint())
}
- fn into_bound_socket(self) -> Arc<AnyBoundSocket> {
+ fn into_bound_socket(self) -> AnyBoundSocket {
self.bound_socket
}
}
diff --git a/test/apps/network/listen_backlog.c b/test/apps/network/listen_backlog.c
--- a/test/apps/network/listen_backlog.c
+++ b/test/apps/network/listen_backlog.c
@@ -131,7 +131,7 @@ int main(void)
for (backlog = 0; backlog <= MAX_TEST_BACKLOG; ++backlog) {
// Avoid "bind: Address already in use"
- addr.sin_port = htons(8080 + backlog);
+ addr.sin_port = htons(10000 + backlog);
err = test_listen_backlog(&addr, backlog);
if (err != 0)
diff --git a/test/apps/network/send_buf_full.c b/test/apps/network/send_buf_full.c
--- a/test/apps/network/send_buf_full.c
+++ b/test/apps/network/send_buf_full.c
@@ -265,7 +265,7 @@ int main(void)
struct sockaddr_in addr;
addr.sin_family = AF_INET;
- addr.sin_port = htons(8080);
+ addr.sin_port = htons(9999);
if (inet_aton("127.0.0.1", &addr.sin_addr) < 0) {
fprintf(stderr, "inet_aton cannot parse 127.0.0.1\n");
return -1;
diff --git a/test/apps/network/tcp_err.c b/test/apps/network/tcp_err.c
--- a/test/apps/network/tcp_err.c
+++ b/test/apps/network/tcp_err.c
@@ -338,26 +338,23 @@ FN_TEST(sendmsg_and_recvmsg)
// Send two message and receive two message
- // This test is commented out due to a known issue:
- // See <https://github.com/asterinas/asterinas/issues/819>
-
- // iov[0].iov_base = message;
- // iov[0].iov_len = strlen(message);
- // msg.msg_iovlen = 1;
- // TEST_RES(sendmsg(sk_accepted, &msg, 0), _ret == strlen(message));
- // TEST_RES(sendmsg(sk_accepted, &msg, 0), _ret == strlen(message));
-
- // char first_buffer[BUFFER_SIZE] = { 0 };
- // char second_buffer[BUFFER_SIZE] = { 0 };
- // iov[0].iov_base = first_buffer;
- // iov[0].iov_len = BUFFER_SIZE;
- // iov[1].iov_base = second_buffer;
- // iov[1].iov_len = BUFFER_SIZE;
- // msg.msg_iovlen = 2;
-
- // // Ensure two messages are prepared for receiving
- // sleep(1);
-
- // TEST_RES(recvmsg(sk_connected, &msg, 0), _ret == strlen(message) * 2);
+ iov[0].iov_base = message;
+ iov[0].iov_len = strlen(message);
+ msg.msg_iovlen = 1;
+ TEST_RES(sendmsg(sk_accepted, &msg, 0), _ret == strlen(message));
+ TEST_RES(sendmsg(sk_accepted, &msg, 0), _ret == strlen(message));
+
+ char first_buffer[BUFFER_SIZE] = { 0 };
+ char second_buffer[BUFFER_SIZE] = { 0 };
+ iov[0].iov_base = first_buffer;
+ iov[0].iov_len = BUFFER_SIZE;
+ iov[1].iov_base = second_buffer;
+ iov[1].iov_len = BUFFER_SIZE;
+ msg.msg_iovlen = 2;
+
+ // Ensure two messages are prepared for receiving
+ sleep(1);
+
+ TEST_RES(recvmsg(sk_connected, &msg, 0), _ret == strlen(message) * 2);
}
END_TEST()
|
2024-07-26T01:51:02Z
|
562e64437584279783f244edba10b512beddc81d
|
|
asterinas/asterinas
|
diff --git a/.github/workflows/test_asterinas.yml b/.github/workflows/test_asterinas.yml
--- a/.github/workflows/test_asterinas.yml
+++ b/.github/workflows/test_asterinas.yml
@@ -60,36 +60,24 @@ jobs:
id: boot_test_mb
run: make run AUTO_TEST=boot ENABLE_KVM=1 BOOT_PROTOCOL=multiboot RELEASE=1
- - name: Boot Test (Multiboot2)
- id: boot_test_mb2
- run: make run AUTO_TEST=boot ENABLE_KVM=1 BOOT_PROTOCOL=multiboot2 RELEASE=1
-
- - name: Boot Test (MicroVM)
- id: boot_test_microvm
- run: make run AUTO_TEST=boot ENABLE_KVM=1 SCHEME=microvm RELEASE=1
-
- name: Boot Test (Linux Legacy 32-bit Boot Protocol)
id: boot_test_linux_legacy32
run: make run AUTO_TEST=boot ENABLE_KVM=1 BOOT_PROTOCOL=linux-legacy32 RELEASE=1
- - name: Boot Test (Linux EFI Handover Boot Protocol)
- id: boot_test_linux_efi_handover64
- run: make run AUTO_TEST=boot ENABLE_KVM=1 BOOT_PROTOCOL=linux-efi-handover64 RELEASE=1
-
- - name: Syscall Test (Linux EFI Handover Boot Protocol)
+ - name: Syscall Test (Linux EFI Handover Boot Protocol) (Debug Build)
id: syscall_test
- run: make run AUTO_TEST=syscall ENABLE_KVM=1 BOOT_PROTOCOL=linux-efi-handover64 RELEASE=1
+ run: make run AUTO_TEST=syscall ENABLE_KVM=1 BOOT_PROTOCOL=linux-efi-handover64 RELEASE=0
- name: Syscall Test at Ext2 (MicroVM)
id: syscall_test_at_ext2
run: make run AUTO_TEST=syscall SYSCALL_TEST_DIR=/ext2 ENABLE_KVM=1 SCHEME=microvm RELEASE=1
- - name: Syscall Test at Exfat and without KVM enabled
+ - name: Syscall Test at Exfat (Multiboot2) (without KVM enabled)
id: syscall_test_at_exfat_linux
run: |
make run AUTO_TEST=syscall \
SYSCALL_TEST_DIR=/exfat EXTRA_BLOCKLISTS_DIRS=blocklists.exfat \
- ENABLE_KVM=0 BOOT_PROTOCOL=linux-efi-handover64 RELEASE=1
+ ENABLE_KVM=0 BOOT_PROTOCOL=multiboot2 RELEASE=1
- name: General Test (Linux EFI Handover Boot Protocol)
id: test_linux
|
[
"1069"
] |
0.6
|
5aa28eae7e14594bbe68827114443b31002bf742
|
CPU local memory is used before initialized
The use (in `ostd`):
`init` → `mm::heap_allocator::init` → `HEAP_ALLOCATOR.init` → `SpinLock::lock_irq_disabled` → `trap::irq::disable_local` → `task::processor::disable_preempt` → `PREEMPT_COUNT.increase_num_locks`, where `PREEMPT_COUNT` is a cpu-local variable.
The initialization:
`init` → `cpu::cpu_local::init_on_bsp` → ...
The use is before the initialization since `mm::heap_allocator::init` is called prior to `cpu::cpu_local::init_on_bsp`.
https://github.com/asterinas/asterinas/blob/94eba6d85eb9e62ddd904c1132d556b808cc3174/ostd/src/lib.rs#L51-L82
---
It does not fault in x86 because `fsbase` is by default `0`, and the OS has write access to the memory near `0x0`, so the error is silent. But in RISC-V, this memory region is not writable, so it faults.
And I guess this is not the only case since `SpinLock` is widely used in `ostd`, it might be other uses of `SpinLock` before CPU local memory is initialized, for example, `mm::kspace::init_boot_page_table` → `BOOT_PAGE_TABLE.lock`.
|
asterinas__asterinas-1073
| 1,073
|
diff --git a/.github/workflows/test_asterinas.yml b/.github/workflows/test_asterinas.yml
--- a/.github/workflows/test_asterinas.yml
+++ b/.github/workflows/test_asterinas.yml
@@ -60,36 +60,24 @@ jobs:
id: boot_test_mb
run: make run AUTO_TEST=boot ENABLE_KVM=1 BOOT_PROTOCOL=multiboot RELEASE=1
- - name: Boot Test (Multiboot2)
- id: boot_test_mb2
- run: make run AUTO_TEST=boot ENABLE_KVM=1 BOOT_PROTOCOL=multiboot2 RELEASE=1
-
- - name: Boot Test (MicroVM)
- id: boot_test_microvm
- run: make run AUTO_TEST=boot ENABLE_KVM=1 SCHEME=microvm RELEASE=1
-
- name: Boot Test (Linux Legacy 32-bit Boot Protocol)
id: boot_test_linux_legacy32
run: make run AUTO_TEST=boot ENABLE_KVM=1 BOOT_PROTOCOL=linux-legacy32 RELEASE=1
- - name: Boot Test (Linux EFI Handover Boot Protocol)
- id: boot_test_linux_efi_handover64
- run: make run AUTO_TEST=boot ENABLE_KVM=1 BOOT_PROTOCOL=linux-efi-handover64 RELEASE=1
-
- - name: Syscall Test (Linux EFI Handover Boot Protocol)
+ - name: Syscall Test (Linux EFI Handover Boot Protocol) (Debug Build)
id: syscall_test
- run: make run AUTO_TEST=syscall ENABLE_KVM=1 BOOT_PROTOCOL=linux-efi-handover64 RELEASE=1
+ run: make run AUTO_TEST=syscall ENABLE_KVM=1 BOOT_PROTOCOL=linux-efi-handover64 RELEASE=0
- name: Syscall Test at Ext2 (MicroVM)
id: syscall_test_at_ext2
run: make run AUTO_TEST=syscall SYSCALL_TEST_DIR=/ext2 ENABLE_KVM=1 SCHEME=microvm RELEASE=1
- - name: Syscall Test at Exfat and without KVM enabled
+ - name: Syscall Test at Exfat (Multiboot2) (without KVM enabled)
id: syscall_test_at_exfat_linux
run: |
make run AUTO_TEST=syscall \
SYSCALL_TEST_DIR=/exfat EXTRA_BLOCKLISTS_DIRS=blocklists.exfat \
- ENABLE_KVM=0 BOOT_PROTOCOL=linux-efi-handover64 RELEASE=1
+ ENABLE_KVM=0 BOOT_PROTOCOL=multiboot2 RELEASE=1
- name: General Test (Linux EFI Handover Boot Protocol)
id: test_linux
diff --git a/osdk/src/base_crate/x86_64.ld.template b/osdk/src/base_crate/x86_64.ld.template
--- a/osdk/src/base_crate/x86_64.ld.template
+++ b/osdk/src/base_crate/x86_64.ld.template
@@ -58,6 +58,16 @@ SECTIONS
# areas for the application processors.
.cpu_local : AT(ADDR(.cpu_local) - KERNEL_VMA) {
__cpu_local_start = .;
+
+ # These 4 bytes are used to store the CPU ID.
+ . += 4;
+
+ # These 4 bytes are used to store the number of preemption locks held.
+ # The reason is stated in the Rust documentation of
+ # [`ostd::task::processor::PreemptInfo`].
+ __cpu_local_preempt_lock_count = . - __cpu_local_start;
+ . += 4;
+
KEEP(*(SORT(.cpu_local)))
__cpu_local_end = .;
}
diff --git a/osdk/src/base_crate/x86_64.ld.template b/osdk/src/base_crate/x86_64.ld.template
--- a/osdk/src/base_crate/x86_64.ld.template
+++ b/osdk/src/base_crate/x86_64.ld.template
@@ -58,6 +58,16 @@ SECTIONS
# areas for the application processors.
.cpu_local : AT(ADDR(.cpu_local) - KERNEL_VMA) {
__cpu_local_start = .;
+
+ # These 4 bytes are used to store the CPU ID.
+ . += 4;
+
+ # These 4 bytes are used to store the number of preemption locks held.
+ # The reason is stated in the Rust documentation of
+ # [`ostd::task::processor::PreemptInfo`].
+ __cpu_local_preempt_lock_count = . - __cpu_local_start;
+ . += 4;
+
KEEP(*(SORT(.cpu_local)))
__cpu_local_end = .;
}
diff --git /dev/null b/ostd/src/arch/x86/cpu/local.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/arch/x86/cpu/local.rs
@@ -0,0 +1,87 @@
+// SPDX-License-Identifier: MPL-2.0
+
+//! Architecture dependent CPU-local information utilities.
+
+use x86_64::registers::segmentation::{Segment64, FS};
+
+/// Sets the base address for the CPU local storage by writing to the FS base model-specific register.
+/// This operation is marked as `unsafe` because it directly interfaces with low-level CPU registers.
+///
+/// # Safety
+///
+/// - This function is safe to call provided that the FS register is dedicated entirely for CPU local storage
+/// and is not concurrently accessed for other purposes.
+/// - The caller must ensure that `addr` is a valid address and properly aligned, as required by the CPU.
+/// - This function should only be called in contexts where the CPU is in a state to accept such changes,
+/// such as during processor initialization.
+pub(crate) unsafe fn set_base(addr: u64) {
+ FS::write_base(x86_64::addr::VirtAddr::new(addr));
+}
+
+/// Gets the base address for the CPU local storage by reading the FS base model-specific register.
+pub(crate) fn get_base() -> u64 {
+ FS::read_base().as_u64()
+}
+
+pub mod preempt_lock_count {
+ //! We need to increment/decrement the per-CPU preemption lock count using
+ //! a single instruction. This requirement is stated by
+ //! [`crate::task::processor::PreemptInfo`].
+
+ /// The GDT ensures that the FS segment is initialized to zero on boot.
+ /// This assertion checks that the base address has been set.
+ macro_rules! debug_assert_initialized {
+ () => {
+ // The compiler may think that [`super::get_base`] has side effects
+ // so it may not be optimized out. We make sure that it will be
+ // conditionally compiled only in debug builds.
+ #[cfg(debug_assertions)]
+ debug_assert_ne!(super::get_base(), 0);
+ };
+ }
+
+ /// Increments the per-CPU preemption lock count using one instruction.
+ pub(crate) fn inc() {
+ debug_assert_initialized!();
+
+ // SAFETY: The inline assembly increments the lock count in one
+ // instruction without side effects.
+ unsafe {
+ core::arch::asm!(
+ "add dword ptr fs:[__cpu_local_preempt_lock_count], 1",
+ options(nostack),
+ );
+ }
+ }
+
+ /// Decrements the per-CPU preemption lock count using one instruction.
+ pub(crate) fn dec() {
+ debug_assert_initialized!();
+
+ // SAFETY: The inline assembly decrements the lock count in one
+ // instruction without side effects.
+ unsafe {
+ core::arch::asm!(
+ "sub dword ptr fs:[__cpu_local_preempt_lock_count], 1",
+ options(nostack),
+ );
+ }
+ }
+
+ /// Gets the per-CPU preemption lock count using one instruction.
+ pub(crate) fn get() -> u32 {
+ debug_assert_initialized!();
+
+ let count: u32;
+ // SAFETY: The inline assembly reads the lock count in one instruction
+ // without side effects.
+ unsafe {
+ core::arch::asm!(
+ "mov {0:e}, fs:[__cpu_local_preempt_lock_count]",
+ out(reg) count,
+ options(nostack, readonly),
+ );
+ }
+ count
+ }
+}
diff --git /dev/null b/ostd/src/arch/x86/cpu/local.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/arch/x86/cpu/local.rs
@@ -0,0 +1,87 @@
+// SPDX-License-Identifier: MPL-2.0
+
+//! Architecture dependent CPU-local information utilities.
+
+use x86_64::registers::segmentation::{Segment64, FS};
+
+/// Sets the base address for the CPU local storage by writing to the FS base model-specific register.
+/// This operation is marked as `unsafe` because it directly interfaces with low-level CPU registers.
+///
+/// # Safety
+///
+/// - This function is safe to call provided that the FS register is dedicated entirely for CPU local storage
+/// and is not concurrently accessed for other purposes.
+/// - The caller must ensure that `addr` is a valid address and properly aligned, as required by the CPU.
+/// - This function should only be called in contexts where the CPU is in a state to accept such changes,
+/// such as during processor initialization.
+pub(crate) unsafe fn set_base(addr: u64) {
+ FS::write_base(x86_64::addr::VirtAddr::new(addr));
+}
+
+/// Gets the base address for the CPU local storage by reading the FS base model-specific register.
+pub(crate) fn get_base() -> u64 {
+ FS::read_base().as_u64()
+}
+
+pub mod preempt_lock_count {
+ //! We need to increment/decrement the per-CPU preemption lock count using
+ //! a single instruction. This requirement is stated by
+ //! [`crate::task::processor::PreemptInfo`].
+
+ /// The GDT ensures that the FS segment is initialized to zero on boot.
+ /// This assertion checks that the base address has been set.
+ macro_rules! debug_assert_initialized {
+ () => {
+ // The compiler may think that [`super::get_base`] has side effects
+ // so it may not be optimized out. We make sure that it will be
+ // conditionally compiled only in debug builds.
+ #[cfg(debug_assertions)]
+ debug_assert_ne!(super::get_base(), 0);
+ };
+ }
+
+ /// Increments the per-CPU preemption lock count using one instruction.
+ pub(crate) fn inc() {
+ debug_assert_initialized!();
+
+ // SAFETY: The inline assembly increments the lock count in one
+ // instruction without side effects.
+ unsafe {
+ core::arch::asm!(
+ "add dword ptr fs:[__cpu_local_preempt_lock_count], 1",
+ options(nostack),
+ );
+ }
+ }
+
+ /// Decrements the per-CPU preemption lock count using one instruction.
+ pub(crate) fn dec() {
+ debug_assert_initialized!();
+
+ // SAFETY: The inline assembly decrements the lock count in one
+ // instruction without side effects.
+ unsafe {
+ core::arch::asm!(
+ "sub dword ptr fs:[__cpu_local_preempt_lock_count], 1",
+ options(nostack),
+ );
+ }
+ }
+
+ /// Gets the per-CPU preemption lock count using one instruction.
+ pub(crate) fn get() -> u32 {
+ debug_assert_initialized!();
+
+ let count: u32;
+ // SAFETY: The inline assembly reads the lock count in one instruction
+ // without side effects.
+ unsafe {
+ core::arch::asm!(
+ "mov {0:e}, fs:[__cpu_local_preempt_lock_count]",
+ out(reg) count,
+ options(nostack, readonly),
+ );
+ }
+ count
+ }
+}
diff --git a/ostd/src/arch/x86/cpu.rs b/ostd/src/arch/x86/cpu/mod.rs
--- a/ostd/src/arch/x86/cpu.rs
+++ b/ostd/src/arch/x86/cpu/mod.rs
@@ -2,6 +2,8 @@
//! CPU.
+pub mod local;
+
use alloc::vec::Vec;
use core::{
arch::x86_64::{_fxrstor, _fxsave},
diff --git a/ostd/src/arch/x86/cpu.rs b/ostd/src/arch/x86/cpu/mod.rs
--- a/ostd/src/arch/x86/cpu.rs
+++ b/ostd/src/arch/x86/cpu/mod.rs
@@ -2,6 +2,8 @@
//! CPU.
+pub mod local;
+
use alloc::vec::Vec;
use core::{
arch::x86_64::{_fxrstor, _fxsave},
diff --git a/ostd/src/arch/x86/cpu.rs b/ostd/src/arch/x86/cpu/mod.rs
--- a/ostd/src/arch/x86/cpu.rs
+++ b/ostd/src/arch/x86/cpu/mod.rs
@@ -18,10 +20,7 @@ use log::debug;
use tdx_guest::tdcall;
pub use trapframe::GeneralRegs as RawGeneralRegs;
use trapframe::UserContext as RawUserContext;
-use x86_64::registers::{
- rflags::RFlags,
- segmentation::{Segment64, FS},
-};
+use x86_64::registers::rflags::RFlags;
#[cfg(feature = "intel_tdx")]
use crate::arch::tdx_guest::{handle_virtual_exception, TdxTrapFrame};
diff --git a/ostd/src/arch/x86/cpu.rs b/ostd/src/arch/x86/cpu/mod.rs
--- a/ostd/src/arch/x86/cpu.rs
+++ b/ostd/src/arch/x86/cpu/mod.rs
@@ -18,10 +20,7 @@ use log::debug;
use tdx_guest::tdcall;
pub use trapframe::GeneralRegs as RawGeneralRegs;
use trapframe::UserContext as RawUserContext;
-use x86_64::registers::{
- rflags::RFlags,
- segmentation::{Segment64, FS},
-};
+use x86_64::registers::rflags::RFlags;
#[cfg(feature = "intel_tdx")]
use crate::arch::tdx_guest::{handle_virtual_exception, TdxTrapFrame};
diff --git a/ostd/src/arch/x86/cpu.rs b/ostd/src/arch/x86/cpu/mod.rs
--- a/ostd/src/arch/x86/cpu.rs
+++ b/ostd/src/arch/x86/cpu/mod.rs
@@ -673,22 +672,3 @@ impl Default for FpRegs {
struct FxsaveArea {
data: [u8; 512], // 512 bytes
}
-
-/// Sets the base address for the CPU local storage by writing to the FS base model-specific register.
-/// This operation is marked as `unsafe` because it directly interfaces with low-level CPU registers.
-///
-/// # Safety
-///
-/// - This function is safe to call provided that the FS register is dedicated entirely for CPU local storage
-/// and is not concurrently accessed for other purposes.
-/// - The caller must ensure that `addr` is a valid address and properly aligned, as required by the CPU.
-/// - This function should only be called in contexts where the CPU is in a state to accept such changes,
-/// such as during processor initialization.
-pub(crate) unsafe fn set_cpu_local_base(addr: u64) {
- FS::write_base(x86_64::addr::VirtAddr::new(addr));
-}
-
-/// Gets the base address for the CPU local storage by reading the FS base model-specific register.
-pub(crate) fn get_cpu_local_base() -> u64 {
- FS::read_base().as_u64()
-}
diff --git a/ostd/src/arch/x86/cpu.rs b/ostd/src/arch/x86/cpu/mod.rs
--- a/ostd/src/arch/x86/cpu.rs
+++ b/ostd/src/arch/x86/cpu/mod.rs
@@ -673,22 +672,3 @@ impl Default for FpRegs {
struct FxsaveArea {
data: [u8; 512], // 512 bytes
}
-
-/// Sets the base address for the CPU local storage by writing to the FS base model-specific register.
-/// This operation is marked as `unsafe` because it directly interfaces with low-level CPU registers.
-///
-/// # Safety
-///
-/// - This function is safe to call provided that the FS register is dedicated entirely for CPU local storage
-/// and is not concurrently accessed for other purposes.
-/// - The caller must ensure that `addr` is a valid address and properly aligned, as required by the CPU.
-/// - This function should only be called in contexts where the CPU is in a state to accept such changes,
-/// such as during processor initialization.
-pub(crate) unsafe fn set_cpu_local_base(addr: u64) {
- FS::write_base(x86_64::addr::VirtAddr::new(addr));
-}
-
-/// Gets the base address for the CPU local storage by reading the FS base model-specific register.
-pub(crate) fn get_cpu_local_base() -> u64 {
- FS::read_base().as_u64()
-}
diff --git a/ostd/src/cpu/cpu_local.rs b/ostd/src/cpu/cpu_local.rs
--- a/ostd/src/cpu/cpu_local.rs
+++ b/ostd/src/cpu/cpu_local.rs
@@ -21,7 +21,7 @@
use core::ops::Deref;
use crate::{
- cpu::{get_cpu_local_base, set_cpu_local_base},
+ arch,
trap::{disable_local, DisabledLocalIrqGuard},
};
diff --git a/ostd/src/cpu/cpu_local.rs b/ostd/src/cpu/cpu_local.rs
--- a/ostd/src/cpu/cpu_local.rs
+++ b/ostd/src/cpu/cpu_local.rs
@@ -21,7 +21,7 @@
use core::ops::Deref;
use crate::{
- cpu::{get_cpu_local_base, set_cpu_local_base},
+ arch,
trap::{disable_local, DisabledLocalIrqGuard},
};
diff --git a/ostd/src/cpu/cpu_local.rs b/ostd/src/cpu/cpu_local.rs
--- a/ostd/src/cpu/cpu_local.rs
+++ b/ostd/src/cpu/cpu_local.rs
@@ -82,6 +82,13 @@ impl<T> !Clone for CpuLocal<T> {}
// other tasks as they should live on other CPUs to make sending useful.
impl<T> !Send for CpuLocal<T> {}
+// A check to ensure that the CPU-local object is never accessed before the
+// initialization for all CPUs.
+#[cfg(debug_assertions)]
+use core::sync::atomic::{AtomicBool, Ordering};
+#[cfg(debug_assertions)]
+static IS_INITIALIZED: AtomicBool = AtomicBool::new(false);
+
impl<T> CpuLocal<T> {
/// Initialize a CPU-local object.
///
diff --git a/ostd/src/cpu/cpu_local.rs b/ostd/src/cpu/cpu_local.rs
--- a/ostd/src/cpu/cpu_local.rs
+++ b/ostd/src/cpu/cpu_local.rs
@@ -82,6 +82,13 @@ impl<T> !Clone for CpuLocal<T> {}
// other tasks as they should live on other CPUs to make sending useful.
impl<T> !Send for CpuLocal<T> {}
+// A check to ensure that the CPU-local object is never accessed before the
+// initialization for all CPUs.
+#[cfg(debug_assertions)]
+use core::sync::atomic::{AtomicBool, Ordering};
+#[cfg(debug_assertions)]
+static IS_INITIALIZED: AtomicBool = AtomicBool::new(false);
+
impl<T> CpuLocal<T> {
/// Initialize a CPU-local object.
///
diff --git a/ostd/src/cpu/cpu_local.rs b/ostd/src/cpu/cpu_local.rs
--- a/ostd/src/cpu/cpu_local.rs
+++ b/ostd/src/cpu/cpu_local.rs
@@ -115,6 +122,11 @@ impl<T> CpuLocal<T> {
/// This function calculates the virtual address of the CPU-local object based on the per-
/// cpu base address and the offset in the BSP.
fn get(&self) -> *const T {
+ // CPU-local objects should be initialized before being accessed. It should be ensured
+ // by the implementation of OSTD initialization.
+ #[cfg(debug_assertions)]
+ debug_assert!(IS_INITIALIZED.load(Ordering::Relaxed));
+
let offset = {
let bsp_va = self as *const _ as usize;
let bsp_base = __cpu_local_start as usize;
diff --git a/ostd/src/cpu/cpu_local.rs b/ostd/src/cpu/cpu_local.rs
--- a/ostd/src/cpu/cpu_local.rs
+++ b/ostd/src/cpu/cpu_local.rs
@@ -115,6 +122,11 @@ impl<T> CpuLocal<T> {
/// This function calculates the virtual address of the CPU-local object based on the per-
/// cpu base address and the offset in the BSP.
fn get(&self) -> *const T {
+ // CPU-local objects should be initialized before being accessed. It should be ensured
+ // by the implementation of OSTD initialization.
+ #[cfg(debug_assertions)]
+ debug_assert!(IS_INITIALIZED.load(Ordering::Relaxed));
+
let offset = {
let bsp_va = self as *const _ as usize;
let bsp_base = __cpu_local_start as usize;
diff --git a/ostd/src/cpu/cpu_local.rs b/ostd/src/cpu/cpu_local.rs
--- a/ostd/src/cpu/cpu_local.rs
+++ b/ostd/src/cpu/cpu_local.rs
@@ -124,7 +136,7 @@ impl<T> CpuLocal<T> {
bsp_va - bsp_base as usize
};
- let local_base = get_cpu_local_base() as usize;
+ let local_base = arch::cpu::local::get_base() as usize;
let local_va = local_base + offset;
// A sanity check about the alignment.
diff --git a/ostd/src/cpu/cpu_local.rs b/ostd/src/cpu/cpu_local.rs
--- a/ostd/src/cpu/cpu_local.rs
+++ b/ostd/src/cpu/cpu_local.rs
@@ -124,7 +136,7 @@ impl<T> CpuLocal<T> {
bsp_va - bsp_base as usize
};
- let local_base = get_cpu_local_base() as usize;
+ let local_base = arch::cpu::local::get_base() as usize;
let local_va = local_base + offset;
// A sanity check about the alignment.
diff --git a/ostd/src/cpu/cpu_local.rs b/ostd/src/cpu/cpu_local.rs
--- a/ostd/src/cpu/cpu_local.rs
+++ b/ostd/src/cpu/cpu_local.rs
@@ -170,6 +182,24 @@ impl<T> Deref for CpuLocalDerefGuard<'_, T> {
}
}
+/// Sets the base address of the CPU-local storage for the bootstrap processor.
+///
+/// It should be called early to let [`crate::task::disable_preempt`] work,
+/// which needs to update a CPU-local preempt lock count. Otherwise it may
+/// panic when calling [`crate::task::disable_preempt`].
+///
+/// # Safety
+///
+/// It should be called only once and only on the BSP.
+pub(crate) unsafe fn early_init_bsp_local_base() {
+ let start_base_va = __cpu_local_start as usize as u64;
+ // SAFETY: The base to be set is the start of the `.cpu_local` section,
+ // where accessing the CPU-local objects have defined behaviors.
+ unsafe {
+ arch::cpu::local::set_base(start_base_va);
+ }
+}
+
/// Initializes the CPU local data for the bootstrap processor (BSP).
///
/// # Safety
diff --git a/ostd/src/cpu/cpu_local.rs b/ostd/src/cpu/cpu_local.rs
--- a/ostd/src/cpu/cpu_local.rs
+++ b/ostd/src/cpu/cpu_local.rs
@@ -170,6 +182,24 @@ impl<T> Deref for CpuLocalDerefGuard<'_, T> {
}
}
+/// Sets the base address of the CPU-local storage for the bootstrap processor.
+///
+/// It should be called early to let [`crate::task::disable_preempt`] work,
+/// which needs to update a CPU-local preempt lock count. Otherwise it may
+/// panic when calling [`crate::task::disable_preempt`].
+///
+/// # Safety
+///
+/// It should be called only once and only on the BSP.
+pub(crate) unsafe fn early_init_bsp_local_base() {
+ let start_base_va = __cpu_local_start as usize as u64;
+ // SAFETY: The base to be set is the start of the `.cpu_local` section,
+ // where accessing the CPU-local objects have defined behaviors.
+ unsafe {
+ arch::cpu::local::set_base(start_base_va);
+ }
+}
+
/// Initializes the CPU local data for the bootstrap processor (BSP).
///
/// # Safety
diff --git a/ostd/src/cpu/cpu_local.rs b/ostd/src/cpu/cpu_local.rs
--- a/ostd/src/cpu/cpu_local.rs
+++ b/ostd/src/cpu/cpu_local.rs
@@ -179,9 +209,14 @@ impl<T> Deref for CpuLocalDerefGuard<'_, T> {
/// It must be guaranteed that the BSP will not access local data before
/// this function being called, otherwise copying non-constant values
/// will result in pretty bad undefined behavior.
-pub unsafe fn init_on_bsp() {
- let start_base_va = __cpu_local_start as usize as u64;
- set_cpu_local_base(start_base_va);
+pub(crate) unsafe fn init_on_bsp() {
+ // TODO: allocate the pages for application processors and copy the
+ // CPU-local objects to the allocated pages.
+
+ #[cfg(debug_assertions)]
+ {
+ IS_INITIALIZED.store(true, Ordering::Relaxed);
+ }
}
// These symbols are provided by the linker script.
diff --git a/ostd/src/cpu/cpu_local.rs b/ostd/src/cpu/cpu_local.rs
--- a/ostd/src/cpu/cpu_local.rs
+++ b/ostd/src/cpu/cpu_local.rs
@@ -179,9 +209,14 @@ impl<T> Deref for CpuLocalDerefGuard<'_, T> {
/// It must be guaranteed that the BSP will not access local data before
/// this function being called, otherwise copying non-constant values
/// will result in pretty bad undefined behavior.
-pub unsafe fn init_on_bsp() {
- let start_base_va = __cpu_local_start as usize as u64;
- set_cpu_local_base(start_base_va);
+pub(crate) unsafe fn init_on_bsp() {
+ // TODO: allocate the pages for application processors and copy the
+ // CPU-local objects to the allocated pages.
+
+ #[cfg(debug_assertions)]
+ {
+ IS_INITIALIZED.store(true, Ordering::Relaxed);
+ }
}
// These symbols are provided by the linker script.
diff --git a/ostd/src/lib.rs b/ostd/src/lib.rs
--- a/ostd/src/lib.rs
+++ b/ostd/src/lib.rs
@@ -59,6 +59,9 @@ pub use self::{cpu::cpu_local::CpuLocal, error::Error, prelude::Result};
pub fn init() {
arch::before_all_init();
+ // SAFETY: This function is called only once and only on the BSP.
+ unsafe { cpu::cpu_local::early_init_bsp_local_base() };
+
mm::heap_allocator::init();
boot::init();
diff --git a/ostd/src/lib.rs b/ostd/src/lib.rs
--- a/ostd/src/lib.rs
+++ b/ostd/src/lib.rs
@@ -59,6 +59,9 @@ pub use self::{cpu::cpu_local::CpuLocal, error::Error, prelude::Result};
pub fn init() {
arch::before_all_init();
+ // SAFETY: This function is called only once and only on the BSP.
+ unsafe { cpu::cpu_local::early_init_bsp_local_base() };
+
mm::heap_allocator::init();
boot::init();
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -340,8 +340,10 @@ impl<'a> VmReader<'a, KernelSpace> {
/// it should _not_ overlap with other `VmWriter`s.
/// The user space memory is treated as untyped.
pub unsafe fn from_kernel_space(ptr: *const u8, len: usize) -> Self {
- debug_assert!(KERNEL_BASE_VADDR <= ptr as usize);
- debug_assert!(ptr.add(len) as usize <= KERNEL_END_VADDR);
+ // If casting a zero sized slice to a pointer, the pointer may be null
+ // and does not reside in our kernel space range.
+ debug_assert!(len == 0 || KERNEL_BASE_VADDR <= ptr as usize);
+ debug_assert!(len == 0 || ptr.add(len) as usize <= KERNEL_END_VADDR);
Self {
cursor: ptr,
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -340,8 +340,10 @@ impl<'a> VmReader<'a, KernelSpace> {
/// it should _not_ overlap with other `VmWriter`s.
/// The user space memory is treated as untyped.
pub unsafe fn from_kernel_space(ptr: *const u8, len: usize) -> Self {
- debug_assert!(KERNEL_BASE_VADDR <= ptr as usize);
- debug_assert!(ptr.add(len) as usize <= KERNEL_END_VADDR);
+ // If casting a zero sized slice to a pointer, the pointer may be null
+ // and does not reside in our kernel space range.
+ debug_assert!(len == 0 || KERNEL_BASE_VADDR <= ptr as usize);
+ debug_assert!(len == 0 || ptr.add(len) as usize <= KERNEL_END_VADDR);
Self {
cursor: ptr,
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -516,8 +518,10 @@ impl<'a> VmWriter<'a, KernelSpace> {
/// is typed, it should _not_ overlap with other `VmReader`s and `VmWriter`s.
/// The user space memory is treated as untyped.
pub unsafe fn from_kernel_space(ptr: *mut u8, len: usize) -> Self {
- debug_assert!(KERNEL_BASE_VADDR <= ptr as usize);
- debug_assert!(ptr.add(len) as usize <= KERNEL_END_VADDR);
+ // If casting a zero sized slice to a pointer, the pointer may be null
+ // and does not reside in our kernel space range.
+ debug_assert!(len == 0 || KERNEL_BASE_VADDR <= ptr as usize);
+ debug_assert!(len == 0 || ptr.add(len) as usize <= KERNEL_END_VADDR);
Self {
cursor: ptr,
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -516,8 +518,10 @@ impl<'a> VmWriter<'a, KernelSpace> {
/// is typed, it should _not_ overlap with other `VmReader`s and `VmWriter`s.
/// The user space memory is treated as untyped.
pub unsafe fn from_kernel_space(ptr: *mut u8, len: usize) -> Self {
- debug_assert!(KERNEL_BASE_VADDR <= ptr as usize);
- debug_assert!(ptr.add(len) as usize <= KERNEL_END_VADDR);
+ // If casting a zero sized slice to a pointer, the pointer may be null
+ // and does not reside in our kernel space range.
+ debug_assert!(len == 0 || KERNEL_BASE_VADDR <= ptr as usize);
+ debug_assert!(len == 0 || ptr.add(len) as usize <= KERNEL_END_VADDR);
Self {
cursor: ptr,
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -1,17 +1,14 @@
// SPDX-License-Identifier: MPL-2.0
use alloc::sync::Arc;
-use core::{
- cell::RefCell,
- sync::atomic::{AtomicUsize, Ordering::Relaxed},
-};
+use core::cell::RefCell;
use super::{
scheduler::{fetch_task, GLOBAL_SCHEDULER},
task::{context_switch, TaskContext},
Task, TaskStatus,
};
-use crate::cpu_local;
+use crate::{arch, cpu_local};
pub struct Processor {
current: Option<Arc<Task>>,
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -1,17 +1,14 @@
// SPDX-License-Identifier: MPL-2.0
use alloc::sync::Arc;
-use core::{
- cell::RefCell,
- sync::atomic::{AtomicUsize, Ordering::Relaxed},
-};
+use core::cell::RefCell;
use super::{
scheduler::{fetch_task, GLOBAL_SCHEDULER},
task::{context_switch, TaskContext},
Task, TaskStatus,
};
-use crate::cpu_local;
+use crate::{arch, cpu_local};
pub struct Processor {
current: Option<Arc<Task>>,
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -154,38 +151,50 @@ fn switch_to_task(next_task: Arc<Task>) {
// to the next task switching.
}
-cpu_local! {
- static PREEMPT_COUNT: PreemptInfo = PreemptInfo::new();
-}
+static PREEMPT_COUNT: PreemptInfo = PreemptInfo::new();
-/// Currently, ``PreemptInfo`` only holds the number of spin
-/// locks held by the current CPU. When it has a non-zero value,
-/// the CPU cannot call ``schedule()``.
-struct PreemptInfo {
- num_locks: AtomicUsize,
-}
+/// Currently, it only holds the number of preemption locks held by the
+/// current CPU. When it has a non-zero value, the CPU cannot call
+/// [`schedule()`].
+///
+/// For per-CPU preemption lock count, we cannot afford two non-atomic
+/// operations to increment and decrement the count. The [`crate::cpu_local`]
+/// implementation is free to read the base register and then calculate the
+/// address of the per-CPU variable using an additional instruction. Interrupts
+/// can happen between the address calculation and modification to that
+/// address. If the task is preempted to another CPU by this interrupt, the
+/// count of the original CPU will be mistakenly modified. To avoid this, we
+/// introduce [`crate::arch::cpu::local::preempt_lock_count`]. For x86_64 we
+/// can implement this using one instruction. In other less expressive
+/// architectures, we may need to disable interrupts.
+///
+/// Also, the preemption count is reserved in the `.cpu_local` section
+/// specified in the linker script. The reason is that we need to access the
+/// preemption count before we can copy the section for application processors.
+/// So, the preemption count is not copied from bootstrap processor's section
+/// as the initialization. Instead it is initialized to zero for application
+/// processors.
+struct PreemptInfo {}
impl PreemptInfo {
const fn new() -> Self {
- Self {
- num_locks: AtomicUsize::new(0),
- }
+ Self {}
}
fn increase_num_locks(&self) {
- self.num_locks.fetch_add(1, Relaxed);
+ arch::cpu::local::preempt_lock_count::inc();
}
fn decrease_num_locks(&self) {
- self.num_locks.fetch_sub(1, Relaxed);
+ arch::cpu::local::preempt_lock_count::dec();
}
fn is_preemptive(&self) -> bool {
- self.num_locks.load(Relaxed) == 0
+ arch::cpu::local::preempt_lock_count::get() == 0
}
fn num_locks(&self) -> usize {
- self.num_locks.load(Relaxed)
+ arch::cpu::local::preempt_lock_count::get() as usize
}
}
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -154,38 +151,50 @@ fn switch_to_task(next_task: Arc<Task>) {
// to the next task switching.
}
-cpu_local! {
- static PREEMPT_COUNT: PreemptInfo = PreemptInfo::new();
-}
+static PREEMPT_COUNT: PreemptInfo = PreemptInfo::new();
-/// Currently, ``PreemptInfo`` only holds the number of spin
-/// locks held by the current CPU. When it has a non-zero value,
-/// the CPU cannot call ``schedule()``.
-struct PreemptInfo {
- num_locks: AtomicUsize,
-}
+/// Currently, it only holds the number of preemption locks held by the
+/// current CPU. When it has a non-zero value, the CPU cannot call
+/// [`schedule()`].
+///
+/// For per-CPU preemption lock count, we cannot afford two non-atomic
+/// operations to increment and decrement the count. The [`crate::cpu_local`]
+/// implementation is free to read the base register and then calculate the
+/// address of the per-CPU variable using an additional instruction. Interrupts
+/// can happen between the address calculation and modification to that
+/// address. If the task is preempted to another CPU by this interrupt, the
+/// count of the original CPU will be mistakenly modified. To avoid this, we
+/// introduce [`crate::arch::cpu::local::preempt_lock_count`]. For x86_64 we
+/// can implement this using one instruction. In other less expressive
+/// architectures, we may need to disable interrupts.
+///
+/// Also, the preemption count is reserved in the `.cpu_local` section
+/// specified in the linker script. The reason is that we need to access the
+/// preemption count before we can copy the section for application processors.
+/// So, the preemption count is not copied from bootstrap processor's section
+/// as the initialization. Instead it is initialized to zero for application
+/// processors.
+struct PreemptInfo {}
impl PreemptInfo {
const fn new() -> Self {
- Self {
- num_locks: AtomicUsize::new(0),
- }
+ Self {}
}
fn increase_num_locks(&self) {
- self.num_locks.fetch_add(1, Relaxed);
+ arch::cpu::local::preempt_lock_count::inc();
}
fn decrease_num_locks(&self) {
- self.num_locks.fetch_sub(1, Relaxed);
+ arch::cpu::local::preempt_lock_count::dec();
}
fn is_preemptive(&self) -> bool {
- self.num_locks.load(Relaxed) == 0
+ arch::cpu::local::preempt_lock_count::get() == 0
}
fn num_locks(&self) -> usize {
- self.num_locks.load(Relaxed)
+ arch::cpu::local::preempt_lock_count::get() as usize
}
}
|
Modifying `ostd::arch::x86::cpu::get_cpu_local_base` to
``` rust
/// Gets the base address for the CPU local storage by reading the FS base model-specific register.
pub(crate) fn get_cpu_local_base() -> u64 {
let fsbase = FS::read_base().as_u64();
debug_assert_ne!(fsbase, 0, "CPU local memory is used before initialized");
fsbase
}
```
may help with discovering cpu local used before initialization bugs.
> And I guess this is not the only case since SpinLock is widely used in ostd, it might be other uses of SpinLock before CPU local memory is initialized, for example, mm::kspace::init_boot_page_table → BOOT_PAGE_TABLE.lock.
Indeed. CPU local variables should not be accessed before initialization of `mod cpu_local`. I will look into it.
|
2024-07-19T13:26:35Z
|
562e64437584279783f244edba10b512beddc81d
|
asterinas/asterinas
|
diff --git a/test/syscall_test/blocklists/epoll_test b/test/syscall_test/blocklists/epoll_test
--- a/test/syscall_test/blocklists/epoll_test
+++ b/test/syscall_test/blocklists/epoll_test
@@ -6,4 +6,7 @@ EpollTest.EdgeTriggered_NoRandomSave
EpollTest.OneshotAndEdgeTriggered
EpollTest.CycleOfOneDisallowed
EpollTest.CycleOfThreeDisallowed
-EpollTest.CloseFile
\ No newline at end of file
+EpollTest.CloseFile
+# `UnblockWithSignal` contains races. Better not to enable it.
+# See https://github.com/asterinas/asterinas/pull/1035 for details.
+EpollTest.UnblockWithSignal
diff --git a/test/syscall_test/run_syscall_test.sh b/test/syscall_test/run_syscall_test.sh
--- a/test/syscall_test/run_syscall_test.sh
+++ b/test/syscall_test/run_syscall_test.sh
@@ -17,7 +17,7 @@ NC='\033[0m'
get_blocklist_subtests(){
if [ -f $BLOCKLIST_DIR/$1 ]; then
- BLOCK=$(sed ':a;N;$!ba;s/\n/:/g' $BLOCKLIST_DIR/$1)
+ BLOCK=$(grep -v '^#' $BLOCKLIST_DIR/$1 | tr '\n' ':')
else
BLOCK=""
return 1
diff --git a/test/syscall_test/run_syscall_test.sh b/test/syscall_test/run_syscall_test.sh
--- a/test/syscall_test/run_syscall_test.sh
+++ b/test/syscall_test/run_syscall_test.sh
@@ -25,7 +25,7 @@ get_blocklist_subtests(){
for extra_dir in $EXTRA_BLOCKLISTS_DIRS ; do
if [ -f $SCRIPT_DIR/$extra_dir/$1 ]; then
- BLOCK="${BLOCK}:$(sed ':a;N;$!ba;s/\n/:/g' $SCRIPT_DIR/$extra_dir/$1)"
+ BLOCK="${BLOCK}:$(grep -v '^#' $SCRIPT_DIR/$extra_dir/$1 | tr '\n' ':')"
fi
done
|
[
"868"
] |
0.6
|
c7d2a908e04f359f99443e6ea9423fff736de361
|
Epoll syscall tests crash occasionally
When running tests with the command `make run AUTO_TEST=syscall ENABLE_KVM=1 BOOT_PROTOCOL=linux-efi-handover64 RELEASE=1`, some `epoll` tests (from gvisor) will crash.
```
EpollTest.TimeoutNoFds
EpollTest.UnblockWithNewFD
EpollTest.Oneshot
```
The above tests crashed with a "page fault handler" error with message "page fault addr is not in current vmar" (shown below).

```
EpollTest.EdgeTriggered_NoRandomSave
EpollTest.OneshotAndEdgeTriggered
EpollTest.CloseFile
```
The above tests crashed with a "page fault handler" error with message "perm chech fails" (shown below).

|
asterinas__asterinas-1035
| 1,035
|
diff --git a/test/syscall_test/blocklists/epoll_test b/test/syscall_test/blocklists/epoll_test
--- a/test/syscall_test/blocklists/epoll_test
+++ b/test/syscall_test/blocklists/epoll_test
@@ -6,4 +6,7 @@ EpollTest.EdgeTriggered_NoRandomSave
EpollTest.OneshotAndEdgeTriggered
EpollTest.CycleOfOneDisallowed
EpollTest.CycleOfThreeDisallowed
-EpollTest.CloseFile
\ No newline at end of file
+EpollTest.CloseFile
+# `UnblockWithSignal` contains races. Better not to enable it.
+# See https://github.com/asterinas/asterinas/pull/1035 for details.
+EpollTest.UnblockWithSignal
diff --git a/test/syscall_test/run_syscall_test.sh b/test/syscall_test/run_syscall_test.sh
--- a/test/syscall_test/run_syscall_test.sh
+++ b/test/syscall_test/run_syscall_test.sh
@@ -17,7 +17,7 @@ NC='\033[0m'
get_blocklist_subtests(){
if [ -f $BLOCKLIST_DIR/$1 ]; then
- BLOCK=$(sed ':a;N;$!ba;s/\n/:/g' $BLOCKLIST_DIR/$1)
+ BLOCK=$(grep -v '^#' $BLOCKLIST_DIR/$1 | tr '\n' ':')
else
BLOCK=""
return 1
diff --git a/test/syscall_test/run_syscall_test.sh b/test/syscall_test/run_syscall_test.sh
--- a/test/syscall_test/run_syscall_test.sh
+++ b/test/syscall_test/run_syscall_test.sh
@@ -25,7 +25,7 @@ get_blocklist_subtests(){
for extra_dir in $EXTRA_BLOCKLISTS_DIRS ; do
if [ -f $SCRIPT_DIR/$extra_dir/$1 ]; then
- BLOCK="${BLOCK}:$(sed ':a;N;$!ba;s/\n/:/g' $SCRIPT_DIR/$extra_dir/$1)"
+ BLOCK="${BLOCK}:$(grep -v '^#' $SCRIPT_DIR/$extra_dir/$1 | tr '\n' ':')"
fi
done
|
2024-07-07T20:03:32Z
|
562e64437584279783f244edba10b512beddc81d
|
|
asterinas/asterinas
|
diff --git a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
--- a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
+++ b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
@@ -13,7 +13,8 @@ use alloc::vec;
use ostd::arch::qemu::{exit_qemu, QemuExitCode};
use ostd::cpu::UserContext;
use ostd::mm::{
- FrameAllocOptions, PageFlags, Vaddr, VmIo, VmMapOptions, VmSpace, VmWriter, PAGE_SIZE,
+ CachePolicy, FrameAllocOptions, PageFlags, PageProperty, Vaddr, VmIo, VmSpace, VmWriter,
+ PAGE_SIZE,
};
use ostd::prelude::*;
use ostd::task::{Task, TaskOptions};
diff --git a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
--- a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
+++ b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
@@ -32,8 +33,8 @@ pub fn main() {
}
fn create_user_space(program: &[u8]) -> UserSpace {
+ let nframes = program.len().align_up(PAGE_SIZE) / PAGE_SIZE;
let user_pages = {
- let nframes = program.len().align_up(PAGE_SIZE) / PAGE_SIZE;
let vm_frames = FrameAllocOptions::new(nframes).alloc().unwrap();
// Phyiscal memory pages can be only accessed
// via the Frame abstraction.
diff --git a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
--- a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
+++ b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
@@ -45,11 +46,15 @@ fn create_user_space(program: &[u8]) -> UserSpace {
// The page table of the user space can be
// created and manipulated safely through
- // the VmSpace abstraction.
+ // the `VmSpace` abstraction.
let vm_space = VmSpace::new();
- let mut options = VmMapOptions::new();
- options.addr(Some(MAP_ADDR)).flags(PageFlags::RWX);
- vm_space.map(user_pages, &options).unwrap();
+ let mut cursor = vm_space
+ .cursor_mut(&(MAP_ADDR..MAP_ADDR + nframes * PAGE_SIZE))
+ .unwrap();
+ let map_prop = PageProperty::new(PageFlags::RWX, CachePolicy::Writeback);
+ for frame in user_pages {
+ cursor.map(frame, map_prop);
+ }
Arc::new(vm_space)
};
let user_cpu_state = {
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -14,8 +14,8 @@ use crate::{
mod node;
use node::*;
-mod cursor;
-pub(crate) use cursor::{Cursor, CursorMut, PageTableQueryResult};
+pub mod cursor;
+pub use cursor::{Cursor, CursorMut, PageTableQueryResult};
#[cfg(ktest)]
mod test;
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -232,16 +234,17 @@ where
/// Note that this function may fail reflect an accurate result if there are
/// cursors concurrently accessing the same virtual address range, just like what
/// happens for the hardware MMU walk.
- pub(crate) fn query(&self, vaddr: Vaddr) -> Option<(Paddr, PageProperty)> {
+ #[cfg(ktest)]
+ pub fn query(&self, vaddr: Vaddr) -> Option<(Paddr, PageProperty)> {
// SAFETY: The root node is a valid page table node so the address is valid.
unsafe { page_walk::<E, C>(self.root_paddr(), vaddr) }
}
/// Create a new cursor exclusively accessing the virtual address range for mapping.
///
- /// If another cursor is already accessing the range, the new cursor will wait until the
+ /// If another cursor is already accessing the range, the new cursor may wait until the
/// previous cursor is dropped.
- pub(crate) fn cursor_mut(
+ pub fn cursor_mut(
&'a self,
va: &Range<Vaddr>,
) -> Result<CursorMut<'a, M, E, C>, PageTableError> {
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -288,13 +289,14 @@ where
///
/// To mitigate this problem, the page table nodes are by default not
/// actively recycled, until we find an appropriate solution.
+#[cfg(ktest)]
pub(super) unsafe fn page_walk<E: PageTableEntryTrait, C: PagingConstsTrait>(
root_paddr: Paddr,
vaddr: Vaddr,
) -> Option<(Paddr, PageProperty)> {
- // We disable preemt here to mimic the MMU walk, which will not be interrupted
- // then must finish within a given time.
- let _guard = crate::task::disable_preempt();
+ use super::paddr_to_vaddr;
+
+ let preempt_guard = crate::task::disable_preempt();
let mut cur_level = C::NR_LEVELS;
let mut cur_pte = {
diff --git a/tools/format_all.sh b/tools/format_all.sh
--- a/tools/format_all.sh
+++ b/tools/format_all.sh
@@ -29,6 +29,14 @@ else
cargo fmt
fi
+# Format the 100-line kernel demo as well
+KERNEL_DEMO_FILE="$WORKSPACE_ROOT/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs"
+if [ "$CHECK_MODE" = true ]; then
+ cargo fmt --check -- $KERNEL_DEMO_FILE
+else
+ cargo fmt -- $KERNEL_DEMO_FILE
+fi
+
for CRATE in $EXCLUDED_CRATES; do
CRATE_DIR="$WORKSPACE_ROOT/$CRATE"
|
[
"681"
] |
0.6
|
94eba6d85eb9e62ddd904c1132d556b808cc3174
|
The APIs of `VmSpace` are vulnerable to race conditions
```rust
#[derive(Debug, Clone)]
pub struct VmSpace {
memory_set: Arc<Mutex<MemorySet>>,
}
impl VmSpace {
/// determine whether a vaddr is already mapped
pub fn is_mapped(&self, vaddr: Vaddr) -> bool {
let memory_set = self.memory_set.lock();
memory_set.is_mapped(vaddr)
}
}
```
- This API is racy by design *unless an external lock is used properly*.
- `is_mapped` returns whether the page is mapped or not *when the method is called*, but the result can be changed immediately just after the method returns (because it releases the `VmSpace`'s lock).
- Even `type VmSpace = Arc<Mutex<MemorySet>>` is probably better, at least it makes the lock explicit.
- Something like `vm_space.lock().is_mapped(vaddr1) && vm_space.lock().is_mapped(vaddr2)` is obviously wrong (or at least not optimized) code.
|
asterinas__asterinas-1026
| 1,026
|
diff --git a/kernel/aster-nix/src/vm/vmar/vm_mapping.rs b/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
--- a/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
+++ b/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
@@ -5,7 +5,9 @@
use core::ops::Range;
-use ostd::mm::{Frame, FrameVec, PageFlags, VmIo, VmMapOptions, VmSpace};
+use ostd::mm::{
+ vm_space::VmQueryResult, CachePolicy, Frame, PageFlags, PageProperty, VmIo, VmSpace,
+};
use super::{interval::Interval, is_intersected, Vmar, Vmar_};
use crate::{
diff --git a/kernel/aster-nix/src/vm/vmar/vm_mapping.rs b/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
--- a/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
+++ b/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
@@ -5,7 +5,9 @@
use core::ops::Range;
-use ostd::mm::{Frame, FrameVec, PageFlags, VmIo, VmMapOptions, VmSpace};
+use ostd::mm::{
+ vm_space::VmQueryResult, CachePolicy, Frame, PageFlags, PageProperty, VmIo, VmSpace,
+};
use super::{interval::Interval, is_intersected, Vmar, Vmar_};
use crate::{
diff --git a/kernel/aster-nix/src/vm/vmar/vm_mapping.rs b/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
--- a/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
+++ b/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
@@ -194,22 +196,41 @@ impl VmMapping {
let write_perms = VmPerms::WRITE;
self.check_perms(&write_perms)?;
- let mut page_addr =
- self.map_to_addr() - self.vmo_offset() + page_idx_range.start * PAGE_SIZE;
- for page_idx in page_idx_range {
- let parent = self.parent.upgrade().unwrap();
- let vm_space = parent.vm_space();
-
- // The `VmMapping` has the write permission but the corresponding PTE is present and is read-only.
- // This means this PTE is set to read-only due to the COW mechanism. In this situation we need to trigger a
- // page fault before writing at the VMO to guarantee the consistency between VMO and the page table.
- let need_page_fault = vm_space
- .query(page_addr)?
- .is_some_and(|prop| !prop.flags.contains(PageFlags::W));
- if need_page_fault {
- self.handle_page_fault(page_addr, false, true)?;
+ // We need to make sure the mapping exists.
+ //
+ // Also, if the `VmMapping` has the write permission but the corresponding
+ // PTE is present and is read-only, it would be a copy-on-write page. In
+ // this situation we need to trigger a page fault before writing at the
+ // VMO to guarantee the consistency between VMO and the page table.
+ {
+ let virt_addr =
+ self.map_to_addr() - self.vmo_offset() + page_idx_range.start * PAGE_SIZE;
+ let virt_range = virt_addr..virt_addr + page_idx_range.len() * PAGE_SIZE;
+
+ // FIXME: any sane developer would recommend using `parent.vm_space().cursor(&virt_range)`
+ // to lock the range and check the mapping status. However, this will cause a deadlock because
+ // `Self::handle_page_fault` would like to create a cursor again. The following implementation
+ // indeed introduces a TOCTOU bug.
+ for page_va in virt_range.step_by(PAGE_SIZE) {
+ let parent = self.parent.upgrade().unwrap();
+ let mut cursor = parent
+ .vm_space()
+ .cursor(&(page_va..page_va + PAGE_SIZE))
+ .unwrap();
+ let map_info = cursor.query().unwrap();
+ drop(cursor);
+
+ match map_info {
+ VmQueryResult::Mapped { va, prop, .. } => {
+ if !prop.flags.contains(PageFlags::W) {
+ self.handle_page_fault(va, false, true)?;
+ }
+ }
+ VmQueryResult::NotMapped { va, .. } => {
+ self.handle_page_fault(va, true, true)?;
+ }
+ }
}
- page_addr += PAGE_SIZE;
}
self.vmo.write_bytes(vmo_write_offset, buf)?;
diff --git a/kernel/aster-nix/src/vm/vmar/vm_mapping.rs b/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
--- a/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
+++ b/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
@@ -194,22 +196,41 @@ impl VmMapping {
let write_perms = VmPerms::WRITE;
self.check_perms(&write_perms)?;
- let mut page_addr =
- self.map_to_addr() - self.vmo_offset() + page_idx_range.start * PAGE_SIZE;
- for page_idx in page_idx_range {
- let parent = self.parent.upgrade().unwrap();
- let vm_space = parent.vm_space();
-
- // The `VmMapping` has the write permission but the corresponding PTE is present and is read-only.
- // This means this PTE is set to read-only due to the COW mechanism. In this situation we need to trigger a
- // page fault before writing at the VMO to guarantee the consistency between VMO and the page table.
- let need_page_fault = vm_space
- .query(page_addr)?
- .is_some_and(|prop| !prop.flags.contains(PageFlags::W));
- if need_page_fault {
- self.handle_page_fault(page_addr, false, true)?;
+ // We need to make sure the mapping exists.
+ //
+ // Also, if the `VmMapping` has the write permission but the corresponding
+ // PTE is present and is read-only, it would be a copy-on-write page. In
+ // this situation we need to trigger a page fault before writing at the
+ // VMO to guarantee the consistency between VMO and the page table.
+ {
+ let virt_addr =
+ self.map_to_addr() - self.vmo_offset() + page_idx_range.start * PAGE_SIZE;
+ let virt_range = virt_addr..virt_addr + page_idx_range.len() * PAGE_SIZE;
+
+ // FIXME: any sane developer would recommend using `parent.vm_space().cursor(&virt_range)`
+ // to lock the range and check the mapping status. However, this will cause a deadlock because
+ // `Self::handle_page_fault` would like to create a cursor again. The following implementation
+ // indeed introduces a TOCTOU bug.
+ for page_va in virt_range.step_by(PAGE_SIZE) {
+ let parent = self.parent.upgrade().unwrap();
+ let mut cursor = parent
+ .vm_space()
+ .cursor(&(page_va..page_va + PAGE_SIZE))
+ .unwrap();
+ let map_info = cursor.query().unwrap();
+ drop(cursor);
+
+ match map_info {
+ VmQueryResult::Mapped { va, prop, .. } => {
+ if !prop.flags.contains(PageFlags::W) {
+ self.handle_page_fault(va, false, true)?;
+ }
+ }
+ VmQueryResult::NotMapped { va, .. } => {
+ self.handle_page_fault(va, true, true)?;
+ }
+ }
}
- page_addr += PAGE_SIZE;
}
self.vmo.write_bytes(vmo_write_offset, buf)?;
diff --git a/kernel/aster-nix/src/vm/vmar/vm_mapping.rs b/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
--- a/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
+++ b/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
@@ -458,7 +479,8 @@ impl VmMappingInner {
frame: Frame,
is_readonly: bool,
) -> Result<()> {
- let map_addr = self.page_map_addr(page_idx);
+ let map_va = self.page_map_addr(page_idx);
+ let map_va = map_va..map_va + PAGE_SIZE;
let vm_perms = {
let mut perms = self.perms;
diff --git a/kernel/aster-nix/src/vm/vmar/vm_mapping.rs b/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
--- a/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
+++ b/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
@@ -458,7 +479,8 @@ impl VmMappingInner {
frame: Frame,
is_readonly: bool,
) -> Result<()> {
- let map_addr = self.page_map_addr(page_idx);
+ let map_va = self.page_map_addr(page_idx);
+ let map_va = map_va..map_va + PAGE_SIZE;
let vm_perms = {
let mut perms = self.perms;
diff --git a/kernel/aster-nix/src/vm/vmar/vm_mapping.rs b/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
--- a/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
+++ b/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
@@ -468,23 +490,11 @@ impl VmMappingInner {
}
perms
};
+ let map_prop = PageProperty::new(vm_perms.into(), CachePolicy::Writeback);
- let vm_map_options = {
- let mut options = VmMapOptions::new();
- options.addr(Some(map_addr));
- options.flags(vm_perms.into());
-
- // After `fork()`, the entire memory space of the parent and child processes is
- // protected as read-only. Therefore, whether the pages need to be COWed (if the memory
- // region is private) or not (if the memory region is shared), it is necessary to
- // overwrite the page table entry to make the page writable again when the parent or
- // child process first tries to write to the memory region.
- options.can_overwrite(true);
-
- options
- };
+ let mut cursor = vm_space.cursor_mut(&map_va).unwrap();
+ cursor.map(frame, map_prop);
- vm_space.map(FrameVec::from_one_frame(frame), &vm_map_options)?;
self.mapped_pages.insert(page_idx);
Ok(())
}
diff --git a/kernel/aster-nix/src/vm/vmar/vm_mapping.rs b/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
--- a/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
+++ b/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
@@ -468,23 +490,11 @@ impl VmMappingInner {
}
perms
};
+ let map_prop = PageProperty::new(vm_perms.into(), CachePolicy::Writeback);
- let vm_map_options = {
- let mut options = VmMapOptions::new();
- options.addr(Some(map_addr));
- options.flags(vm_perms.into());
-
- // After `fork()`, the entire memory space of the parent and child processes is
- // protected as read-only. Therefore, whether the pages need to be COWed (if the memory
- // region is private) or not (if the memory region is shared), it is necessary to
- // overwrite the page table entry to make the page writable again when the parent or
- // child process first tries to write to the memory region.
- options.can_overwrite(true);
-
- options
- };
+ let mut cursor = vm_space.cursor_mut(&map_va).unwrap();
+ cursor.map(frame, map_prop);
- vm_space.map(FrameVec::from_one_frame(frame), &vm_map_options)?;
self.mapped_pages.insert(page_idx);
Ok(())
}
diff --git a/kernel/aster-nix/src/vm/vmar/vm_mapping.rs b/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
--- a/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
+++ b/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
@@ -492,9 +502,10 @@ impl VmMappingInner {
fn unmap_one_page(&mut self, vm_space: &VmSpace, page_idx: usize) -> Result<()> {
let map_addr = self.page_map_addr(page_idx);
let range = map_addr..(map_addr + PAGE_SIZE);
- if vm_space.query(map_addr)?.is_some() {
- vm_space.unmap(&range)?;
- }
+
+ let mut cursor = vm_space.cursor_mut(&range).unwrap();
+ cursor.unmap(PAGE_SIZE);
+
self.mapped_pages.remove(&page_idx);
Ok(())
}
diff --git a/kernel/aster-nix/src/vm/vmar/vm_mapping.rs b/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
--- a/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
+++ b/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
@@ -492,9 +502,10 @@ impl VmMappingInner {
fn unmap_one_page(&mut self, vm_space: &VmSpace, page_idx: usize) -> Result<()> {
let map_addr = self.page_map_addr(page_idx);
let range = map_addr..(map_addr + PAGE_SIZE);
- if vm_space.query(map_addr)?.is_some() {
- vm_space.unmap(&range)?;
- }
+
+ let mut cursor = vm_space.cursor_mut(&range).unwrap();
+ cursor.unmap(PAGE_SIZE);
+
self.mapped_pages.remove(&page_idx);
Ok(())
}
diff --git a/kernel/aster-nix/src/vm/vmar/vm_mapping.rs b/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
--- a/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
+++ b/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
@@ -528,17 +539,8 @@ impl VmMappingInner {
) -> Result<()> {
debug_assert!(range.start % PAGE_SIZE == 0);
debug_assert!(range.end % PAGE_SIZE == 0);
- let start_page = (range.start - self.map_to_addr + self.vmo_offset) / PAGE_SIZE;
- let end_page = (range.end - self.map_to_addr + self.vmo_offset) / PAGE_SIZE;
- let flags: PageFlags = perms.into();
- for page_idx in start_page..end_page {
- let page_addr = self.page_map_addr(page_idx);
- if vm_space.query(page_addr)?.is_some() {
- // If the page is already mapped, we will modify page table
- let page_range = page_addr..(page_addr + PAGE_SIZE);
- vm_space.protect(&page_range, |p| p.flags = flags)?;
- }
- }
+ let mut cursor = vm_space.cursor_mut(&range).unwrap();
+ cursor.protect(range.len(), |p| p.flags = perms.into(), true)?;
Ok(())
}
diff --git a/kernel/aster-nix/src/vm/vmar/vm_mapping.rs b/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
--- a/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
+++ b/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
@@ -528,17 +539,8 @@ impl VmMappingInner {
) -> Result<()> {
debug_assert!(range.start % PAGE_SIZE == 0);
debug_assert!(range.end % PAGE_SIZE == 0);
- let start_page = (range.start - self.map_to_addr + self.vmo_offset) / PAGE_SIZE;
- let end_page = (range.end - self.map_to_addr + self.vmo_offset) / PAGE_SIZE;
- let flags: PageFlags = perms.into();
- for page_idx in start_page..end_page {
- let page_addr = self.page_map_addr(page_idx);
- if vm_space.query(page_addr)?.is_some() {
- // If the page is already mapped, we will modify page table
- let page_range = page_addr..(page_addr + PAGE_SIZE);
- vm_space.protect(&page_range, |p| p.flags = flags)?;
- }
- }
+ let mut cursor = vm_space.cursor_mut(&range).unwrap();
+ cursor.protect(range.len(), |p| p.flags = perms.into(), true)?;
Ok(())
}
diff --git a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
--- a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
+++ b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
@@ -13,7 +13,8 @@ use alloc::vec;
use ostd::arch::qemu::{exit_qemu, QemuExitCode};
use ostd::cpu::UserContext;
use ostd::mm::{
- FrameAllocOptions, PageFlags, Vaddr, VmIo, VmMapOptions, VmSpace, VmWriter, PAGE_SIZE,
+ CachePolicy, FrameAllocOptions, PageFlags, PageProperty, Vaddr, VmIo, VmSpace, VmWriter,
+ PAGE_SIZE,
};
use ostd::prelude::*;
use ostd::task::{Task, TaskOptions};
diff --git a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
--- a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
+++ b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
@@ -32,8 +33,8 @@ pub fn main() {
}
fn create_user_space(program: &[u8]) -> UserSpace {
+ let nframes = program.len().align_up(PAGE_SIZE) / PAGE_SIZE;
let user_pages = {
- let nframes = program.len().align_up(PAGE_SIZE) / PAGE_SIZE;
let vm_frames = FrameAllocOptions::new(nframes).alloc().unwrap();
// Phyiscal memory pages can be only accessed
// via the Frame abstraction.
diff --git a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
--- a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
+++ b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
@@ -45,11 +46,15 @@ fn create_user_space(program: &[u8]) -> UserSpace {
// The page table of the user space can be
// created and manipulated safely through
- // the VmSpace abstraction.
+ // the `VmSpace` abstraction.
let vm_space = VmSpace::new();
- let mut options = VmMapOptions::new();
- options.addr(Some(MAP_ADDR)).flags(PageFlags::RWX);
- vm_space.map(user_pages, &options).unwrap();
+ let mut cursor = vm_space
+ .cursor_mut(&(MAP_ADDR..MAP_ADDR + nframes * PAGE_SIZE))
+ .unwrap();
+ let map_prop = PageProperty::new(PageFlags::RWX, CachePolicy::Writeback);
+ for frame in user_pages {
+ cursor.map(frame, map_prop);
+ }
Arc::new(vm_space)
};
let user_cpu_state = {
diff --git a/ostd/src/mm/frame/frame_vec.rs /dev/null
--- a/ostd/src/mm/frame/frame_vec.rs
+++ /dev/null
@@ -1,172 +0,0 @@
-// SPDX-License-Identifier: MPL-2.0
-
-//! Page frames.
-
-use alloc::{vec, vec::Vec};
-
-use crate::{
- mm::{Frame, VmIo, VmReader, VmWriter, PAGE_SIZE},
- Error, Result,
-};
-
-/// A collection of base page frames (regular physical memory pages).
-///
-/// For the most parts, `FrameVec` is like `Vec<Frame>`. But the
-/// implementation may or may not be based on [`Vec`]. Having a dedicated
-/// type to represent a series of page frames is convenient because,
-/// more often than not, one needs to operate on a batch of frames rather
-/// a single frame.
-#[derive(Debug, Clone)]
-pub struct FrameVec(pub(crate) Vec<Frame>);
-
-impl FrameVec {
- /// Retrieves a reference to a [`Frame`] at the specified index.
- pub fn get(&self, index: usize) -> Option<&Frame> {
- self.0.get(index)
- }
-
- /// Creates an empty `FrameVec`.
- pub fn empty() -> Self {
- Self(Vec::new())
- }
-
- /// Creates a new `FrameVec` with the specified capacity.
- pub fn new_with_capacity(capacity: usize) -> Self {
- Self(Vec::with_capacity(capacity))
- }
-
- /// Pushes a new frame to the collection.
- pub fn push(&mut self, new_frame: Frame) {
- self.0.push(new_frame);
- }
-
- /// Pops a frame from the collection.
- pub fn pop(&mut self) -> Option<Frame> {
- self.0.pop()
- }
-
- /// Removes a frame at a position.
- pub fn remove(&mut self, at: usize) -> Frame {
- self.0.remove(at)
- }
-
- /// Appends all the [`Frame`]s from `more` to the end of this collection.
- /// and clears the frames in `more`.
- pub fn append(&mut self, more: &mut FrameVec) -> Result<()> {
- self.0.append(&mut more.0);
- Ok(())
- }
-
- /// Truncates the `FrameVec` to the specified length.
- ///
- /// If `new_len >= self.len()`, then this method has no effect.
- pub fn truncate(&mut self, new_len: usize) {
- if new_len >= self.0.len() {
- return;
- }
- self.0.truncate(new_len)
- }
-
- /// Returns an iterator over all frames.
- pub fn iter(&self) -> core::slice::Iter<'_, Frame> {
- self.0.iter()
- }
-
- /// Returns the number of frames.
- pub fn len(&self) -> usize {
- self.0.len()
- }
-
- /// Returns whether the frame collection is empty.
- pub fn is_empty(&self) -> bool {
- self.0.is_empty()
- }
-
- /// Returns the number of bytes.
- ///
- /// This method is equivalent to `self.len() * BASE_PAGE_SIZE`.
- pub fn nbytes(&self) -> usize {
- self.0.len() * PAGE_SIZE
- }
-
- /// Creates a new `FrameVec` from a single [`Frame`].
- pub fn from_one_frame(frame: Frame) -> Self {
- Self(vec![frame])
- }
-}
-
-impl IntoIterator for FrameVec {
- type Item = Frame;
-
- type IntoIter = alloc::vec::IntoIter<Self::Item>;
-
- fn into_iter(self) -> Self::IntoIter {
- self.0.into_iter()
- }
-}
-
-impl VmIo for FrameVec {
- fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> Result<()> {
- // Do bound check with potential integer overflow in mind
- let max_offset = offset.checked_add(buf.len()).ok_or(Error::Overflow)?;
- if max_offset > self.nbytes() {
- return Err(Error::InvalidArgs);
- }
-
- let num_unread_pages = offset / PAGE_SIZE;
- let mut start = offset % PAGE_SIZE;
- let mut buf_writer: VmWriter = buf.into();
- for frame in self.0.iter().skip(num_unread_pages) {
- let read_len = frame.reader().skip(start).read(&mut buf_writer);
- if read_len == 0 {
- break;
- }
- start = 0;
- }
- Ok(())
- }
-
- fn write_bytes(&self, offset: usize, buf: &[u8]) -> Result<()> {
- // Do bound check with potential integer overflow in mind
- let max_offset = offset.checked_add(buf.len()).ok_or(Error::Overflow)?;
- if max_offset > self.nbytes() {
- return Err(Error::InvalidArgs);
- }
-
- let num_unwrite_pages = offset / PAGE_SIZE;
- let mut start = offset % PAGE_SIZE;
- let mut buf_reader: VmReader = buf.into();
- for frame in self.0.iter().skip(num_unwrite_pages) {
- let write_len = frame.writer().skip(start).write(&mut buf_reader);
- if write_len == 0 {
- break;
- }
- start = 0;
- }
- Ok(())
- }
-}
-
-/// An iterator for frames.
-pub struct FrameVecIter<'a> {
- frames: &'a FrameVec,
- current: usize,
-}
-
-impl<'a> FrameVecIter<'a> {
- /// Creates a new `FrameVecIter` from the given [`FrameVec`].
- pub fn new(frames: &'a FrameVec) -> Self {
- Self { frames, current: 0 }
- }
-}
-
-impl<'a> Iterator for FrameVecIter<'a> {
- type Item = &'a Frame;
-
- fn next(&mut self) -> Option<Self::Item> {
- if self.current >= self.frames.0.len() {
- return None;
- }
- Some(self.frames.0.get(self.current).unwrap())
- }
-}
diff --git a/ostd/src/mm/frame/frame_vec.rs /dev/null
--- a/ostd/src/mm/frame/frame_vec.rs
+++ /dev/null
@@ -1,172 +0,0 @@
-// SPDX-License-Identifier: MPL-2.0
-
-//! Page frames.
-
-use alloc::{vec, vec::Vec};
-
-use crate::{
- mm::{Frame, VmIo, VmReader, VmWriter, PAGE_SIZE},
- Error, Result,
-};
-
-/// A collection of base page frames (regular physical memory pages).
-///
-/// For the most parts, `FrameVec` is like `Vec<Frame>`. But the
-/// implementation may or may not be based on [`Vec`]. Having a dedicated
-/// type to represent a series of page frames is convenient because,
-/// more often than not, one needs to operate on a batch of frames rather
-/// a single frame.
-#[derive(Debug, Clone)]
-pub struct FrameVec(pub(crate) Vec<Frame>);
-
-impl FrameVec {
- /// Retrieves a reference to a [`Frame`] at the specified index.
- pub fn get(&self, index: usize) -> Option<&Frame> {
- self.0.get(index)
- }
-
- /// Creates an empty `FrameVec`.
- pub fn empty() -> Self {
- Self(Vec::new())
- }
-
- /// Creates a new `FrameVec` with the specified capacity.
- pub fn new_with_capacity(capacity: usize) -> Self {
- Self(Vec::with_capacity(capacity))
- }
-
- /// Pushes a new frame to the collection.
- pub fn push(&mut self, new_frame: Frame) {
- self.0.push(new_frame);
- }
-
- /// Pops a frame from the collection.
- pub fn pop(&mut self) -> Option<Frame> {
- self.0.pop()
- }
-
- /// Removes a frame at a position.
- pub fn remove(&mut self, at: usize) -> Frame {
- self.0.remove(at)
- }
-
- /// Appends all the [`Frame`]s from `more` to the end of this collection.
- /// and clears the frames in `more`.
- pub fn append(&mut self, more: &mut FrameVec) -> Result<()> {
- self.0.append(&mut more.0);
- Ok(())
- }
-
- /// Truncates the `FrameVec` to the specified length.
- ///
- /// If `new_len >= self.len()`, then this method has no effect.
- pub fn truncate(&mut self, new_len: usize) {
- if new_len >= self.0.len() {
- return;
- }
- self.0.truncate(new_len)
- }
-
- /// Returns an iterator over all frames.
- pub fn iter(&self) -> core::slice::Iter<'_, Frame> {
- self.0.iter()
- }
-
- /// Returns the number of frames.
- pub fn len(&self) -> usize {
- self.0.len()
- }
-
- /// Returns whether the frame collection is empty.
- pub fn is_empty(&self) -> bool {
- self.0.is_empty()
- }
-
- /// Returns the number of bytes.
- ///
- /// This method is equivalent to `self.len() * BASE_PAGE_SIZE`.
- pub fn nbytes(&self) -> usize {
- self.0.len() * PAGE_SIZE
- }
-
- /// Creates a new `FrameVec` from a single [`Frame`].
- pub fn from_one_frame(frame: Frame) -> Self {
- Self(vec![frame])
- }
-}
-
-impl IntoIterator for FrameVec {
- type Item = Frame;
-
- type IntoIter = alloc::vec::IntoIter<Self::Item>;
-
- fn into_iter(self) -> Self::IntoIter {
- self.0.into_iter()
- }
-}
-
-impl VmIo for FrameVec {
- fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> Result<()> {
- // Do bound check with potential integer overflow in mind
- let max_offset = offset.checked_add(buf.len()).ok_or(Error::Overflow)?;
- if max_offset > self.nbytes() {
- return Err(Error::InvalidArgs);
- }
-
- let num_unread_pages = offset / PAGE_SIZE;
- let mut start = offset % PAGE_SIZE;
- let mut buf_writer: VmWriter = buf.into();
- for frame in self.0.iter().skip(num_unread_pages) {
- let read_len = frame.reader().skip(start).read(&mut buf_writer);
- if read_len == 0 {
- break;
- }
- start = 0;
- }
- Ok(())
- }
-
- fn write_bytes(&self, offset: usize, buf: &[u8]) -> Result<()> {
- // Do bound check with potential integer overflow in mind
- let max_offset = offset.checked_add(buf.len()).ok_or(Error::Overflow)?;
- if max_offset > self.nbytes() {
- return Err(Error::InvalidArgs);
- }
-
- let num_unwrite_pages = offset / PAGE_SIZE;
- let mut start = offset % PAGE_SIZE;
- let mut buf_reader: VmReader = buf.into();
- for frame in self.0.iter().skip(num_unwrite_pages) {
- let write_len = frame.writer().skip(start).write(&mut buf_reader);
- if write_len == 0 {
- break;
- }
- start = 0;
- }
- Ok(())
- }
-}
-
-/// An iterator for frames.
-pub struct FrameVecIter<'a> {
- frames: &'a FrameVec,
- current: usize,
-}
-
-impl<'a> FrameVecIter<'a> {
- /// Creates a new `FrameVecIter` from the given [`FrameVec`].
- pub fn new(frames: &'a FrameVec) -> Self {
- Self { frames, current: 0 }
- }
-}
-
-impl<'a> Iterator for FrameVecIter<'a> {
- type Item = &'a Frame;
-
- fn next(&mut self) -> Option<Self::Item> {
- if self.current >= self.frames.0.len() {
- return None;
- }
- Some(self.frames.0.get(self.current).unwrap())
- }
-}
diff --git a/ostd/src/mm/frame/mod.rs b/ostd/src/mm/frame/mod.rs
--- a/ostd/src/mm/frame/mod.rs
+++ b/ostd/src/mm/frame/mod.rs
@@ -8,13 +8,11 @@
//! frames. Frames, with all the properties of pages, can additionally be safely
//! read and written by the kernel or the user.
-pub mod frame_vec;
pub mod options;
pub mod segment;
use core::mem::ManuallyDrop;
-pub use frame_vec::{FrameVec, FrameVecIter};
pub use segment::Segment;
use super::page::{
diff --git a/ostd/src/mm/frame/mod.rs b/ostd/src/mm/frame/mod.rs
--- a/ostd/src/mm/frame/mod.rs
+++ b/ostd/src/mm/frame/mod.rs
@@ -8,13 +8,11 @@
//! frames. Frames, with all the properties of pages, can additionally be safely
//! read and written by the kernel or the user.
-pub mod frame_vec;
pub mod options;
pub mod segment;
use core::mem::ManuallyDrop;
-pub use frame_vec::{FrameVec, FrameVecIter};
pub use segment::Segment;
use super::page::{
diff --git a/ostd/src/mm/frame/mod.rs b/ostd/src/mm/frame/mod.rs
--- a/ostd/src/mm/frame/mod.rs
+++ b/ostd/src/mm/frame/mod.rs
@@ -155,6 +153,48 @@ impl VmIo for Frame {
}
}
+impl VmIo for alloc::vec::Vec<Frame> {
+ fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> Result<()> {
+ // Do bound check with potential integer overflow in mind
+ let max_offset = offset.checked_add(buf.len()).ok_or(Error::Overflow)?;
+ if max_offset > self.len() * PAGE_SIZE {
+ return Err(Error::InvalidArgs);
+ }
+
+ let num_skip_pages = offset / PAGE_SIZE;
+ let mut start = offset % PAGE_SIZE;
+ let mut buf_writer: VmWriter = buf.into();
+ for frame in self.iter().skip(num_skip_pages) {
+ let read_len = frame.reader().skip(start).read(&mut buf_writer);
+ if read_len == 0 {
+ break;
+ }
+ start = 0;
+ }
+ Ok(())
+ }
+
+ fn write_bytes(&self, offset: usize, buf: &[u8]) -> Result<()> {
+ // Do bound check with potential integer overflow in mind
+ let max_offset = offset.checked_add(buf.len()).ok_or(Error::Overflow)?;
+ if max_offset > self.len() * PAGE_SIZE {
+ return Err(Error::InvalidArgs);
+ }
+
+ let num_skip_pages = offset / PAGE_SIZE;
+ let mut start = offset % PAGE_SIZE;
+ let mut buf_reader: VmReader = buf.into();
+ for frame in self.iter().skip(num_skip_pages) {
+ let write_len = frame.writer().skip(start).write(&mut buf_reader);
+ if write_len == 0 {
+ break;
+ }
+ start = 0;
+ }
+ Ok(())
+ }
+}
+
impl PageMeta for FrameMeta {
const USAGE: PageUsage = PageUsage::Frame;
diff --git a/ostd/src/mm/frame/mod.rs b/ostd/src/mm/frame/mod.rs
--- a/ostd/src/mm/frame/mod.rs
+++ b/ostd/src/mm/frame/mod.rs
@@ -155,6 +153,48 @@ impl VmIo for Frame {
}
}
+impl VmIo for alloc::vec::Vec<Frame> {
+ fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> Result<()> {
+ // Do bound check with potential integer overflow in mind
+ let max_offset = offset.checked_add(buf.len()).ok_or(Error::Overflow)?;
+ if max_offset > self.len() * PAGE_SIZE {
+ return Err(Error::InvalidArgs);
+ }
+
+ let num_skip_pages = offset / PAGE_SIZE;
+ let mut start = offset % PAGE_SIZE;
+ let mut buf_writer: VmWriter = buf.into();
+ for frame in self.iter().skip(num_skip_pages) {
+ let read_len = frame.reader().skip(start).read(&mut buf_writer);
+ if read_len == 0 {
+ break;
+ }
+ start = 0;
+ }
+ Ok(())
+ }
+
+ fn write_bytes(&self, offset: usize, buf: &[u8]) -> Result<()> {
+ // Do bound check with potential integer overflow in mind
+ let max_offset = offset.checked_add(buf.len()).ok_or(Error::Overflow)?;
+ if max_offset > self.len() * PAGE_SIZE {
+ return Err(Error::InvalidArgs);
+ }
+
+ let num_skip_pages = offset / PAGE_SIZE;
+ let mut start = offset % PAGE_SIZE;
+ let mut buf_reader: VmReader = buf.into();
+ for frame in self.iter().skip(num_skip_pages) {
+ let write_len = frame.writer().skip(start).write(&mut buf_reader);
+ if write_len == 0 {
+ break;
+ }
+ start = 0;
+ }
+ Ok(())
+ }
+}
+
impl PageMeta for FrameMeta {
const USAGE: PageUsage = PageUsage::Frame;
diff --git a/ostd/src/mm/frame/options.rs b/ostd/src/mm/frame/options.rs
--- a/ostd/src/mm/frame/options.rs
+++ b/ostd/src/mm/frame/options.rs
@@ -2,7 +2,7 @@
//! Options for allocating frames
-use super::{Frame, FrameVec, Segment};
+use super::{Frame, Segment};
use crate::{
mm::{
page::{self, meta::FrameMeta},
diff --git a/ostd/src/mm/frame/options.rs b/ostd/src/mm/frame/options.rs
--- a/ostd/src/mm/frame/options.rs
+++ b/ostd/src/mm/frame/options.rs
@@ -2,7 +2,7 @@
//! Options for allocating frames
-use super::{Frame, FrameVec, Segment};
+use super::{Frame, Segment};
use crate::{
mm::{
page::{self, meta::FrameMeta},
diff --git a/ostd/src/mm/frame/options.rs b/ostd/src/mm/frame/options.rs
--- a/ostd/src/mm/frame/options.rs
+++ b/ostd/src/mm/frame/options.rs
@@ -55,7 +55,7 @@ impl FrameAllocOptions {
}
/// Allocates a collection of page frames according to the given options.
- pub fn alloc(&self) -> Result<FrameVec> {
+ pub fn alloc(&self) -> Result<Vec<Frame>> {
let pages = if self.is_contiguous {
page::allocator::alloc(self.nframes * PAGE_SIZE).ok_or(Error::NoMemory)?
} else {
diff --git a/ostd/src/mm/frame/options.rs b/ostd/src/mm/frame/options.rs
--- a/ostd/src/mm/frame/options.rs
+++ b/ostd/src/mm/frame/options.rs
@@ -55,7 +55,7 @@ impl FrameAllocOptions {
}
/// Allocates a collection of page frames according to the given options.
- pub fn alloc(&self) -> Result<FrameVec> {
+ pub fn alloc(&self) -> Result<Vec<Frame>> {
let pages = if self.is_contiguous {
page::allocator::alloc(self.nframes * PAGE_SIZE).ok_or(Error::NoMemory)?
} else {
diff --git a/ostd/src/mm/frame/options.rs b/ostd/src/mm/frame/options.rs
--- a/ostd/src/mm/frame/options.rs
+++ b/ostd/src/mm/frame/options.rs
@@ -63,7 +63,7 @@ impl FrameAllocOptions {
.ok_or(Error::NoMemory)?
.into()
};
- let frames = FrameVec(pages.into_iter().map(|page| Frame { page }).collect());
+ let frames: Vec<_> = pages.into_iter().map(|page| Frame { page }).collect();
if !self.uninit {
for frame in frames.iter() {
frame.writer().fill(0);
diff --git a/ostd/src/mm/frame/options.rs b/ostd/src/mm/frame/options.rs
--- a/ostd/src/mm/frame/options.rs
+++ b/ostd/src/mm/frame/options.rs
@@ -63,7 +63,7 @@ impl FrameAllocOptions {
.ok_or(Error::NoMemory)?
.into()
};
- let frames = FrameVec(pages.into_iter().map(|page| Frame { page }).collect());
+ let frames: Vec<_> = pages.into_iter().map(|page| Frame { page }).collect();
if !self.uninit {
for frame in frames.iter() {
frame.writer().fill(0);
diff --git a/ostd/src/mm/frame/segment.rs b/ostd/src/mm/frame/segment.rs
--- a/ostd/src/mm/frame/segment.rs
+++ b/ostd/src/mm/frame/segment.rs
@@ -16,15 +16,10 @@ use crate::{
/// A handle to a contiguous range of page frames (physical memory pages).
///
-/// The biggest difference between `Segment` and [`FrameVec`] is that
-/// the page frames must be contiguous for `Segment`.
-///
/// A cloned `Segment` refers to the same page frames as the original.
/// As the original and cloned instances point to the same physical address,
/// they are treated as equal to each other.
///
-/// [`FrameVec`]: crate::mm::FrameVec
-///
/// #Example
///
/// ```rust
diff --git a/ostd/src/mm/frame/segment.rs b/ostd/src/mm/frame/segment.rs
--- a/ostd/src/mm/frame/segment.rs
+++ b/ostd/src/mm/frame/segment.rs
@@ -16,15 +16,10 @@ use crate::{
/// A handle to a contiguous range of page frames (physical memory pages).
///
-/// The biggest difference between `Segment` and [`FrameVec`] is that
-/// the page frames must be contiguous for `Segment`.
-///
/// A cloned `Segment` refers to the same page frames as the original.
/// As the original and cloned instances point to the same physical address,
/// they are treated as equal to each other.
///
-/// [`FrameVec`]: crate::mm::FrameVec
-///
/// #Example
///
/// ```rust
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -18,7 +18,7 @@ use crate::{
};
/// A trait that enables reading/writing data from/to a VM object,
-/// e.g., [`VmSpace`], [`FrameVec`], and [`Frame`].
+/// e.g., [`Segment`], [`Vec<Frame>`] and [`Frame`].
///
/// # Concurrency
///
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -18,7 +18,7 @@ use crate::{
};
/// A trait that enables reading/writing data from/to a VM object,
-/// e.g., [`VmSpace`], [`FrameVec`], and [`Frame`].
+/// e.g., [`Segment`], [`Vec<Frame>`] and [`Frame`].
///
/// # Concurrency
///
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -27,8 +27,7 @@ use crate::{
/// desire predictability or atomicity, the users should add extra mechanism
/// for such properties.
///
-/// [`VmSpace`]: crate::mm::VmSpace
-/// [`FrameVec`]: crate::mm::FrameVec
+/// [`Segment`]: crate::mm::Segment
/// [`Frame`]: crate::mm::Frame
pub trait VmIo: Send + Sync {
/// Reads a specified number of bytes at a specified offset into a given buffer.
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -27,8 +27,7 @@ use crate::{
/// desire predictability or atomicity, the users should add extra mechanism
/// for such properties.
///
-/// [`VmSpace`]: crate::mm::VmSpace
-/// [`FrameVec`]: crate::mm::FrameVec
+/// [`Segment`]: crate::mm::Segment
/// [`Frame`]: crate::mm::Frame
pub trait VmIo: Send + Sync {
/// Reads a specified number of bytes at a specified offset into a given buffer.
diff --git a/ostd/src/mm/mod.rs b/ostd/src/mm/mod.rs
--- a/ostd/src/mm/mod.rs
+++ b/ostd/src/mm/mod.rs
@@ -17,7 +17,7 @@ mod offset;
pub(crate) mod page;
pub(crate) mod page_prop;
pub(crate) mod page_table;
-mod space;
+pub mod vm_space;
use alloc::vec::Vec;
use core::{fmt::Debug, ops::Range};
diff --git a/ostd/src/mm/mod.rs b/ostd/src/mm/mod.rs
--- a/ostd/src/mm/mod.rs
+++ b/ostd/src/mm/mod.rs
@@ -17,7 +17,7 @@ mod offset;
pub(crate) mod page;
pub(crate) mod page_prop;
pub(crate) mod page_table;
-mod space;
+pub mod vm_space;
use alloc::vec::Vec;
use core::{fmt::Debug, ops::Range};
diff --git a/ostd/src/mm/mod.rs b/ostd/src/mm/mod.rs
--- a/ostd/src/mm/mod.rs
+++ b/ostd/src/mm/mod.rs
@@ -26,10 +26,10 @@ use spin::Once;
pub use self::{
dma::{Daddr, DmaCoherent, DmaDirection, DmaStream, DmaStreamSlice, HasDaddr},
- frame::{options::FrameAllocOptions, Frame, FrameVec, FrameVecIter, Segment},
+ frame::{options::FrameAllocOptions, Frame, Segment},
io::{KernelSpace, UserSpace, VmIo, VmReader, VmWriter},
page_prop::{CachePolicy, PageFlags, PageProperty},
- space::{VmMapOptions, VmSpace},
+ vm_space::VmSpace,
};
pub(crate) use self::{
kspace::paddr_to_vaddr, page::meta::init as init_page_meta, page_prop::PrivilegedPageFlags,
diff --git a/ostd/src/mm/mod.rs b/ostd/src/mm/mod.rs
--- a/ostd/src/mm/mod.rs
+++ b/ostd/src/mm/mod.rs
@@ -26,10 +26,10 @@ use spin::Once;
pub use self::{
dma::{Daddr, DmaCoherent, DmaDirection, DmaStream, DmaStreamSlice, HasDaddr},
- frame::{options::FrameAllocOptions, Frame, FrameVec, FrameVecIter, Segment},
+ frame::{options::FrameAllocOptions, Frame, Segment},
io::{KernelSpace, UserSpace, VmIo, VmReader, VmWriter},
page_prop::{CachePolicy, PageFlags, PageProperty},
- space::{VmMapOptions, VmSpace},
+ vm_space::VmSpace,
};
pub(crate) use self::{
kspace::paddr_to_vaddr, page::meta::init as init_page_meta, page_prop::PrivilegedPageFlags,
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -76,7 +76,7 @@ use super::{
use crate::mm::{page::DynPage, Paddr, PageProperty, Vaddr};
#[derive(Clone, Debug)]
-pub(crate) enum PageTableQueryResult {
+pub enum PageTableQueryResult {
NotMapped {
va: Vaddr,
len: usize,
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -76,7 +76,7 @@ use super::{
use crate::mm::{page::DynPage, Paddr, PageProperty, Vaddr};
#[derive(Clone, Debug)]
-pub(crate) enum PageTableQueryResult {
+pub enum PageTableQueryResult {
NotMapped {
va: Vaddr,
len: usize,
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -105,7 +105,7 @@ pub(crate) enum PageTableQueryResult {
/// simulate the recursion, and adpot a page table locking protocol to
/// provide concurrency.
#[derive(Debug)]
-pub(crate) struct Cursor<'a, M: PageTableMode, E: PageTableEntryTrait, C: PagingConstsTrait>
+pub struct Cursor<'a, M: PageTableMode, E: PageTableEntryTrait, C: PagingConstsTrait>
where
[(); C::NR_LEVELS as usize]:,
{
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -105,7 +105,7 @@ pub(crate) enum PageTableQueryResult {
/// simulate the recursion, and adpot a page table locking protocol to
/// provide concurrency.
#[derive(Debug)]
-pub(crate) struct Cursor<'a, M: PageTableMode, E: PageTableEntryTrait, C: PagingConstsTrait>
+pub struct Cursor<'a, M: PageTableMode, E: PageTableEntryTrait, C: PagingConstsTrait>
where
[(); C::NR_LEVELS as usize]:,
{
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -140,10 +140,7 @@ where
///
/// Note that this function does not ensure exclusive access to the claimed
/// virtual address range. The accesses using this cursor may block or fail.
- pub(crate) fn new(
- pt: &'a PageTable<M, E, C>,
- va: &Range<Vaddr>,
- ) -> Result<Self, PageTableError> {
+ pub fn new(pt: &'a PageTable<M, E, C>, va: &Range<Vaddr>) -> Result<Self, PageTableError> {
if !M::covers(va) {
return Err(PageTableError::InvalidVaddrRange(va.start, va.end));
}
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -140,10 +140,7 @@ where
///
/// Note that this function does not ensure exclusive access to the claimed
/// virtual address range. The accesses using this cursor may block or fail.
- pub(crate) fn new(
- pt: &'a PageTable<M, E, C>,
- va: &Range<Vaddr>,
- ) -> Result<Self, PageTableError> {
+ pub fn new(pt: &'a PageTable<M, E, C>, va: &Range<Vaddr>) -> Result<Self, PageTableError> {
if !M::covers(va) {
return Err(PageTableError::InvalidVaddrRange(va.start, va.end));
}
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -198,9 +195,9 @@ where
}
/// Gets the information of the current slot.
- pub(crate) fn query(&mut self) -> Option<PageTableQueryResult> {
+ pub fn query(&mut self) -> Result<PageTableQueryResult, PageTableError> {
if self.va >= self.barrier_va.end {
- return None;
+ return Err(PageTableError::InvalidVaddr(self.va));
}
loop {
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -198,9 +195,9 @@ where
}
/// Gets the information of the current slot.
- pub(crate) fn query(&mut self) -> Option<PageTableQueryResult> {
+ pub fn query(&mut self) -> Result<PageTableQueryResult, PageTableError> {
if self.va >= self.barrier_va.end {
- return None;
+ return Err(PageTableError::InvalidVaddr(self.va));
}
loop {
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -209,7 +206,7 @@ where
let pte = self.read_cur_pte();
if !pte.is_present() {
- return Some(PageTableQueryResult::NotMapped {
+ return Ok(PageTableQueryResult::NotMapped {
va,
len: page_size::<C>(level),
});
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -209,7 +206,7 @@ where
let pte = self.read_cur_pte();
if !pte.is_present() {
- return Some(PageTableQueryResult::NotMapped {
+ return Ok(PageTableQueryResult::NotMapped {
va,
len: page_size::<C>(level),
});
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -221,14 +218,14 @@ where
match self.cur_child() {
Child::Page(page) => {
- return Some(PageTableQueryResult::Mapped {
+ return Ok(PageTableQueryResult::Mapped {
va,
page,
prop: pte.prop(),
});
}
Child::Untracked(pa) => {
- return Some(PageTableQueryResult::MappedUntracked {
+ return Ok(PageTableQueryResult::MappedUntracked {
va,
pa,
len: page_size::<C>(level),
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -221,14 +218,14 @@ where
match self.cur_child() {
Child::Page(page) => {
- return Some(PageTableQueryResult::Mapped {
+ return Ok(PageTableQueryResult::Mapped {
va,
page,
prop: pte.prop(),
});
}
Child::Untracked(pa) => {
- return Some(PageTableQueryResult::MappedUntracked {
+ return Ok(PageTableQueryResult::MappedUntracked {
va,
pa,
len: page_size::<C>(level),
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -246,7 +243,7 @@ where
///
/// If reached the end of a page table node, it leads itself up to the next page of the parent
/// page if possible.
- fn move_forward(&mut self) {
+ pub(in crate::mm) fn move_forward(&mut self) {
let page_size = page_size::<C>(self.level);
let next_va = self.va.align_down(page_size) + page_size;
while self.level < self.guard_level && pte_index::<C>(next_va, self.level) == 0 {
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -246,7 +243,7 @@ where
///
/// If reached the end of a page table node, it leads itself up to the next page of the parent
/// page if possible.
- fn move_forward(&mut self) {
+ pub(in crate::mm) fn move_forward(&mut self) {
let page_size = page_size::<C>(self.level);
let next_va = self.va.align_down(page_size) + page_size;
while self.level < self.guard_level && pte_index::<C>(next_va, self.level) == 0 {
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -255,6 +252,41 @@ where
self.va = next_va;
}
+ /// Jumps to the given virtual address.
+ ///
+ /// # Panics
+ ///
+ /// This method panics if the address is out of the range where the cursor is required to operate,
+ /// or has bad alignment.
+ pub fn jump(&mut self, va: Vaddr) {
+ assert!(self.barrier_va.contains(&va));
+ assert!(va % C::BASE_PAGE_SIZE == 0);
+
+ loop {
+ let cur_node_start = self.va & !(page_size::<C>(self.level + 1) - 1);
+ let cur_node_end = cur_node_start + page_size::<C>(self.level + 1);
+ // If the address is within the current node, we can jump directly.
+ if cur_node_start <= va && va < cur_node_end {
+ self.va = va;
+ return;
+ }
+
+ // There is a corner case that the cursor is depleted, sitting at the start of the
+ // next node but the next node is not locked because the parent is not locked.
+ if self.va >= self.barrier_va.end && self.level == self.guard_level {
+ self.va = va;
+ return;
+ }
+
+ debug_assert!(self.level < self.guard_level);
+ self.level_up();
+ }
+ }
+
+ pub fn virt_addr(&self) -> Vaddr {
+ self.va
+ }
+
/// Goes up a level. We release the current page if it has no mappings since the cursor only moves
/// forward. And if needed we will do the final cleanup using this method after re-walk when the
/// cursor is dropped.
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -255,6 +252,41 @@ where
self.va = next_va;
}
+ /// Jumps to the given virtual address.
+ ///
+ /// # Panics
+ ///
+ /// This method panics if the address is out of the range where the cursor is required to operate,
+ /// or has bad alignment.
+ pub fn jump(&mut self, va: Vaddr) {
+ assert!(self.barrier_va.contains(&va));
+ assert!(va % C::BASE_PAGE_SIZE == 0);
+
+ loop {
+ let cur_node_start = self.va & !(page_size::<C>(self.level + 1) - 1);
+ let cur_node_end = cur_node_start + page_size::<C>(self.level + 1);
+ // If the address is within the current node, we can jump directly.
+ if cur_node_start <= va && va < cur_node_end {
+ self.va = va;
+ return;
+ }
+
+ // There is a corner case that the cursor is depleted, sitting at the start of the
+ // next node but the next node is not locked because the parent is not locked.
+ if self.va >= self.barrier_va.end && self.level == self.guard_level {
+ self.va = va;
+ return;
+ }
+
+ debug_assert!(self.level < self.guard_level);
+ self.level_up();
+ }
+ }
+
+ pub fn virt_addr(&self) -> Vaddr {
+ self.va
+ }
+
/// Goes up a level. We release the current page if it has no mappings since the cursor only moves
/// forward. And if needed we will do the final cleanup using this method after re-walk when the
/// cursor is dropped.
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -327,10 +359,10 @@ where
fn next(&mut self) -> Option<Self::Item> {
let result = self.query();
- if result.is_some() {
+ if result.is_ok() {
self.move_forward();
}
- result
+ result.ok()
}
}
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -327,10 +359,10 @@ where
fn next(&mut self) -> Option<Self::Item> {
let result = self.query();
- if result.is_some() {
+ if result.is_ok() {
self.move_forward();
}
- result
+ result.ok()
}
}
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -339,7 +371,7 @@ where
/// Also, it has all the capabilities of a [`Cursor`]. A virtual address range
/// in a page table can only be accessed by one cursor whether it is mutable or not.
#[derive(Debug)]
-pub(crate) struct CursorMut<'a, M: PageTableMode, E: PageTableEntryTrait, C: PagingConstsTrait>(
+pub struct CursorMut<'a, M: PageTableMode, E: PageTableEntryTrait, C: PagingConstsTrait>(
Cursor<'a, M, E, C>,
)
where
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -339,7 +371,7 @@ where
/// Also, it has all the capabilities of a [`Cursor`]. A virtual address range
/// in a page table can only be accessed by one cursor whether it is mutable or not.
#[derive(Debug)]
-pub(crate) struct CursorMut<'a, M: PageTableMode, E: PageTableEntryTrait, C: PagingConstsTrait>(
+pub struct CursorMut<'a, M: PageTableMode, E: PageTableEntryTrait, C: PagingConstsTrait>(
Cursor<'a, M, E, C>,
)
where
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -365,43 +397,26 @@ where
Cursor::new(pt, va).map(|inner| Self(inner))
}
- /// Gets the information of the current slot and go to the next slot.
- ///
- /// We choose not to implement `Iterator` or `IterMut` for [`CursorMut`]
- /// because the mutable cursor is indeed not an iterator.
- pub(crate) fn next(&mut self) -> Option<PageTableQueryResult> {
- self.0.next()
- }
-
/// Jumps to the given virtual address.
///
+ /// This is the same as [`Cursor::jump`].
+ ///
/// # Panics
///
/// This method panics if the address is out of the range where the cursor is required to operate,
/// or has bad alignment.
- pub(crate) fn jump(&mut self, va: Vaddr) {
- assert!(self.0.barrier_va.contains(&va));
- assert!(va % C::BASE_PAGE_SIZE == 0);
-
- loop {
- let cur_node_start = self.0.va & !(page_size::<C>(self.0.level + 1) - 1);
- let cur_node_end = cur_node_start + page_size::<C>(self.0.level + 1);
- // If the address is within the current node, we can jump directly.
- if cur_node_start <= va && va < cur_node_end {
- self.0.va = va;
- return;
- }
+ pub fn jump(&mut self, va: Vaddr) {
+ self.0.jump(va)
+ }
- // There is a corner case that the cursor is depleted, sitting at the start of the
- // next node but the next node is not locked because the parent is not locked.
- if self.0.va >= self.0.barrier_va.end && self.0.level == self.0.guard_level {
- self.0.va = va;
- return;
- }
+ /// Gets the current virtual address.
+ pub fn virt_addr(&self) -> Vaddr {
+ self.0.virt_addr()
+ }
- debug_assert!(self.0.level < self.0.guard_level);
- self.0.level_up();
- }
+ /// Gets the information of the current slot.
+ pub fn query(&mut self) -> Result<PageTableQueryResult, PageTableError> {
+ self.0.query()
}
/// Maps the range starting from the current address to a [`DynPage`].
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -365,43 +397,26 @@ where
Cursor::new(pt, va).map(|inner| Self(inner))
}
- /// Gets the information of the current slot and go to the next slot.
- ///
- /// We choose not to implement `Iterator` or `IterMut` for [`CursorMut`]
- /// because the mutable cursor is indeed not an iterator.
- pub(crate) fn next(&mut self) -> Option<PageTableQueryResult> {
- self.0.next()
- }
-
/// Jumps to the given virtual address.
///
+ /// This is the same as [`Cursor::jump`].
+ ///
/// # Panics
///
/// This method panics if the address is out of the range where the cursor is required to operate,
/// or has bad alignment.
- pub(crate) fn jump(&mut self, va: Vaddr) {
- assert!(self.0.barrier_va.contains(&va));
- assert!(va % C::BASE_PAGE_SIZE == 0);
-
- loop {
- let cur_node_start = self.0.va & !(page_size::<C>(self.0.level + 1) - 1);
- let cur_node_end = cur_node_start + page_size::<C>(self.0.level + 1);
- // If the address is within the current node, we can jump directly.
- if cur_node_start <= va && va < cur_node_end {
- self.0.va = va;
- return;
- }
+ pub fn jump(&mut self, va: Vaddr) {
+ self.0.jump(va)
+ }
- // There is a corner case that the cursor is depleted, sitting at the start of the
- // next node but the next node is not locked because the parent is not locked.
- if self.0.va >= self.0.barrier_va.end && self.0.level == self.0.guard_level {
- self.0.va = va;
- return;
- }
+ /// Gets the current virtual address.
+ pub fn virt_addr(&self) -> Vaddr {
+ self.0.virt_addr()
+ }
- debug_assert!(self.0.level < self.0.guard_level);
- self.0.level_up();
- }
+ /// Gets the information of the current slot.
+ pub fn query(&mut self) -> Result<PageTableQueryResult, PageTableError> {
+ self.0.query()
}
/// Maps the range starting from the current address to a [`DynPage`].
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -417,7 +432,7 @@ where
///
/// The caller should ensure that the virtual range being mapped does
/// not affect kernel's memory safety.
- pub(crate) unsafe fn map(&mut self, page: DynPage, prop: PageProperty) {
+ pub unsafe fn map(&mut self, page: DynPage, prop: PageProperty) {
let end = self.0.va + page.size();
assert!(end <= self.0.barrier_va.end);
debug_assert!(self.0.in_tracked_range());
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -417,7 +432,7 @@ where
///
/// The caller should ensure that the virtual range being mapped does
/// not affect kernel's memory safety.
- pub(crate) unsafe fn map(&mut self, page: DynPage, prop: PageProperty) {
+ pub unsafe fn map(&mut self, page: DynPage, prop: PageProperty) {
let end = self.0.va + page.size();
assert!(end <= self.0.barrier_va.end);
debug_assert!(self.0.in_tracked_range());
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -472,7 +487,7 @@ where
/// - the range being mapped does not affect kernel's memory safety;
/// - the physical address to be mapped is valid and safe to use;
/// - it is allowed to map untracked pages in this virtual address range.
- pub(crate) unsafe fn map_pa(&mut self, pa: &Range<Paddr>, prop: PageProperty) {
+ pub unsafe fn map_pa(&mut self, pa: &Range<Paddr>, prop: PageProperty) {
let end = self.0.va + pa.len();
let mut pa = pa.start;
assert!(end <= self.0.barrier_va.end);
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -472,7 +487,7 @@ where
/// - the range being mapped does not affect kernel's memory safety;
/// - the physical address to be mapped is valid and safe to use;
/// - it is allowed to map untracked pages in this virtual address range.
- pub(crate) unsafe fn map_pa(&mut self, pa: &Range<Paddr>, prop: PageProperty) {
+ pub unsafe fn map_pa(&mut self, pa: &Range<Paddr>, prop: PageProperty) {
let end = self.0.va + pa.len();
let mut pa = pa.start;
assert!(end <= self.0.barrier_va.end);
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -522,7 +537,7 @@ where
/// This function will panic if:
/// - the range to be unmapped is out of the range where the cursor is required to operate;
/// - the range covers only a part of a page.
- pub(crate) unsafe fn unmap(&mut self, len: usize) {
+ pub unsafe fn unmap(&mut self, len: usize) {
let end = self.0.va + len;
assert!(end <= self.0.barrier_va.end);
assert!(end % C::BASE_PAGE_SIZE == 0);
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -522,7 +537,7 @@ where
/// This function will panic if:
/// - the range to be unmapped is out of the range where the cursor is required to operate;
/// - the range covers only a part of a page.
- pub(crate) unsafe fn unmap(&mut self, len: usize) {
+ pub unsafe fn unmap(&mut self, len: usize) {
let end = self.0.va + len;
assert!(end <= self.0.barrier_va.end);
assert!(end % C::BASE_PAGE_SIZE == 0);
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -579,7 +594,7 @@ where
///
/// This function will panic if:
/// - the range to be protected is out of the range where the cursor is required to operate.
- pub(crate) unsafe fn protect(
+ pub unsafe fn protect(
&mut self,
len: usize,
mut op: impl FnMut(&mut PageProperty),
diff --git a/ostd/src/mm/page_table/cursor.rs b/ostd/src/mm/page_table/cursor.rs
--- a/ostd/src/mm/page_table/cursor.rs
+++ b/ostd/src/mm/page_table/cursor.rs
@@ -579,7 +594,7 @@ where
///
/// This function will panic if:
/// - the range to be protected is out of the range where the cursor is required to operate.
- pub(crate) unsafe fn protect(
+ pub unsafe fn protect(
&mut self,
len: usize,
mut op: impl FnMut(&mut PageProperty),
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -3,7 +3,7 @@
use core::{fmt::Debug, marker::PhantomData, ops::Range};
use super::{
- nr_subpage_per_huge, paddr_to_vaddr,
+ nr_subpage_per_huge,
page_prop::{PageFlags, PageProperty},
page_size, Paddr, PagingConstsTrait, PagingLevel, Vaddr,
};
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -3,7 +3,7 @@
use core::{fmt::Debug, marker::PhantomData, ops::Range};
use super::{
- nr_subpage_per_huge, paddr_to_vaddr,
+ nr_subpage_per_huge,
page_prop::{PageFlags, PageProperty},
page_size, Paddr, PagingConstsTrait, PagingLevel, Vaddr,
};
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -14,8 +14,8 @@ use crate::{
mod node;
use node::*;
-mod cursor;
-pub(crate) use cursor::{Cursor, CursorMut, PageTableQueryResult};
+pub mod cursor;
+pub use cursor::{Cursor, CursorMut, PageTableQueryResult};
#[cfg(ktest)]
mod test;
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -23,8 +23,10 @@ pub(in crate::mm) mod boot_pt;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum PageTableError {
- /// The virtual address range is invalid.
+ /// The provided virtual address range is invalid.
InvalidVaddrRange(Vaddr, Vaddr),
+ /// The provided virtual address is invalid.
+ InvalidVaddr(Vaddr),
/// Using virtual address not aligned.
UnalignedVaddr,
/// Protecting a mapping that does not exist.
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -23,8 +23,10 @@ pub(in crate::mm) mod boot_pt;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum PageTableError {
- /// The virtual address range is invalid.
+ /// The provided virtual address range is invalid.
InvalidVaddrRange(Vaddr, Vaddr),
+ /// The provided virtual address is invalid.
+ InvalidVaddr(Vaddr),
/// Using virtual address not aligned.
UnalignedVaddr,
/// Protecting a mapping that does not exist.
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -76,7 +78,7 @@ const fn pte_index<C: PagingConstsTrait>(va: Vaddr, level: PagingLevel) -> usize
/// A handle to a page table.
/// A page table can track the lifetime of the mapped physical pages.
#[derive(Debug)]
-pub(crate) struct PageTable<
+pub struct PageTable<
M: PageTableMode,
E: PageTableEntryTrait = PageTableEntry,
C: PagingConstsTrait = PagingConsts,
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -76,7 +78,7 @@ const fn pte_index<C: PagingConstsTrait>(va: Vaddr, level: PagingLevel) -> usize
/// A handle to a page table.
/// A page table can track the lifetime of the mapped physical pages.
#[derive(Debug)]
-pub(crate) struct PageTable<
+pub struct PageTable<
M: PageTableMode,
E: PageTableEntryTrait = PageTableEntry,
C: PagingConstsTrait = PagingConsts,
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -88,7 +90,7 @@ pub(crate) struct PageTable<
}
impl PageTable<UserMode> {
- pub(crate) fn activate(&self) {
+ pub fn activate(&self) {
// SAFETY: The usermode page table is safe to activate since the kernel
// mappings are shared.
unsafe {
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -88,7 +90,7 @@ pub(crate) struct PageTable<
}
impl PageTable<UserMode> {
- pub(crate) fn activate(&self) {
+ pub fn activate(&self) {
// SAFETY: The usermode page table is safe to activate since the kernel
// mappings are shared.
unsafe {
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -100,7 +102,7 @@ impl PageTable<UserMode> {
/// new page table.
///
/// TODO: We may consider making the page table itself copy-on-write.
- pub(crate) fn fork_copy_on_write(&self) -> Self {
+ pub fn fork_copy_on_write(&self) -> Self {
let mut cursor = self.cursor_mut(&UserMode::VADDR_RANGE).unwrap();
// SAFETY: Protecting the user page table is safe.
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -100,7 +102,7 @@ impl PageTable<UserMode> {
/// new page table.
///
/// TODO: We may consider making the page table itself copy-on-write.
- pub(crate) fn fork_copy_on_write(&self) -> Self {
+ pub fn fork_copy_on_write(&self) -> Self {
let mut cursor = self.cursor_mut(&UserMode::VADDR_RANGE).unwrap();
// SAFETY: Protecting the user page table is safe.
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -139,7 +141,7 @@ impl PageTable<KernelMode> {
///
/// Then, one can use a user page table to call [`fork_copy_on_write`], creating
/// other child page tables.
- pub(crate) fn create_user_page_table(&self) -> PageTable<UserMode> {
+ pub fn create_user_page_table(&self) -> PageTable<UserMode> {
let root_node = self.root.clone_shallow().lock();
const NR_PTES_PER_NODE: usize = nr_subpage_per_huge::<PagingConsts>();
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -139,7 +141,7 @@ impl PageTable<KernelMode> {
///
/// Then, one can use a user page table to call [`fork_copy_on_write`], creating
/// other child page tables.
- pub(crate) fn create_user_page_table(&self) -> PageTable<UserMode> {
+ pub fn create_user_page_table(&self) -> PageTable<UserMode> {
let root_node = self.root.clone_shallow().lock();
const NR_PTES_PER_NODE: usize = nr_subpage_per_huge::<PagingConsts>();
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -157,7 +159,7 @@ impl PageTable<KernelMode> {
/// The virtual address range should be aligned to the root level page size. Considering
/// usize overflows, the caller should provide the index range of the root level pages
/// instead of the virtual address range.
- pub(crate) fn make_shared_tables(&self, root_index: Range<usize>) {
+ pub fn make_shared_tables(&self, root_index: Range<usize>) {
const NR_PTES_PER_NODE: usize = nr_subpage_per_huge::<PagingConsts>();
let start = root_index.start;
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -157,7 +159,7 @@ impl PageTable<KernelMode> {
/// The virtual address range should be aligned to the root level page size. Considering
/// usize overflows, the caller should provide the index range of the root level pages
/// instead of the virtual address range.
- pub(crate) fn make_shared_tables(&self, root_index: Range<usize>) {
+ pub fn make_shared_tables(&self, root_index: Range<usize>) {
const NR_PTES_PER_NODE: usize = nr_subpage_per_huge::<PagingConsts>();
let start = root_index.start;
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -182,7 +184,7 @@ where
[(); C::NR_LEVELS as usize]:,
{
/// Create a new empty page table. Useful for the kernel page table and IOMMU page tables only.
- pub(crate) fn empty() -> Self {
+ pub fn empty() -> Self {
PageTable {
root: PageTableNode::<E, C>::alloc(C::NR_LEVELS).into_raw(),
_phantom: PhantomData,
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -182,7 +184,7 @@ where
[(); C::NR_LEVELS as usize]:,
{
/// Create a new empty page table. Useful for the kernel page table and IOMMU page tables only.
- pub(crate) fn empty() -> Self {
+ pub fn empty() -> Self {
PageTable {
root: PageTableNode::<E, C>::alloc(C::NR_LEVELS).into_raw(),
_phantom: PhantomData,
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -197,11 +199,11 @@ where
///
/// It is dangerous to directly provide the physical address of the root page table to the
/// hardware since the page table node may be dropped, resulting in UAF.
- pub(crate) unsafe fn root_paddr(&self) -> Paddr {
+ pub unsafe fn root_paddr(&self) -> Paddr {
self.root.paddr()
}
- pub(crate) unsafe fn map(
+ pub unsafe fn map(
&self,
vaddr: &Range<Vaddr>,
paddr: &Range<Paddr>,
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -197,11 +199,11 @@ where
///
/// It is dangerous to directly provide the physical address of the root page table to the
/// hardware since the page table node may be dropped, resulting in UAF.
- pub(crate) unsafe fn root_paddr(&self) -> Paddr {
+ pub unsafe fn root_paddr(&self) -> Paddr {
self.root.paddr()
}
- pub(crate) unsafe fn map(
+ pub unsafe fn map(
&self,
vaddr: &Range<Vaddr>,
paddr: &Range<Paddr>,
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -211,12 +213,12 @@ where
Ok(())
}
- pub(crate) unsafe fn unmap(&self, vaddr: &Range<Vaddr>) -> Result<(), PageTableError> {
+ pub unsafe fn unmap(&self, vaddr: &Range<Vaddr>) -> Result<(), PageTableError> {
self.cursor_mut(vaddr)?.unmap(vaddr.len());
Ok(())
}
- pub(crate) unsafe fn protect(
+ pub unsafe fn protect(
&self,
vaddr: &Range<Vaddr>,
op: impl FnMut(&mut PageProperty),
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -211,12 +213,12 @@ where
Ok(())
}
- pub(crate) unsafe fn unmap(&self, vaddr: &Range<Vaddr>) -> Result<(), PageTableError> {
+ pub unsafe fn unmap(&self, vaddr: &Range<Vaddr>) -> Result<(), PageTableError> {
self.cursor_mut(vaddr)?.unmap(vaddr.len());
Ok(())
}
- pub(crate) unsafe fn protect(
+ pub unsafe fn protect(
&self,
vaddr: &Range<Vaddr>,
op: impl FnMut(&mut PageProperty),
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -232,16 +234,17 @@ where
/// Note that this function may fail reflect an accurate result if there are
/// cursors concurrently accessing the same virtual address range, just like what
/// happens for the hardware MMU walk.
- pub(crate) fn query(&self, vaddr: Vaddr) -> Option<(Paddr, PageProperty)> {
+ #[cfg(ktest)]
+ pub fn query(&self, vaddr: Vaddr) -> Option<(Paddr, PageProperty)> {
// SAFETY: The root node is a valid page table node so the address is valid.
unsafe { page_walk::<E, C>(self.root_paddr(), vaddr) }
}
/// Create a new cursor exclusively accessing the virtual address range for mapping.
///
- /// If another cursor is already accessing the range, the new cursor will wait until the
+ /// If another cursor is already accessing the range, the new cursor may wait until the
/// previous cursor is dropped.
- pub(crate) fn cursor_mut(
+ pub fn cursor_mut(
&'a self,
va: &Range<Vaddr>,
) -> Result<CursorMut<'a, M, E, C>, PageTableError> {
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -250,19 +253,17 @@ where
/// Create a new cursor exclusively accessing the virtual address range for querying.
///
- /// If another cursor is already accessing the range, the new cursor will wait until the
- /// previous cursor is dropped.
- pub(crate) fn cursor(
- &'a self,
- va: &Range<Vaddr>,
- ) -> Result<Cursor<'a, M, E, C>, PageTableError> {
+ /// If another cursor is already accessing the range, the new cursor may wait until the
+ /// previous cursor is dropped. The modification to the mapping by the cursor may also
+ /// block or be overriden by the mapping of another cursor.
+ pub fn cursor(&'a self, va: &Range<Vaddr>) -> Result<Cursor<'a, M, E, C>, PageTableError> {
Cursor::new(self, va)
}
/// Create a new reference to the same page table.
/// The caller must ensure that the kernel page table is not copied.
/// This is only useful for IOMMU page tables. Think twice before using it in other cases.
- pub(crate) unsafe fn shallow_copy(&self) -> Self {
+ pub unsafe fn shallow_copy(&self) -> Self {
PageTable {
root: self.root.clone_shallow(),
_phantom: PhantomData,
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -250,19 +253,17 @@ where
/// Create a new cursor exclusively accessing the virtual address range for querying.
///
- /// If another cursor is already accessing the range, the new cursor will wait until the
- /// previous cursor is dropped.
- pub(crate) fn cursor(
- &'a self,
- va: &Range<Vaddr>,
- ) -> Result<Cursor<'a, M, E, C>, PageTableError> {
+ /// If another cursor is already accessing the range, the new cursor may wait until the
+ /// previous cursor is dropped. The modification to the mapping by the cursor may also
+ /// block or be overriden by the mapping of another cursor.
+ pub fn cursor(&'a self, va: &Range<Vaddr>) -> Result<Cursor<'a, M, E, C>, PageTableError> {
Cursor::new(self, va)
}
/// Create a new reference to the same page table.
/// The caller must ensure that the kernel page table is not copied.
/// This is only useful for IOMMU page tables. Think twice before using it in other cases.
- pub(crate) unsafe fn shallow_copy(&self) -> Self {
+ pub unsafe fn shallow_copy(&self) -> Self {
PageTable {
root: self.root.clone_shallow(),
_phantom: PhantomData,
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -288,13 +289,14 @@ where
///
/// To mitigate this problem, the page table nodes are by default not
/// actively recycled, until we find an appropriate solution.
+#[cfg(ktest)]
pub(super) unsafe fn page_walk<E: PageTableEntryTrait, C: PagingConstsTrait>(
root_paddr: Paddr,
vaddr: Vaddr,
) -> Option<(Paddr, PageProperty)> {
- // We disable preemt here to mimic the MMU walk, which will not be interrupted
- // then must finish within a given time.
- let _guard = crate::task::disable_preempt();
+ use super::paddr_to_vaddr;
+
+ let preempt_guard = crate::task::disable_preempt();
let mut cur_level = C::NR_LEVELS;
let mut cur_pte = {
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -336,9 +338,7 @@ pub(super) unsafe fn page_walk<E: PageTableEntryTrait, C: PagingConstsTrait>(
/// The interface for defining architecture-specific page table entries.
///
/// Note that a default PTE shoud be a PTE that points to nothing.
-pub(crate) trait PageTableEntryTrait:
- Clone + Copy + Debug + Default + Pod + Sized + Sync
-{
+pub trait PageTableEntryTrait: Clone + Copy + Debug + Default + Pod + Sized + Sync {
/// Create a set of new invalid page table flags that indicates an absent page.
///
/// Note that currently the implementation requires an all zero PTE to be an absent PTE.
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -336,9 +338,7 @@ pub(super) unsafe fn page_walk<E: PageTableEntryTrait, C: PagingConstsTrait>(
/// The interface for defining architecture-specific page table entries.
///
/// Note that a default PTE shoud be a PTE that points to nothing.
-pub(crate) trait PageTableEntryTrait:
- Clone + Copy + Debug + Default + Pod + Sized + Sync
-{
+pub trait PageTableEntryTrait: Clone + Copy + Debug + Default + Pod + Sized + Sync {
/// Create a set of new invalid page table flags that indicates an absent page.
///
/// Note that currently the implementation requires an all zero PTE to be an absent PTE.
diff --git a/ostd/src/mm/space.rs /dev/null
--- a/ostd/src/mm/space.rs
+++ /dev/null
@@ -1,408 +0,0 @@
-// SPDX-License-Identifier: MPL-2.0
-
-use core::ops::Range;
-
-use spin::Once;
-
-use super::{
- io::UserSpace,
- is_page_aligned,
- kspace::KERNEL_PAGE_TABLE,
- page_table::{PageTable, PageTableMode, UserMode},
- CachePolicy, FrameVec, PageFlags, PageProperty, PagingConstsTrait, PrivilegedPageFlags,
- VmReader, VmWriter, PAGE_SIZE,
-};
-use crate::{
- arch::mm::{
- current_page_table_paddr, tlb_flush_addr_range, tlb_flush_all_excluding_global,
- PageTableEntry, PagingConsts,
- },
- cpu::CpuExceptionInfo,
- mm::{
- page_table::{Cursor, PageTableQueryResult as PtQr},
- Frame, MAX_USERSPACE_VADDR,
- },
- prelude::*,
- Error,
-};
-
-/// Virtual memory space.
-///
-/// A virtual memory space (`VmSpace`) can be created and assigned to a user space so that
-/// the virtual memory of the user space can be manipulated safely. For example,
-/// given an arbitrary user-space pointer, one can read and write the memory
-/// location referred to by the user-space pointer without the risk of breaking the
-/// memory safety of the kernel space.
-///
-/// A newly-created `VmSpace` is not backed by any physical memory pages.
-/// To provide memory pages for a `VmSpace`, one can allocate and map
-/// physical memory ([`Frame`]s) to the `VmSpace`.
-///
-/// A `VmSpace` can also attach a page fault handler, which will be invoked to handle
-/// page faults generated from user space.
-///
-/// A `VmSpace` can also attach a page fault handler, which will be invoked to handle
-/// page faults generated from user space.
-#[allow(clippy::type_complexity)]
-pub struct VmSpace {
- pt: PageTable<UserMode>,
- page_fault_handler: Once<fn(&VmSpace, &CpuExceptionInfo) -> core::result::Result<(), ()>>,
-}
-
-// Notes on TLB flushing:
-//
-// We currently assume that:
-// 1. `VmSpace` _might_ be activated on the current CPU and the user memory _might_ be used
-// immediately after we make changes to the page table entries. So we must invalidate the
-// corresponding TLB caches accordingly.
-// 2. `VmSpace` must _not_ be activated on another CPU. This assumption is trivial, since SMP
-// support is not yet available. But we need to consider this situation in the future (TODO).
-
-impl VmSpace {
- /// Creates a new VM address space.
- pub fn new() -> Self {
- Self {
- pt: KERNEL_PAGE_TABLE.get().unwrap().create_user_page_table(),
- page_fault_handler: Once::new(),
- }
- }
-
- /// Activates the page table.
- pub(crate) fn activate(&self) {
- self.pt.activate();
- }
-
- pub(crate) fn handle_page_fault(
- &self,
- info: &CpuExceptionInfo,
- ) -> core::result::Result<(), ()> {
- if let Some(func) = self.page_fault_handler.get() {
- return func(self, info);
- }
- Err(())
- }
-
- /// Registers the page fault handler in this `VmSpace`.
- ///
- /// The page fault handler of a `VmSpace` can only be initialized once.
- /// If it has been initialized before, calling this method will have no effect.
- pub fn register_page_fault_handler(
- &self,
- func: fn(&VmSpace, &CpuExceptionInfo) -> core::result::Result<(), ()>,
- ) {
- self.page_fault_handler.call_once(|| func);
- }
-
- /// Maps some physical memory pages into the VM space according to the given
- /// options, returning the address where the mapping is created.
- ///
- /// The ownership of the frames will be transferred to the `VmSpace`.
- ///
- /// For more information, see [`VmMapOptions`].
- pub fn map(&self, frames: FrameVec, options: &VmMapOptions) -> Result<Vaddr> {
- if options.addr.is_none() {
- return Err(Error::InvalidArgs);
- }
-
- let addr = options.addr.unwrap();
-
- if addr % PAGE_SIZE != 0 {
- return Err(Error::InvalidArgs);
- }
-
- let size = frames.nbytes();
- let end = addr.checked_add(size).ok_or(Error::InvalidArgs)?;
-
- let va_range = addr..end;
- if !UserMode::covers(&va_range) {
- return Err(Error::InvalidArgs);
- }
-
- let mut cursor = self.pt.cursor_mut(&va_range)?;
-
- // If overwrite is forbidden, we should check if there are existing mappings
- if !options.can_overwrite {
- while let Some(qr) = cursor.next() {
- if matches!(qr, PtQr::Mapped { .. }) {
- return Err(Error::MapAlreadyMappedVaddr);
- }
- }
- cursor.jump(va_range.start);
- }
-
- let prop = PageProperty {
- flags: options.flags,
- cache: CachePolicy::Writeback,
- priv_flags: PrivilegedPageFlags::USER,
- };
-
- for frame in frames.into_iter() {
- // SAFETY: mapping in the user space with `Frame` is safe.
- unsafe {
- cursor.map(frame.into(), prop);
- }
- }
-
- drop(cursor);
- tlb_flush_addr_range(&va_range);
-
- Ok(addr)
- }
-
- /// Queries about a range of virtual memory.
- /// You will get an iterator of `VmQueryResult` which contains the information of
- /// each parts of the range.
- pub fn query_range(&self, range: &Range<Vaddr>) -> Result<VmQueryIter> {
- Ok(VmQueryIter {
- cursor: self.pt.cursor(range)?,
- })
- }
-
- /// Queries about the mapping information about a byte in virtual memory.
- /// This is more handy than [`query_range`], but less efficient if you want
- /// to query in a batch.
- ///
- /// [`query_range`]: VmSpace::query_range
- pub fn query(&self, vaddr: Vaddr) -> Result<Option<PageProperty>> {
- if !(0..MAX_USERSPACE_VADDR).contains(&vaddr) {
- return Err(Error::AccessDenied);
- }
- Ok(self.pt.query(vaddr).map(|(_pa, prop)| prop))
- }
-
- /// Unmaps the physical memory pages within the VM address range.
- ///
- /// The range is allowed to contain gaps, where no physical memory pages
- /// are mapped.
- pub fn unmap(&self, range: &Range<Vaddr>) -> Result<()> {
- if !is_page_aligned(range.start) || !is_page_aligned(range.end) {
- return Err(Error::InvalidArgs);
- }
- if !UserMode::covers(range) {
- return Err(Error::InvalidArgs);
- }
-
- // SAFETY: unmapping in the user space is safe.
- unsafe {
- self.pt.unmap(range)?;
- }
- tlb_flush_addr_range(range);
-
- Ok(())
- }
-
- /// Clears all mappings
- pub fn clear(&self) {
- // SAFETY: unmapping user space is safe, and we don't care unmapping
- // invalid ranges.
- unsafe {
- self.pt.unmap(&(0..MAX_USERSPACE_VADDR)).unwrap();
- }
- tlb_flush_all_excluding_global();
- }
-
- /// Updates the VM protection permissions within the VM address range.
- ///
- /// If any of the page in the given range is not mapped, it is skipped.
- /// The method panics when virtual address is not aligned to base page
- /// size.
- ///
- /// It is guarenteed that the operation is called once for each valid
- /// page found in the range.
- ///
- /// TODO: It returns error when invalid operations such as protect
- /// partial huge page happens, and efforts are not reverted, leaving us
- /// in a bad state.
- pub fn protect(&self, range: &Range<Vaddr>, op: impl FnMut(&mut PageProperty)) -> Result<()> {
- if !is_page_aligned(range.start) || !is_page_aligned(range.end) {
- return Err(Error::InvalidArgs);
- }
- if !UserMode::covers(range) {
- return Err(Error::InvalidArgs);
- }
-
- // SAFETY: protecting in the user space is safe.
- unsafe {
- self.pt.protect(range, op)?;
- }
- tlb_flush_addr_range(range);
-
- Ok(())
- }
-
- /// Forks a new VM space with copy-on-write semantics.
- ///
- /// Both the parent and the newly forked VM space will be marked as
- /// read-only. And both the VM space will take handles to the same
- /// physical memory pages.
- pub fn fork_copy_on_write(&self) -> Self {
- let page_fault_handler = {
- let new_handler = Once::new();
- if let Some(handler) = self.page_fault_handler.get() {
- new_handler.call_once(|| *handler);
- }
- new_handler
- };
- let new_space = Self {
- pt: self.pt.fork_copy_on_write(),
- page_fault_handler,
- };
- tlb_flush_all_excluding_global();
- new_space
- }
-
- /// Creates a reader to read data from the user space of the current task.
- ///
- /// Returns `Err` if this `VmSpace` is not belonged to the user space of the current task
- /// or the `vaddr` and `len` do not represent a user space memory range.
- pub fn reader(&self, vaddr: Vaddr, len: usize) -> Result<VmReader<'_, UserSpace>> {
- if current_page_table_paddr() != unsafe { self.pt.root_paddr() } {
- return Err(Error::AccessDenied);
- }
-
- if vaddr.checked_add(len).unwrap_or(usize::MAX) > MAX_USERSPACE_VADDR {
- return Err(Error::AccessDenied);
- }
-
- // SAFETY: As long as the current task owns user space, the page table of
- // the current task will be activated during the execution of the current task.
- // Since `VmReader` is neither `Sync` nor `Send`, it will not live longer than
- // the current task. Hence, it is ensured that the correct page table
- // is activated during the usage period of the `VmReader`.
- Ok(unsafe { VmReader::<UserSpace>::from_user_space(vaddr as *const u8, len) })
- }
-
- /// Creates a writer to write data into the user space.
- ///
- /// Returns `Err` if this `VmSpace` is not belonged to the user space of the current task
- /// or the `vaddr` and `len` do not represent a user space memory range.
- pub fn writer(&self, vaddr: Vaddr, len: usize) -> Result<VmWriter<'_, UserSpace>> {
- if current_page_table_paddr() != unsafe { self.pt.root_paddr() } {
- return Err(Error::AccessDenied);
- }
-
- if vaddr.checked_add(len).unwrap_or(usize::MAX) > MAX_USERSPACE_VADDR {
- return Err(Error::AccessDenied);
- }
-
- // SAFETY: As long as the current task owns user space, the page table of
- // the current task will be activated during the execution of the current task.
- // Since `VmWriter` is neither `Sync` nor `Send`, it will not live longer than
- // the current task. Hence, it is ensured that the correct page table
- // is activated during the usage period of the `VmWriter`.
- Ok(unsafe { VmWriter::<UserSpace>::from_user_space(vaddr as *mut u8, len) })
- }
-}
-
-impl Default for VmSpace {
- fn default() -> Self {
- Self::new()
- }
-}
-
-/// Options for mapping physical memory pages into a VM address space.
-/// See [`VmSpace::map`].
-#[derive(Clone, Debug)]
-pub struct VmMapOptions {
- /// Starting virtual address
- addr: Option<Vaddr>,
- /// Map align
- align: usize,
- /// Page permissions and status
- flags: PageFlags,
- /// Can overwrite
- can_overwrite: bool,
-}
-
-impl VmMapOptions {
- /// Creates the default options.
- pub fn new() -> Self {
- Self {
- addr: None,
- align: PagingConsts::BASE_PAGE_SIZE,
- flags: PageFlags::empty(),
- can_overwrite: false,
- }
- }
-
- /// Sets the alignment of the address of the mapping.
- ///
- /// The alignment must be a power-of-2 and greater than or equal to the
- /// page size.
- ///
- /// The default value of this option is the page size.
- pub fn align(&mut self, align: usize) -> &mut Self {
- self.align = align;
- self
- }
-
- /// Sets the permissions of the mapping, which affects whether
- /// the mapping can be read, written, or executed.
- ///
- /// The default value of this option is read-only.
- pub fn flags(&mut self, flags: PageFlags) -> &mut Self {
- self.flags = flags;
- self
- }
-
- /// Sets the address of the new mapping.
- ///
- /// The default value of this option is `None`.
- pub fn addr(&mut self, addr: Option<Vaddr>) -> &mut Self {
- if addr.is_none() {
- return self;
- }
- self.addr = Some(addr.unwrap());
- self
- }
-
- /// Sets whether the mapping can overwrite any existing mappings.
- ///
- /// If this option is `true`, then the address option must be `Some(_)`.
- ///
- /// The default value of this option is `false`.
- pub fn can_overwrite(&mut self, can_overwrite: bool) -> &mut Self {
- self.can_overwrite = can_overwrite;
- self
- }
-}
-
-impl Default for VmMapOptions {
- fn default() -> Self {
- Self::new()
- }
-}
-
-/// The iterator for querying over the VM space without modifying it.
-pub struct VmQueryIter<'a> {
- cursor: Cursor<'a, UserMode, PageTableEntry, PagingConsts>,
-}
-
-pub enum VmQueryResult {
- NotMapped {
- va: Vaddr,
- len: usize,
- },
- Mapped {
- va: Vaddr,
- frame: Frame,
- prop: PageProperty,
- },
-}
-
-impl Iterator for VmQueryIter<'_> {
- type Item = VmQueryResult;
-
- fn next(&mut self) -> Option<Self::Item> {
- self.cursor.next().map(|ptqr| match ptqr {
- PtQr::NotMapped { va, len } => VmQueryResult::NotMapped { va, len },
- PtQr::Mapped { va, page, prop } => VmQueryResult::Mapped {
- va,
- frame: page.try_into().unwrap(),
- prop,
- },
- // It is not possible to map untyped memory in user space.
- PtQr::MappedUntracked { .. } => unreachable!(),
- })
- }
-}
diff --git a/ostd/src/mm/space.rs /dev/null
--- a/ostd/src/mm/space.rs
+++ /dev/null
@@ -1,408 +0,0 @@
-// SPDX-License-Identifier: MPL-2.0
-
-use core::ops::Range;
-
-use spin::Once;
-
-use super::{
- io::UserSpace,
- is_page_aligned,
- kspace::KERNEL_PAGE_TABLE,
- page_table::{PageTable, PageTableMode, UserMode},
- CachePolicy, FrameVec, PageFlags, PageProperty, PagingConstsTrait, PrivilegedPageFlags,
- VmReader, VmWriter, PAGE_SIZE,
-};
-use crate::{
- arch::mm::{
- current_page_table_paddr, tlb_flush_addr_range, tlb_flush_all_excluding_global,
- PageTableEntry, PagingConsts,
- },
- cpu::CpuExceptionInfo,
- mm::{
- page_table::{Cursor, PageTableQueryResult as PtQr},
- Frame, MAX_USERSPACE_VADDR,
- },
- prelude::*,
- Error,
-};
-
-/// Virtual memory space.
-///
-/// A virtual memory space (`VmSpace`) can be created and assigned to a user space so that
-/// the virtual memory of the user space can be manipulated safely. For example,
-/// given an arbitrary user-space pointer, one can read and write the memory
-/// location referred to by the user-space pointer without the risk of breaking the
-/// memory safety of the kernel space.
-///
-/// A newly-created `VmSpace` is not backed by any physical memory pages.
-/// To provide memory pages for a `VmSpace`, one can allocate and map
-/// physical memory ([`Frame`]s) to the `VmSpace`.
-///
-/// A `VmSpace` can also attach a page fault handler, which will be invoked to handle
-/// page faults generated from user space.
-///
-/// A `VmSpace` can also attach a page fault handler, which will be invoked to handle
-/// page faults generated from user space.
-#[allow(clippy::type_complexity)]
-pub struct VmSpace {
- pt: PageTable<UserMode>,
- page_fault_handler: Once<fn(&VmSpace, &CpuExceptionInfo) -> core::result::Result<(), ()>>,
-}
-
-// Notes on TLB flushing:
-//
-// We currently assume that:
-// 1. `VmSpace` _might_ be activated on the current CPU and the user memory _might_ be used
-// immediately after we make changes to the page table entries. So we must invalidate the
-// corresponding TLB caches accordingly.
-// 2. `VmSpace` must _not_ be activated on another CPU. This assumption is trivial, since SMP
-// support is not yet available. But we need to consider this situation in the future (TODO).
-
-impl VmSpace {
- /// Creates a new VM address space.
- pub fn new() -> Self {
- Self {
- pt: KERNEL_PAGE_TABLE.get().unwrap().create_user_page_table(),
- page_fault_handler: Once::new(),
- }
- }
-
- /// Activates the page table.
- pub(crate) fn activate(&self) {
- self.pt.activate();
- }
-
- pub(crate) fn handle_page_fault(
- &self,
- info: &CpuExceptionInfo,
- ) -> core::result::Result<(), ()> {
- if let Some(func) = self.page_fault_handler.get() {
- return func(self, info);
- }
- Err(())
- }
-
- /// Registers the page fault handler in this `VmSpace`.
- ///
- /// The page fault handler of a `VmSpace` can only be initialized once.
- /// If it has been initialized before, calling this method will have no effect.
- pub fn register_page_fault_handler(
- &self,
- func: fn(&VmSpace, &CpuExceptionInfo) -> core::result::Result<(), ()>,
- ) {
- self.page_fault_handler.call_once(|| func);
- }
-
- /// Maps some physical memory pages into the VM space according to the given
- /// options, returning the address where the mapping is created.
- ///
- /// The ownership of the frames will be transferred to the `VmSpace`.
- ///
- /// For more information, see [`VmMapOptions`].
- pub fn map(&self, frames: FrameVec, options: &VmMapOptions) -> Result<Vaddr> {
- if options.addr.is_none() {
- return Err(Error::InvalidArgs);
- }
-
- let addr = options.addr.unwrap();
-
- if addr % PAGE_SIZE != 0 {
- return Err(Error::InvalidArgs);
- }
-
- let size = frames.nbytes();
- let end = addr.checked_add(size).ok_or(Error::InvalidArgs)?;
-
- let va_range = addr..end;
- if !UserMode::covers(&va_range) {
- return Err(Error::InvalidArgs);
- }
-
- let mut cursor = self.pt.cursor_mut(&va_range)?;
-
- // If overwrite is forbidden, we should check if there are existing mappings
- if !options.can_overwrite {
- while let Some(qr) = cursor.next() {
- if matches!(qr, PtQr::Mapped { .. }) {
- return Err(Error::MapAlreadyMappedVaddr);
- }
- }
- cursor.jump(va_range.start);
- }
-
- let prop = PageProperty {
- flags: options.flags,
- cache: CachePolicy::Writeback,
- priv_flags: PrivilegedPageFlags::USER,
- };
-
- for frame in frames.into_iter() {
- // SAFETY: mapping in the user space with `Frame` is safe.
- unsafe {
- cursor.map(frame.into(), prop);
- }
- }
-
- drop(cursor);
- tlb_flush_addr_range(&va_range);
-
- Ok(addr)
- }
-
- /// Queries about a range of virtual memory.
- /// You will get an iterator of `VmQueryResult` which contains the information of
- /// each parts of the range.
- pub fn query_range(&self, range: &Range<Vaddr>) -> Result<VmQueryIter> {
- Ok(VmQueryIter {
- cursor: self.pt.cursor(range)?,
- })
- }
-
- /// Queries about the mapping information about a byte in virtual memory.
- /// This is more handy than [`query_range`], but less efficient if you want
- /// to query in a batch.
- ///
- /// [`query_range`]: VmSpace::query_range
- pub fn query(&self, vaddr: Vaddr) -> Result<Option<PageProperty>> {
- if !(0..MAX_USERSPACE_VADDR).contains(&vaddr) {
- return Err(Error::AccessDenied);
- }
- Ok(self.pt.query(vaddr).map(|(_pa, prop)| prop))
- }
-
- /// Unmaps the physical memory pages within the VM address range.
- ///
- /// The range is allowed to contain gaps, where no physical memory pages
- /// are mapped.
- pub fn unmap(&self, range: &Range<Vaddr>) -> Result<()> {
- if !is_page_aligned(range.start) || !is_page_aligned(range.end) {
- return Err(Error::InvalidArgs);
- }
- if !UserMode::covers(range) {
- return Err(Error::InvalidArgs);
- }
-
- // SAFETY: unmapping in the user space is safe.
- unsafe {
- self.pt.unmap(range)?;
- }
- tlb_flush_addr_range(range);
-
- Ok(())
- }
-
- /// Clears all mappings
- pub fn clear(&self) {
- // SAFETY: unmapping user space is safe, and we don't care unmapping
- // invalid ranges.
- unsafe {
- self.pt.unmap(&(0..MAX_USERSPACE_VADDR)).unwrap();
- }
- tlb_flush_all_excluding_global();
- }
-
- /// Updates the VM protection permissions within the VM address range.
- ///
- /// If any of the page in the given range is not mapped, it is skipped.
- /// The method panics when virtual address is not aligned to base page
- /// size.
- ///
- /// It is guarenteed that the operation is called once for each valid
- /// page found in the range.
- ///
- /// TODO: It returns error when invalid operations such as protect
- /// partial huge page happens, and efforts are not reverted, leaving us
- /// in a bad state.
- pub fn protect(&self, range: &Range<Vaddr>, op: impl FnMut(&mut PageProperty)) -> Result<()> {
- if !is_page_aligned(range.start) || !is_page_aligned(range.end) {
- return Err(Error::InvalidArgs);
- }
- if !UserMode::covers(range) {
- return Err(Error::InvalidArgs);
- }
-
- // SAFETY: protecting in the user space is safe.
- unsafe {
- self.pt.protect(range, op)?;
- }
- tlb_flush_addr_range(range);
-
- Ok(())
- }
-
- /// Forks a new VM space with copy-on-write semantics.
- ///
- /// Both the parent and the newly forked VM space will be marked as
- /// read-only. And both the VM space will take handles to the same
- /// physical memory pages.
- pub fn fork_copy_on_write(&self) -> Self {
- let page_fault_handler = {
- let new_handler = Once::new();
- if let Some(handler) = self.page_fault_handler.get() {
- new_handler.call_once(|| *handler);
- }
- new_handler
- };
- let new_space = Self {
- pt: self.pt.fork_copy_on_write(),
- page_fault_handler,
- };
- tlb_flush_all_excluding_global();
- new_space
- }
-
- /// Creates a reader to read data from the user space of the current task.
- ///
- /// Returns `Err` if this `VmSpace` is not belonged to the user space of the current task
- /// or the `vaddr` and `len` do not represent a user space memory range.
- pub fn reader(&self, vaddr: Vaddr, len: usize) -> Result<VmReader<'_, UserSpace>> {
- if current_page_table_paddr() != unsafe { self.pt.root_paddr() } {
- return Err(Error::AccessDenied);
- }
-
- if vaddr.checked_add(len).unwrap_or(usize::MAX) > MAX_USERSPACE_VADDR {
- return Err(Error::AccessDenied);
- }
-
- // SAFETY: As long as the current task owns user space, the page table of
- // the current task will be activated during the execution of the current task.
- // Since `VmReader` is neither `Sync` nor `Send`, it will not live longer than
- // the current task. Hence, it is ensured that the correct page table
- // is activated during the usage period of the `VmReader`.
- Ok(unsafe { VmReader::<UserSpace>::from_user_space(vaddr as *const u8, len) })
- }
-
- /// Creates a writer to write data into the user space.
- ///
- /// Returns `Err` if this `VmSpace` is not belonged to the user space of the current task
- /// or the `vaddr` and `len` do not represent a user space memory range.
- pub fn writer(&self, vaddr: Vaddr, len: usize) -> Result<VmWriter<'_, UserSpace>> {
- if current_page_table_paddr() != unsafe { self.pt.root_paddr() } {
- return Err(Error::AccessDenied);
- }
-
- if vaddr.checked_add(len).unwrap_or(usize::MAX) > MAX_USERSPACE_VADDR {
- return Err(Error::AccessDenied);
- }
-
- // SAFETY: As long as the current task owns user space, the page table of
- // the current task will be activated during the execution of the current task.
- // Since `VmWriter` is neither `Sync` nor `Send`, it will not live longer than
- // the current task. Hence, it is ensured that the correct page table
- // is activated during the usage period of the `VmWriter`.
- Ok(unsafe { VmWriter::<UserSpace>::from_user_space(vaddr as *mut u8, len) })
- }
-}
-
-impl Default for VmSpace {
- fn default() -> Self {
- Self::new()
- }
-}
-
-/// Options for mapping physical memory pages into a VM address space.
-/// See [`VmSpace::map`].
-#[derive(Clone, Debug)]
-pub struct VmMapOptions {
- /// Starting virtual address
- addr: Option<Vaddr>,
- /// Map align
- align: usize,
- /// Page permissions and status
- flags: PageFlags,
- /// Can overwrite
- can_overwrite: bool,
-}
-
-impl VmMapOptions {
- /// Creates the default options.
- pub fn new() -> Self {
- Self {
- addr: None,
- align: PagingConsts::BASE_PAGE_SIZE,
- flags: PageFlags::empty(),
- can_overwrite: false,
- }
- }
-
- /// Sets the alignment of the address of the mapping.
- ///
- /// The alignment must be a power-of-2 and greater than or equal to the
- /// page size.
- ///
- /// The default value of this option is the page size.
- pub fn align(&mut self, align: usize) -> &mut Self {
- self.align = align;
- self
- }
-
- /// Sets the permissions of the mapping, which affects whether
- /// the mapping can be read, written, or executed.
- ///
- /// The default value of this option is read-only.
- pub fn flags(&mut self, flags: PageFlags) -> &mut Self {
- self.flags = flags;
- self
- }
-
- /// Sets the address of the new mapping.
- ///
- /// The default value of this option is `None`.
- pub fn addr(&mut self, addr: Option<Vaddr>) -> &mut Self {
- if addr.is_none() {
- return self;
- }
- self.addr = Some(addr.unwrap());
- self
- }
-
- /// Sets whether the mapping can overwrite any existing mappings.
- ///
- /// If this option is `true`, then the address option must be `Some(_)`.
- ///
- /// The default value of this option is `false`.
- pub fn can_overwrite(&mut self, can_overwrite: bool) -> &mut Self {
- self.can_overwrite = can_overwrite;
- self
- }
-}
-
-impl Default for VmMapOptions {
- fn default() -> Self {
- Self::new()
- }
-}
-
-/// The iterator for querying over the VM space without modifying it.
-pub struct VmQueryIter<'a> {
- cursor: Cursor<'a, UserMode, PageTableEntry, PagingConsts>,
-}
-
-pub enum VmQueryResult {
- NotMapped {
- va: Vaddr,
- len: usize,
- },
- Mapped {
- va: Vaddr,
- frame: Frame,
- prop: PageProperty,
- },
-}
-
-impl Iterator for VmQueryIter<'_> {
- type Item = VmQueryResult;
-
- fn next(&mut self) -> Option<Self::Item> {
- self.cursor.next().map(|ptqr| match ptqr {
- PtQr::NotMapped { va, len } => VmQueryResult::NotMapped { va, len },
- PtQr::Mapped { va, page, prop } => VmQueryResult::Mapped {
- va,
- frame: page.try_into().unwrap(),
- prop,
- },
- // It is not possible to map untyped memory in user space.
- PtQr::MappedUntracked { .. } => unreachable!(),
- })
- }
-}
diff --git /dev/null b/ostd/src/mm/vm_space.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/mm/vm_space.rs
@@ -0,0 +1,373 @@
+// SPDX-License-Identifier: MPL-2.0
+
+//! Virtual memory space management.
+//!
+//! The [`VmSpace`] struct is provided to manage the virtual memory space of a
+//! user. Cursors are used to traverse and modify over the virtual memory space
+//! concurrently. The VM space cursor [`self::Cursor`] is just a wrapper over
+//! the page table cursor [`super::page_table::Cursor`], providing efficient,
+//! powerful concurrent accesses to the page table, and suffers from the same
+//! validity concerns as described in [`super::page_table::cursor`].
+
+use core::ops::Range;
+
+use spin::Once;
+
+use super::{
+ io::UserSpace,
+ kspace::KERNEL_PAGE_TABLE,
+ page_table::{PageTable, UserMode},
+ PageProperty, VmReader, VmWriter,
+};
+use crate::{
+ arch::mm::{
+ current_page_table_paddr, tlb_flush_addr_range, tlb_flush_all_excluding_global,
+ PageTableEntry, PagingConsts,
+ },
+ cpu::CpuExceptionInfo,
+ mm::{
+ page_table::{self, PageTableQueryResult as PtQr},
+ Frame, MAX_USERSPACE_VADDR,
+ },
+ prelude::*,
+ Error,
+};
+
+/// Virtual memory space.
+///
+/// A virtual memory space (`VmSpace`) can be created and assigned to a user
+/// space so that the virtual memory of the user space can be manipulated
+/// safely. For example, given an arbitrary user-space pointer, one can read
+/// and write the memory location referred to by the user-space pointer without
+/// the risk of breaking the memory safety of the kernel space.
+///
+/// A newly-created `VmSpace` is not backed by any physical memory pages. To
+/// provide memory pages for a `VmSpace`, one can allocate and map physical
+/// memory ([`Frame`]s) to the `VmSpace` using the cursor.
+///
+/// A `VmSpace` can also attach a page fault handler, which will be invoked to
+/// handle page faults generated from user space.
+#[allow(clippy::type_complexity)]
+pub struct VmSpace {
+ pt: PageTable<UserMode>,
+ page_fault_handler: Once<fn(&VmSpace, &CpuExceptionInfo) -> core::result::Result<(), ()>>,
+}
+
+// Notes on TLB flushing:
+//
+// We currently assume that:
+// 1. `VmSpace` _might_ be activated on the current CPU and the user memory _might_ be used
+// immediately after we make changes to the page table entries. So we must invalidate the
+// corresponding TLB caches accordingly.
+// 2. `VmSpace` must _not_ be activated on another CPU. This assumption is trivial, since SMP
+// support is not yet available. But we need to consider this situation in the future (TODO).
+impl VmSpace {
+ /// Creates a new VM address space.
+ pub fn new() -> Self {
+ Self {
+ pt: KERNEL_PAGE_TABLE.get().unwrap().create_user_page_table(),
+ page_fault_handler: Once::new(),
+ }
+ }
+
+ /// Gets an immutable cursor in the virtual address range.
+ ///
+ /// The cursor behaves like a lock guard, exclusively owning a sub-tree of
+ /// the page table, preventing others from creating a cursor in it. So be
+ /// sure to drop the cursor as soon as possible.
+ ///
+ /// The creation of the cursor may block if another cursor having an
+ /// overlapping range is alive.
+ pub fn cursor(&self, va: &Range<Vaddr>) -> Result<Cursor<'_>> {
+ Ok(self.pt.cursor(va).map(Cursor)?)
+ }
+
+ /// Gets an mutable cursor in the virtual address range.
+ ///
+ /// The same as [`Self::cursor`], the cursor behaves like a lock guard,
+ /// exclusively owning a sub-tree of the page table, preventing others
+ /// from creating a cursor in it. So be sure to drop the cursor as soon as
+ /// possible.
+ ///
+ /// The creation of the cursor may block if another cursor having an
+ /// overlapping range is alive. The modification to the mapping by the
+ /// cursor may also block or be overriden the mapping of another cursor.
+ pub fn cursor_mut(&self, va: &Range<Vaddr>) -> Result<CursorMut<'_>> {
+ Ok(self.pt.cursor_mut(va).map(CursorMut)?)
+ }
+
+ /// Activates the page table.
+ pub(crate) fn activate(&self) {
+ self.pt.activate();
+ }
+
+ pub(crate) fn handle_page_fault(
+ &self,
+ info: &CpuExceptionInfo,
+ ) -> core::result::Result<(), ()> {
+ if let Some(func) = self.page_fault_handler.get() {
+ return func(self, info);
+ }
+ Err(())
+ }
+
+ /// Registers the page fault handler in this `VmSpace`.
+ ///
+ /// The page fault handler of a `VmSpace` can only be initialized once.
+ /// If it has been initialized before, calling this method will have no effect.
+ pub fn register_page_fault_handler(
+ &self,
+ func: fn(&VmSpace, &CpuExceptionInfo) -> core::result::Result<(), ()>,
+ ) {
+ self.page_fault_handler.call_once(|| func);
+ }
+
+ /// Clears all mappings
+ pub fn clear(&self) {
+ // SAFETY: unmapping user space is safe, and we don't care unmapping
+ // invalid ranges.
+ unsafe {
+ self.pt.unmap(&(0..MAX_USERSPACE_VADDR)).unwrap();
+ }
+ tlb_flush_all_excluding_global();
+ }
+
+ /// Forks a new VM space with copy-on-write semantics.
+ ///
+ /// Both the parent and the newly forked VM space will be marked as
+ /// read-only. And both the VM space will take handles to the same
+ /// physical memory pages.
+ pub fn fork_copy_on_write(&self) -> Self {
+ let page_fault_handler = {
+ let new_handler = Once::new();
+ if let Some(handler) = self.page_fault_handler.get() {
+ new_handler.call_once(|| *handler);
+ }
+ new_handler
+ };
+ let new_space = Self {
+ pt: self.pt.fork_copy_on_write(),
+ page_fault_handler,
+ };
+ tlb_flush_all_excluding_global();
+ new_space
+ }
+
+ /// Creates a reader to read data from the user space of the current task.
+ ///
+ /// Returns `Err` if this `VmSpace` is not belonged to the user space of the current task
+ /// or the `vaddr` and `len` do not represent a user space memory range.
+ pub fn reader(&self, vaddr: Vaddr, len: usize) -> Result<VmReader<'_, UserSpace>> {
+ if current_page_table_paddr() != unsafe { self.pt.root_paddr() } {
+ return Err(Error::AccessDenied);
+ }
+
+ if vaddr.checked_add(len).unwrap_or(usize::MAX) > MAX_USERSPACE_VADDR {
+ return Err(Error::AccessDenied);
+ }
+
+ // SAFETY: As long as the current task owns user space, the page table of
+ // the current task will be activated during the execution of the current task.
+ // Since `VmReader` is neither `Sync` nor `Send`, it will not live longer than
+ // the current task. Hence, it is ensured that the correct page table
+ // is activated during the usage period of the `VmReader`.
+ Ok(unsafe { VmReader::<UserSpace>::from_user_space(vaddr as *const u8, len) })
+ }
+
+ /// Creates a writer to write data into the user space.
+ ///
+ /// Returns `Err` if this `VmSpace` is not belonged to the user space of the current task
+ /// or the `vaddr` and `len` do not represent a user space memory range.
+ pub fn writer(&self, vaddr: Vaddr, len: usize) -> Result<VmWriter<'_, UserSpace>> {
+ if current_page_table_paddr() != unsafe { self.pt.root_paddr() } {
+ return Err(Error::AccessDenied);
+ }
+
+ if vaddr.checked_add(len).unwrap_or(usize::MAX) > MAX_USERSPACE_VADDR {
+ return Err(Error::AccessDenied);
+ }
+
+ // SAFETY: As long as the current task owns user space, the page table of
+ // the current task will be activated during the execution of the current task.
+ // Since `VmWriter` is neither `Sync` nor `Send`, it will not live longer than
+ // the current task. Hence, it is ensured that the correct page table
+ // is activated during the usage period of the `VmWriter`.
+ Ok(unsafe { VmWriter::<UserSpace>::from_user_space(vaddr as *mut u8, len) })
+ }
+}
+
+impl Default for VmSpace {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// The cursor for querying over the VM space without modifying it.
+///
+/// It exclusively owns a sub-tree of the page table, preventing others from
+/// reading or modifying the same sub-tree. Two read-only cursors can not be
+/// created from the same virtual address range either.
+pub struct Cursor<'a>(page_table::Cursor<'a, UserMode, PageTableEntry, PagingConsts>);
+
+impl Iterator for Cursor<'_> {
+ type Item = VmQueryResult;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ let result = self.query();
+ if result.is_ok() {
+ self.0.move_forward();
+ }
+ result.ok()
+ }
+}
+
+impl Cursor<'_> {
+ /// Query about the current slot.
+ ///
+ /// This function won't bring the cursor to the next slot.
+ pub fn query(&mut self) -> Result<VmQueryResult> {
+ Ok(self.0.query().map(|ptqr| ptqr.try_into().unwrap())?)
+ }
+
+ /// Jump to the virtual address.
+ pub fn jump(&mut self, va: Vaddr) {
+ self.0.jump(va);
+ }
+
+ /// Get the virtual address of the current slot.
+ pub fn virt_addr(&self) -> Vaddr {
+ self.0.virt_addr()
+ }
+}
+
+/// The cursor for modifying the mappings in VM space.
+///
+/// It exclusively owns a sub-tree of the page table, preventing others from
+/// reading or modifying the same sub-tree.
+pub struct CursorMut<'a>(page_table::CursorMut<'a, UserMode, PageTableEntry, PagingConsts>);
+
+impl CursorMut<'_> {
+ /// Query about the current slot.
+ ///
+ /// This is the same as [`Cursor::query`].
+ ///
+ /// This function won't bring the cursor to the next slot.
+ pub fn query(&mut self) -> Result<VmQueryResult> {
+ Ok(self.0.query().map(|ptqr| ptqr.try_into().unwrap())?)
+ }
+
+ /// Jump to the virtual address.
+ ///
+ /// This is the same as [`Cursor::jump`].
+ pub fn jump(&mut self, va: Vaddr) {
+ self.0.jump(va);
+ }
+
+ /// Get the virtual address of the current slot.
+ pub fn virt_addr(&self) -> Vaddr {
+ self.0.virt_addr()
+ }
+
+ /// Map a frame into the current slot.
+ ///
+ /// This method will bring the cursor to the next slot after the modification.
+ pub fn map(&mut self, frame: Frame, prop: PageProperty) {
+ let start_va = self.virt_addr();
+ let end_va = start_va + frame.size();
+
+ // SAFETY: It is safe to map untyped memory into the userspace.
+ unsafe {
+ self.0.map(frame.into(), prop);
+ }
+
+ tlb_flush_addr_range(&(start_va..end_va));
+ }
+
+ /// Clear the mapping starting from the current slot.
+ ///
+ /// This method will bring the cursor forward by `len` bytes in the virtual
+ /// address space after the modification.
+ ///
+ /// # Panics
+ ///
+ /// This method will panic if `len` is not page-aligned.
+ pub fn unmap(&mut self, len: usize) {
+ assert!(len % super::PAGE_SIZE == 0);
+ let start_va = self.virt_addr();
+ let end_va = start_va + len;
+
+ // SAFETY: It is safe to un-map memory in the userspace.
+ unsafe {
+ self.0.unmap(len);
+ }
+
+ tlb_flush_addr_range(&(start_va..end_va));
+ }
+
+ /// Change the mapping property starting from the current slot.
+ ///
+ /// This method will bring the cursor forward by `len` bytes in the virtual
+ /// address space after the modification.
+ ///
+ /// The way to change the property is specified by the closure `op`.
+ ///
+ /// # Panics
+ ///
+ /// This method will panic if `len` is not page-aligned.
+ pub fn protect(
+ &mut self,
+ len: usize,
+ op: impl FnMut(&mut PageProperty),
+ allow_protect_absent: bool,
+ ) -> Result<()> {
+ assert!(len % super::PAGE_SIZE == 0);
+ let start_va = self.virt_addr();
+ let end_va = start_va + len;
+
+ // SAFETY: It is safe to protect memory in the userspace.
+ let result = unsafe { self.0.protect(len, op, allow_protect_absent) };
+
+ tlb_flush_addr_range(&(start_va..end_va));
+
+ Ok(result?)
+ }
+}
+
+/// The result of a query over the VM space.
+#[derive(Debug)]
+pub enum VmQueryResult {
+ /// The current slot is not mapped.
+ NotMapped {
+ /// The virtual address of the slot.
+ va: Vaddr,
+ /// The length of the slot.
+ len: usize,
+ },
+ /// The current slot is mapped.
+ Mapped {
+ /// The virtual address of the slot.
+ va: Vaddr,
+ /// The mapped frame.
+ frame: Frame,
+ /// The property of the slot.
+ prop: PageProperty,
+ },
+}
+
+impl TryFrom<PtQr> for VmQueryResult {
+ type Error = &'static str;
+
+ fn try_from(ptqr: PtQr) -> core::result::Result<Self, Self::Error> {
+ match ptqr {
+ PtQr::NotMapped { va, len } => Ok(VmQueryResult::NotMapped { va, len }),
+ PtQr::Mapped { va, page, prop } => Ok(VmQueryResult::Mapped {
+ va,
+ frame: page
+ .try_into()
+ .map_err(|_| "found typed memory mapped into `VmSpace`")?,
+ prop,
+ }),
+ PtQr::MappedUntracked { .. } => Err("found untracked memory mapped into `VmSpace`"),
+ }
+ }
+}
diff --git /dev/null b/ostd/src/mm/vm_space.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/mm/vm_space.rs
@@ -0,0 +1,373 @@
+// SPDX-License-Identifier: MPL-2.0
+
+//! Virtual memory space management.
+//!
+//! The [`VmSpace`] struct is provided to manage the virtual memory space of a
+//! user. Cursors are used to traverse and modify over the virtual memory space
+//! concurrently. The VM space cursor [`self::Cursor`] is just a wrapper over
+//! the page table cursor [`super::page_table::Cursor`], providing efficient,
+//! powerful concurrent accesses to the page table, and suffers from the same
+//! validity concerns as described in [`super::page_table::cursor`].
+
+use core::ops::Range;
+
+use spin::Once;
+
+use super::{
+ io::UserSpace,
+ kspace::KERNEL_PAGE_TABLE,
+ page_table::{PageTable, UserMode},
+ PageProperty, VmReader, VmWriter,
+};
+use crate::{
+ arch::mm::{
+ current_page_table_paddr, tlb_flush_addr_range, tlb_flush_all_excluding_global,
+ PageTableEntry, PagingConsts,
+ },
+ cpu::CpuExceptionInfo,
+ mm::{
+ page_table::{self, PageTableQueryResult as PtQr},
+ Frame, MAX_USERSPACE_VADDR,
+ },
+ prelude::*,
+ Error,
+};
+
+/// Virtual memory space.
+///
+/// A virtual memory space (`VmSpace`) can be created and assigned to a user
+/// space so that the virtual memory of the user space can be manipulated
+/// safely. For example, given an arbitrary user-space pointer, one can read
+/// and write the memory location referred to by the user-space pointer without
+/// the risk of breaking the memory safety of the kernel space.
+///
+/// A newly-created `VmSpace` is not backed by any physical memory pages. To
+/// provide memory pages for a `VmSpace`, one can allocate and map physical
+/// memory ([`Frame`]s) to the `VmSpace` using the cursor.
+///
+/// A `VmSpace` can also attach a page fault handler, which will be invoked to
+/// handle page faults generated from user space.
+#[allow(clippy::type_complexity)]
+pub struct VmSpace {
+ pt: PageTable<UserMode>,
+ page_fault_handler: Once<fn(&VmSpace, &CpuExceptionInfo) -> core::result::Result<(), ()>>,
+}
+
+// Notes on TLB flushing:
+//
+// We currently assume that:
+// 1. `VmSpace` _might_ be activated on the current CPU and the user memory _might_ be used
+// immediately after we make changes to the page table entries. So we must invalidate the
+// corresponding TLB caches accordingly.
+// 2. `VmSpace` must _not_ be activated on another CPU. This assumption is trivial, since SMP
+// support is not yet available. But we need to consider this situation in the future (TODO).
+impl VmSpace {
+ /// Creates a new VM address space.
+ pub fn new() -> Self {
+ Self {
+ pt: KERNEL_PAGE_TABLE.get().unwrap().create_user_page_table(),
+ page_fault_handler: Once::new(),
+ }
+ }
+
+ /// Gets an immutable cursor in the virtual address range.
+ ///
+ /// The cursor behaves like a lock guard, exclusively owning a sub-tree of
+ /// the page table, preventing others from creating a cursor in it. So be
+ /// sure to drop the cursor as soon as possible.
+ ///
+ /// The creation of the cursor may block if another cursor having an
+ /// overlapping range is alive.
+ pub fn cursor(&self, va: &Range<Vaddr>) -> Result<Cursor<'_>> {
+ Ok(self.pt.cursor(va).map(Cursor)?)
+ }
+
+ /// Gets an mutable cursor in the virtual address range.
+ ///
+ /// The same as [`Self::cursor`], the cursor behaves like a lock guard,
+ /// exclusively owning a sub-tree of the page table, preventing others
+ /// from creating a cursor in it. So be sure to drop the cursor as soon as
+ /// possible.
+ ///
+ /// The creation of the cursor may block if another cursor having an
+ /// overlapping range is alive. The modification to the mapping by the
+ /// cursor may also block or be overriden the mapping of another cursor.
+ pub fn cursor_mut(&self, va: &Range<Vaddr>) -> Result<CursorMut<'_>> {
+ Ok(self.pt.cursor_mut(va).map(CursorMut)?)
+ }
+
+ /// Activates the page table.
+ pub(crate) fn activate(&self) {
+ self.pt.activate();
+ }
+
+ pub(crate) fn handle_page_fault(
+ &self,
+ info: &CpuExceptionInfo,
+ ) -> core::result::Result<(), ()> {
+ if let Some(func) = self.page_fault_handler.get() {
+ return func(self, info);
+ }
+ Err(())
+ }
+
+ /// Registers the page fault handler in this `VmSpace`.
+ ///
+ /// The page fault handler of a `VmSpace` can only be initialized once.
+ /// If it has been initialized before, calling this method will have no effect.
+ pub fn register_page_fault_handler(
+ &self,
+ func: fn(&VmSpace, &CpuExceptionInfo) -> core::result::Result<(), ()>,
+ ) {
+ self.page_fault_handler.call_once(|| func);
+ }
+
+ /// Clears all mappings
+ pub fn clear(&self) {
+ // SAFETY: unmapping user space is safe, and we don't care unmapping
+ // invalid ranges.
+ unsafe {
+ self.pt.unmap(&(0..MAX_USERSPACE_VADDR)).unwrap();
+ }
+ tlb_flush_all_excluding_global();
+ }
+
+ /// Forks a new VM space with copy-on-write semantics.
+ ///
+ /// Both the parent and the newly forked VM space will be marked as
+ /// read-only. And both the VM space will take handles to the same
+ /// physical memory pages.
+ pub fn fork_copy_on_write(&self) -> Self {
+ let page_fault_handler = {
+ let new_handler = Once::new();
+ if let Some(handler) = self.page_fault_handler.get() {
+ new_handler.call_once(|| *handler);
+ }
+ new_handler
+ };
+ let new_space = Self {
+ pt: self.pt.fork_copy_on_write(),
+ page_fault_handler,
+ };
+ tlb_flush_all_excluding_global();
+ new_space
+ }
+
+ /// Creates a reader to read data from the user space of the current task.
+ ///
+ /// Returns `Err` if this `VmSpace` is not belonged to the user space of the current task
+ /// or the `vaddr` and `len` do not represent a user space memory range.
+ pub fn reader(&self, vaddr: Vaddr, len: usize) -> Result<VmReader<'_, UserSpace>> {
+ if current_page_table_paddr() != unsafe { self.pt.root_paddr() } {
+ return Err(Error::AccessDenied);
+ }
+
+ if vaddr.checked_add(len).unwrap_or(usize::MAX) > MAX_USERSPACE_VADDR {
+ return Err(Error::AccessDenied);
+ }
+
+ // SAFETY: As long as the current task owns user space, the page table of
+ // the current task will be activated during the execution of the current task.
+ // Since `VmReader` is neither `Sync` nor `Send`, it will not live longer than
+ // the current task. Hence, it is ensured that the correct page table
+ // is activated during the usage period of the `VmReader`.
+ Ok(unsafe { VmReader::<UserSpace>::from_user_space(vaddr as *const u8, len) })
+ }
+
+ /// Creates a writer to write data into the user space.
+ ///
+ /// Returns `Err` if this `VmSpace` is not belonged to the user space of the current task
+ /// or the `vaddr` and `len` do not represent a user space memory range.
+ pub fn writer(&self, vaddr: Vaddr, len: usize) -> Result<VmWriter<'_, UserSpace>> {
+ if current_page_table_paddr() != unsafe { self.pt.root_paddr() } {
+ return Err(Error::AccessDenied);
+ }
+
+ if vaddr.checked_add(len).unwrap_or(usize::MAX) > MAX_USERSPACE_VADDR {
+ return Err(Error::AccessDenied);
+ }
+
+ // SAFETY: As long as the current task owns user space, the page table of
+ // the current task will be activated during the execution of the current task.
+ // Since `VmWriter` is neither `Sync` nor `Send`, it will not live longer than
+ // the current task. Hence, it is ensured that the correct page table
+ // is activated during the usage period of the `VmWriter`.
+ Ok(unsafe { VmWriter::<UserSpace>::from_user_space(vaddr as *mut u8, len) })
+ }
+}
+
+impl Default for VmSpace {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// The cursor for querying over the VM space without modifying it.
+///
+/// It exclusively owns a sub-tree of the page table, preventing others from
+/// reading or modifying the same sub-tree. Two read-only cursors can not be
+/// created from the same virtual address range either.
+pub struct Cursor<'a>(page_table::Cursor<'a, UserMode, PageTableEntry, PagingConsts>);
+
+impl Iterator for Cursor<'_> {
+ type Item = VmQueryResult;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ let result = self.query();
+ if result.is_ok() {
+ self.0.move_forward();
+ }
+ result.ok()
+ }
+}
+
+impl Cursor<'_> {
+ /// Query about the current slot.
+ ///
+ /// This function won't bring the cursor to the next slot.
+ pub fn query(&mut self) -> Result<VmQueryResult> {
+ Ok(self.0.query().map(|ptqr| ptqr.try_into().unwrap())?)
+ }
+
+ /// Jump to the virtual address.
+ pub fn jump(&mut self, va: Vaddr) {
+ self.0.jump(va);
+ }
+
+ /// Get the virtual address of the current slot.
+ pub fn virt_addr(&self) -> Vaddr {
+ self.0.virt_addr()
+ }
+}
+
+/// The cursor for modifying the mappings in VM space.
+///
+/// It exclusively owns a sub-tree of the page table, preventing others from
+/// reading or modifying the same sub-tree.
+pub struct CursorMut<'a>(page_table::CursorMut<'a, UserMode, PageTableEntry, PagingConsts>);
+
+impl CursorMut<'_> {
+ /// Query about the current slot.
+ ///
+ /// This is the same as [`Cursor::query`].
+ ///
+ /// This function won't bring the cursor to the next slot.
+ pub fn query(&mut self) -> Result<VmQueryResult> {
+ Ok(self.0.query().map(|ptqr| ptqr.try_into().unwrap())?)
+ }
+
+ /// Jump to the virtual address.
+ ///
+ /// This is the same as [`Cursor::jump`].
+ pub fn jump(&mut self, va: Vaddr) {
+ self.0.jump(va);
+ }
+
+ /// Get the virtual address of the current slot.
+ pub fn virt_addr(&self) -> Vaddr {
+ self.0.virt_addr()
+ }
+
+ /// Map a frame into the current slot.
+ ///
+ /// This method will bring the cursor to the next slot after the modification.
+ pub fn map(&mut self, frame: Frame, prop: PageProperty) {
+ let start_va = self.virt_addr();
+ let end_va = start_va + frame.size();
+
+ // SAFETY: It is safe to map untyped memory into the userspace.
+ unsafe {
+ self.0.map(frame.into(), prop);
+ }
+
+ tlb_flush_addr_range(&(start_va..end_va));
+ }
+
+ /// Clear the mapping starting from the current slot.
+ ///
+ /// This method will bring the cursor forward by `len` bytes in the virtual
+ /// address space after the modification.
+ ///
+ /// # Panics
+ ///
+ /// This method will panic if `len` is not page-aligned.
+ pub fn unmap(&mut self, len: usize) {
+ assert!(len % super::PAGE_SIZE == 0);
+ let start_va = self.virt_addr();
+ let end_va = start_va + len;
+
+ // SAFETY: It is safe to un-map memory in the userspace.
+ unsafe {
+ self.0.unmap(len);
+ }
+
+ tlb_flush_addr_range(&(start_va..end_va));
+ }
+
+ /// Change the mapping property starting from the current slot.
+ ///
+ /// This method will bring the cursor forward by `len` bytes in the virtual
+ /// address space after the modification.
+ ///
+ /// The way to change the property is specified by the closure `op`.
+ ///
+ /// # Panics
+ ///
+ /// This method will panic if `len` is not page-aligned.
+ pub fn protect(
+ &mut self,
+ len: usize,
+ op: impl FnMut(&mut PageProperty),
+ allow_protect_absent: bool,
+ ) -> Result<()> {
+ assert!(len % super::PAGE_SIZE == 0);
+ let start_va = self.virt_addr();
+ let end_va = start_va + len;
+
+ // SAFETY: It is safe to protect memory in the userspace.
+ let result = unsafe { self.0.protect(len, op, allow_protect_absent) };
+
+ tlb_flush_addr_range(&(start_va..end_va));
+
+ Ok(result?)
+ }
+}
+
+/// The result of a query over the VM space.
+#[derive(Debug)]
+pub enum VmQueryResult {
+ /// The current slot is not mapped.
+ NotMapped {
+ /// The virtual address of the slot.
+ va: Vaddr,
+ /// The length of the slot.
+ len: usize,
+ },
+ /// The current slot is mapped.
+ Mapped {
+ /// The virtual address of the slot.
+ va: Vaddr,
+ /// The mapped frame.
+ frame: Frame,
+ /// The property of the slot.
+ prop: PageProperty,
+ },
+}
+
+impl TryFrom<PtQr> for VmQueryResult {
+ type Error = &'static str;
+
+ fn try_from(ptqr: PtQr) -> core::result::Result<Self, Self::Error> {
+ match ptqr {
+ PtQr::NotMapped { va, len } => Ok(VmQueryResult::NotMapped { va, len }),
+ PtQr::Mapped { va, page, prop } => Ok(VmQueryResult::Mapped {
+ va,
+ frame: page
+ .try_into()
+ .map_err(|_| "found typed memory mapped into `VmSpace`")?,
+ prop,
+ }),
+ PtQr::MappedUntracked { .. } => Err("found untracked memory mapped into `VmSpace`"),
+ }
+ }
+}
diff --git a/tools/format_all.sh b/tools/format_all.sh
--- a/tools/format_all.sh
+++ b/tools/format_all.sh
@@ -29,6 +29,14 @@ else
cargo fmt
fi
+# Format the 100-line kernel demo as well
+KERNEL_DEMO_FILE="$WORKSPACE_ROOT/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs"
+if [ "$CHECK_MODE" = true ]; then
+ cargo fmt --check -- $KERNEL_DEMO_FILE
+else
+ cargo fmt -- $KERNEL_DEMO_FILE
+fi
+
for CRATE in $EXCLUDED_CRATES; do
CRATE_DIR="$WORKSPACE_ROOT/$CRATE"
|
2024-07-04T11:40:07Z
|
562e64437584279783f244edba10b512beddc81d
|
|
asterinas/asterinas
|
diff --git a/.github/workflows/publish_api_docs.yml /dev/null
--- a/.github/workflows/publish_api_docs.yml
+++ /dev/null
@@ -1,43 +0,0 @@
-name: Update API docs
-
-on:
- # Scheduled events for nightly API docs
- schedule:
- # UTC 00:00 everyday
- - cron: "0 0 * * *"
- # Events for API docs of new release
- push:
- branches:
- - main
- paths:
- - VERSION
-
-jobs:
- build_and_upload:
- runs-on: ubuntu-latest
- timeout-minutes: 15
- container: asterinas/asterinas:0.6.2
-
- steps:
- - uses: actions/checkout@v2
- with:
- repository: 'asterinas/asterinas'
- path: 'asterinas'
-
- - name: Build & Upload Nightly API Docs
- if: github.event_name == 'schedule'
- env:
- API_DOCS_NIGHTLY_PUBLISH_KEY: ${{ secrets.API_DOCS_NIGHTLY_PUBLISH_KEY }}
- run: |
- KEY_FILE=./api_docs_nightly_publish_key
- echo "$API_DOCS_NIGHTLY_PUBLISH_KEY\n" > ${KEY_FILE}
- bash asterinas/tools/github_workflows/build_and_upload_api_docs.sh nightly ${KEY_FILE}
-
- - name: Build & Upload Release API Docs
- if: github.event_name == 'push'
- env:
- API_DOCS_PUBLISH_KEY: ${{ secrets.API_DOCS_PUBLISH_KEY }}
- run: |
- KEY_FILE=./api_docs_publish_key
- echo "$API_DOCS_PUBLISH_KEY\n" > ${KEY_FILE}
- bash asterinas/tools/github_workflows/build_and_upload_api_docs.sh release ${KEY_FILE}
diff --git a/.github/workflows/publish_osdk.yml /dev/null
--- a/.github/workflows/publish_osdk.yml
+++ /dev/null
@@ -1,36 +0,0 @@
-name: Publish OSDK
-
-on:
- pull_request:
- paths:
- - VERSION
- - osdk/Cargo.toml
- push:
- branches:
- - main
- paths:
- - VERSION
-
-jobs:
- osdk-publish:
- runs-on: ubuntu-latest
- timeout-minutes: 10
- container: asterinas/asterinas:0.6.2
- steps:
- - uses: actions/checkout@v4
-
- - name: Check Publish
- # On pull request, set `--dry-run` to check whether OSDK can publish
- if: github.event_name == 'pull_request'
- run: |
- cd osdk
- cargo publish --dry-run
-
- - name: Publish
- # On push, OSDK will be published
- if: github.event_name == 'push'
- env:
- REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
- run: |
- cd osdk
- cargo publish --token ${REGISTRY_TOKEN}
diff --git /dev/null b/.github/workflows/publish_osdk_and_ostd.yml
new file mode 100644
--- /dev/null
+++ b/.github/workflows/publish_osdk_and_ostd.yml
@@ -0,0 +1,69 @@
+name: Publish OSDK and OSTD
+
+on:
+ pull_request:
+ paths:
+ - VERSION
+ - ostd/**
+ - osdk/**
+ push:
+ branches:
+ - main
+ paths:
+ - VERSION
+
+jobs:
+ osdk-publish:
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ container: asterinas/asterinas:0.6.2
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Check Publish OSDK
+ # On pull request, set `--dry-run` to check whether OSDK can publish
+ if: github.event_name == 'pull_request'
+ run: |
+ cd osdk
+ cargo publish --dry-run
+
+ - name: Publish OSDK
+ # On push, OSDK will be published
+ if: github.event_name == 'push'
+ env:
+ REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
+ run: |
+ cd osdk
+ cargo publish --token ${REGISTRY_TOKEN}
+
+ ostd-publish:
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ container: asterinas/asterinas:0.6.2
+ strategy:
+ matrix:
+ # All supported targets, this array should keep consistent with
+ # `package.metadata.docs.rs.targets` in `ostd/Cargo.toml`
+ target: ['x86_64-unknown-none']
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Check Publish OSTD
+ # On pull request, set `--dry-run` to check whether OSDK can publish
+ if: github.event_name == 'pull_request'
+ run: |
+ cd ostd
+ cargo publish --target ${{ matrix.target }} --dry-run
+ cargo doc --target ${{ matrix.target }}
+
+ - name: Publish OSTD
+ if: github.event_name == 'push'
+ env:
+ REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
+ # Using any target that OSTD supports for publishing is ok.
+ # Here we use the same target as
+ # `package.metadata.docs.rs.default-target` in `ostd/Cargo.toml`.
+ run: |
+ cd ostd
+ cargo publish --target x86_64-unknown-none --token ${REGISTRY_TOKEN}
+
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -795,13 +790,6 @@ checksum = "078e285eafdfb6c4b434e0d31e8cfcb5115b651496faca5749b88fafd4f23bfd"
name = "keyable-arc"
version = "0.1.0"
-[[package]]
-name = "ktest"
-version = "0.1.0"
-dependencies = [
- "owo-colors",
-]
-
[[package]]
name = "lazy_static"
version = "1.4.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1094,7 +1082,6 @@ dependencies = [
"inherit-methods-macro",
"int-to-c-enum",
"intrusive-collections",
- "ktest",
"lazy_static",
"linux-boot-params",
"log",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1103,8 +1090,9 @@ dependencies = [
"num-derive",
"num-traits",
"ostd-macros",
+ "ostd-pod",
+ "ostd-test",
"owo-colors",
- "pod",
"rsdp",
"spin 0.9.8",
"static_assertions",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1127,6 +1115,31 @@ dependencies = [
"syn 2.0.49",
]
+[[package]]
+name = "ostd-pod"
+version = "0.1.1"
+source = "git+https://github.com/asterinas/ostd-pod?rev=c4644be#c4644be401cae1e046a810574078b64e35924f5f"
+dependencies = [
+ "ostd-pod-derive",
+]
+
+[[package]]
+name = "ostd-pod-derive"
+version = "0.1.1"
+source = "git+https://github.com/asterinas/ostd-pod?rev=c4644be#c4644be401cae1e046a810574078b64e35924f5f"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "ostd-test"
+version = "0.1.0"
+dependencies = [
+ "owo-colors",
+]
+
[[package]]
name = "owo-colors"
version = "3.5.0"
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -8,7 +8,7 @@ members = [
"ostd/libs/linux-bzimage/builder",
"ostd/libs/linux-bzimage/boot-params",
"ostd/libs/linux-bzimage/setup",
- "ostd/libs/ktest",
+ "ostd/libs/ostd-test",
"kernel",
"kernel/aster-nix",
"kernel/comps/block",
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -91,8 +91,8 @@ NON_OSDK_CRATES := \
ostd/libs/id-alloc \
ostd/libs/linux-bzimage/builder \
ostd/libs/linux-bzimage/boot-params \
- ostd/libs/ktest \
ostd/libs/ostd-macros \
+ ostd/libs/ostd-test \
kernel/libs/cpio-decoder \
kernel/libs/int-to-c-enum \
kernel/libs/int-to-c-enum/derive \
diff --git a/docs/src/ostd/README.md b/docs/src/ostd/README.md
--- a/docs/src/ostd/README.md
+++ b/docs/src/ostd/README.md
@@ -39,9 +39,7 @@ To explore how these APIs come into play,
see [the example of a 100-line kernel in safe Rust](a-100-line-kernel.md).
The OSTD APIs have been extensively documented.
-You can access the comprehensive API documentation for each release by visiting the [API docs](https://asterinas.github.io/api-docs).
-Additionally, you can refer to the latest nightly version API documentation at [API docs nightly](https://asterinas.github.io/api-docs-nightly),
-which remains in sync with the latest changes in the main branch.
+You can access the comprehensive API documentation by visiting the [docs.rs](https://docs.rs/ostd/latest/ostd).
## Four Requirements Satisfied
diff --git a/osdk/tests/util/mod.rs b/osdk/tests/util/mod.rs
--- a/osdk/tests/util/mod.rs
+++ b/osdk/tests/util/mod.rs
@@ -88,7 +88,7 @@ pub fn add_member_to_workspace(workspace: impl AsRef<Path>, new_member: &str) {
}
/// Makes crates created by `cargo ostd new` depends on ostd locally,
-/// instead of ostd from local branch.
+/// instead of ostd from remote source(git repo/crates.io).
///
/// Each crate created by `cargo ostd new` should add this patch.
pub fn depends_on_local_ostd(manifest_path: impl AsRef<Path>) {
diff --git a/ostd/Cargo.toml b/ostd/Cargo.toml
--- a/ostd/Cargo.toml
+++ b/ostd/Cargo.toml
@@ -2,41 +2,48 @@
name = "ostd"
version = "0.6.2"
edition = "2021"
+description = "Rust OS framework that facilitates the development of and innovation in OS kernels"
+license = "MPL-2.0"
+readme = "README.md"
+repository = "https://github.com/asterinas/asterinas"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+# Settings for publishing docs in docs.rs
+[package.metadata.docs.rs]
+default-target = "x86_64-unknown-none"
+targets = ["x86_64-unknown-none"]
+
[dependencies]
-align_ext = { path = "libs/align_ext" }
-ostd-macros = { path = "libs/ostd-macros" }
+align_ext = { path = "libs/align_ext", version = "0.1.0" }
+array-init = "2.0"
bit_field = "0.10.1"
+buddy_system_allocator = "0.9.0"
bitflags = "1.3"
bitvec = { version = "1.0", default-features = false, features = ["alloc"] }
-linux-boot-params = { path = "libs/linux-bzimage/boot-params" }
-buddy_system_allocator = "0.9.0"
cfg-if = "1.0"
gimli = { version = "0.28", default-features = false, features = ["read-core"] }
-inherit-methods-macro = { git = "https://github.com/asterinas/inherit-methods-macro", rev = "98f7e3e" }
-xarray = { git = "https://github.com/asterinas/xarray", rev = "72a4067" }
-int-to-c-enum = { path = "../kernel/libs/int-to-c-enum" }
-# instrusive-collections of version 0.9.6 fails to compile with current rust toolchain,
-# So we set a fixed version 0.9.5 for this crate
-intrusive-collections = { version = "=0.9.5", features = ["nightly"] }
-array-init = "2.0"
-ktest = { path = "libs/ktest" }
-id-alloc = { path = "libs/id-alloc" }
+id-alloc = { path = "libs/id-alloc", version = "0.1.0" }
+inherit-methods-macro = { git = "https://github.com/asterinas/inherit-methods-macro", rev = "98f7e3e", version = "0.1.0" }
+int-to-c-enum = { path = "../kernel/libs/int-to-c-enum", version = "0.1.0" }
+intrusive-collections = { version = "0.9.6", features = ["nightly"] }
lazy_static = { version = "1.0", features = ["spin_no_std"] }
+linux-boot-params = { path = "libs/linux-bzimage/boot-params", version = "0.1.0" }
log = "0.4"
num = { version = "0.4", default-features = false }
num-derive = { version = "0.4", default-features = false }
num-traits = { version = "0.2", default-features = false }
-pod = { git = "https://github.com/asterinas/pod", rev = "d7dba56" }
+ostd-macros = { path = "libs/ostd-macros", version = "0.1.4" }
+ostd-test = { path = "libs/ostd-test", version = "0.1.0" }
+owo-colors = { version = "3", optional = true }
+ostd-pod = { git = "https://github.com/asterinas/ostd-pod", rev = "c4644be", version = "0.1.1" }
spin = "0.9.4"
static_assertions = "1.1.0"
tdx-guest = { version = "0.1.5", optional = true }
-trapframe = { git = "https://github.com/asterinas/trapframe-rs", rev = "4739428" }
+trapframe = "0.10.0"
unwinding = { version = "0.2.2", default-features = false, features = ["fde-gnu-eh-frame-hdr", "hide-trace", "panic", "personality", "unwinder"] }
volatile = { version = "0.4.5", features = ["unstable"] }
-owo-colors = { version = "3", optional = true }
+xarray = { git = "https://github.com/asterinas/xarray", rev = "72a4067", version = "0.1.0" }
[target.x86_64-unknown-none.dependencies]
x86_64 = "0.14.2"
diff --git a/ostd/README.md b/ostd/README.md
--- a/ostd/README.md
+++ b/ostd/README.md
@@ -18,12 +18,4 @@ Asterinas OSTD offers the following key values.
## OSTD APIs
-TODO
-
-## Implementation status
-
-TODO
-
-## Roadmap and plan
-
-TODO
\ No newline at end of file
+See [API docs](https://docs.rs/ostd/latest/ostd).
diff --git a/ostd/libs/ostd-macros/src/lib.rs b/ostd/libs/ostd-macros/src/lib.rs
--- a/ostd/libs/ostd-macros/src/lib.rs
+++ b/ostd/libs/ostd-macros/src/lib.rs
@@ -44,7 +46,7 @@ pub fn main(_attr: TokenStream, item: TokenStream) -> TokenStream {
/// For crates other than ostd,
/// this macro can be used in the following form.
///
-/// ```norun
+/// ```ignore
/// use ostd::prelude::*;
///
/// #[ktest]
diff --git a/ostd/libs/ostd-macros/src/lib.rs b/ostd/libs/ostd-macros/src/lib.rs
--- a/ostd/libs/ostd-macros/src/lib.rs
+++ b/ostd/libs/ostd-macros/src/lib.rs
@@ -56,7 +58,7 @@ pub fn main(_attr: TokenStream, item: TokenStream) -> TokenStream {
/// For ostd crate itself,
/// this macro can be used in the form
///
-/// ```norun
+/// ```ignore
/// use crate::prelude::*;
///
/// #[ktest]
diff --git a/ostd/libs/ostd-macros/src/lib.rs b/ostd/libs/ostd-macros/src/lib.rs
--- a/ostd/libs/ostd-macros/src/lib.rs
+++ b/ostd/libs/ostd-macros/src/lib.rs
@@ -144,10 +146,10 @@ pub fn ktest(_attr: TokenStream, item: TokenStream) -> TokenStream {
#[cfg(ktest)]
#[used]
#[link_section = ".ktest_array"]
- static #fn_ktest_item_name: ktest::KtestItem = ktest::KtestItem::new(
+ static #fn_ktest_item_name: ostd_test::KtestItem = ostd_test::KtestItem::new(
#fn_name,
(#should_panic, #expectation_tokens),
- ktest::KtestItemInfo {
+ ostd_test::KtestItemInfo {
module_path: module_path!(),
fn_name: stringify!(#fn_name),
package: #package_name,
diff --git a/ostd/libs/ktest/Cargo.toml b/ostd/libs/ostd-test/Cargo.toml
--- a/ostd/libs/ktest/Cargo.toml
+++ b/ostd/libs/ostd-test/Cargo.toml
@@ -1,7 +1,10 @@
[package]
-name = "ktest"
+name = "ostd-test"
version = "0.1.0"
edition = "2021"
+description = "The kernel mode testing framework of OSTD"
+license = "MPL-2.0"
+repository ="https://github.com/asterinas/asterinas"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
diff --git a/ostd/libs/ktest/src/lib.rs b/ostd/libs/ostd-test/src/lib.rs
--- a/ostd/libs/ktest/src/lib.rs
+++ b/ostd/libs/ostd-test/src/lib.rs
@@ -1,20 +1,20 @@
// SPDX-License-Identifier: MPL-2.0
-//! # The kernel mode testing framework of Asterinas.
+//! # The kernel mode testing framework of OSTD.
//!
-//! `ktest` stands for kernel-mode testing framework. Its goal is to provide a
+//! `ostd-test` stands for kernel-mode testing framework for OSTD. Its goal is to provide a
//! `cargo test`-like experience for any `#![no_std]` bare metal crates.
//!
-//! In Asterinas, all the tests written in the source tree of the crates will be run
+//! In OSTD, all the tests written in the source tree of the crates will be run
//! immediately after the initialization of `ostd`. Thus you can use any
//! feature provided by the frame including the heap allocator, etc.
//!
-//! By all means, ktest is an individule crate that only requires:
+//! By all means, ostd-test is an individule crate that only requires:
//! - a custom linker script section `.ktest_array`,
//! - and an alloc implementation.
//!
-//! And the frame happens to provide both of them. Thus, any crates depending
-//! on the frame can use ktest without any extra dependency.
+//! And the OSTD happens to provide both of them. Thus, any crates depending
+//! on the OSTD can use ostd-test without any extra dependency.
//!
//! ## Usage
//!
diff --git a/ostd/libs/ktest/src/lib.rs b/ostd/libs/ostd-test/src/lib.rs
--- a/ostd/libs/ktest/src/lib.rs
+++ b/ostd/libs/ostd-test/src/lib.rs
@@ -43,7 +43,7 @@
//! }
//! ```
//!
-//! Any crates using the ktest framework should be linked with ostd.
+//! Any crates using the ostd-test framework should be linked with ostd.
//!
//! ```toml
//! # Cargo.toml
diff --git a/ostd/src/boot/mod.rs b/ostd/src/boot/mod.rs
--- a/ostd/src/boot/mod.rs
+++ b/ostd/src/boot/mod.rs
@@ -156,7 +156,7 @@ fn run_ktests(test_whitelist: Option<&[&str]>, crate_whitelist: Option<&[&str]>)
let fn_catch_unwind = &(unwinding::panic::catch_unwind::<(), fn()>
as fn(fn()) -> Result<(), Box<(dyn Any + Send + 'static)>>);
- use ktest::runner::{run_ktests, KtestResult};
+ use ostd_test::runner::{run_ktests, KtestResult};
match run_ktests(
&crate::console::early_print,
fn_catch_unwind,
diff --git a/ostd/src/lib.rs b/ostd/src/lib.rs
--- a/ostd/src/lib.rs
+++ b/ostd/src/lib.rs
@@ -123,5 +124,5 @@ mod test {
/// The module re-exports everything from the ktest crate
#[cfg(ktest)]
pub mod ktest {
- pub use ktest::*;
+ pub use ostd_test::*;
}
diff --git a/ostd/src/panicking.rs b/ostd/src/panicking.rs
--- a/ostd/src/panicking.rs
+++ b/ostd/src/panicking.rs
@@ -29,7 +29,7 @@ use unwinding::{
/// panic handler in the binary crate.
#[export_name = "__aster_panic_handler"]
pub fn panic_handler(info: &core::panic::PanicInfo) -> ! {
- let throw_info = ktest::PanicInfo {
+ let throw_info = ostd_test::PanicInfo {
message: info.message().to_string(),
file: info.location().unwrap().file().to_string(),
line: info.location().unwrap().line() as usize,
diff --git a/ostd/src/sync/atomic_bits.rs b/ostd/src/sync/atomic_bits.rs
--- a/ostd/src/sync/atomic_bits.rs
+++ b/ostd/src/sync/atomic_bits.rs
@@ -293,7 +293,6 @@ impl fmt::Debug for AtomicBits {
#[cfg(ktest)]
mod test {
use super::*;
- use crate::prelude::*;
#[ktest]
fn new() {
|
[
"1009"
] |
0.6
|
8a9c012249d36c54712030c41388d20a608939f5
|
Tracking issue for publishing OSTD to crates.io
# Description
This issue tracks the issue of publishing OSTD to `crates.io`
- [x] Publishing all dependent crates of OSTD to `crates.io`
- [x] align_ext ([v0.1.0](https://crates.io/crates/align_ext))
- [x] ostd-macros([v0.1.1](https://crates.io/crates/ostd-macros))
- [x] linux-boot-params([v0.1.0](https://crates.io/crates/linux-boot-params))
- [x] inherit-methods-macro([v0.1.0](https://crates.io/crates/inherit-methods-macro))
- [x] xarray([v0.1.0](https://crates.io/crates/xarray))
- [x] int-to-c-enum([v0.1.0](https://crates.io/crates/int-to-c-enum))
- [x] ktest(renamed as `ostd-test`, [v0.1.0](https://crates.io/crates/ostd-test))
- [x] id-alloc([v0.1.0](https://crates.io/crates/id-alloc))
- [x] pod(renamed as `pod-rs`, [v0.1.1](https://crates.io/crates/pod-rs))
- [x] trapframe([v0.9.0](https://crates.io/crates/trapframe) works, just without our patch to speed)
- [x] unwinding([v0.2.2](https://crates.io/crates/unwinding) works)
- [x] Publish OSTD itself to `crate.io`
- [x] Publish API documentation of OSTD to `docs.rs`
|
asterinas__asterinas-1018
| 1,018
|
diff --git a/.github/workflows/publish_api_docs.yml /dev/null
--- a/.github/workflows/publish_api_docs.yml
+++ /dev/null
@@ -1,43 +0,0 @@
-name: Update API docs
-
-on:
- # Scheduled events for nightly API docs
- schedule:
- # UTC 00:00 everyday
- - cron: "0 0 * * *"
- # Events for API docs of new release
- push:
- branches:
- - main
- paths:
- - VERSION
-
-jobs:
- build_and_upload:
- runs-on: ubuntu-latest
- timeout-minutes: 15
- container: asterinas/asterinas:0.6.2
-
- steps:
- - uses: actions/checkout@v2
- with:
- repository: 'asterinas/asterinas'
- path: 'asterinas'
-
- - name: Build & Upload Nightly API Docs
- if: github.event_name == 'schedule'
- env:
- API_DOCS_NIGHTLY_PUBLISH_KEY: ${{ secrets.API_DOCS_NIGHTLY_PUBLISH_KEY }}
- run: |
- KEY_FILE=./api_docs_nightly_publish_key
- echo "$API_DOCS_NIGHTLY_PUBLISH_KEY\n" > ${KEY_FILE}
- bash asterinas/tools/github_workflows/build_and_upload_api_docs.sh nightly ${KEY_FILE}
-
- - name: Build & Upload Release API Docs
- if: github.event_name == 'push'
- env:
- API_DOCS_PUBLISH_KEY: ${{ secrets.API_DOCS_PUBLISH_KEY }}
- run: |
- KEY_FILE=./api_docs_publish_key
- echo "$API_DOCS_PUBLISH_KEY\n" > ${KEY_FILE}
- bash asterinas/tools/github_workflows/build_and_upload_api_docs.sh release ${KEY_FILE}
diff --git a/.github/workflows/publish_osdk.yml /dev/null
--- a/.github/workflows/publish_osdk.yml
+++ /dev/null
@@ -1,36 +0,0 @@
-name: Publish OSDK
-
-on:
- pull_request:
- paths:
- - VERSION
- - osdk/Cargo.toml
- push:
- branches:
- - main
- paths:
- - VERSION
-
-jobs:
- osdk-publish:
- runs-on: ubuntu-latest
- timeout-minutes: 10
- container: asterinas/asterinas:0.6.2
- steps:
- - uses: actions/checkout@v4
-
- - name: Check Publish
- # On pull request, set `--dry-run` to check whether OSDK can publish
- if: github.event_name == 'pull_request'
- run: |
- cd osdk
- cargo publish --dry-run
-
- - name: Publish
- # On push, OSDK will be published
- if: github.event_name == 'push'
- env:
- REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
- run: |
- cd osdk
- cargo publish --token ${REGISTRY_TOKEN}
diff --git /dev/null b/.github/workflows/publish_osdk_and_ostd.yml
new file mode 100644
--- /dev/null
+++ b/.github/workflows/publish_osdk_and_ostd.yml
@@ -0,0 +1,69 @@
+name: Publish OSDK and OSTD
+
+on:
+ pull_request:
+ paths:
+ - VERSION
+ - ostd/**
+ - osdk/**
+ push:
+ branches:
+ - main
+ paths:
+ - VERSION
+
+jobs:
+ osdk-publish:
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ container: asterinas/asterinas:0.6.2
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Check Publish OSDK
+ # On pull request, set `--dry-run` to check whether OSDK can publish
+ if: github.event_name == 'pull_request'
+ run: |
+ cd osdk
+ cargo publish --dry-run
+
+ - name: Publish OSDK
+ # On push, OSDK will be published
+ if: github.event_name == 'push'
+ env:
+ REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
+ run: |
+ cd osdk
+ cargo publish --token ${REGISTRY_TOKEN}
+
+ ostd-publish:
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ container: asterinas/asterinas:0.6.2
+ strategy:
+ matrix:
+ # All supported targets, this array should keep consistent with
+ # `package.metadata.docs.rs.targets` in `ostd/Cargo.toml`
+ target: ['x86_64-unknown-none']
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Check Publish OSTD
+ # On pull request, set `--dry-run` to check whether OSDK can publish
+ if: github.event_name == 'pull_request'
+ run: |
+ cd ostd
+ cargo publish --target ${{ matrix.target }} --dry-run
+ cargo doc --target ${{ matrix.target }}
+
+ - name: Publish OSTD
+ if: github.event_name == 'push'
+ env:
+ REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
+ # Using any target that OSTD supports for publishing is ok.
+ # Here we use the same target as
+ # `package.metadata.docs.rs.default-target` in `ostd/Cargo.toml`.
+ run: |
+ cd ostd
+ cargo publish --target x86_64-unknown-none --token ${REGISTRY_TOKEN}
+
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -84,7 +84,6 @@ dependencies = [
"lazy_static",
"log",
"ostd",
- "pod",
"spin 0.9.8",
"static_assertions",
]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -84,7 +84,6 @@ dependencies = [
"lazy_static",
"log",
"ostd",
- "pod",
"spin 0.9.8",
"static_assertions",
]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -141,7 +140,6 @@ dependencies = [
"int-to-c-enum",
"log",
"ostd",
- "pod",
"ringbuf",
"smoltcp",
"spin 0.9.8",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -141,7 +140,6 @@ dependencies = [
"int-to-c-enum",
"log",
"ostd",
- "pod",
"ringbuf",
"smoltcp",
"spin 0.9.8",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -185,7 +183,6 @@ dependencies = [
"lru",
"ostd",
"paste",
- "pod",
"rand",
"ringbuf",
"smoltcp",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -185,7 +183,6 @@ dependencies = [
"lru",
"ostd",
"paste",
- "pod",
"rand",
"ringbuf",
"smoltcp",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -238,7 +235,6 @@ dependencies = [
"aster-rights-proc",
"inherit-methods-macro",
"ostd",
- "pod",
"typeflags-util",
]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -238,7 +235,6 @@ dependencies = [
"aster-rights-proc",
"inherit-methods-macro",
"ostd",
- "pod",
"typeflags-util",
]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -261,7 +257,6 @@ dependencies = [
"int-to-c-enum",
"log",
"ostd",
- "pod",
"smoltcp",
"spin 0.9.8",
"typeflags-util",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -261,7 +257,6 @@ dependencies = [
"int-to-c-enum",
"log",
"ostd",
- "pod",
"smoltcp",
"spin 0.9.8",
"typeflags-util",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -277,7 +272,7 @@ dependencies = [
"component",
"id-alloc",
"ostd",
- "x86_64",
+ "x86_64 0.14.11",
]
[[package]]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -277,7 +272,7 @@ dependencies = [
"component",
"id-alloc",
"ostd",
- "x86_64",
+ "x86_64 0.14.11",
]
[[package]]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -760,9 +755,9 @@ dependencies = [
[[package]]
name = "intrusive-collections"
-version = "0.9.5"
+version = "0.9.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3f4f90afb01281fdeffb0f8e082d230cbe4f888f837cc90759696b858db1a700"
+checksum = "b694dc9f70c3bda874626d2aed13b780f137aab435f4e9814121955cf706122e"
dependencies = [
"memoffset",
]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -760,9 +755,9 @@ dependencies = [
[[package]]
name = "intrusive-collections"
-version = "0.9.5"
+version = "0.9.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3f4f90afb01281fdeffb0f8e082d230cbe4f888f837cc90759696b858db1a700"
+checksum = "b694dc9f70c3bda874626d2aed13b780f137aab435f4e9814121955cf706122e"
dependencies = [
"memoffset",
]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -795,13 +790,6 @@ checksum = "078e285eafdfb6c4b434e0d31e8cfcb5115b651496faca5749b88fafd4f23bfd"
name = "keyable-arc"
version = "0.1.0"
-[[package]]
-name = "ktest"
-version = "0.1.0"
-dependencies = [
- "owo-colors",
-]
-
[[package]]
name = "lazy_static"
version = "1.4.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -891,7 +879,7 @@ dependencies = [
"uart_16550",
"uefi",
"uefi-services",
- "x86_64",
+ "x86_64 0.14.11",
"xmas-elf 0.8.0",
]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -891,7 +879,7 @@ dependencies = [
"uart_16550",
"uefi",
"uefi-services",
- "x86_64",
+ "x86_64 0.14.11",
"xmas-elf 0.8.0",
]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -950,9 +938,9 @@ checksum = "523dc4f511e55ab87b694dc30d0f820d60906ef06413f93d4d7a1385599cc149"
[[package]]
name = "memoffset"
-version = "0.8.0"
+version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d61c719bcfbcf5d62b3a09efa6088de8c54bc0bfcd3ea7ae39fcc186108b8de1"
+checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
dependencies = [
"autocfg",
]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -950,9 +938,9 @@ checksum = "523dc4f511e55ab87b694dc30d0f820d60906ef06413f93d4d7a1385599cc149"
[[package]]
name = "memoffset"
-version = "0.8.0"
+version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d61c719bcfbcf5d62b3a09efa6088de8c54bc0bfcd3ea7ae39fcc186108b8de1"
+checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
dependencies = [
"autocfg",
]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1094,7 +1082,6 @@ dependencies = [
"inherit-methods-macro",
"int-to-c-enum",
"intrusive-collections",
- "ktest",
"lazy_static",
"linux-boot-params",
"log",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1103,8 +1090,9 @@ dependencies = [
"num-derive",
"num-traits",
"ostd-macros",
+ "ostd-pod",
+ "ostd-test",
"owo-colors",
- "pod",
"rsdp",
"spin 0.9.8",
"static_assertions",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1113,13 +1101,13 @@ dependencies = [
"unwinding",
"volatile",
"x86",
- "x86_64",
+ "x86_64 0.14.11",
"xarray",
]
[[package]]
name = "ostd-macros"
-version = "0.1.0"
+version = "0.1.4"
dependencies = [
"proc-macro2",
"quote",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1113,13 +1101,13 @@ dependencies = [
"unwinding",
"volatile",
"x86",
- "x86_64",
+ "x86_64 0.14.11",
"xarray",
]
[[package]]
name = "ostd-macros"
-version = "0.1.0"
+version = "0.1.4"
dependencies = [
"proc-macro2",
"quote",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1127,6 +1115,31 @@ dependencies = [
"syn 2.0.49",
]
+[[package]]
+name = "ostd-pod"
+version = "0.1.1"
+source = "git+https://github.com/asterinas/ostd-pod?rev=c4644be#c4644be401cae1e046a810574078b64e35924f5f"
+dependencies = [
+ "ostd-pod-derive",
+]
+
+[[package]]
+name = "ostd-pod-derive"
+version = "0.1.1"
+source = "git+https://github.com/asterinas/ostd-pod?rev=c4644be#c4644be401cae1e046a810574078b64e35924f5f"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "ostd-test"
+version = "0.1.0"
+dependencies = [
+ "owo-colors",
+]
+
[[package]]
name = "owo-colors"
version = "3.5.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1139,24 +1152,6 @@ version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "de3145af08024dea9fa9914f381a17b8fc6034dfb00f3a84013f7ff43f29ed4c"
-[[package]]
-name = "pod"
-version = "0.1.0"
-source = "git+https://github.com/asterinas/pod?rev=d7dba56#d7dba56cc202a10d483b60aba4f734b1f49cb37b"
-dependencies = [
- "pod-derive",
-]
-
-[[package]]
-name = "pod-derive"
-version = "0.1.0"
-source = "git+https://github.com/asterinas/pod?rev=d7dba56#d7dba56cc202a10d483b60aba4f734b1f49cb37b"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 1.0.109",
-]
-
[[package]]
name = "polonius-the-crab"
version = "0.2.1"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1139,24 +1152,6 @@ version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "de3145af08024dea9fa9914f381a17b8fc6034dfb00f3a84013f7ff43f29ed4c"
-[[package]]
-name = "pod"
-version = "0.1.0"
-source = "git+https://github.com/asterinas/pod?rev=d7dba56#d7dba56cc202a10d483b60aba4f734b1f49cb37b"
-dependencies = [
- "pod-derive",
-]
-
-[[package]]
-name = "pod-derive"
-version = "0.1.0"
-source = "git+https://github.com/asterinas/pod?rev=d7dba56#d7dba56cc202a10d483b60aba4f734b1f49cb37b"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 1.0.109",
-]
-
[[package]]
name = "polonius-the-crab"
version = "0.2.1"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1276,6 +1271,15 @@ dependencies = [
"bitflags 1.3.2",
]
+[[package]]
+name = "raw-cpuid"
+version = "11.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e29830cbb1290e404f24c73af91c5d8d631ce7e128691e9477556b540cd01ecd"
+dependencies = [
+ "bitflags 2.4.1",
+]
+
[[package]]
name = "ringbuf"
version = "0.3.3"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1276,6 +1271,15 @@ dependencies = [
"bitflags 1.3.2",
]
+[[package]]
+name = "raw-cpuid"
+version = "11.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e29830cbb1290e404f24c73af91c5d8d631ce7e128691e9477556b540cd01ecd"
+dependencies = [
+ "bitflags 2.4.1",
+]
+
[[package]]
name = "ringbuf"
version = "0.3.3"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1358,9 +1362,9 @@ dependencies = [
[[package]]
name = "smallvec"
-version = "1.13.1"
+version = "1.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e6ecd384b10a64542d77071bd64bd7b231f4ed5940fba55e98c3de13824cf3d7"
+checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
[[package]]
name = "smoltcp"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1358,9 +1362,9 @@ dependencies = [
[[package]]
name = "smallvec"
-version = "1.13.1"
+version = "1.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e6ecd384b10a64542d77071bd64bd7b231f4ed5940fba55e98c3de13824cf3d7"
+checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
[[package]]
name = "smoltcp"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1462,8 +1466,8 @@ dependencies = [
"bitflags 1.3.2",
"iced-x86",
"lazy_static",
- "raw-cpuid",
- "x86_64",
+ "raw-cpuid 10.7.0",
+ "x86_64 0.14.11",
]
[[package]]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1462,8 +1466,8 @@ dependencies = [
"bitflags 1.3.2",
"iced-x86",
"lazy_static",
- "raw-cpuid",
- "x86_64",
+ "raw-cpuid 10.7.0",
+ "x86_64 0.14.11",
]
[[package]]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1539,13 +1543,12 @@ dependencies = [
[[package]]
name = "trapframe"
-version = "0.9.0"
-source = "git+https://github.com/asterinas/trapframe-rs?rev=4739428#4739428fd51685c74e6e88e73e5f04cb89f465ee"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "105000258ba41c463b63403c9341c55a298f35f6137b1cca08c10f0409ef8d3a"
dependencies = [
- "log",
- "pod",
- "raw-cpuid",
- "x86_64",
+ "raw-cpuid 11.0.2",
+ "x86_64 0.15.1",
]
[[package]]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1539,13 +1543,12 @@ dependencies = [
[[package]]
name = "trapframe"
-version = "0.9.0"
-source = "git+https://github.com/asterinas/trapframe-rs?rev=4739428#4739428fd51685c74e6e88e73e5f04cb89f465ee"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "105000258ba41c463b63403c9341c55a298f35f6137b1cca08c10f0409ef8d3a"
dependencies = [
- "log",
- "pod",
- "raw-cpuid",
- "x86_64",
+ "raw-cpuid 11.0.2",
+ "x86_64 0.15.1",
]
[[package]]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1723,7 +1726,7 @@ checksum = "2781db97787217ad2a2845c396a5efe286f87467a5810836db6d74926e94a385"
dependencies = [
"bit_field",
"bitflags 1.3.2",
- "raw-cpuid",
+ "raw-cpuid 10.7.0",
]
[[package]]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1723,7 +1726,7 @@ checksum = "2781db97787217ad2a2845c396a5efe286f87467a5810836db6d74926e94a385"
dependencies = [
"bit_field",
"bitflags 1.3.2",
- "raw-cpuid",
+ "raw-cpuid 10.7.0",
]
[[package]]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1738,6 +1741,18 @@ dependencies = [
"volatile",
]
+[[package]]
+name = "x86_64"
+version = "0.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4bc79523af8abf92fb1a970c3e086c5a343f6bcc1a0eb890f575cbb3b45743df"
+dependencies = [
+ "bit_field",
+ "bitflags 2.4.1",
+ "rustversion",
+ "volatile",
+]
+
[[package]]
name = "xarray"
version = "0.1.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1738,6 +1741,18 @@ dependencies = [
"volatile",
]
+[[package]]
+name = "x86_64"
+version = "0.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4bc79523af8abf92fb1a970c3e086c5a343f6bcc1a0eb890f575cbb3b45743df"
+dependencies = [
+ "bit_field",
+ "bitflags 2.4.1",
+ "rustversion",
+ "volatile",
+]
+
[[package]]
name = "xarray"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -8,7 +8,7 @@ members = [
"ostd/libs/linux-bzimage/builder",
"ostd/libs/linux-bzimage/boot-params",
"ostd/libs/linux-bzimage/setup",
- "ostd/libs/ktest",
+ "ostd/libs/ostd-test",
"kernel",
"kernel/aster-nix",
"kernel/comps/block",
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -91,8 +91,8 @@ NON_OSDK_CRATES := \
ostd/libs/id-alloc \
ostd/libs/linux-bzimage/builder \
ostd/libs/linux-bzimage/boot-params \
- ostd/libs/ktest \
ostd/libs/ostd-macros \
+ ostd/libs/ostd-test \
kernel/libs/cpio-decoder \
kernel/libs/int-to-c-enum \
kernel/libs/int-to-c-enum/derive \
diff --git a/docs/src/ostd/README.md b/docs/src/ostd/README.md
--- a/docs/src/ostd/README.md
+++ b/docs/src/ostd/README.md
@@ -39,9 +39,7 @@ To explore how these APIs come into play,
see [the example of a 100-line kernel in safe Rust](a-100-line-kernel.md).
The OSTD APIs have been extensively documented.
-You can access the comprehensive API documentation for each release by visiting the [API docs](https://asterinas.github.io/api-docs).
-Additionally, you can refer to the latest nightly version API documentation at [API docs nightly](https://asterinas.github.io/api-docs-nightly),
-which remains in sync with the latest changes in the main branch.
+You can access the comprehensive API documentation by visiting the [docs.rs](https://docs.rs/ostd/latest/ostd).
## Four Requirements Satisfied
diff --git a/kernel/aster-nix/Cargo.toml b/kernel/aster-nix/Cargo.toml
--- a/kernel/aster-nix/Cargo.toml
+++ b/kernel/aster-nix/Cargo.toml
@@ -6,9 +6,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
-ostd = { path = "../../ostd" }
align_ext = { path = "../../ostd/libs/align_ext" }
-pod = { git = "https://github.com/asterinas/pod", rev = "d7dba56" }
aster-input = { path = "../comps/input" }
aster-block = { path = "../comps/block" }
aster-network = { path = "../comps/network" }
diff --git a/kernel/aster-nix/Cargo.toml b/kernel/aster-nix/Cargo.toml
--- a/kernel/aster-nix/Cargo.toml
+++ b/kernel/aster-nix/Cargo.toml
@@ -6,9 +6,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
-ostd = { path = "../../ostd" }
align_ext = { path = "../../ostd/libs/align_ext" }
-pod = { git = "https://github.com/asterinas/pod", rev = "d7dba56" }
aster-input = { path = "../comps/input" }
aster-block = { path = "../comps/block" }
aster-network = { path = "../comps/network" }
diff --git a/kernel/aster-nix/Cargo.toml b/kernel/aster-nix/Cargo.toml
--- a/kernel/aster-nix/Cargo.toml
+++ b/kernel/aster-nix/Cargo.toml
@@ -17,6 +15,7 @@ aster-time = { path = "../comps/time" }
aster-virtio = { path = "../comps/virtio" }
aster-rights = { path = "../libs/aster-rights" }
controlled = { path = "../libs/comp-sys/controlled" }
+ostd = { path = "../../ostd" }
typeflags = { path = "../libs/typeflags" }
typeflags-util = { path = "../libs/typeflags-util" }
aster-rights-proc = { path = "../libs/aster-rights-proc" }
diff --git a/kernel/aster-nix/Cargo.toml b/kernel/aster-nix/Cargo.toml
--- a/kernel/aster-nix/Cargo.toml
+++ b/kernel/aster-nix/Cargo.toml
@@ -17,6 +15,7 @@ aster-time = { path = "../comps/time" }
aster-virtio = { path = "../comps/virtio" }
aster-rights = { path = "../libs/aster-rights" }
controlled = { path = "../libs/comp-sys/controlled" }
+ostd = { path = "../../ostd" }
typeflags = { path = "../libs/typeflags" }
typeflags-util = { path = "../libs/typeflags-util" }
aster-rights-proc = { path = "../libs/aster-rights-proc" }
diff --git a/kernel/aster-nix/src/arch/x86/cpu.rs b/kernel/aster-nix/src/arch/x86/cpu.rs
--- a/kernel/aster-nix/src/arch/x86/cpu.rs
+++ b/kernel/aster-nix/src/arch/x86/cpu.rs
@@ -1,6 +1,9 @@
// SPDX-License-Identifier: MPL-2.0
-use ostd::cpu::UserContext;
+use ostd::{
+ cpu::{RawGeneralRegs, UserContext},
+ Pod,
+};
use crate::cpu::LinuxAbi;
diff --git a/kernel/aster-nix/src/arch/x86/cpu.rs b/kernel/aster-nix/src/arch/x86/cpu.rs
--- a/kernel/aster-nix/src/arch/x86/cpu.rs
+++ b/kernel/aster-nix/src/arch/x86/cpu.rs
@@ -1,6 +1,9 @@
// SPDX-License-Identifier: MPL-2.0
-use ostd::cpu::UserContext;
+use ostd::{
+ cpu::{RawGeneralRegs, UserContext},
+ Pod,
+};
use crate::cpu::LinuxAbi;
diff --git a/kernel/aster-nix/src/arch/x86/cpu.rs b/kernel/aster-nix/src/arch/x86/cpu.rs
--- a/kernel/aster-nix/src/arch/x86/cpu.rs
+++ b/kernel/aster-nix/src/arch/x86/cpu.rs
@@ -36,3 +39,64 @@ impl LinuxAbi for UserContext {
self.fsbase()
}
}
+
+/// General-purpose registers.
+#[derive(Debug, Clone, Copy, Pod, Default)]
+#[repr(C)]
+pub struct GpRegs {
+ pub rax: usize,
+ pub rbx: usize,
+ pub rcx: usize,
+ pub rdx: usize,
+ pub rsi: usize,
+ pub rdi: usize,
+ pub rbp: usize,
+ pub rsp: usize,
+ pub r8: usize,
+ pub r9: usize,
+ pub r10: usize,
+ pub r11: usize,
+ pub r12: usize,
+ pub r13: usize,
+ pub r14: usize,
+ pub r15: usize,
+ pub rip: usize,
+ pub rflags: usize,
+ pub fsbase: usize,
+ pub gsbase: usize,
+}
+
+macro_rules! copy_gp_regs {
+ ($src: ident, $dst: ident) => {
+ $dst.rax = $src.rax;
+ $dst.rbx = $src.rax;
+ $dst.rcx = $src.rcx;
+ $dst.rdx = $src.rdx;
+ $dst.rsi = $src.rsi;
+ $dst.rdi = $src.rdi;
+ $dst.rbp = $src.rbp;
+ $dst.rsp = $src.rsp;
+ $dst.r8 = $src.r8;
+ $dst.r9 = $src.r9;
+ $dst.r10 = $src.r10;
+ $dst.r11 = $src.r11;
+ $dst.r12 = $src.r12;
+ $dst.r13 = $src.r13;
+ $dst.r14 = $src.r14;
+ $dst.r15 = $src.r15;
+ $dst.rip = $src.rip;
+ $dst.rflags = $src.rflags;
+ $dst.fsbase = $src.fsbase;
+ $dst.gsbase = $src.gsbase;
+ };
+}
+
+impl GpRegs {
+ pub fn copy_to_raw(&self, dst: &mut RawGeneralRegs) {
+ copy_gp_regs!(self, dst);
+ }
+
+ pub fn copy_from_raw(&mut self, src: &RawGeneralRegs) {
+ copy_gp_regs!(src, self);
+ }
+}
diff --git a/kernel/aster-nix/src/arch/x86/cpu.rs b/kernel/aster-nix/src/arch/x86/cpu.rs
--- a/kernel/aster-nix/src/arch/x86/cpu.rs
+++ b/kernel/aster-nix/src/arch/x86/cpu.rs
@@ -36,3 +39,64 @@ impl LinuxAbi for UserContext {
self.fsbase()
}
}
+
+/// General-purpose registers.
+#[derive(Debug, Clone, Copy, Pod, Default)]
+#[repr(C)]
+pub struct GpRegs {
+ pub rax: usize,
+ pub rbx: usize,
+ pub rcx: usize,
+ pub rdx: usize,
+ pub rsi: usize,
+ pub rdi: usize,
+ pub rbp: usize,
+ pub rsp: usize,
+ pub r8: usize,
+ pub r9: usize,
+ pub r10: usize,
+ pub r11: usize,
+ pub r12: usize,
+ pub r13: usize,
+ pub r14: usize,
+ pub r15: usize,
+ pub rip: usize,
+ pub rflags: usize,
+ pub fsbase: usize,
+ pub gsbase: usize,
+}
+
+macro_rules! copy_gp_regs {
+ ($src: ident, $dst: ident) => {
+ $dst.rax = $src.rax;
+ $dst.rbx = $src.rax;
+ $dst.rcx = $src.rcx;
+ $dst.rdx = $src.rdx;
+ $dst.rsi = $src.rsi;
+ $dst.rdi = $src.rdi;
+ $dst.rbp = $src.rbp;
+ $dst.rsp = $src.rsp;
+ $dst.r8 = $src.r8;
+ $dst.r9 = $src.r9;
+ $dst.r10 = $src.r10;
+ $dst.r11 = $src.r11;
+ $dst.r12 = $src.r12;
+ $dst.r13 = $src.r13;
+ $dst.r14 = $src.r14;
+ $dst.r15 = $src.r15;
+ $dst.rip = $src.rip;
+ $dst.rflags = $src.rflags;
+ $dst.fsbase = $src.fsbase;
+ $dst.gsbase = $src.gsbase;
+ };
+}
+
+impl GpRegs {
+ pub fn copy_to_raw(&self, dst: &mut RawGeneralRegs) {
+ copy_gp_regs!(self, dst);
+ }
+
+ pub fn copy_from_raw(&mut self, src: &RawGeneralRegs) {
+ copy_gp_regs!(src, self);
+ }
+}
diff --git a/kernel/aster-nix/src/fs/exfat/super_block.rs b/kernel/aster-nix/src/fs/exfat/super_block.rs
--- a/kernel/aster-nix/src/fs/exfat/super_block.rs
+++ b/kernel/aster-nix/src/fs/exfat/super_block.rs
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: MPL-2.0
-use pod::Pod;
+use ostd::Pod;
use super::constants::{EXFAT_FIRST_CLUSTER, EXFAT_RESERVED_CLUSTERS, MEDIA_FAILURE, VOLUME_DIRTY};
use crate::prelude::*;
diff --git a/kernel/aster-nix/src/fs/exfat/super_block.rs b/kernel/aster-nix/src/fs/exfat/super_block.rs
--- a/kernel/aster-nix/src/fs/exfat/super_block.rs
+++ b/kernel/aster-nix/src/fs/exfat/super_block.rs
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: MPL-2.0
-use pod::Pod;
+use ostd::Pod;
use super::constants::{EXFAT_FIRST_CLUSTER, EXFAT_RESERVED_CLUSTERS, MEDIA_FAILURE, VOLUME_DIRTY};
use crate::prelude::*;
diff --git a/kernel/aster-nix/src/prelude.rs b/kernel/aster-nix/src/prelude.rs
--- a/kernel/aster-nix/src/prelude.rs
+++ b/kernel/aster-nix/src/prelude.rs
@@ -19,8 +19,8 @@ pub(crate) use log::{debug, error, info, log_enabled, trace, warn};
pub(crate) use ostd::{
mm::{Vaddr, VmReader, VmWriter, PAGE_SIZE},
sync::{Mutex, MutexGuard, RwLock, RwMutex, SpinLock, SpinLockGuard},
+ Pod,
};
-pub(crate) use pod::Pod;
/// return current process
#[macro_export]
diff --git a/kernel/aster-nix/src/prelude.rs b/kernel/aster-nix/src/prelude.rs
--- a/kernel/aster-nix/src/prelude.rs
+++ b/kernel/aster-nix/src/prelude.rs
@@ -19,8 +19,8 @@ pub(crate) use log::{debug, error, info, log_enabled, trace, warn};
pub(crate) use ostd::{
mm::{Vaddr, VmReader, VmWriter, PAGE_SIZE},
sync::{Mutex, MutexGuard, RwLock, RwMutex, SpinLock, SpinLockGuard},
+ Pod,
};
-pub(crate) use pod::Pod;
/// return current process
#[macro_export]
diff --git a/kernel/aster-nix/src/process/signal/c_types.rs b/kernel/aster-nix/src/process/signal/c_types.rs
--- a/kernel/aster-nix/src/process/signal/c_types.rs
+++ b/kernel/aster-nix/src/process/signal/c_types.rs
@@ -6,10 +6,10 @@
use core::mem::{self, size_of};
use aster_util::{read_union_fields, union_read_ptr::UnionReadPtr};
-use ostd::cpu::GeneralRegs;
use super::sig_num::SigNum;
use crate::{
+ arch::cpu::GpRegs,
prelude::*,
process::{Pid, Uid},
};
diff --git a/kernel/aster-nix/src/process/signal/c_types.rs b/kernel/aster-nix/src/process/signal/c_types.rs
--- a/kernel/aster-nix/src/process/signal/c_types.rs
+++ b/kernel/aster-nix/src/process/signal/c_types.rs
@@ -6,10 +6,10 @@
use core::mem::{self, size_of};
use aster_util::{read_union_fields, union_read_ptr::UnionReadPtr};
-use ostd::cpu::GeneralRegs;
use super::sig_num::SigNum;
use crate::{
+ arch::cpu::GpRegs,
prelude::*,
process::{Pid, Uid},
};
diff --git a/kernel/aster-nix/src/process/signal/c_types.rs b/kernel/aster-nix/src/process/signal/c_types.rs
--- a/kernel/aster-nix/src/process/signal/c_types.rs
+++ b/kernel/aster-nix/src/process/signal/c_types.rs
@@ -206,7 +206,7 @@ pub struct mcontext_t {
#[derive(Debug, Clone, Copy, Pod, Default)]
#[repr(C)]
pub struct SignalCpuContext {
- pub gp_regs: GeneralRegs,
+ pub gp_regs: GpRegs,
pub fpregs_on_heap: u64,
pub fpregs: Vaddr, // *mut FpRegs,
}
diff --git a/kernel/aster-nix/src/process/signal/c_types.rs b/kernel/aster-nix/src/process/signal/c_types.rs
--- a/kernel/aster-nix/src/process/signal/c_types.rs
+++ b/kernel/aster-nix/src/process/signal/c_types.rs
@@ -206,7 +206,7 @@ pub struct mcontext_t {
#[derive(Debug, Clone, Copy, Pod, Default)]
#[repr(C)]
pub struct SignalCpuContext {
- pub gp_regs: GeneralRegs,
+ pub gp_regs: GpRegs,
pub fpregs_on_heap: u64,
pub fpregs: Vaddr, // *mut FpRegs,
}
diff --git a/kernel/aster-nix/src/process/signal/mod.rs b/kernel/aster-nix/src/process/signal/mod.rs
--- a/kernel/aster-nix/src/process/signal/mod.rs
+++ b/kernel/aster-nix/src/process/signal/mod.rs
@@ -166,7 +166,11 @@ pub fn handle_user_signal(
uc_sigmask: mask.as_u64(),
..Default::default()
};
- ucontext.uc_mcontext.inner.gp_regs = *context.general_regs();
+ ucontext
+ .uc_mcontext
+ .inner
+ .gp_regs
+ .copy_from_raw(context.general_regs());
let mut sig_context = posix_thread.sig_context().lock();
if let Some(sig_context_addr) = *sig_context {
ucontext.uc_link = sig_context_addr;
diff --git a/kernel/aster-nix/src/process/signal/mod.rs b/kernel/aster-nix/src/process/signal/mod.rs
--- a/kernel/aster-nix/src/process/signal/mod.rs
+++ b/kernel/aster-nix/src/process/signal/mod.rs
@@ -166,7 +166,11 @@ pub fn handle_user_signal(
uc_sigmask: mask.as_u64(),
..Default::default()
};
- ucontext.uc_mcontext.inner.gp_regs = *context.general_regs();
+ ucontext
+ .uc_mcontext
+ .inner
+ .gp_regs
+ .copy_from_raw(context.general_regs());
let mut sig_context = posix_thread.sig_context().lock();
if let Some(sig_context_addr) = *sig_context {
ucontext.uc_link = sig_context_addr;
diff --git a/kernel/aster-nix/src/syscall/rt_sigreturn.rs b/kernel/aster-nix/src/syscall/rt_sigreturn.rs
--- a/kernel/aster-nix/src/syscall/rt_sigreturn.rs
+++ b/kernel/aster-nix/src/syscall/rt_sigreturn.rs
@@ -38,7 +38,11 @@ pub fn sys_rt_sigreturn(context: &mut UserContext) -> Result<SyscallReturn> {
} else {
*sig_context = Some(ucontext.uc_link);
};
- *context.general_regs_mut() = ucontext.uc_mcontext.inner.gp_regs;
+ ucontext
+ .uc_mcontext
+ .inner
+ .gp_regs
+ .copy_to_raw(context.general_regs_mut());
// unblock sig mask
let sig_mask = ucontext.uc_sigmask;
posix_thread.sig_mask().lock().unblock(sig_mask);
diff --git a/kernel/aster-nix/src/syscall/rt_sigreturn.rs b/kernel/aster-nix/src/syscall/rt_sigreturn.rs
--- a/kernel/aster-nix/src/syscall/rt_sigreturn.rs
+++ b/kernel/aster-nix/src/syscall/rt_sigreturn.rs
@@ -38,7 +38,11 @@ pub fn sys_rt_sigreturn(context: &mut UserContext) -> Result<SyscallReturn> {
} else {
*sig_context = Some(ucontext.uc_link);
};
- *context.general_regs_mut() = ucontext.uc_mcontext.inner.gp_regs;
+ ucontext
+ .uc_mcontext
+ .inner
+ .gp_regs
+ .copy_to_raw(context.general_regs_mut());
// unblock sig mask
let sig_mask = ucontext.uc_sigmask;
posix_thread.sig_mask().lock().unblock(sig_mask);
diff --git a/kernel/aster-nix/src/vdso.rs b/kernel/aster-nix/src/vdso.rs
--- a/kernel/aster-nix/src/vdso.rs
+++ b/kernel/aster-nix/src/vdso.rs
@@ -23,8 +23,8 @@ use aster_util::coeff::Coeff;
use ostd::{
mm::{Frame, VmIo, PAGE_SIZE},
sync::SpinLock,
+ Pod,
};
-use pod::Pod;
use spin::Once;
use crate::{
diff --git a/kernel/aster-nix/src/vdso.rs b/kernel/aster-nix/src/vdso.rs
--- a/kernel/aster-nix/src/vdso.rs
+++ b/kernel/aster-nix/src/vdso.rs
@@ -23,8 +23,8 @@ use aster_util::coeff::Coeff;
use ostd::{
mm::{Frame, VmIo, PAGE_SIZE},
sync::SpinLock,
+ Pod,
};
-use pod::Pod;
use spin::Once;
use crate::{
diff --git a/kernel/comps/block/Cargo.toml b/kernel/comps/block/Cargo.toml
--- a/kernel/comps/block/Cargo.toml
+++ b/kernel/comps/block/Cargo.toml
@@ -8,7 +8,6 @@ edition = "2021"
[dependencies]
bitflags = "1.3"
spin = "0.9.4"
-pod = { git = "https://github.com/asterinas/pod", rev = "d7dba56" }
ostd = { path = "../../../ostd" }
align_ext = { path = "../../../ostd/libs/align_ext" }
aster-util = { path = "../../libs/aster-util" }
diff --git a/kernel/comps/block/Cargo.toml b/kernel/comps/block/Cargo.toml
--- a/kernel/comps/block/Cargo.toml
+++ b/kernel/comps/block/Cargo.toml
@@ -8,7 +8,6 @@ edition = "2021"
[dependencies]
bitflags = "1.3"
spin = "0.9.4"
-pod = { git = "https://github.com/asterinas/pod", rev = "d7dba56" }
ostd = { path = "../../../ostd" }
align_ext = { path = "../../../ostd/libs/align_ext" }
aster-util = { path = "../../libs/aster-util" }
diff --git a/kernel/comps/block/src/id.rs b/kernel/comps/block/src/id.rs
--- a/kernel/comps/block/src/id.rs
+++ b/kernel/comps/block/src/id.rs
@@ -5,7 +5,7 @@ use core::{
ops::{Add, Sub},
};
-use pod::Pod;
+use ostd::Pod;
use static_assertions::const_assert;
/// The block index used in the filesystem.
diff --git a/kernel/comps/block/src/id.rs b/kernel/comps/block/src/id.rs
--- a/kernel/comps/block/src/id.rs
+++ b/kernel/comps/block/src/id.rs
@@ -5,7 +5,7 @@ use core::{
ops::{Add, Sub},
};
-use pod::Pod;
+use ostd::Pod;
use static_assertions::const_assert;
/// The block index used in the filesystem.
diff --git a/kernel/comps/network/Cargo.toml b/kernel/comps/network/Cargo.toml
--- a/kernel/comps/network/Cargo.toml
+++ b/kernel/comps/network/Cargo.toml
@@ -15,7 +15,6 @@ component = { path = "../../libs/comp-sys/component" }
int-to-c-enum = { path = "../../libs/int-to-c-enum" }
log = "0.4"
ostd = { path = "../../../ostd" }
-pod = { git = "https://github.com/asterinas/pod", rev = "d7dba56" }
ringbuf = { version = "0.3.2", default-features = false, features = ["alloc"] }
smoltcp = { version = "0.9.1", default-features = false, features = ["alloc", "log", "medium-ethernet", "medium-ip", "proto-dhcpv4", "proto-ipv4", "proto-igmp", "socket-icmp", "socket-udp", "socket-tcp", "socket-raw", "socket-dhcpv4"] }
spin = "0.9.4"
diff --git a/kernel/comps/network/Cargo.toml b/kernel/comps/network/Cargo.toml
--- a/kernel/comps/network/Cargo.toml
+++ b/kernel/comps/network/Cargo.toml
@@ -15,7 +15,6 @@ component = { path = "../../libs/comp-sys/component" }
int-to-c-enum = { path = "../../libs/int-to-c-enum" }
log = "0.4"
ostd = { path = "../../../ostd" }
-pod = { git = "https://github.com/asterinas/pod", rev = "d7dba56" }
ringbuf = { version = "0.3.2", default-features = false, features = ["alloc"] }
smoltcp = { version = "0.9.1", default-features = false, features = ["alloc", "log", "medium-ethernet", "medium-ip", "proto-dhcpv4", "proto-ipv4", "proto-igmp", "socket-icmp", "socket-udp", "socket-tcp", "socket-raw", "socket-dhcpv4"] }
spin = "0.9.4"
diff --git a/kernel/comps/network/src/buffer.rs b/kernel/comps/network/src/buffer.rs
--- a/kernel/comps/network/src/buffer.rs
+++ b/kernel/comps/network/src/buffer.rs
@@ -8,8 +8,8 @@ use ostd::{
Daddr, DmaDirection, DmaStream, FrameAllocOptions, HasDaddr, VmReader, VmWriter, PAGE_SIZE,
},
sync::SpinLock,
+ Pod,
};
-use pod::Pod;
use spin::Once;
use crate::dma_pool::{DmaPool, DmaSegment};
diff --git a/kernel/comps/network/src/buffer.rs b/kernel/comps/network/src/buffer.rs
--- a/kernel/comps/network/src/buffer.rs
+++ b/kernel/comps/network/src/buffer.rs
@@ -8,8 +8,8 @@ use ostd::{
Daddr, DmaDirection, DmaStream, FrameAllocOptions, HasDaddr, VmReader, VmWriter, PAGE_SIZE,
},
sync::SpinLock,
+ Pod,
};
-use pod::Pod;
use spin::Once;
use crate::dma_pool::{DmaPool, DmaSegment};
diff --git a/kernel/comps/network/src/lib.rs b/kernel/comps/network/src/lib.rs
--- a/kernel/comps/network/src/lib.rs
+++ b/kernel/comps/network/src/lib.rs
@@ -15,11 +15,10 @@ extern crate alloc;
use alloc::{collections::BTreeMap, string::String, sync::Arc, vec::Vec};
use core::{any::Any, fmt::Debug};
-use aster_util::safe_ptr::Pod;
pub use buffer::{RxBuffer, TxBuffer, RX_BUFFER_POOL, TX_BUFFER_POOL};
use component::{init_component, ComponentInitError};
pub use dma_pool::DmaSegment;
-use ostd::sync::SpinLock;
+use ostd::{sync::SpinLock, Pod};
use smoltcp::phy;
use spin::Once;
diff --git a/kernel/comps/network/src/lib.rs b/kernel/comps/network/src/lib.rs
--- a/kernel/comps/network/src/lib.rs
+++ b/kernel/comps/network/src/lib.rs
@@ -15,11 +15,10 @@ extern crate alloc;
use alloc::{collections::BTreeMap, string::String, sync::Arc, vec::Vec};
use core::{any::Any, fmt::Debug};
-use aster_util::safe_ptr::Pod;
pub use buffer::{RxBuffer, TxBuffer, RX_BUFFER_POOL, TX_BUFFER_POOL};
use component::{init_component, ComponentInitError};
pub use dma_pool::DmaSegment;
-use ostd::sync::SpinLock;
+use ostd::{sync::SpinLock, Pod};
use smoltcp::phy;
use spin::Once;
diff --git a/kernel/comps/virtio/Cargo.toml b/kernel/comps/virtio/Cargo.toml
--- a/kernel/comps/virtio/Cargo.toml
+++ b/kernel/comps/virtio/Cargo.toml
@@ -19,7 +19,6 @@ aster-rights = { path = "../../libs/aster-rights" }
id-alloc = { path = "../../../ostd/libs/id-alloc" }
typeflags-util = { path = "../../libs/typeflags-util" }
ostd = { path = "../../../ostd" }
-pod = { git = "https://github.com/asterinas/pod", rev = "d7dba56" }
component = { path = "../../libs/comp-sys/component" }
log = "0.4"
bit_field = "0.10.1"
diff --git a/kernel/comps/virtio/Cargo.toml b/kernel/comps/virtio/Cargo.toml
--- a/kernel/comps/virtio/Cargo.toml
+++ b/kernel/comps/virtio/Cargo.toml
@@ -19,7 +19,6 @@ aster-rights = { path = "../../libs/aster-rights" }
id-alloc = { path = "../../../ostd/libs/id-alloc" }
typeflags-util = { path = "../../libs/typeflags-util" }
ostd = { path = "../../../ostd" }
-pod = { git = "https://github.com/asterinas/pod", rev = "d7dba56" }
component = { path = "../../libs/comp-sys/component" }
log = "0.4"
bit_field = "0.10.1"
diff --git a/kernel/comps/virtio/src/device/block/device.rs b/kernel/comps/virtio/src/device/block/device.rs
--- a/kernel/comps/virtio/src/device/block/device.rs
+++ b/kernel/comps/virtio/src/device/block/device.rs
@@ -15,8 +15,8 @@ use ostd::{
mm::{DmaDirection, DmaStream, DmaStreamSlice, FrameAllocOptions, VmIo},
sync::SpinLock,
trap::TrapFrame,
+ Pod,
};
-use pod::Pod;
use super::{BlockFeatures, VirtioBlockConfig};
use crate::{
diff --git a/kernel/comps/virtio/src/device/block/device.rs b/kernel/comps/virtio/src/device/block/device.rs
--- a/kernel/comps/virtio/src/device/block/device.rs
+++ b/kernel/comps/virtio/src/device/block/device.rs
@@ -15,8 +15,8 @@ use ostd::{
mm::{DmaDirection, DmaStream, DmaStreamSlice, FrameAllocOptions, VmIo},
sync::SpinLock,
trap::TrapFrame,
+ Pod,
};
-use pod::Pod;
use super::{BlockFeatures, VirtioBlockConfig};
use crate::{
diff --git a/kernel/comps/virtio/src/device/block/mod.rs b/kernel/comps/virtio/src/device/block/mod.rs
--- a/kernel/comps/virtio/src/device/block/mod.rs
+++ b/kernel/comps/virtio/src/device/block/mod.rs
@@ -5,8 +5,7 @@ pub mod device;
use aster_util::safe_ptr::SafePtr;
use bitflags::bitflags;
use int_to_c_enum::TryFromInt;
-use ostd::io_mem::IoMem;
-use pod::Pod;
+use ostd::{io_mem::IoMem, Pod};
use crate::transport::VirtioTransport;
diff --git a/kernel/comps/virtio/src/device/block/mod.rs b/kernel/comps/virtio/src/device/block/mod.rs
--- a/kernel/comps/virtio/src/device/block/mod.rs
+++ b/kernel/comps/virtio/src/device/block/mod.rs
@@ -5,8 +5,7 @@ pub mod device;
use aster_util::safe_ptr::SafePtr;
use bitflags::bitflags;
use int_to_c_enum::TryFromInt;
-use ostd::io_mem::IoMem;
-use pod::Pod;
+use ostd::{io_mem::IoMem, Pod};
use crate::transport::VirtioTransport;
diff --git a/kernel/comps/virtio/src/device/console/config.rs b/kernel/comps/virtio/src/device/console/config.rs
--- a/kernel/comps/virtio/src/device/console/config.rs
+++ b/kernel/comps/virtio/src/device/console/config.rs
@@ -1,8 +1,7 @@
// SPDX-License-Identifier: MPL-2.0
use aster_util::safe_ptr::SafePtr;
-use ostd::io_mem::IoMem;
-use pod::Pod;
+use ostd::{io_mem::IoMem, Pod};
use crate::transport::VirtioTransport;
diff --git a/kernel/comps/virtio/src/device/console/config.rs b/kernel/comps/virtio/src/device/console/config.rs
--- a/kernel/comps/virtio/src/device/console/config.rs
+++ b/kernel/comps/virtio/src/device/console/config.rs
@@ -1,8 +1,7 @@
// SPDX-License-Identifier: MPL-2.0
use aster_util::safe_ptr::SafePtr;
-use ostd::io_mem::IoMem;
-use pod::Pod;
+use ostd::{io_mem::IoMem, Pod};
use crate::transport::VirtioTransport;
diff --git a/kernel/comps/virtio/src/device/input/mod.rs b/kernel/comps/virtio/src/device/input/mod.rs
--- a/kernel/comps/virtio/src/device/input/mod.rs
+++ b/kernel/comps/virtio/src/device/input/mod.rs
@@ -28,8 +28,7 @@
pub mod device;
use aster_util::safe_ptr::SafePtr;
-use ostd::io_mem::IoMem;
-use pod::Pod;
+use ostd::{io_mem::IoMem, Pod};
use crate::transport::VirtioTransport;
diff --git a/kernel/comps/virtio/src/device/input/mod.rs b/kernel/comps/virtio/src/device/input/mod.rs
--- a/kernel/comps/virtio/src/device/input/mod.rs
+++ b/kernel/comps/virtio/src/device/input/mod.rs
@@ -28,8 +28,7 @@
pub mod device;
use aster_util::safe_ptr::SafePtr;
-use ostd::io_mem::IoMem;
-use pod::Pod;
+use ostd::{io_mem::IoMem, Pod};
use crate::transport::VirtioTransport;
diff --git a/kernel/comps/virtio/src/device/network/config.rs b/kernel/comps/virtio/src/device/network/config.rs
--- a/kernel/comps/virtio/src/device/network/config.rs
+++ b/kernel/comps/virtio/src/device/network/config.rs
@@ -3,8 +3,7 @@
use aster_network::EthernetAddr;
use aster_util::safe_ptr::SafePtr;
use bitflags::bitflags;
-use ostd::io_mem::IoMem;
-use pod::Pod;
+use ostd::{io_mem::IoMem, Pod};
use crate::transport::VirtioTransport;
diff --git a/kernel/comps/virtio/src/device/network/config.rs b/kernel/comps/virtio/src/device/network/config.rs
--- a/kernel/comps/virtio/src/device/network/config.rs
+++ b/kernel/comps/virtio/src/device/network/config.rs
@@ -3,8 +3,7 @@
use aster_network::EthernetAddr;
use aster_util::safe_ptr::SafePtr;
use bitflags::bitflags;
-use ostd::io_mem::IoMem;
-use pod::Pod;
+use ostd::{io_mem::IoMem, Pod};
use crate::transport::VirtioTransport;
diff --git a/kernel/comps/virtio/src/device/network/header.rs b/kernel/comps/virtio/src/device/network/header.rs
--- a/kernel/comps/virtio/src/device/network/header.rs
+++ b/kernel/comps/virtio/src/device/network/header.rs
@@ -2,7 +2,7 @@
use bitflags::bitflags;
use int_to_c_enum::TryFromInt;
-use pod::Pod;
+use ostd::Pod;
pub const VIRTIO_NET_HDR_LEN: usize = core::mem::size_of::<VirtioNetHdr>();
diff --git a/kernel/comps/virtio/src/device/network/header.rs b/kernel/comps/virtio/src/device/network/header.rs
--- a/kernel/comps/virtio/src/device/network/header.rs
+++ b/kernel/comps/virtio/src/device/network/header.rs
@@ -2,7 +2,7 @@
use bitflags::bitflags;
use int_to_c_enum::TryFromInt;
-use pod::Pod;
+use ostd::Pod;
pub const VIRTIO_NET_HDR_LEN: usize = core::mem::size_of::<VirtioNetHdr>();
diff --git a/kernel/comps/virtio/src/device/socket/config.rs b/kernel/comps/virtio/src/device/socket/config.rs
--- a/kernel/comps/virtio/src/device/socket/config.rs
+++ b/kernel/comps/virtio/src/device/socket/config.rs
@@ -2,8 +2,7 @@
use aster_util::safe_ptr::SafePtr;
use bitflags::bitflags;
-use ostd::io_mem::IoMem;
-use pod::Pod;
+use ostd::{io_mem::IoMem, Pod};
use crate::transport::VirtioTransport;
diff --git a/kernel/comps/virtio/src/device/socket/config.rs b/kernel/comps/virtio/src/device/socket/config.rs
--- a/kernel/comps/virtio/src/device/socket/config.rs
+++ b/kernel/comps/virtio/src/device/socket/config.rs
@@ -2,8 +2,7 @@
use aster_util::safe_ptr::SafePtr;
use bitflags::bitflags;
-use ostd::io_mem::IoMem;
-use pod::Pod;
+use ostd::{io_mem::IoMem, Pod};
use crate::transport::VirtioTransport;
diff --git a/kernel/comps/virtio/src/device/socket/device.rs b/kernel/comps/virtio/src/device/socket/device.rs
--- a/kernel/comps/virtio/src/device/socket/device.rs
+++ b/kernel/comps/virtio/src/device/socket/device.rs
@@ -6,8 +6,7 @@ use core::{fmt::Debug, hint::spin_loop, mem::size_of};
use aster_network::{RxBuffer, TxBuffer};
use aster_util::{field_ptr, slot_vec::SlotVec};
use log::debug;
-use ostd::{mm::VmWriter, offset_of, sync::SpinLock, trap::TrapFrame};
-use pod::Pod;
+use ostd::{mm::VmWriter, offset_of, sync::SpinLock, trap::TrapFrame, Pod};
use super::{
config::{VirtioVsockConfig, VsockFeatures},
diff --git a/kernel/comps/virtio/src/device/socket/device.rs b/kernel/comps/virtio/src/device/socket/device.rs
--- a/kernel/comps/virtio/src/device/socket/device.rs
+++ b/kernel/comps/virtio/src/device/socket/device.rs
@@ -6,8 +6,7 @@ use core::{fmt::Debug, hint::spin_loop, mem::size_of};
use aster_network::{RxBuffer, TxBuffer};
use aster_util::{field_ptr, slot_vec::SlotVec};
use log::debug;
-use ostd::{mm::VmWriter, offset_of, sync::SpinLock, trap::TrapFrame};
-use pod::Pod;
+use ostd::{mm::VmWriter, offset_of, sync::SpinLock, trap::TrapFrame, Pod};
use super::{
config::{VirtioVsockConfig, VsockFeatures},
diff --git a/kernel/comps/virtio/src/device/socket/header.rs b/kernel/comps/virtio/src/device/socket/header.rs
--- a/kernel/comps/virtio/src/device/socket/header.rs
+++ b/kernel/comps/virtio/src/device/socket/header.rs
@@ -27,7 +27,7 @@
//
use bitflags::bitflags;
use int_to_c_enum::TryFromInt;
-use pod::Pod;
+use ostd::Pod;
use super::error::{self, SocketError};
diff --git a/kernel/comps/virtio/src/device/socket/header.rs b/kernel/comps/virtio/src/device/socket/header.rs
--- a/kernel/comps/virtio/src/device/socket/header.rs
+++ b/kernel/comps/virtio/src/device/socket/header.rs
@@ -27,7 +27,7 @@
//
use bitflags::bitflags;
use int_to_c_enum::TryFromInt;
-use pod::Pod;
+use ostd::Pod;
use super::error::{self, SocketError};
diff --git a/kernel/comps/virtio/src/queue.rs b/kernel/comps/virtio/src/queue.rs
--- a/kernel/comps/virtio/src/queue.rs
+++ b/kernel/comps/virtio/src/queue.rs
@@ -15,9 +15,8 @@ use log::debug;
use ostd::{
io_mem::IoMem,
mm::{DmaCoherent, FrameAllocOptions},
- offset_of,
+ offset_of, Pod,
};
-use pod::Pod;
use crate::{dma_buf::DmaBuf, transport::VirtioTransport};
diff --git a/kernel/comps/virtio/src/queue.rs b/kernel/comps/virtio/src/queue.rs
--- a/kernel/comps/virtio/src/queue.rs
+++ b/kernel/comps/virtio/src/queue.rs
@@ -15,9 +15,8 @@ use log::debug;
use ostd::{
io_mem::IoMem,
mm::{DmaCoherent, FrameAllocOptions},
- offset_of,
+ offset_of, Pod,
};
-use pod::Pod;
use crate::{dma_buf::DmaBuf, transport::VirtioTransport};
diff --git a/kernel/comps/virtio/src/transport/mmio/layout.rs b/kernel/comps/virtio/src/transport/mmio/layout.rs
--- a/kernel/comps/virtio/src/transport/mmio/layout.rs
+++ b/kernel/comps/virtio/src/transport/mmio/layout.rs
@@ -2,7 +2,7 @@
use core::fmt::Debug;
-use pod::Pod;
+use ostd::Pod;
#[derive(Clone, Copy, Pod)]
#[repr(C)]
diff --git a/kernel/comps/virtio/src/transport/mmio/layout.rs b/kernel/comps/virtio/src/transport/mmio/layout.rs
--- a/kernel/comps/virtio/src/transport/mmio/layout.rs
+++ b/kernel/comps/virtio/src/transport/mmio/layout.rs
@@ -2,7 +2,7 @@
use core::fmt::Debug;
-use pod::Pod;
+use ostd::Pod;
#[derive(Clone, Copy, Pod)]
#[repr(C)]
diff --git a/kernel/comps/virtio/src/transport/pci/common_cfg.rs b/kernel/comps/virtio/src/transport/pci/common_cfg.rs
--- a/kernel/comps/virtio/src/transport/pci/common_cfg.rs
+++ b/kernel/comps/virtio/src/transport/pci/common_cfg.rs
@@ -1,8 +1,7 @@
// SPDX-License-Identifier: MPL-2.0
use aster_util::safe_ptr::SafePtr;
-use ostd::io_mem::IoMem;
-use pod::Pod;
+use ostd::{io_mem::IoMem, Pod};
use super::capability::VirtioPciCapabilityData;
use crate::transport::pci::capability::VirtioPciCpabilityType;
diff --git a/kernel/comps/virtio/src/transport/pci/common_cfg.rs b/kernel/comps/virtio/src/transport/pci/common_cfg.rs
--- a/kernel/comps/virtio/src/transport/pci/common_cfg.rs
+++ b/kernel/comps/virtio/src/transport/pci/common_cfg.rs
@@ -1,8 +1,7 @@
// SPDX-License-Identifier: MPL-2.0
use aster_util::safe_ptr::SafePtr;
-use ostd::io_mem::IoMem;
-use pod::Pod;
+use ostd::{io_mem::IoMem, Pod};
use super::capability::VirtioPciCapabilityData;
use crate::transport::pci::capability::VirtioPciCpabilityType;
diff --git a/kernel/libs/aster-util/Cargo.toml b/kernel/libs/aster-util/Cargo.toml
--- a/kernel/libs/aster-util/Cargo.toml
+++ b/kernel/libs/aster-util/Cargo.toml
@@ -7,7 +7,6 @@ edition = "2021"
[dependencies]
ostd = { path = "../../../ostd" }
-pod = { git = "https://github.com/asterinas/pod", rev = "d7dba56" }
typeflags-util = { path = "../typeflags-util" }
aster-rights-proc = { path = "../aster-rights-proc" }
aster-rights = { path = "../aster-rights" }
diff --git a/kernel/libs/aster-util/Cargo.toml b/kernel/libs/aster-util/Cargo.toml
--- a/kernel/libs/aster-util/Cargo.toml
+++ b/kernel/libs/aster-util/Cargo.toml
@@ -7,7 +7,6 @@ edition = "2021"
[dependencies]
ostd = { path = "../../../ostd" }
-pod = { git = "https://github.com/asterinas/pod", rev = "d7dba56" }
typeflags-util = { path = "../typeflags-util" }
aster-rights-proc = { path = "../aster-rights-proc" }
aster-rights = { path = "../aster-rights" }
diff --git a/kernel/libs/aster-util/src/safe_ptr.rs b/kernel/libs/aster-util/src/safe_ptr.rs
--- a/kernel/libs/aster-util/src/safe_ptr.rs
+++ b/kernel/libs/aster-util/src/safe_ptr.rs
@@ -5,11 +5,11 @@ use core::{fmt::Debug, marker::PhantomData};
use aster_rights::{Dup, Exec, Full, Read, Signal, TRightSet, TRights, Write};
use aster_rights_proc::require;
use inherit_methods_macro::inherit_methods;
+pub use ostd::Pod;
use ostd::{
mm::{Daddr, DmaStream, HasDaddr, HasPaddr, Paddr, VmIo},
Result,
};
-pub use pod::Pod;
pub use typeflags_util::SetContain;
/// Safe pointers.
diff --git a/kernel/libs/aster-util/src/safe_ptr.rs b/kernel/libs/aster-util/src/safe_ptr.rs
--- a/kernel/libs/aster-util/src/safe_ptr.rs
+++ b/kernel/libs/aster-util/src/safe_ptr.rs
@@ -5,11 +5,11 @@ use core::{fmt::Debug, marker::PhantomData};
use aster_rights::{Dup, Exec, Full, Read, Signal, TRightSet, TRights, Write};
use aster_rights_proc::require;
use inherit_methods_macro::inherit_methods;
+pub use ostd::Pod;
use ostd::{
mm::{Daddr, DmaStream, HasDaddr, HasPaddr, Paddr, VmIo},
Result,
};
-pub use pod::Pod;
pub use typeflags_util::SetContain;
/// Safe pointers.
diff --git a/kernel/libs/aster-util/src/union_read_ptr.rs b/kernel/libs/aster-util/src/union_read_ptr.rs
--- a/kernel/libs/aster-util/src/union_read_ptr.rs
+++ b/kernel/libs/aster-util/src/union_read_ptr.rs
@@ -2,7 +2,7 @@
use core::marker::PhantomData;
-use pod::Pod;
+use ostd::Pod;
/// This ptr is designed to read union field safely.
/// Write to union field is safe operation. While reading union field is UB.
diff --git a/kernel/libs/aster-util/src/union_read_ptr.rs b/kernel/libs/aster-util/src/union_read_ptr.rs
--- a/kernel/libs/aster-util/src/union_read_ptr.rs
+++ b/kernel/libs/aster-util/src/union_read_ptr.rs
@@ -2,7 +2,7 @@
use core::marker::PhantomData;
-use pod::Pod;
+use ostd::Pod;
/// This ptr is designed to read union field safely.
/// Write to union field is safe operation. While reading union field is UB.
diff --git a/kernel/libs/int-to-c-enum/Cargo.toml b/kernel/libs/int-to-c-enum/Cargo.toml
--- a/kernel/libs/int-to-c-enum/Cargo.toml
+++ b/kernel/libs/int-to-c-enum/Cargo.toml
@@ -2,11 +2,15 @@
name = "int-to-c-enum"
version = "0.1.0"
edition = "2021"
+license = "MPL-2.0"
+readme = "README.md"
+description = "TryFromInt - A convenient derive macro for converting an integer to an enum"
+repository = "https://github.com/asterinas/asterinas"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
-int-to-c-enum-derive = { path = "derive", optional = true }
+int-to-c-enum-derive = { path = "derive", optional = true, version = "0.1.0"}
[features]
default = ["derive"]
diff --git a/kernel/libs/int-to-c-enum/Cargo.toml b/kernel/libs/int-to-c-enum/Cargo.toml
--- a/kernel/libs/int-to-c-enum/Cargo.toml
+++ b/kernel/libs/int-to-c-enum/Cargo.toml
@@ -2,11 +2,15 @@
name = "int-to-c-enum"
version = "0.1.0"
edition = "2021"
+license = "MPL-2.0"
+readme = "README.md"
+description = "TryFromInt - A convenient derive macro for converting an integer to an enum"
+repository = "https://github.com/asterinas/asterinas"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
-int-to-c-enum-derive = { path = "derive", optional = true }
+int-to-c-enum-derive = { path = "derive", optional = true, version = "0.1.0"}
[features]
default = ["derive"]
diff --git a/kernel/libs/int-to-c-enum/derive/Cargo.toml b/kernel/libs/int-to-c-enum/derive/Cargo.toml
--- a/kernel/libs/int-to-c-enum/derive/Cargo.toml
+++ b/kernel/libs/int-to-c-enum/derive/Cargo.toml
@@ -2,6 +2,9 @@
name = "int-to-c-enum-derive"
version = "0.1.0"
edition = "2021"
+license = "MPL-2.0"
+description = "int-to-c-enum's proc macros"
+repository = "https://github.com/asterinas/asterinas"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
diff --git a/kernel/libs/int-to-c-enum/derive/Cargo.toml b/kernel/libs/int-to-c-enum/derive/Cargo.toml
--- a/kernel/libs/int-to-c-enum/derive/Cargo.toml
+++ b/kernel/libs/int-to-c-enum/derive/Cargo.toml
@@ -2,6 +2,9 @@
name = "int-to-c-enum-derive"
version = "0.1.0"
edition = "2021"
+license = "MPL-2.0"
+description = "int-to-c-enum's proc macros"
+repository = "https://github.com/asterinas/asterinas"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
diff --git a/osdk/src/commands/build/bin.rs b/osdk/src/commands/build/bin.rs
--- a/osdk/src/commands/build/bin.rs
+++ b/osdk/src/commands/build/bin.rs
@@ -157,10 +157,9 @@ fn install_setup_with_arch(
cmd.arg("install").arg("linux-bzimage-setup");
cmd.arg("--force");
cmd.arg("--root").arg(install_dir.as_ref());
- cmd.arg("--git").arg(crate::util::ASTER_GIT_LINK);
- // FIXME: Uses a fixed tag instaed of relies on remote branch
- cmd.arg("--tag").arg("v0.5.1");
- // cmd.arg("--tag").arg(crate::util::ASTER_GIT_TAG);
+ // Remember to upgrade this version if new version of linux-bzimage-setup is released.
+ const LINUX_BZIMAGE_SETUP_VERSION: &str = "0.1.0";
+ cmd.arg("--version").arg(LINUX_BZIMAGE_SETUP_VERSION);
cmd.arg("--target").arg(match arch {
SetupInstallArch::X86_64 => "x86_64-unknown-none",
SetupInstallArch::Other(path) => path.to_str().unwrap(),
diff --git a/osdk/src/commands/build/bin.rs b/osdk/src/commands/build/bin.rs
--- a/osdk/src/commands/build/bin.rs
+++ b/osdk/src/commands/build/bin.rs
@@ -157,10 +157,9 @@ fn install_setup_with_arch(
cmd.arg("install").arg("linux-bzimage-setup");
cmd.arg("--force");
cmd.arg("--root").arg(install_dir.as_ref());
- cmd.arg("--git").arg(crate::util::ASTER_GIT_LINK);
- // FIXME: Uses a fixed tag instaed of relies on remote branch
- cmd.arg("--tag").arg("v0.5.1");
- // cmd.arg("--tag").arg(crate::util::ASTER_GIT_TAG);
+ // Remember to upgrade this version if new version of linux-bzimage-setup is released.
+ const LINUX_BZIMAGE_SETUP_VERSION: &str = "0.1.0";
+ cmd.arg("--version").arg(LINUX_BZIMAGE_SETUP_VERSION);
cmd.arg("--target").arg(match arch {
SetupInstallArch::X86_64 => "x86_64-unknown-none",
SetupInstallArch::Other(path) => path.to_str().unwrap(),
diff --git a/osdk/src/commands/new/mod.rs b/osdk/src/commands/new/mod.rs
--- a/osdk/src/commands/new/mod.rs
+++ b/osdk/src/commands/new/mod.rs
@@ -7,7 +7,7 @@ use crate::{
config::manifest::ProjectType,
error::Errno,
error_msg,
- util::{aster_crate_dep, cargo_new_lib, get_cargo_metadata},
+ util::{cargo_new_lib, get_cargo_metadata, ostd_dep},
};
pub fn execute_new_command(args: &NewArgs) {
diff --git a/osdk/src/commands/new/mod.rs b/osdk/src/commands/new/mod.rs
--- a/osdk/src/commands/new/mod.rs
+++ b/osdk/src/commands/new/mod.rs
@@ -7,7 +7,7 @@ use crate::{
config::manifest::ProjectType,
error::Errno,
error_msg,
- util::{aster_crate_dep, cargo_new_lib, get_cargo_metadata},
+ util::{cargo_new_lib, get_cargo_metadata, ostd_dep},
};
pub fn execute_new_command(args: &NewArgs) {
diff --git a/osdk/src/commands/new/mod.rs b/osdk/src/commands/new/mod.rs
--- a/osdk/src/commands/new/mod.rs
+++ b/osdk/src/commands/new/mod.rs
@@ -40,7 +40,7 @@ fn add_manifest_dependencies(cargo_metadata: &serde_json::Value, crate_name: &st
let dependencies = manifest.get_mut("dependencies").unwrap();
- let ostd_dep = toml::Table::from_str(&aster_crate_dep("ostd")).unwrap();
+ let ostd_dep = toml::Table::from_str(&ostd_dep()).unwrap();
dependencies.as_table_mut().unwrap().extend(ostd_dep);
let content = toml::to_string(&manifest).unwrap();
diff --git a/osdk/src/commands/new/mod.rs b/osdk/src/commands/new/mod.rs
--- a/osdk/src/commands/new/mod.rs
+++ b/osdk/src/commands/new/mod.rs
@@ -40,7 +40,7 @@ fn add_manifest_dependencies(cargo_metadata: &serde_json::Value, crate_name: &st
let dependencies = manifest.get_mut("dependencies").unwrap();
- let ostd_dep = toml::Table::from_str(&aster_crate_dep("ostd")).unwrap();
+ let ostd_dep = toml::Table::from_str(&ostd_dep()).unwrap();
dependencies.as_table_mut().unwrap().extend(ostd_dep);
let content = toml::to_string(&manifest).unwrap();
diff --git a/osdk/src/util.rs b/osdk/src/util.rs
--- a/osdk/src/util.rs
+++ b/osdk/src/util.rs
@@ -12,18 +12,12 @@ use crate::{error::Errno, error_msg};
use quote::ToTokens;
-/// FIXME: We should publish the asterinas crates to a public registry
-/// and use the published version in the generated Cargo.toml.
-pub const ASTER_GIT_LINK: &str = "https://github.com/asterinas/asterinas";
-/// Make sure it syncs with the builder dependency in Cargo.toml.
-/// We cannot use `include_str!("../../VERSION")` here
-/// because `cargo publish` does not allow using files outside of the crate directory.
-pub const ASTER_GIT_TAG: &str = concat!("v", env!("CARGO_PKG_VERSION"));
-pub fn aster_crate_dep(crate_name: &str) -> String {
- format!(
- "{} = {{ git = \"{}\", tag = \"{}\" }}",
- crate_name, ASTER_GIT_LINK, ASTER_GIT_TAG
- )
+/// The version of OSTD on crates.io.
+///
+/// OSTD shares the same version with OSDK, so just use the version of OSDK here.
+pub const OSTD_VERSION: &str = env!("CARGO_PKG_VERSION");
+pub fn ostd_dep() -> String {
+ format!("ostd = {{ version = \"{}\" }}", OSTD_VERSION)
}
fn cargo() -> Command {
diff --git a/osdk/src/util.rs b/osdk/src/util.rs
--- a/osdk/src/util.rs
+++ b/osdk/src/util.rs
@@ -12,18 +12,12 @@ use crate::{error::Errno, error_msg};
use quote::ToTokens;
-/// FIXME: We should publish the asterinas crates to a public registry
-/// and use the published version in the generated Cargo.toml.
-pub const ASTER_GIT_LINK: &str = "https://github.com/asterinas/asterinas";
-/// Make sure it syncs with the builder dependency in Cargo.toml.
-/// We cannot use `include_str!("../../VERSION")` here
-/// because `cargo publish` does not allow using files outside of the crate directory.
-pub const ASTER_GIT_TAG: &str = concat!("v", env!("CARGO_PKG_VERSION"));
-pub fn aster_crate_dep(crate_name: &str) -> String {
- format!(
- "{} = {{ git = \"{}\", tag = \"{}\" }}",
- crate_name, ASTER_GIT_LINK, ASTER_GIT_TAG
- )
+/// The version of OSTD on crates.io.
+///
+/// OSTD shares the same version with OSDK, so just use the version of OSDK here.
+pub const OSTD_VERSION: &str = env!("CARGO_PKG_VERSION");
+pub fn ostd_dep() -> String {
+ format!("ostd = {{ version = \"{}\" }}", OSTD_VERSION)
}
fn cargo() -> Command {
diff --git a/osdk/tests/util/mod.rs b/osdk/tests/util/mod.rs
--- a/osdk/tests/util/mod.rs
+++ b/osdk/tests/util/mod.rs
@@ -88,7 +88,7 @@ pub fn add_member_to_workspace(workspace: impl AsRef<Path>, new_member: &str) {
}
/// Makes crates created by `cargo ostd new` depends on ostd locally,
-/// instead of ostd from local branch.
+/// instead of ostd from remote source(git repo/crates.io).
///
/// Each crate created by `cargo ostd new` should add this patch.
pub fn depends_on_local_ostd(manifest_path: impl AsRef<Path>) {
diff --git a/ostd/Cargo.toml b/ostd/Cargo.toml
--- a/ostd/Cargo.toml
+++ b/ostd/Cargo.toml
@@ -2,41 +2,48 @@
name = "ostd"
version = "0.6.2"
edition = "2021"
+description = "Rust OS framework that facilitates the development of and innovation in OS kernels"
+license = "MPL-2.0"
+readme = "README.md"
+repository = "https://github.com/asterinas/asterinas"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+# Settings for publishing docs in docs.rs
+[package.metadata.docs.rs]
+default-target = "x86_64-unknown-none"
+targets = ["x86_64-unknown-none"]
+
[dependencies]
-align_ext = { path = "libs/align_ext" }
-ostd-macros = { path = "libs/ostd-macros" }
+align_ext = { path = "libs/align_ext", version = "0.1.0" }
+array-init = "2.0"
bit_field = "0.10.1"
+buddy_system_allocator = "0.9.0"
bitflags = "1.3"
bitvec = { version = "1.0", default-features = false, features = ["alloc"] }
-linux-boot-params = { path = "libs/linux-bzimage/boot-params" }
-buddy_system_allocator = "0.9.0"
cfg-if = "1.0"
gimli = { version = "0.28", default-features = false, features = ["read-core"] }
-inherit-methods-macro = { git = "https://github.com/asterinas/inherit-methods-macro", rev = "98f7e3e" }
-xarray = { git = "https://github.com/asterinas/xarray", rev = "72a4067" }
-int-to-c-enum = { path = "../kernel/libs/int-to-c-enum" }
-# instrusive-collections of version 0.9.6 fails to compile with current rust toolchain,
-# So we set a fixed version 0.9.5 for this crate
-intrusive-collections = { version = "=0.9.5", features = ["nightly"] }
-array-init = "2.0"
-ktest = { path = "libs/ktest" }
-id-alloc = { path = "libs/id-alloc" }
+id-alloc = { path = "libs/id-alloc", version = "0.1.0" }
+inherit-methods-macro = { git = "https://github.com/asterinas/inherit-methods-macro", rev = "98f7e3e", version = "0.1.0" }
+int-to-c-enum = { path = "../kernel/libs/int-to-c-enum", version = "0.1.0" }
+intrusive-collections = { version = "0.9.6", features = ["nightly"] }
lazy_static = { version = "1.0", features = ["spin_no_std"] }
+linux-boot-params = { path = "libs/linux-bzimage/boot-params", version = "0.1.0" }
log = "0.4"
num = { version = "0.4", default-features = false }
num-derive = { version = "0.4", default-features = false }
num-traits = { version = "0.2", default-features = false }
-pod = { git = "https://github.com/asterinas/pod", rev = "d7dba56" }
+ostd-macros = { path = "libs/ostd-macros", version = "0.1.4" }
+ostd-test = { path = "libs/ostd-test", version = "0.1.0" }
+owo-colors = { version = "3", optional = true }
+ostd-pod = { git = "https://github.com/asterinas/ostd-pod", rev = "c4644be", version = "0.1.1" }
spin = "0.9.4"
static_assertions = "1.1.0"
tdx-guest = { version = "0.1.5", optional = true }
-trapframe = { git = "https://github.com/asterinas/trapframe-rs", rev = "4739428" }
+trapframe = "0.10.0"
unwinding = { version = "0.2.2", default-features = false, features = ["fde-gnu-eh-frame-hdr", "hide-trace", "panic", "personality", "unwinder"] }
volatile = { version = "0.4.5", features = ["unstable"] }
-owo-colors = { version = "3", optional = true }
+xarray = { git = "https://github.com/asterinas/xarray", rev = "72a4067", version = "0.1.0" }
[target.x86_64-unknown-none.dependencies]
x86_64 = "0.14.2"
diff --git a/ostd/README.md b/ostd/README.md
--- a/ostd/README.md
+++ b/ostd/README.md
@@ -18,12 +18,4 @@ Asterinas OSTD offers the following key values.
## OSTD APIs
-TODO
-
-## Implementation status
-
-TODO
-
-## Roadmap and plan
-
-TODO
\ No newline at end of file
+See [API docs](https://docs.rs/ostd/latest/ostd).
diff --git a/ostd/libs/id-alloc/Cargo.toml b/ostd/libs/id-alloc/Cargo.toml
--- a/ostd/libs/id-alloc/Cargo.toml
+++ b/ostd/libs/id-alloc/Cargo.toml
@@ -2,6 +2,9 @@
name = "id-alloc"
version = "0.1.0"
edition = "2021"
+license = "MPL-2.0"
+description = "An id allocator implemented by the bitmap"
+repository = "https://github.com/asterinas/asterinas"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
diff --git a/ostd/libs/id-alloc/Cargo.toml b/ostd/libs/id-alloc/Cargo.toml
--- a/ostd/libs/id-alloc/Cargo.toml
+++ b/ostd/libs/id-alloc/Cargo.toml
@@ -2,6 +2,9 @@
name = "id-alloc"
version = "0.1.0"
edition = "2021"
+license = "MPL-2.0"
+description = "An id allocator implemented by the bitmap"
+repository = "https://github.com/asterinas/asterinas"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
diff --git a/ostd/libs/linux-bzimage/boot-params/Cargo.toml b/ostd/libs/linux-bzimage/boot-params/Cargo.toml
--- a/ostd/libs/linux-bzimage/boot-params/Cargo.toml
+++ b/ostd/libs/linux-bzimage/boot-params/Cargo.toml
@@ -2,6 +2,9 @@
name = "linux-boot-params"
version = "0.1.0"
edition = "2021"
+description = "The Boot Parameters for Linux Boot Protocol"
+license = "MPL-2.0"
+repository = "https://github.com/asterinas/asterinas"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
diff --git a/ostd/libs/linux-bzimage/boot-params/Cargo.toml b/ostd/libs/linux-bzimage/boot-params/Cargo.toml
--- a/ostd/libs/linux-bzimage/boot-params/Cargo.toml
+++ b/ostd/libs/linux-bzimage/boot-params/Cargo.toml
@@ -2,6 +2,9 @@
name = "linux-boot-params"
version = "0.1.0"
edition = "2021"
+description = "The Boot Parameters for Linux Boot Protocol"
+license = "MPL-2.0"
+repository = "https://github.com/asterinas/asterinas"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
diff --git a/ostd/libs/linux-bzimage/setup/Cargo.toml b/ostd/libs/linux-bzimage/setup/Cargo.toml
--- a/ostd/libs/linux-bzimage/setup/Cargo.toml
+++ b/ostd/libs/linux-bzimage/setup/Cargo.toml
@@ -2,6 +2,9 @@
name = "linux-bzimage-setup"
version = "0.1.0"
edition = "2021"
+description = "The linux bzImage setup binary"
+license = "MPL-2.0"
+repository = "https://github.com/asterinas/asterinas"
[[bin]]
name = "linux-bzimage-setup"
diff --git a/ostd/libs/linux-bzimage/setup/Cargo.toml b/ostd/libs/linux-bzimage/setup/Cargo.toml
--- a/ostd/libs/linux-bzimage/setup/Cargo.toml
+++ b/ostd/libs/linux-bzimage/setup/Cargo.toml
@@ -2,6 +2,9 @@
name = "linux-bzimage-setup"
version = "0.1.0"
edition = "2021"
+description = "The linux bzImage setup binary"
+license = "MPL-2.0"
+repository = "https://github.com/asterinas/asterinas"
[[bin]]
name = "linux-bzimage-setup"
diff --git a/ostd/libs/linux-bzimage/setup/Cargo.toml b/ostd/libs/linux-bzimage/setup/Cargo.toml
--- a/ostd/libs/linux-bzimage/setup/Cargo.toml
+++ b/ostd/libs/linux-bzimage/setup/Cargo.toml
@@ -11,7 +14,7 @@ path = "src/main.rs"
[dependencies]
cfg-if = "1.0.0"
-linux-boot-params = { path = "../boot-params" }
+linux-boot-params = { path = "../boot-params", version = "0.1.0" }
uart_16550 = "0.3.0"
xmas-elf = "0.8.0"
diff --git a/ostd/libs/linux-bzimage/setup/Cargo.toml b/ostd/libs/linux-bzimage/setup/Cargo.toml
--- a/ostd/libs/linux-bzimage/setup/Cargo.toml
+++ b/ostd/libs/linux-bzimage/setup/Cargo.toml
@@ -11,7 +14,7 @@ path = "src/main.rs"
[dependencies]
cfg-if = "1.0.0"
-linux-boot-params = { path = "../boot-params" }
+linux-boot-params = { path = "../boot-params", version = "0.1.0" }
uart_16550 = "0.3.0"
xmas-elf = "0.8.0"
diff --git a/ostd/libs/ostd-macros/Cargo.toml b/ostd/libs/ostd-macros/Cargo.toml
--- a/ostd/libs/ostd-macros/Cargo.toml
+++ b/ostd/libs/ostd-macros/Cargo.toml
@@ -1,7 +1,10 @@
[package]
name = "ostd-macros"
-version = "0.1.0"
+version = "0.1.4"
edition = "2021"
+description = "OSTD's proc macros"
+license = "MPL-2.0"
+repository ="https://github.com/asterinas/asterinas"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
diff --git a/ostd/libs/ostd-macros/Cargo.toml b/ostd/libs/ostd-macros/Cargo.toml
--- a/ostd/libs/ostd-macros/Cargo.toml
+++ b/ostd/libs/ostd-macros/Cargo.toml
@@ -1,7 +1,10 @@
[package]
name = "ostd-macros"
-version = "0.1.0"
+version = "0.1.4"
edition = "2021"
+description = "OSTD's proc macros"
+license = "MPL-2.0"
+repository ="https://github.com/asterinas/asterinas"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
diff --git a/ostd/libs/ostd-macros/src/lib.rs b/ostd/libs/ostd-macros/src/lib.rs
--- a/ostd/libs/ostd-macros/src/lib.rs
+++ b/ostd/libs/ostd-macros/src/lib.rs
@@ -11,7 +11,9 @@ use syn::{parse_macro_input, Expr, Ident, ItemFn};
///
/// # Example
///
-/// ```norun
+/// ```ignore
+/// #![no_std]
+///
/// use ostd::prelude::*;
///
/// #[ostd::main]
diff --git a/ostd/libs/ostd-macros/src/lib.rs b/ostd/libs/ostd-macros/src/lib.rs
--- a/ostd/libs/ostd-macros/src/lib.rs
+++ b/ostd/libs/ostd-macros/src/lib.rs
@@ -11,7 +11,9 @@ use syn::{parse_macro_input, Expr, Ident, ItemFn};
///
/// # Example
///
-/// ```norun
+/// ```ignore
+/// #![no_std]
+///
/// use ostd::prelude::*;
///
/// #[ostd::main]
diff --git a/ostd/libs/ostd-macros/src/lib.rs b/ostd/libs/ostd-macros/src/lib.rs
--- a/ostd/libs/ostd-macros/src/lib.rs
+++ b/ostd/libs/ostd-macros/src/lib.rs
@@ -44,7 +46,7 @@ pub fn main(_attr: TokenStream, item: TokenStream) -> TokenStream {
/// For crates other than ostd,
/// this macro can be used in the following form.
///
-/// ```norun
+/// ```ignore
/// use ostd::prelude::*;
///
/// #[ktest]
diff --git a/ostd/libs/ostd-macros/src/lib.rs b/ostd/libs/ostd-macros/src/lib.rs
--- a/ostd/libs/ostd-macros/src/lib.rs
+++ b/ostd/libs/ostd-macros/src/lib.rs
@@ -56,7 +58,7 @@ pub fn main(_attr: TokenStream, item: TokenStream) -> TokenStream {
/// For ostd crate itself,
/// this macro can be used in the form
///
-/// ```norun
+/// ```ignore
/// use crate::prelude::*;
///
/// #[ktest]
diff --git a/ostd/libs/ostd-macros/src/lib.rs b/ostd/libs/ostd-macros/src/lib.rs
--- a/ostd/libs/ostd-macros/src/lib.rs
+++ b/ostd/libs/ostd-macros/src/lib.rs
@@ -144,10 +146,10 @@ pub fn ktest(_attr: TokenStream, item: TokenStream) -> TokenStream {
#[cfg(ktest)]
#[used]
#[link_section = ".ktest_array"]
- static #fn_ktest_item_name: ktest::KtestItem = ktest::KtestItem::new(
+ static #fn_ktest_item_name: ostd_test::KtestItem = ostd_test::KtestItem::new(
#fn_name,
(#should_panic, #expectation_tokens),
- ktest::KtestItemInfo {
+ ostd_test::KtestItemInfo {
module_path: module_path!(),
fn_name: stringify!(#fn_name),
package: #package_name,
diff --git a/ostd/libs/ktest/Cargo.toml b/ostd/libs/ostd-test/Cargo.toml
--- a/ostd/libs/ktest/Cargo.toml
+++ b/ostd/libs/ostd-test/Cargo.toml
@@ -1,7 +1,10 @@
[package]
-name = "ktest"
+name = "ostd-test"
version = "0.1.0"
edition = "2021"
+description = "The kernel mode testing framework of OSTD"
+license = "MPL-2.0"
+repository ="https://github.com/asterinas/asterinas"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
diff --git a/ostd/libs/ktest/src/lib.rs b/ostd/libs/ostd-test/src/lib.rs
--- a/ostd/libs/ktest/src/lib.rs
+++ b/ostd/libs/ostd-test/src/lib.rs
@@ -1,20 +1,20 @@
// SPDX-License-Identifier: MPL-2.0
-//! # The kernel mode testing framework of Asterinas.
+//! # The kernel mode testing framework of OSTD.
//!
-//! `ktest` stands for kernel-mode testing framework. Its goal is to provide a
+//! `ostd-test` stands for kernel-mode testing framework for OSTD. Its goal is to provide a
//! `cargo test`-like experience for any `#![no_std]` bare metal crates.
//!
-//! In Asterinas, all the tests written in the source tree of the crates will be run
+//! In OSTD, all the tests written in the source tree of the crates will be run
//! immediately after the initialization of `ostd`. Thus you can use any
//! feature provided by the frame including the heap allocator, etc.
//!
-//! By all means, ktest is an individule crate that only requires:
+//! By all means, ostd-test is an individule crate that only requires:
//! - a custom linker script section `.ktest_array`,
//! - and an alloc implementation.
//!
-//! And the frame happens to provide both of them. Thus, any crates depending
-//! on the frame can use ktest without any extra dependency.
+//! And the OSTD happens to provide both of them. Thus, any crates depending
+//! on the OSTD can use ostd-test without any extra dependency.
//!
//! ## Usage
//!
diff --git a/ostd/libs/ktest/src/lib.rs b/ostd/libs/ostd-test/src/lib.rs
--- a/ostd/libs/ktest/src/lib.rs
+++ b/ostd/libs/ostd-test/src/lib.rs
@@ -43,7 +43,7 @@
//! }
//! ```
//!
-//! Any crates using the ktest framework should be linked with ostd.
+//! Any crates using the ostd-test framework should be linked with ostd.
//!
//! ```toml
//! # Cargo.toml
diff --git a/ostd/src/arch/x86/cpu.rs b/ostd/src/arch/x86/cpu.rs
--- a/ostd/src/arch/x86/cpu.rs
+++ b/ostd/src/arch/x86/cpu.rs
@@ -16,7 +16,8 @@ use bitvec::{
use log::debug;
#[cfg(feature = "intel_tdx")]
use tdx_guest::tdcall;
-use trapframe::{GeneralRegs, UserContext as RawUserContext};
+pub use trapframe::GeneralRegs as RawGeneralRegs;
+use trapframe::UserContext as RawUserContext;
use x86_64::registers::{
rflags::RFlags,
segmentation::{Segment64, FS},
diff --git a/ostd/src/arch/x86/cpu.rs b/ostd/src/arch/x86/cpu.rs
--- a/ostd/src/arch/x86/cpu.rs
+++ b/ostd/src/arch/x86/cpu.rs
@@ -16,7 +16,8 @@ use bitvec::{
use log::debug;
#[cfg(feature = "intel_tdx")]
use tdx_guest::tdcall;
-use trapframe::{GeneralRegs, UserContext as RawUserContext};
+pub use trapframe::GeneralRegs as RawGeneralRegs;
+use trapframe::UserContext as RawUserContext;
use x86_64::registers::{
rflags::RFlags,
segmentation::{Segment64, FS},
diff --git a/ostd/src/arch/x86/cpu.rs b/ostd/src/arch/x86/cpu.rs
--- a/ostd/src/arch/x86/cpu.rs
+++ b/ostd/src/arch/x86/cpu.rs
@@ -131,7 +132,7 @@ pub struct CpuExceptionInfo {
}
#[cfg(feature = "intel_tdx")]
-impl TdxTrapFrame for GeneralRegs {
+impl TdxTrapFrame for RawGeneralRegs {
fn rax(&self) -> usize {
self.rax
}
diff --git a/ostd/src/arch/x86/cpu.rs b/ostd/src/arch/x86/cpu.rs
--- a/ostd/src/arch/x86/cpu.rs
+++ b/ostd/src/arch/x86/cpu.rs
@@ -131,7 +132,7 @@ pub struct CpuExceptionInfo {
}
#[cfg(feature = "intel_tdx")]
-impl TdxTrapFrame for GeneralRegs {
+impl TdxTrapFrame for RawGeneralRegs {
fn rax(&self) -> usize {
self.rax
}
diff --git a/ostd/src/arch/x86/cpu.rs b/ostd/src/arch/x86/cpu.rs
--- a/ostd/src/arch/x86/cpu.rs
+++ b/ostd/src/arch/x86/cpu.rs
@@ -258,12 +259,12 @@ impl UserPreemption {
impl UserContext {
/// Returns a reference to the general registers.
- pub fn general_regs(&self) -> &GeneralRegs {
+ pub fn general_regs(&self) -> &RawGeneralRegs {
&self.user_context.general
}
/// Returns a mutable reference to the general registers
- pub fn general_regs_mut(&mut self) -> &mut GeneralRegs {
+ pub fn general_regs_mut(&mut self) -> &mut RawGeneralRegs {
&mut self.user_context.general
}
diff --git a/ostd/src/arch/x86/cpu.rs b/ostd/src/arch/x86/cpu.rs
--- a/ostd/src/arch/x86/cpu.rs
+++ b/ostd/src/arch/x86/cpu.rs
@@ -258,12 +259,12 @@ impl UserPreemption {
impl UserContext {
/// Returns a reference to the general registers.
- pub fn general_regs(&self) -> &GeneralRegs {
+ pub fn general_regs(&self) -> &RawGeneralRegs {
&self.user_context.general
}
/// Returns a mutable reference to the general registers
- pub fn general_regs_mut(&mut self) -> &mut GeneralRegs {
+ pub fn general_regs_mut(&mut self) -> &mut RawGeneralRegs {
&mut self.user_context.general
}
diff --git a/ostd/src/arch/x86/iommu/context_table.rs b/ostd/src/arch/x86/iommu/context_table.rs
--- a/ostd/src/arch/x86/iommu/context_table.rs
+++ b/ostd/src/arch/x86/iommu/context_table.rs
@@ -6,7 +6,6 @@ use alloc::collections::BTreeMap;
use core::mem::size_of;
use log::warn;
-use pod::Pod;
use super::second_stage::{DeviceMode, PageTableEntry, PagingConsts};
use crate::{
diff --git a/ostd/src/arch/x86/iommu/context_table.rs b/ostd/src/arch/x86/iommu/context_table.rs
--- a/ostd/src/arch/x86/iommu/context_table.rs
+++ b/ostd/src/arch/x86/iommu/context_table.rs
@@ -6,7 +6,6 @@ use alloc::collections::BTreeMap;
use core::mem::size_of;
use log::warn;
-use pod::Pod;
use super::second_stage::{DeviceMode, PageTableEntry, PagingConsts};
use crate::{
diff --git a/ostd/src/arch/x86/iommu/context_table.rs b/ostd/src/arch/x86/iommu/context_table.rs
--- a/ostd/src/arch/x86/iommu/context_table.rs
+++ b/ostd/src/arch/x86/iommu/context_table.rs
@@ -17,6 +16,7 @@ use crate::{
page_table::PageTableError,
Frame, FrameAllocOptions, Paddr, PageFlags, PageTable, VmIo, PAGE_SIZE,
},
+ Pod,
};
/// Bit 0 is `Present` bit, indicating whether this entry is present.
diff --git a/ostd/src/arch/x86/iommu/context_table.rs b/ostd/src/arch/x86/iommu/context_table.rs
--- a/ostd/src/arch/x86/iommu/context_table.rs
+++ b/ostd/src/arch/x86/iommu/context_table.rs
@@ -17,6 +16,7 @@ use crate::{
page_table::PageTableError,
Frame, FrameAllocOptions, Paddr, PageFlags, PageTable, VmIo, PAGE_SIZE,
},
+ Pod,
};
/// Bit 0 is `Present` bit, indicating whether this entry is present.
diff --git a/ostd/src/arch/x86/iommu/second_stage.rs b/ostd/src/arch/x86/iommu/second_stage.rs
--- a/ostd/src/arch/x86/iommu/second_stage.rs
+++ b/ostd/src/arch/x86/iommu/second_stage.rs
@@ -4,12 +4,13 @@
use core::ops::Range;
-use pod::Pod;
-
-use crate::mm::{
- page_prop::{CachePolicy, PageFlags, PrivilegedPageFlags as PrivFlags},
- page_table::{PageTableEntryTrait, PageTableMode},
- Paddr, PageProperty, PagingConstsTrait, PagingLevel, Vaddr,
+use crate::{
+ mm::{
+ page_prop::{CachePolicy, PageFlags, PrivilegedPageFlags as PrivFlags},
+ page_table::{PageTableEntryTrait, PageTableMode},
+ Paddr, PageProperty, PagingConstsTrait, PagingLevel, Vaddr,
+ },
+ Pod,
};
/// The page table used by iommu maps the device address
diff --git a/ostd/src/arch/x86/iommu/second_stage.rs b/ostd/src/arch/x86/iommu/second_stage.rs
--- a/ostd/src/arch/x86/iommu/second_stage.rs
+++ b/ostd/src/arch/x86/iommu/second_stage.rs
@@ -4,12 +4,13 @@
use core::ops::Range;
-use pod::Pod;
-
-use crate::mm::{
- page_prop::{CachePolicy, PageFlags, PrivilegedPageFlags as PrivFlags},
- page_table::{PageTableEntryTrait, PageTableMode},
- Paddr, PageProperty, PagingConstsTrait, PagingLevel, Vaddr,
+use crate::{
+ mm::{
+ page_prop::{CachePolicy, PageFlags, PrivilegedPageFlags as PrivFlags},
+ page_table::{PageTableEntryTrait, PageTableMode},
+ Paddr, PageProperty, PagingConstsTrait, PagingLevel, Vaddr,
+ },
+ Pod,
};
/// The page table used by iommu maps the device address
diff --git a/ostd/src/arch/x86/mm/mod.rs b/ostd/src/arch/x86/mm/mod.rs
--- a/ostd/src/arch/x86/mm/mod.rs
+++ b/ostd/src/arch/x86/mm/mod.rs
@@ -5,14 +5,16 @@
use alloc::fmt;
use core::ops::Range;
-use pod::Pod;
pub(crate) use util::__memcpy_fallible;
use x86_64::{instructions::tlb, structures::paging::PhysFrame, VirtAddr};
-use crate::mm::{
- page_prop::{CachePolicy, PageFlags, PageProperty, PrivilegedPageFlags as PrivFlags},
- page_table::PageTableEntryTrait,
- Paddr, PagingConstsTrait, PagingLevel, Vaddr, PAGE_SIZE,
+use crate::{
+ mm::{
+ page_prop::{CachePolicy, PageFlags, PageProperty, PrivilegedPageFlags as PrivFlags},
+ page_table::PageTableEntryTrait,
+ Paddr, PagingConstsTrait, PagingLevel, Vaddr, PAGE_SIZE,
+ },
+ Pod,
};
mod util;
diff --git a/ostd/src/arch/x86/mm/mod.rs b/ostd/src/arch/x86/mm/mod.rs
--- a/ostd/src/arch/x86/mm/mod.rs
+++ b/ostd/src/arch/x86/mm/mod.rs
@@ -5,14 +5,16 @@
use alloc::fmt;
use core::ops::Range;
-use pod::Pod;
pub(crate) use util::__memcpy_fallible;
use x86_64::{instructions::tlb, structures::paging::PhysFrame, VirtAddr};
-use crate::mm::{
- page_prop::{CachePolicy, PageFlags, PageProperty, PrivilegedPageFlags as PrivFlags},
- page_table::PageTableEntryTrait,
- Paddr, PagingConstsTrait, PagingLevel, Vaddr, PAGE_SIZE,
+use crate::{
+ mm::{
+ page_prop::{CachePolicy, PageFlags, PageProperty, PrivilegedPageFlags as PrivFlags},
+ page_table::PageTableEntryTrait,
+ Paddr, PagingConstsTrait, PagingLevel, Vaddr, PAGE_SIZE,
+ },
+ Pod,
};
mod util;
diff --git a/ostd/src/boot/mod.rs b/ostd/src/boot/mod.rs
--- a/ostd/src/boot/mod.rs
+++ b/ostd/src/boot/mod.rs
@@ -156,7 +156,7 @@ fn run_ktests(test_whitelist: Option<&[&str]>, crate_whitelist: Option<&[&str]>)
let fn_catch_unwind = &(unwinding::panic::catch_unwind::<(), fn()>
as fn(fn()) -> Result<(), Box<(dyn Any + Send + 'static)>>);
- use ktest::runner::{run_ktests, KtestResult};
+ use ostd_test::runner::{run_ktests, KtestResult};
match run_ktests(
&crate::console::early_print,
fn_catch_unwind,
diff --git a/ostd/src/cpu/mod.rs b/ostd/src/cpu/mod.rs
--- a/ostd/src/cpu/mod.rs
+++ b/ostd/src/cpu/mod.rs
@@ -6,7 +6,6 @@ pub mod cpu_local;
cfg_if::cfg_if! {
if #[cfg(target_arch = "x86_64")]{
- pub use trapframe::GeneralRegs;
pub use crate::arch::x86::cpu::*;
}
}
diff --git a/ostd/src/cpu/mod.rs b/ostd/src/cpu/mod.rs
--- a/ostd/src/cpu/mod.rs
+++ b/ostd/src/cpu/mod.rs
@@ -6,7 +6,6 @@ pub mod cpu_local;
cfg_if::cfg_if! {
if #[cfg(target_arch = "x86_64")]{
- pub use trapframe::GeneralRegs;
pub use crate::arch::x86::cpu::*;
}
}
diff --git a/ostd/src/io_mem.rs b/ostd/src/io_mem.rs
--- a/ostd/src/io_mem.rs
+++ b/ostd/src/io_mem.rs
@@ -4,11 +4,9 @@
use core::{mem::size_of, ops::Range};
-use pod::Pod;
-
use crate::{
mm::{kspace::LINEAR_MAPPING_BASE_VADDR, paddr_to_vaddr, HasPaddr, Paddr, Vaddr, VmIo},
- Error, Result,
+ Error, Pod, Result,
};
/// I/O memory.
diff --git a/ostd/src/io_mem.rs b/ostd/src/io_mem.rs
--- a/ostd/src/io_mem.rs
+++ b/ostd/src/io_mem.rs
@@ -4,11 +4,9 @@
use core::{mem::size_of, ops::Range};
-use pod::Pod;
-
use crate::{
mm::{kspace::LINEAR_MAPPING_BASE_VADDR, paddr_to_vaddr, HasPaddr, Paddr, Vaddr, VmIo},
- Error, Result,
+ Error, Pod, Result,
};
/// I/O memory.
diff --git a/ostd/src/lib.rs b/ostd/src/lib.rs
--- a/ostd/src/lib.rs
+++ b/ostd/src/lib.rs
@@ -44,6 +44,7 @@ pub mod trap;
pub mod user;
pub use ostd_macros::main;
+pub use ostd_pod::Pod;
pub use self::{cpu::cpu_local::CpuLocal, error::Error, prelude::Result};
diff --git a/ostd/src/lib.rs b/ostd/src/lib.rs
--- a/ostd/src/lib.rs
+++ b/ostd/src/lib.rs
@@ -44,6 +44,7 @@ pub mod trap;
pub mod user;
pub use ostd_macros::main;
+pub use ostd_pod::Pod;
pub use self::{cpu::cpu_local::CpuLocal, error::Error, prelude::Result};
diff --git a/ostd/src/lib.rs b/ostd/src/lib.rs
--- a/ostd/src/lib.rs
+++ b/ostd/src/lib.rs
@@ -123,5 +124,5 @@ mod test {
/// The module re-exports everything from the ktest crate
#[cfg(ktest)]
pub mod ktest {
- pub use ktest::*;
+ pub use ostd_test::*;
}
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -6,7 +6,6 @@ use core::marker::PhantomData;
use align_ext::AlignExt;
use inherit_methods_macro::inherit_methods;
-use pod::Pod;
use crate::{
arch::mm::__memcpy_fallible,
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -6,7 +6,6 @@ use core::marker::PhantomData;
use align_ext::AlignExt;
use inherit_methods_macro::inherit_methods;
-use pod::Pod;
use crate::{
arch::mm::__memcpy_fallible,
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -15,7 +14,7 @@ use crate::{
MAX_USERSPACE_VADDR,
},
prelude::*,
- Error,
+ Error, Pod,
};
/// A trait that enables reading/writing data from/to a VM object,
diff --git a/ostd/src/mm/io.rs b/ostd/src/mm/io.rs
--- a/ostd/src/mm/io.rs
+++ b/ostd/src/mm/io.rs
@@ -15,7 +14,7 @@ use crate::{
MAX_USERSPACE_VADDR,
},
prelude::*,
- Error,
+ Error, Pod,
};
/// A trait that enables reading/writing data from/to a VM object,
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -2,14 +2,15 @@
use core::{fmt::Debug, marker::PhantomData, ops::Range};
-use pod::Pod;
-
use super::{
nr_subpage_per_huge, paddr_to_vaddr,
page_prop::{PageFlags, PageProperty},
page_size, Paddr, PagingConstsTrait, PagingLevel, Vaddr,
};
-use crate::arch::mm::{PageTableEntry, PagingConsts};
+use crate::{
+ arch::mm::{PageTableEntry, PagingConsts},
+ Pod,
+};
mod node;
use node::*;
diff --git a/ostd/src/mm/page_table/mod.rs b/ostd/src/mm/page_table/mod.rs
--- a/ostd/src/mm/page_table/mod.rs
+++ b/ostd/src/mm/page_table/mod.rs
@@ -2,14 +2,15 @@
use core::{fmt::Debug, marker::PhantomData, ops::Range};
-use pod::Pod;
-
use super::{
nr_subpage_per_huge, paddr_to_vaddr,
page_prop::{PageFlags, PageProperty},
page_size, Paddr, PagingConstsTrait, PagingLevel, Vaddr,
};
-use crate::arch::mm::{PageTableEntry, PagingConsts};
+use crate::{
+ arch::mm::{PageTableEntry, PagingConsts},
+ Pod,
+};
mod node;
use node::*;
diff --git a/ostd/src/panicking.rs b/ostd/src/panicking.rs
--- a/ostd/src/panicking.rs
+++ b/ostd/src/panicking.rs
@@ -29,7 +29,7 @@ use unwinding::{
/// panic handler in the binary crate.
#[export_name = "__aster_panic_handler"]
pub fn panic_handler(info: &core::panic::PanicInfo) -> ! {
- let throw_info = ktest::PanicInfo {
+ let throw_info = ostd_test::PanicInfo {
message: info.message().to_string(),
file: info.location().unwrap().file().to_string(),
line: info.location().unwrap().line() as usize,
diff --git a/ostd/src/sync/atomic_bits.rs b/ostd/src/sync/atomic_bits.rs
--- a/ostd/src/sync/atomic_bits.rs
+++ b/ostd/src/sync/atomic_bits.rs
@@ -293,7 +293,6 @@ impl fmt::Debug for AtomicBits {
#[cfg(ktest)]
mod test {
use super::*;
- use crate::prelude::*;
#[ktest]
fn new() {
|
2024-07-03T08:57:04Z
|
562e64437584279783f244edba10b512beddc81d
|
|
asterinas/asterinas
|
diff --git a/ostd/src/boot/mod.rs b/ostd/src/boot/mod.rs
--- a/ostd/src/boot/mod.rs
+++ b/ostd/src/boot/mod.rs
@@ -137,10 +137,6 @@ pub fn call_ostd_main() -> ! {
static KTEST_TEST_WHITELIST: Option<&'static [&'static str]>;
static KTEST_CRATE_WHITELIST: Option<&'static [&'static str]>;
}
- // Set the global scheduler a FIFO scheduler.
- let simple_scheduler = Box::new(FifoScheduler::new());
- let static_scheduler: &'static dyn Scheduler = Box::leak(simple_scheduler);
- set_scheduler(static_scheduler);
let test_task = move || {
run_ktests(KTEST_TEST_WHITELIST, KTEST_CRATE_WHITELIST);
|
[
"944"
] |
0.6
|
4844e7ca7ca6d78896a51a71487a6fdfe9ca6654
|
RFC: The new scheduling API of Asterinas Framework
## Introduction
This RFC proposes a new set of API for the scheduling subsystem of Asterinas Framework. The new API aims at enabling the Framework users to implement advanced scheduler algorithms such as Linux's CFS and support multiple schedulers such as Linux's scheduling classes.
## Background
While Asterinas Framework grows out of Asterinas, it is intended to serve as a general OS development framework that may be used to build OS kernels with different characteristics, including different scheduling policies and algorithms.
The current scheduler API is summarized below.
```rust
/// Set the global task scheduler.
///
/// This must be called before invoking `Task::spawn`.
pub fn set_scheduler(scheduler: &'static dyn Scheduler) {
GLOBAL_SCHEDULER.lock_irq_disabled().scheduler = Some(scheduler);
}
/// A scheduler for tasks.
///
/// An implementation of scheduler can attach scheduler-related information
/// with the `TypeMap` returned from `task.data()`.
pub trait Scheduler: Sync + Send {
/// Enqueues a task to the scheduler.
fn enqueue(&self, task: Arc<Task>);
/// Dequeues a task from the scheduler.
fn dequeue(&self) -> Option<Arc<Task>>;
/// Tells whether the given task should be preempted by other tasks in the queue.
fn should_preempt(&self, task: &Arc<Task>) -> bool;
}
```
The drawbacks of the current design are:
* No API to do time accounting
* No SMP support
* Unable to do unit testing
## Proposal
We now provide a high-level overview of the new API and its usage.
### Initialization
Upon initialization, the kernel (e.g., `aster-nix`) injects a task scheduler into the Framework (i.e., `aster-frame`).
```rust
/// Injects a task scheduler into the Framework.
///
/// # Panics
///
/// This function can only be called once and
/// should only be done at the initialization state of the kernel.
pub fn inject_scheduler(scheduler: &'static dyn Scheduler) { ... }
/// Abstracts a task scheduler.
pub trait Scheduler<T = Task> {
/// Enqueue a runnable task.
fn enqueue(&self, runnable: Arc<T>, flags: EnqueueFlags) -> Option<QueueReceipt>;
/// Get an immutable access to the local runqueue of the current CPU core.
fn local_rq_with(&self, f: &mut dyn FnMut(&dyn LocalRunQueue<T>));
/// Get a mutable access to the local runqueue of the current CPU core.
fn local_mut_rq_with(&self, f: &mut dyn FnMut(&mut dyn LocalRunQueue<T>));
/// Get the runqueue of a particular CPU core.
fn rq(&self, cpu: CpuId) -> &Arc<dyn RunQueue>;
}
```
This abstract scheduler maintains a local runqueue represented by `RunQueue` and `LocalRunqueue` for each CPU core.
```rust
/// The _remote_ view of a per-CPU runqueue.
///
/// This remote view provides the interface for the runqueue of a CPU core
/// to be inspected by the code running on an another CPU core.
pub trait RunQueue: Sync + Send {
/// Returns whether there are any runnable tasks managed by the scheduler.
fn is_empty(&self) -> bool;
/// Returns whether the number of runnable tasks managed by the scheduler.
fn len(&self) -> usize;
}
/// The _local_ view of a per-CPU runqueue.
///
/// This local view provides the interface for the runqueue of a CPU core
/// to be inspected and manipulated by the code running on this particular CPU core.
///
/// Conceptually, a local runqueue consists of two parts:
/// (1) a priority queue of runnable tasks;
/// (2) the current running task.
/// The exact definition of "priority" is left for the concrete implementation to decide.
pub trait LocalRunQueue<T = Task>: RunQueue {
/// Update the current runnable task's time statistics and
/// potentially its position in the queue.
fn update_current(&mut self, flags: UpdateFlags) -> bool;
/// Dequeue the current runnable task.
///
/// The current task should be dequeued if it needs to go to sleep or has exited.
fn dequeue_current(&mut self) -> Option<Arc<T>>;
/// Pick the next current runnable task, returning the new currenet.
///
/// If there is no runnable task, the method returns `None`.
fn pick_next_current(&mut self) -> Option<&Arc<T>>;
/// Gets the current task.
///
/// The current task is the head of the queue.
/// If the queue is empty, the method returns `None`.
fn current(&self) -> Option<&Arc<T>>;
}
```
### Task spawning
After creating a new task or waking up a sleeping task, calls `Scheduler::enqueue` to put this new runnable task into the scheduler. This `enqueue` method selects a suitable CPU core properly (e.g., by taking into account CPU affinity and load balanacing) and enqueues the new runnable task into the local runqueue of the target CPU core.
```rust
impl TaskOptions {
pub fn spawn(self) -> Result<Arc<Task>> {
let task = self.build()?;
task.run();
Ok(task)
}
}
impl Task {
pub fn run(self: &Arc<Self>) {
sched::spawn_task(self);
}
}
```
The `sched::spawn_task` function calls the `enqueue` method of the injected scheduler singleton.
```rust
pub(crate) fn spawn_task(task: &Arc<Task>) {
let should_reschedule = SCHEDULER.enqueue(task, EnqueueFlags::Spawn);
if !should_reschedule {
return;
}
reschedule(|local_rq| {
let Some(next_current) = local_rq.pick_next_current() else {
return ReschedAction::DoNothing;
};
ReschedAction::SwitchTo(next_current.clone())
});
}
```
The `sched::reschedule` function do the rescheduling according to the rescheduling action returned by the given closure.
```rust
pub(crate) ReschedAction {
DoNothing,
Retry,
SwitchTo(Arc<Task>),
}
pub(crate) fn reschedule<F>(f: F)
F: Fn(&mut dyn LocalRunQueue) -> ReschedAction
{
...
}
```
### Yielding
```rust
impl Task {
pub fn yield_now() {
sched::reschedule(|local_rq| {
let should_pick_next = local_rq.update_current(UpdateFlags::YIELD);
if !should_pick_next {
return ReschedAction::DoNothing;
}
let Some(next_current) = local_rq.pick_next_current() else {
return ReschedAction::DoNothing;
};
ReschedAction::SwitchTo(next_current.clone())
});
}
}
````
### Sleeping
```rust
impl Waker {
fn do_wait(&self) {
while !self.has_woken.load(Ordering::Acquire) {
let mut task = self.task.inner_exclusive_access();
// After holding the lock, check again to avoid races
if self.has_woken.load(Ordering::Acquire) {
break;
}
task.task_status = TaskStatus::Sleepy;
drop(task);
sched::reschedule(|local_rq| {
let should_pick_next = local_rq.update_current(UpdateFlags::WAIT);
local_rq.dequeue_current();
let Some(next_current) = local_rq.pick_next_current() else {
return ReschedAction::Retry;
};
ReschedAction::SwitchTo(next_current.clone())
});
}
self.has_woken.store(false, Ordering::Release);
}
}
```
### Preemption
Periodically (e.g., on system timer interrupts), a CPU to get its local runqueue using `Scheduler::local_mut_rq_with` to do time accounting for the current task.
```rust
fn do_timer_interrupt(...) {
SCHEDULER.local_rq_with(|local_rq| {
let should_preempt = local_rq.update_current(SchedEvent::Tick);
if should_preempt {
local_rq.current().set_should_preempt(true);
}
});
}
```
On the next most convenient timing, the current task can be preempted by doing this.
```rust
fn might_preempt(current: &Arc<Task>) {
if !current.should_preempt() {
return;
}
current.set_should_preempt(false);
sched::reschedule(|local_rq| {
let Some(next_current) = local_rq.pick_next_current() else {
return ReschedAction::DoNothing;
};
Resched::SwitchTo(next_current.clone())
});
}
```
## Detailed Design
More details need to be worked out, but I don't have the time to do so...
|
asterinas__asterinas-990
| 990
|
diff --git a/kernel/aster-nix/src/sched/priority_scheduler.rs b/kernel/aster-nix/src/sched/priority_scheduler.rs
--- a/kernel/aster-nix/src/sched/priority_scheduler.rs
+++ b/kernel/aster-nix/src/sched/priority_scheduler.rs
@@ -1,56 +1,234 @@
// SPDX-License-Identifier: MPL-2.0
-use intrusive_collections::LinkedList;
-use ostd::task::{set_scheduler, Scheduler, Task, TaskAdapter};
+use ostd::{
+ cpu::{num_cpus, this_cpu},
+ task::{
+ scheduler::{inject_scheduler, EnqueueFlags, LocalRunQueue, Scheduler, UpdateFlags},
+ AtomicCpuId, Priority, Task,
+ },
+};
use crate::prelude::*;
pub fn init() {
- let preempt_scheduler = Box::new(PreemptScheduler::new());
- let scheduler = Box::<PreemptScheduler>::leak(preempt_scheduler);
- set_scheduler(scheduler);
+ let preempt_scheduler = Box::new(PreemptScheduler::default());
+ let scheduler = Box::<PreemptScheduler<Task>>::leak(preempt_scheduler);
+ inject_scheduler(scheduler);
}
-/// The preempt scheduler
+/// The preempt scheduler.
///
-/// Real-time tasks are placed in the `real_time_tasks` queue and
+/// Real-time tasks are placed in the `real_time_entities` queue and
/// are always prioritized during scheduling.
-/// Normal tasks are placed in the `normal_tasks` queue and are only
+/// Normal tasks are placed in the `normal_entities` queue and are only
/// scheduled for execution when there are no real-time tasks.
-struct PreemptScheduler {
- /// Tasks with a priority of less than 100 are regarded as real-time tasks.
- real_time_tasks: SpinLock<LinkedList<TaskAdapter>>,
- /// Tasks with a priority greater than or equal to 100 are regarded as normal tasks.
- normal_tasks: SpinLock<LinkedList<TaskAdapter>>,
+struct PreemptScheduler<T: PreemptSchedInfo> {
+ rq: Vec<SpinLock<PreemptRunQueue<T>>>,
}
-impl PreemptScheduler {
+impl<T: PreemptSchedInfo> PreemptScheduler<T> {
+ fn new(nr_cpus: u32) -> Self {
+ let mut rq = Vec::with_capacity(nr_cpus as usize);
+ for _ in 0..nr_cpus {
+ rq.push(SpinLock::new(PreemptRunQueue::new()));
+ }
+ Self { rq }
+ }
+
+ /// Selects a cpu for task to run on.
+ fn select_cpu(&self, _runnable: &Arc<T>) -> u32 {
+ // FIXME: adopt more reasonable policy once we fully enable SMP.
+ 0
+ }
+}
+
+impl<T: Sync + Send + PreemptSchedInfo> Scheduler<T> for PreemptScheduler<T> {
+ fn enqueue(&self, runnable: Arc<T>, flags: EnqueueFlags) -> Option<u32> {
+ let mut still_in_rq = false;
+ let target_cpu = {
+ let mut cpu_id = self.select_cpu(&runnable);
+ if let Err(task_cpu_id) = runnable.cpu().set_if_is_none(cpu_id) {
+ debug_assert!(flags != EnqueueFlags::Spawn);
+ still_in_rq = true;
+ cpu_id = task_cpu_id;
+ }
+
+ cpu_id
+ };
+
+ let mut rq = self.rq[target_cpu as usize].lock_irq_disabled();
+ if still_in_rq && let Err(_) = runnable.cpu().set_if_is_none(target_cpu) {
+ return None;
+ }
+ let entity = PreemptSchedEntity::new(runnable);
+ if entity.is_real_time() {
+ rq.real_time_entities.push_back(entity);
+ } else {
+ rq.normal_entities.push_back(entity);
+ }
+
+ Some(target_cpu)
+ }
+
+ fn local_rq_with(&self, f: &mut dyn FnMut(&dyn LocalRunQueue<T>)) {
+ let local_rq: &PreemptRunQueue<T> = &self.rq[this_cpu() as usize].lock_irq_disabled();
+ f(local_rq);
+ }
+
+ fn local_mut_rq_with(&self, f: &mut dyn FnMut(&mut dyn LocalRunQueue<T>)) {
+ let local_rq: &mut PreemptRunQueue<T> =
+ &mut self.rq[this_cpu() as usize].lock_irq_disabled();
+ f(local_rq);
+ }
+}
+
+impl Default for PreemptScheduler<Task> {
+ fn default() -> Self {
+ Self::new(num_cpus())
+ }
+}
+
+struct PreemptRunQueue<T: PreemptSchedInfo> {
+ current: Option<PreemptSchedEntity<T>>,
+ real_time_entities: VecDeque<PreemptSchedEntity<T>>,
+ normal_entities: VecDeque<PreemptSchedEntity<T>>,
+}
+
+impl<T: PreemptSchedInfo> PreemptRunQueue<T> {
pub fn new() -> Self {
Self {
- real_time_tasks: SpinLock::new(LinkedList::new(TaskAdapter::new())),
- normal_tasks: SpinLock::new(LinkedList::new(TaskAdapter::new())),
+ current: None,
+ real_time_entities: VecDeque::new(),
+ normal_entities: VecDeque::new(),
}
}
}
-impl Scheduler for PreemptScheduler {
- fn enqueue(&self, task: Arc<Task>) {
- if task.is_real_time() {
- self.real_time_tasks.lock_irq_disabled().push_back(task);
- } else {
- self.normal_tasks.lock_irq_disabled().push_back(task);
+impl<T: Sync + Send + PreemptSchedInfo> LocalRunQueue<T> for PreemptRunQueue<T> {
+ fn current(&self) -> Option<&Arc<T>> {
+ self.current.as_ref().map(|entity| &entity.runnable)
+ }
+
+ fn update_current(&mut self, flags: UpdateFlags) -> bool {
+ match flags {
+ UpdateFlags::Tick => {
+ let Some(ref mut current_entity) = self.current else {
+ return false;
+ };
+ current_entity.tick()
+ || (!current_entity.is_real_time() && !self.real_time_entities.is_empty())
+ }
+ _ => true,
}
}
- fn dequeue(&self) -> Option<Arc<Task>> {
- if !self.real_time_tasks.lock_irq_disabled().is_empty() {
- self.real_time_tasks.lock_irq_disabled().pop_front()
+ fn pick_next_current(&mut self) -> Option<&Arc<T>> {
+ let next_entity = if !self.real_time_entities.is_empty() {
+ self.real_time_entities.pop_front()
} else {
- self.normal_tasks.lock_irq_disabled().pop_front()
+ self.normal_entities.pop_front()
+ }?;
+ if let Some(prev_entity) = self.current.replace(next_entity) {
+ if prev_entity.is_real_time() {
+ self.real_time_entities.push_back(prev_entity);
+ } else {
+ self.normal_entities.push_back(prev_entity);
+ }
}
+
+ Some(&self.current.as_ref().unwrap().runnable)
}
- fn should_preempt(&self, task: &Arc<Task>) -> bool {
- !task.is_real_time() && !self.real_time_tasks.lock_irq_disabled().is_empty()
+ fn dequeue_current(&mut self) -> Option<Arc<T>> {
+ self.current.take().map(|entity| {
+ let runnable = entity.runnable;
+ runnable.cpu().set_to_none();
+
+ runnable
+ })
+ }
+}
+
+struct PreemptSchedEntity<T: PreemptSchedInfo> {
+ runnable: Arc<T>,
+ time_slice: TimeSlice,
+}
+
+impl<T: PreemptSchedInfo> PreemptSchedEntity<T> {
+ fn new(runnable: Arc<T>) -> Self {
+ Self {
+ runnable,
+ time_slice: TimeSlice::default(),
+ }
+ }
+
+ fn is_real_time(&self) -> bool {
+ self.runnable.is_real_time()
+ }
+
+ fn tick(&mut self) -> bool {
+ self.time_slice.elapse()
+ }
+}
+
+impl<T: PreemptSchedInfo> Clone for PreemptSchedEntity<T> {
+ fn clone(&self) -> Self {
+ Self {
+ runnable: self.runnable.clone(),
+ time_slice: self.time_slice,
+ }
+ }
+}
+
+#[derive(Clone, Copy)]
+pub struct TimeSlice {
+ elapsed_ticks: u32,
+}
+
+impl TimeSlice {
+ const DEFAULT_TIME_SLICE: u32 = 100;
+
+ pub const fn new() -> Self {
+ TimeSlice { elapsed_ticks: 0 }
+ }
+
+ pub fn elapse(&mut self) -> bool {
+ self.elapsed_ticks = (self.elapsed_ticks + 1) % Self::DEFAULT_TIME_SLICE;
+
+ self.elapsed_ticks == 0
+ }
+}
+
+impl Default for TimeSlice {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl PreemptSchedInfo for Task {
+ type PRIORITY = Priority;
+
+ const REAL_TIME_TASK_PRIORITY: Self::PRIORITY = Priority::new(100);
+
+ fn priority(&self) -> Self::PRIORITY {
+ self.priority()
+ }
+
+ fn cpu(&self) -> &AtomicCpuId {
+ self.cpu()
+ }
+}
+
+trait PreemptSchedInfo {
+ type PRIORITY: Ord + PartialOrd + Eq + PartialEq;
+
+ const REAL_TIME_TASK_PRIORITY: Self::PRIORITY;
+
+ fn priority(&self) -> Self::PRIORITY;
+
+ fn cpu(&self) -> &AtomicCpuId;
+
+ fn is_real_time(&self) -> bool {
+ self.priority() < Self::REAL_TIME_TASK_PRIORITY
}
}
diff --git a/kernel/aster-nix/src/sched/priority_scheduler.rs b/kernel/aster-nix/src/sched/priority_scheduler.rs
--- a/kernel/aster-nix/src/sched/priority_scheduler.rs
+++ b/kernel/aster-nix/src/sched/priority_scheduler.rs
@@ -1,56 +1,234 @@
// SPDX-License-Identifier: MPL-2.0
-use intrusive_collections::LinkedList;
-use ostd::task::{set_scheduler, Scheduler, Task, TaskAdapter};
+use ostd::{
+ cpu::{num_cpus, this_cpu},
+ task::{
+ scheduler::{inject_scheduler, EnqueueFlags, LocalRunQueue, Scheduler, UpdateFlags},
+ AtomicCpuId, Priority, Task,
+ },
+};
use crate::prelude::*;
pub fn init() {
- let preempt_scheduler = Box::new(PreemptScheduler::new());
- let scheduler = Box::<PreemptScheduler>::leak(preempt_scheduler);
- set_scheduler(scheduler);
+ let preempt_scheduler = Box::new(PreemptScheduler::default());
+ let scheduler = Box::<PreemptScheduler<Task>>::leak(preempt_scheduler);
+ inject_scheduler(scheduler);
}
-/// The preempt scheduler
+/// The preempt scheduler.
///
-/// Real-time tasks are placed in the `real_time_tasks` queue and
+/// Real-time tasks are placed in the `real_time_entities` queue and
/// are always prioritized during scheduling.
-/// Normal tasks are placed in the `normal_tasks` queue and are only
+/// Normal tasks are placed in the `normal_entities` queue and are only
/// scheduled for execution when there are no real-time tasks.
-struct PreemptScheduler {
- /// Tasks with a priority of less than 100 are regarded as real-time tasks.
- real_time_tasks: SpinLock<LinkedList<TaskAdapter>>,
- /// Tasks with a priority greater than or equal to 100 are regarded as normal tasks.
- normal_tasks: SpinLock<LinkedList<TaskAdapter>>,
+struct PreemptScheduler<T: PreemptSchedInfo> {
+ rq: Vec<SpinLock<PreemptRunQueue<T>>>,
}
-impl PreemptScheduler {
+impl<T: PreemptSchedInfo> PreemptScheduler<T> {
+ fn new(nr_cpus: u32) -> Self {
+ let mut rq = Vec::with_capacity(nr_cpus as usize);
+ for _ in 0..nr_cpus {
+ rq.push(SpinLock::new(PreemptRunQueue::new()));
+ }
+ Self { rq }
+ }
+
+ /// Selects a cpu for task to run on.
+ fn select_cpu(&self, _runnable: &Arc<T>) -> u32 {
+ // FIXME: adopt more reasonable policy once we fully enable SMP.
+ 0
+ }
+}
+
+impl<T: Sync + Send + PreemptSchedInfo> Scheduler<T> for PreemptScheduler<T> {
+ fn enqueue(&self, runnable: Arc<T>, flags: EnqueueFlags) -> Option<u32> {
+ let mut still_in_rq = false;
+ let target_cpu = {
+ let mut cpu_id = self.select_cpu(&runnable);
+ if let Err(task_cpu_id) = runnable.cpu().set_if_is_none(cpu_id) {
+ debug_assert!(flags != EnqueueFlags::Spawn);
+ still_in_rq = true;
+ cpu_id = task_cpu_id;
+ }
+
+ cpu_id
+ };
+
+ let mut rq = self.rq[target_cpu as usize].lock_irq_disabled();
+ if still_in_rq && let Err(_) = runnable.cpu().set_if_is_none(target_cpu) {
+ return None;
+ }
+ let entity = PreemptSchedEntity::new(runnable);
+ if entity.is_real_time() {
+ rq.real_time_entities.push_back(entity);
+ } else {
+ rq.normal_entities.push_back(entity);
+ }
+
+ Some(target_cpu)
+ }
+
+ fn local_rq_with(&self, f: &mut dyn FnMut(&dyn LocalRunQueue<T>)) {
+ let local_rq: &PreemptRunQueue<T> = &self.rq[this_cpu() as usize].lock_irq_disabled();
+ f(local_rq);
+ }
+
+ fn local_mut_rq_with(&self, f: &mut dyn FnMut(&mut dyn LocalRunQueue<T>)) {
+ let local_rq: &mut PreemptRunQueue<T> =
+ &mut self.rq[this_cpu() as usize].lock_irq_disabled();
+ f(local_rq);
+ }
+}
+
+impl Default for PreemptScheduler<Task> {
+ fn default() -> Self {
+ Self::new(num_cpus())
+ }
+}
+
+struct PreemptRunQueue<T: PreemptSchedInfo> {
+ current: Option<PreemptSchedEntity<T>>,
+ real_time_entities: VecDeque<PreemptSchedEntity<T>>,
+ normal_entities: VecDeque<PreemptSchedEntity<T>>,
+}
+
+impl<T: PreemptSchedInfo> PreemptRunQueue<T> {
pub fn new() -> Self {
Self {
- real_time_tasks: SpinLock::new(LinkedList::new(TaskAdapter::new())),
- normal_tasks: SpinLock::new(LinkedList::new(TaskAdapter::new())),
+ current: None,
+ real_time_entities: VecDeque::new(),
+ normal_entities: VecDeque::new(),
}
}
}
-impl Scheduler for PreemptScheduler {
- fn enqueue(&self, task: Arc<Task>) {
- if task.is_real_time() {
- self.real_time_tasks.lock_irq_disabled().push_back(task);
- } else {
- self.normal_tasks.lock_irq_disabled().push_back(task);
+impl<T: Sync + Send + PreemptSchedInfo> LocalRunQueue<T> for PreemptRunQueue<T> {
+ fn current(&self) -> Option<&Arc<T>> {
+ self.current.as_ref().map(|entity| &entity.runnable)
+ }
+
+ fn update_current(&mut self, flags: UpdateFlags) -> bool {
+ match flags {
+ UpdateFlags::Tick => {
+ let Some(ref mut current_entity) = self.current else {
+ return false;
+ };
+ current_entity.tick()
+ || (!current_entity.is_real_time() && !self.real_time_entities.is_empty())
+ }
+ _ => true,
}
}
- fn dequeue(&self) -> Option<Arc<Task>> {
- if !self.real_time_tasks.lock_irq_disabled().is_empty() {
- self.real_time_tasks.lock_irq_disabled().pop_front()
+ fn pick_next_current(&mut self) -> Option<&Arc<T>> {
+ let next_entity = if !self.real_time_entities.is_empty() {
+ self.real_time_entities.pop_front()
} else {
- self.normal_tasks.lock_irq_disabled().pop_front()
+ self.normal_entities.pop_front()
+ }?;
+ if let Some(prev_entity) = self.current.replace(next_entity) {
+ if prev_entity.is_real_time() {
+ self.real_time_entities.push_back(prev_entity);
+ } else {
+ self.normal_entities.push_back(prev_entity);
+ }
}
+
+ Some(&self.current.as_ref().unwrap().runnable)
}
- fn should_preempt(&self, task: &Arc<Task>) -> bool {
- !task.is_real_time() && !self.real_time_tasks.lock_irq_disabled().is_empty()
+ fn dequeue_current(&mut self) -> Option<Arc<T>> {
+ self.current.take().map(|entity| {
+ let runnable = entity.runnable;
+ runnable.cpu().set_to_none();
+
+ runnable
+ })
+ }
+}
+
+struct PreemptSchedEntity<T: PreemptSchedInfo> {
+ runnable: Arc<T>,
+ time_slice: TimeSlice,
+}
+
+impl<T: PreemptSchedInfo> PreemptSchedEntity<T> {
+ fn new(runnable: Arc<T>) -> Self {
+ Self {
+ runnable,
+ time_slice: TimeSlice::default(),
+ }
+ }
+
+ fn is_real_time(&self) -> bool {
+ self.runnable.is_real_time()
+ }
+
+ fn tick(&mut self) -> bool {
+ self.time_slice.elapse()
+ }
+}
+
+impl<T: PreemptSchedInfo> Clone for PreemptSchedEntity<T> {
+ fn clone(&self) -> Self {
+ Self {
+ runnable: self.runnable.clone(),
+ time_slice: self.time_slice,
+ }
+ }
+}
+
+#[derive(Clone, Copy)]
+pub struct TimeSlice {
+ elapsed_ticks: u32,
+}
+
+impl TimeSlice {
+ const DEFAULT_TIME_SLICE: u32 = 100;
+
+ pub const fn new() -> Self {
+ TimeSlice { elapsed_ticks: 0 }
+ }
+
+ pub fn elapse(&mut self) -> bool {
+ self.elapsed_ticks = (self.elapsed_ticks + 1) % Self::DEFAULT_TIME_SLICE;
+
+ self.elapsed_ticks == 0
+ }
+}
+
+impl Default for TimeSlice {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl PreemptSchedInfo for Task {
+ type PRIORITY = Priority;
+
+ const REAL_TIME_TASK_PRIORITY: Self::PRIORITY = Priority::new(100);
+
+ fn priority(&self) -> Self::PRIORITY {
+ self.priority()
+ }
+
+ fn cpu(&self) -> &AtomicCpuId {
+ self.cpu()
+ }
+}
+
+trait PreemptSchedInfo {
+ type PRIORITY: Ord + PartialOrd + Eq + PartialEq;
+
+ const REAL_TIME_TASK_PRIORITY: Self::PRIORITY;
+
+ fn priority(&self) -> Self::PRIORITY;
+
+ fn cpu(&self) -> &AtomicCpuId;
+
+ fn is_real_time(&self) -> bool {
+ self.priority() < Self::REAL_TIME_TASK_PRIORITY
}
}
diff --git a/kernel/aster-nix/src/thread/task.rs b/kernel/aster-nix/src/thread/task.rs
--- a/kernel/aster-nix/src/thread/task.rs
+++ b/kernel/aster-nix/src/thread/task.rs
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: MPL-2.0
use ostd::{
- task::{preempt, Task, TaskOptions},
+ task::{Task, TaskOptions},
user::{ReturnReason, UserContextApi, UserMode, UserSpace},
};
diff --git a/kernel/aster-nix/src/thread/task.rs b/kernel/aster-nix/src/thread/task.rs
--- a/kernel/aster-nix/src/thread/task.rs
+++ b/kernel/aster-nix/src/thread/task.rs
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: MPL-2.0
use ostd::{
- task::{preempt, Task, TaskOptions},
+ task::{Task, TaskOptions},
user::{ReturnReason, UserContextApi, UserMode, UserSpace},
};
diff --git a/kernel/aster-nix/src/thread/task.rs b/kernel/aster-nix/src/thread/task.rs
--- a/kernel/aster-nix/src/thread/task.rs
+++ b/kernel/aster-nix/src/thread/task.rs
@@ -84,8 +84,6 @@ pub fn create_new_user_task(user_space: Arc<UserSpace>, thread_ref: Weak<Thread>
debug!("exit due to signal");
break;
}
- // a preemption point after handling user event.
- preempt(current_task);
}
debug!("exit user loop");
}
diff --git a/kernel/aster-nix/src/thread/task.rs b/kernel/aster-nix/src/thread/task.rs
--- a/kernel/aster-nix/src/thread/task.rs
+++ b/kernel/aster-nix/src/thread/task.rs
@@ -84,8 +84,6 @@ pub fn create_new_user_task(user_space: Arc<UserSpace>, thread_ref: Weak<Thread>
debug!("exit due to signal");
break;
}
- // a preemption point after handling user event.
- preempt(current_task);
}
debug!("exit user loop");
}
diff --git a/kernel/aster-nix/src/thread/work_queue/worker_pool.rs b/kernel/aster-nix/src/thread/work_queue/worker_pool.rs
--- a/kernel/aster-nix/src/thread/work_queue/worker_pool.rs
+++ b/kernel/aster-nix/src/thread/work_queue/worker_pool.rs
@@ -7,11 +7,7 @@ use core::{
time::Duration,
};
-use ostd::{
- cpu::CpuSet,
- sync::WaitQueue,
- task::{add_task, Priority},
-};
+use ostd::{cpu::CpuSet, sync::WaitQueue, task::Priority};
use super::{simple_scheduler::SimpleScheduler, worker::Worker, WorkItem, WorkPriority, WorkQueue};
use crate::{
diff --git a/kernel/aster-nix/src/thread/work_queue/worker_pool.rs b/kernel/aster-nix/src/thread/work_queue/worker_pool.rs
--- a/kernel/aster-nix/src/thread/work_queue/worker_pool.rs
+++ b/kernel/aster-nix/src/thread/work_queue/worker_pool.rs
@@ -7,11 +7,7 @@ use core::{
time::Duration,
};
-use ostd::{
- cpu::CpuSet,
- sync::WaitQueue,
- task::{add_task, Priority},
-};
+use ostd::{cpu::CpuSet, sync::WaitQueue, task::Priority};
use super::{simple_scheduler::SimpleScheduler, worker::Worker, WorkItem, WorkPriority, WorkQueue};
use crate::{
diff --git a/kernel/aster-nix/src/thread/work_queue/worker_pool.rs b/kernel/aster-nix/src/thread/work_queue/worker_pool.rs
--- a/kernel/aster-nix/src/thread/work_queue/worker_pool.rs
+++ b/kernel/aster-nix/src/thread/work_queue/worker_pool.rs
@@ -81,7 +77,7 @@ impl LocalWorkerPool {
fn add_worker(&self) {
let worker = Worker::new(self.parent.clone(), self.cpu_id);
self.workers.lock_irq_disabled().push_back(worker.clone());
- add_task(worker.bound_thread().task().clone());
+ worker.bound_thread().run();
}
fn remove_worker(&self) {
diff --git a/kernel/aster-nix/src/thread/work_queue/worker_pool.rs b/kernel/aster-nix/src/thread/work_queue/worker_pool.rs
--- a/kernel/aster-nix/src/thread/work_queue/worker_pool.rs
+++ b/kernel/aster-nix/src/thread/work_queue/worker_pool.rs
@@ -81,7 +77,7 @@ impl LocalWorkerPool {
fn add_worker(&self) {
let worker = Worker::new(self.parent.clone(), self.cpu_id);
self.workers.lock_irq_disabled().push_back(worker.clone());
- add_task(worker.bound_thread().task().clone());
+ worker.bound_thread().run();
}
fn remove_worker(&self) {
diff --git a/ostd/src/arch/x86/cpu/mod.rs b/ostd/src/arch/x86/cpu/mod.rs
--- a/ostd/src/arch/x86/cpu/mod.rs
+++ b/ostd/src/arch/x86/cpu/mod.rs
@@ -17,6 +17,7 @@ use trapframe::UserContext as RawUserContext;
use x86_64::registers::rflags::RFlags;
use crate::{
+ task::scheduler,
trap::call_irq_callback_functions,
user::{ReturnReason, UserContextApi, UserContextApiInternal},
};
diff --git a/ostd/src/arch/x86/cpu/mod.rs b/ostd/src/arch/x86/cpu/mod.rs
--- a/ostd/src/arch/x86/cpu/mod.rs
+++ b/ostd/src/arch/x86/cpu/mod.rs
@@ -17,6 +17,7 @@ use trapframe::UserContext as RawUserContext;
use x86_64::registers::rflags::RFlags;
use crate::{
+ task::scheduler,
trap::call_irq_callback_functions,
user::{ReturnReason, UserContextApi, UserContextApiInternal},
};
diff --git a/ostd/src/arch/x86/cpu/mod.rs b/ostd/src/arch/x86/cpu/mod.rs
--- a/ostd/src/arch/x86/cpu/mod.rs
+++ b/ostd/src/arch/x86/cpu/mod.rs
@@ -50,32 +51,6 @@ pub struct CpuExceptionInfo {
pub page_fault_addr: usize,
}
-/// User Preemption.
-pub struct UserPreemption {
- count: u32,
-}
-
-impl UserPreemption {
- const PREEMPTION_INTERVAL: u32 = 100;
-
- /// Creates a new instance of `UserPreemption`.
- #[allow(clippy::new_without_default)]
- pub const fn new() -> Self {
- UserPreemption { count: 0 }
- }
-
- /// Checks if preemption might occur and takes necessary actions.
- pub fn might_preempt(&mut self) {
- self.count = (self.count + 1) % Self::PREEMPTION_INTERVAL;
-
- if self.count == 0 {
- crate::arch::irq::enable_local();
- crate::task::schedule();
- crate::arch::irq::disable_local();
- }
- }
-}
-
impl UserContext {
/// Returns a reference to the general registers.
pub fn general_regs(&self) -> &RawGeneralRegs {
diff --git a/ostd/src/arch/x86/cpu/mod.rs b/ostd/src/arch/x86/cpu/mod.rs
--- a/ostd/src/arch/x86/cpu/mod.rs
+++ b/ostd/src/arch/x86/cpu/mod.rs
@@ -50,32 +51,6 @@ pub struct CpuExceptionInfo {
pub page_fault_addr: usize,
}
-/// User Preemption.
-pub struct UserPreemption {
- count: u32,
-}
-
-impl UserPreemption {
- const PREEMPTION_INTERVAL: u32 = 100;
-
- /// Creates a new instance of `UserPreemption`.
- #[allow(clippy::new_without_default)]
- pub const fn new() -> Self {
- UserPreemption { count: 0 }
- }
-
- /// Checks if preemption might occur and takes necessary actions.
- pub fn might_preempt(&mut self) {
- self.count = (self.count + 1) % Self::PREEMPTION_INTERVAL;
-
- if self.count == 0 {
- crate::arch::irq::enable_local();
- crate::task::schedule();
- crate::arch::irq::disable_local();
- }
- }
-}
-
impl UserContext {
/// Returns a reference to the general registers.
pub fn general_regs(&self) -> &RawGeneralRegs {
diff --git a/ostd/src/arch/x86/cpu/mod.rs b/ostd/src/arch/x86/cpu/mod.rs
--- a/ostd/src/arch/x86/cpu/mod.rs
+++ b/ostd/src/arch/x86/cpu/mod.rs
@@ -115,9 +90,9 @@ impl UserContextApiInternal for UserContext {
let return_reason: ReturnReason;
const SYSCALL_TRAPNUM: u16 = 0x100;
- let mut user_preemption = UserPreemption::new();
// return when it is syscall or cpu exception type is Fault or Trap.
loop {
+ scheduler::might_preempt();
self.user_context.run();
match CpuException::to_cpu_exception(self.user_context.trap_num as u16) {
Some(exception) => {
diff --git a/ostd/src/arch/x86/cpu/mod.rs b/ostd/src/arch/x86/cpu/mod.rs
--- a/ostd/src/arch/x86/cpu/mod.rs
+++ b/ostd/src/arch/x86/cpu/mod.rs
@@ -115,9 +90,9 @@ impl UserContextApiInternal for UserContext {
let return_reason: ReturnReason;
const SYSCALL_TRAPNUM: u16 = 0x100;
- let mut user_preemption = UserPreemption::new();
// return when it is syscall or cpu exception type is Fault or Trap.
loop {
+ scheduler::might_preempt();
self.user_context.run();
match CpuException::to_cpu_exception(self.user_context.trap_num as u16) {
Some(exception) => {
diff --git a/ostd/src/arch/x86/cpu/mod.rs b/ostd/src/arch/x86/cpu/mod.rs
--- a/ostd/src/arch/x86/cpu/mod.rs
+++ b/ostd/src/arch/x86/cpu/mod.rs
@@ -146,8 +121,6 @@ impl UserContextApiInternal for UserContext {
return_reason = ReturnReason::KernelEvent;
break;
}
-
- user_preemption.might_preempt();
}
crate::arch::irq::enable_local();
diff --git a/ostd/src/arch/x86/cpu/mod.rs b/ostd/src/arch/x86/cpu/mod.rs
--- a/ostd/src/arch/x86/cpu/mod.rs
+++ b/ostd/src/arch/x86/cpu/mod.rs
@@ -146,8 +121,6 @@ impl UserContextApiInternal for UserContext {
return_reason = ReturnReason::KernelEvent;
break;
}
-
- user_preemption.might_preempt();
}
crate::arch::irq::enable_local();
diff --git a/ostd/src/boot/mod.rs b/ostd/src/boot/mod.rs
--- a/ostd/src/boot/mod.rs
+++ b/ostd/src/boot/mod.rs
@@ -129,7 +129,7 @@ pub fn call_ostd_main() -> ! {
unsafe {
use alloc::boxed::Box;
- use crate::task::{set_scheduler, FifoScheduler, Scheduler, TaskOptions};
+ use crate::task::TaskOptions;
crate::init();
// The whitelists that will be generated by OSDK runner as static consts.
diff --git a/ostd/src/boot/mod.rs b/ostd/src/boot/mod.rs
--- a/ostd/src/boot/mod.rs
+++ b/ostd/src/boot/mod.rs
@@ -129,7 +129,7 @@ pub fn call_ostd_main() -> ! {
unsafe {
use alloc::boxed::Box;
- use crate::task::{set_scheduler, FifoScheduler, Scheduler, TaskOptions};
+ use crate::task::TaskOptions;
crate::init();
// The whitelists that will be generated by OSDK runner as static consts.
diff --git a/ostd/src/boot/mod.rs b/ostd/src/boot/mod.rs
--- a/ostd/src/boot/mod.rs
+++ b/ostd/src/boot/mod.rs
@@ -137,10 +137,6 @@ pub fn call_ostd_main() -> ! {
static KTEST_TEST_WHITELIST: Option<&'static [&'static str]>;
static KTEST_CRATE_WHITELIST: Option<&'static [&'static str]>;
}
- // Set the global scheduler a FIFO scheduler.
- let simple_scheduler = Box::new(FifoScheduler::new());
- let static_scheduler: &'static dyn Scheduler = Box::leak(simple_scheduler);
- set_scheduler(static_scheduler);
let test_task = move || {
run_ktests(KTEST_TEST_WHITELIST, KTEST_CRATE_WHITELIST);
diff --git a/ostd/src/cpu/local/mod.rs b/ostd/src/cpu/local/mod.rs
--- a/ostd/src/cpu/local/mod.rs
+++ b/ostd/src/cpu/local/mod.rs
@@ -59,20 +59,10 @@ extern "C" {
fn __cpu_local_end();
}
-cpu_local_cell! {
- /// The count of the preempt lock.
- ///
- /// We need to access the preemption count before we can copy the section
- /// for application processors. So, the preemption count is not copied from
- /// bootstrap processor's section as the initialization. Instead it is
- /// initialized to zero for application processors.
- pub(crate) static PREEMPT_LOCK_COUNT: u32 = 0;
-}
-
/// Sets the base address of the CPU-local storage for the bootstrap processor.
///
/// It should be called early to let [`crate::task::disable_preempt`] work,
-/// which needs to update a CPU-local preempt lock count. Otherwise it may
+/// which needs to update a CPU-local preemption info. Otherwise it may
/// panic when calling [`crate::task::disable_preempt`].
///
/// # Safety
diff --git a/ostd/src/cpu/local/mod.rs b/ostd/src/cpu/local/mod.rs
--- a/ostd/src/cpu/local/mod.rs
+++ b/ostd/src/cpu/local/mod.rs
@@ -59,20 +59,10 @@ extern "C" {
fn __cpu_local_end();
}
-cpu_local_cell! {
- /// The count of the preempt lock.
- ///
- /// We need to access the preemption count before we can copy the section
- /// for application processors. So, the preemption count is not copied from
- /// bootstrap processor's section as the initialization. Instead it is
- /// initialized to zero for application processors.
- pub(crate) static PREEMPT_LOCK_COUNT: u32 = 0;
-}
-
/// Sets the base address of the CPU-local storage for the bootstrap processor.
///
/// It should be called early to let [`crate::task::disable_preempt`] work,
-/// which needs to update a CPU-local preempt lock count. Otherwise it may
+/// which needs to update a CPU-local preemption info. Otherwise it may
/// panic when calling [`crate::task::disable_preempt`].
///
/// # Safety
diff --git a/ostd/src/cpu/local/mod.rs b/ostd/src/cpu/local/mod.rs
--- a/ostd/src/cpu/local/mod.rs
+++ b/ostd/src/cpu/local/mod.rs
@@ -133,24 +123,6 @@ pub unsafe fn init_on_bsp() {
(ap_pages_ptr as *mut u32).write(cpu_i);
}
- // SAFETY: the `PREEMPT_LOCK_COUNT` may be dirty on the BSP, so we need
- // to ensure that it is initialized to zero for APs. The safety
- // requirements are met since the static is defined in the `.cpu_local`
- // section and the pointer to that static is the offset in the CPU-
- // local area. It is a `usize` so it is safe to be overwritten.
- unsafe {
- let preempt_count_ptr = &PREEMPT_LOCK_COUNT as *const _ as usize;
- let preempt_count_offset = preempt_count_ptr - __cpu_local_start as usize;
- let ap_preempt_count_ptr = ap_pages_ptr.add(preempt_count_offset) as *mut usize;
- ap_preempt_count_ptr.write(0);
- }
-
- // SAFETY: bytes `8:16` are reserved for storing the pointer to the
- // current task. We initialize it to null.
- unsafe {
- (ap_pages_ptr as *mut u64).add(1).write(0);
- }
-
cpu_local_storages.push(ap_pages);
}
diff --git a/ostd/src/cpu/local/mod.rs b/ostd/src/cpu/local/mod.rs
--- a/ostd/src/cpu/local/mod.rs
+++ b/ostd/src/cpu/local/mod.rs
@@ -133,24 +123,6 @@ pub unsafe fn init_on_bsp() {
(ap_pages_ptr as *mut u32).write(cpu_i);
}
- // SAFETY: the `PREEMPT_LOCK_COUNT` may be dirty on the BSP, so we need
- // to ensure that it is initialized to zero for APs. The safety
- // requirements are met since the static is defined in the `.cpu_local`
- // section and the pointer to that static is the offset in the CPU-
- // local area. It is a `usize` so it is safe to be overwritten.
- unsafe {
- let preempt_count_ptr = &PREEMPT_LOCK_COUNT as *const _ as usize;
- let preempt_count_offset = preempt_count_ptr - __cpu_local_start as usize;
- let ap_preempt_count_ptr = ap_pages_ptr.add(preempt_count_offset) as *mut usize;
- ap_preempt_count_ptr.write(0);
- }
-
- // SAFETY: bytes `8:16` are reserved for storing the pointer to the
- // current task. We initialize it to null.
- unsafe {
- (ap_pages_ptr as *mut u64).add(1).write(0);
- }
-
cpu_local_storages.push(ap_pages);
}
diff --git a/ostd/src/sync/wait.rs b/ostd/src/sync/wait.rs
--- a/ostd/src/sync/wait.rs
+++ b/ostd/src/sync/wait.rs
@@ -4,7 +4,7 @@ use alloc::{collections::VecDeque, sync::Arc};
use core::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use super::SpinLock;
-use crate::task::{add_task, schedule, Task, TaskStatus};
+use crate::task::{scheduler, Task};
// # Explanation on the memory orders
//
diff --git a/ostd/src/sync/wait.rs b/ostd/src/sync/wait.rs
--- a/ostd/src/sync/wait.rs
+++ b/ostd/src/sync/wait.rs
@@ -4,7 +4,7 @@ use alloc::{collections::VecDeque, sync::Arc};
use core::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use super::SpinLock;
-use crate::task::{add_task, schedule, Task, TaskStatus};
+use crate::task::{scheduler, Task};
// # Explanation on the memory orders
//
diff --git a/ostd/src/sync/wait.rs b/ostd/src/sync/wait.rs
--- a/ostd/src/sync/wait.rs
+++ b/ostd/src/sync/wait.rs
@@ -255,36 +255,15 @@ impl Waker {
if self.has_woken.swap(true, Ordering::Release) {
return false;
}
-
- let mut task = self.task.inner_exclusive_access();
- match task.task_status {
- TaskStatus::Sleepy => {
- task.task_status = TaskStatus::Runnable;
- }
- TaskStatus::Sleeping => {
- task.task_status = TaskStatus::Runnable;
-
- // Avoid holding the lock when doing `add_task`
- drop(task);
- add_task(self.task.clone());
- }
- _ => (),
- }
+ scheduler::unpark_target(self.task.clone());
true
}
fn do_wait(&self) {
- while !self.has_woken.swap(false, Ordering::Acquire) {
- let mut task = self.task.inner_exclusive_access();
- // After holding the lock, check again to avoid races
- if self.has_woken.swap(false, Ordering::Acquire) {
- break;
- }
- task.task_status = TaskStatus::Sleepy;
- drop(task);
-
- schedule();
+ let has_woken = &self.has_woken;
+ while !has_woken.swap(false, Ordering::Acquire) {
+ scheduler::park_current(has_woken);
}
}
diff --git a/ostd/src/sync/wait.rs b/ostd/src/sync/wait.rs
--- a/ostd/src/sync/wait.rs
+++ b/ostd/src/sync/wait.rs
@@ -255,36 +255,15 @@ impl Waker {
if self.has_woken.swap(true, Ordering::Release) {
return false;
}
-
- let mut task = self.task.inner_exclusive_access();
- match task.task_status {
- TaskStatus::Sleepy => {
- task.task_status = TaskStatus::Runnable;
- }
- TaskStatus::Sleeping => {
- task.task_status = TaskStatus::Runnable;
-
- // Avoid holding the lock when doing `add_task`
- drop(task);
- add_task(self.task.clone());
- }
- _ => (),
- }
+ scheduler::unpark_target(self.task.clone());
true
}
fn do_wait(&self) {
- while !self.has_woken.swap(false, Ordering::Acquire) {
- let mut task = self.task.inner_exclusive_access();
- // After holding the lock, check again to avoid races
- if self.has_woken.swap(false, Ordering::Acquire) {
- break;
- }
- task.task_status = TaskStatus::Sleepy;
- drop(task);
-
- schedule();
+ let has_woken = &self.has_woken;
+ while !has_woken.swap(false, Ordering::Acquire) {
+ scheduler::park_current(has_woken);
}
}
diff --git a/ostd/src/task/mod.rs b/ostd/src/task/mod.rs
--- a/ostd/src/task/mod.rs
+++ b/ostd/src/task/mod.rs
@@ -2,15 +2,13 @@
//! Tasks are the unit of code execution.
-mod priority;
+mod preempt;
mod processor;
-mod scheduler;
+pub mod scheduler;
#[allow(clippy::module_inception)]
mod task;
pub use self::{
- priority::Priority,
- processor::{disable_preempt, preempt, schedule, DisablePreemptGuard},
- scheduler::{add_task, set_scheduler, FifoScheduler, Scheduler},
- task::{Task, TaskAdapter, TaskContextApi, TaskOptions, TaskStatus},
+ preempt::{disable_preempt, DisablePreemptGuard},
+ task::{AtomicCpuId, Priority, Task, TaskAdapter, TaskContextApi, TaskOptions},
};
diff --git a/ostd/src/task/mod.rs b/ostd/src/task/mod.rs
--- a/ostd/src/task/mod.rs
+++ b/ostd/src/task/mod.rs
@@ -2,15 +2,13 @@
//! Tasks are the unit of code execution.
-mod priority;
+mod preempt;
mod processor;
-mod scheduler;
+pub mod scheduler;
#[allow(clippy::module_inception)]
mod task;
pub use self::{
- priority::Priority,
- processor::{disable_preempt, preempt, schedule, DisablePreemptGuard},
- scheduler::{add_task, set_scheduler, FifoScheduler, Scheduler},
- task::{Task, TaskAdapter, TaskContextApi, TaskOptions, TaskStatus},
+ preempt::{disable_preempt, DisablePreemptGuard},
+ task::{AtomicCpuId, Priority, Task, TaskAdapter, TaskContextApi, TaskOptions},
};
diff --git /dev/null b/ostd/src/task/preempt/cpu_local.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/task/preempt/cpu_local.rs
@@ -0,0 +1,61 @@
+// SPDX-License-Identifier: MPL-2.0
+
+//! This module maintains preemption-related information for the curren task
+//! on a CPU with a single 32-bit, CPU-local integer value.
+//!
+//! * Bits from 0 to 30 represents an unsigned counter called `guard_count`,
+//! which is the number of `DisablePreemptGuard` instances held by the
+//! current CPU;
+//! * Bit 31 is set to `!need_preempt`, where `need_preempt` is a boolean value
+//! that will be set by the scheduler when it decides that the current task
+//! _needs_ to be preempted.
+//!
+//! Thus, the current task on a CPU _should_ be preempted if and only if this
+//! integer is equal to zero.
+//!
+//! The initial value of this integer is equal to `1 << 31`.
+//!
+//! This module provides a set of functions to access and manipulate
+//! `guard_count` and `need_preempt`.
+
+use crate::cpu_local_cell;
+
+/// Returns whether the current task _should_ be preempted or not.
+///
+/// `should_preempt() == need_preempt() && get_guard_count() == 0`.
+pub(in crate::task) fn should_preempt() -> bool {
+ PREEMPT_INFO.load() == 0
+}
+
+#[allow(dead_code)]
+pub(in crate::task) fn need_preempt() -> bool {
+ PREEMPT_INFO.load() & NEED_PREEMPT_MASK == 0
+}
+
+pub(in crate::task) fn set_need_preempt() {
+ PREEMPT_INFO.bitand_assign(!NEED_PREEMPT_MASK);
+}
+
+pub(in crate::task) fn clear_need_preempt() {
+ PREEMPT_INFO.bitor_assign(NEED_PREEMPT_MASK);
+}
+
+pub(in crate::task) fn get_guard_count() -> u32 {
+ PREEMPT_INFO.load() & GUARD_COUNT_MASK
+}
+
+pub(in crate::task) fn inc_guard_count() {
+ PREEMPT_INFO.add_assign(1);
+}
+
+pub(in crate::task) fn dec_guard_count() {
+ debug_assert!(get_guard_count() > 0);
+ PREEMPT_INFO.sub_assign(1);
+}
+
+cpu_local_cell! {
+ static PREEMPT_INFO: u32 = NEED_PREEMPT_MASK;
+}
+
+const NEED_PREEMPT_MASK: u32 = 1 << 31;
+const GUARD_COUNT_MASK: u32 = (1 << 31) - 1;
diff --git /dev/null b/ostd/src/task/preempt/cpu_local.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/task/preempt/cpu_local.rs
@@ -0,0 +1,61 @@
+// SPDX-License-Identifier: MPL-2.0
+
+//! This module maintains preemption-related information for the curren task
+//! on a CPU with a single 32-bit, CPU-local integer value.
+//!
+//! * Bits from 0 to 30 represents an unsigned counter called `guard_count`,
+//! which is the number of `DisablePreemptGuard` instances held by the
+//! current CPU;
+//! * Bit 31 is set to `!need_preempt`, where `need_preempt` is a boolean value
+//! that will be set by the scheduler when it decides that the current task
+//! _needs_ to be preempted.
+//!
+//! Thus, the current task on a CPU _should_ be preempted if and only if this
+//! integer is equal to zero.
+//!
+//! The initial value of this integer is equal to `1 << 31`.
+//!
+//! This module provides a set of functions to access and manipulate
+//! `guard_count` and `need_preempt`.
+
+use crate::cpu_local_cell;
+
+/// Returns whether the current task _should_ be preempted or not.
+///
+/// `should_preempt() == need_preempt() && get_guard_count() == 0`.
+pub(in crate::task) fn should_preempt() -> bool {
+ PREEMPT_INFO.load() == 0
+}
+
+#[allow(dead_code)]
+pub(in crate::task) fn need_preempt() -> bool {
+ PREEMPT_INFO.load() & NEED_PREEMPT_MASK == 0
+}
+
+pub(in crate::task) fn set_need_preempt() {
+ PREEMPT_INFO.bitand_assign(!NEED_PREEMPT_MASK);
+}
+
+pub(in crate::task) fn clear_need_preempt() {
+ PREEMPT_INFO.bitor_assign(NEED_PREEMPT_MASK);
+}
+
+pub(in crate::task) fn get_guard_count() -> u32 {
+ PREEMPT_INFO.load() & GUARD_COUNT_MASK
+}
+
+pub(in crate::task) fn inc_guard_count() {
+ PREEMPT_INFO.add_assign(1);
+}
+
+pub(in crate::task) fn dec_guard_count() {
+ debug_assert!(get_guard_count() > 0);
+ PREEMPT_INFO.sub_assign(1);
+}
+
+cpu_local_cell! {
+ static PREEMPT_INFO: u32 = NEED_PREEMPT_MASK;
+}
+
+const NEED_PREEMPT_MASK: u32 = 1 << 31;
+const GUARD_COUNT_MASK: u32 = (1 << 31) - 1;
diff --git /dev/null b/ostd/src/task/preempt/guard.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/task/preempt/guard.rs
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: MPL-2.0
+
+/// A guard for disable preempt.
+#[clippy::has_significant_drop]
+#[must_use]
+pub struct DisablePreemptGuard {
+ // This private field prevents user from constructing values of this type directly.
+ _private: (),
+}
+
+impl !Send for DisablePreemptGuard {}
+
+impl DisablePreemptGuard {
+ fn new() -> Self {
+ super::cpu_local::inc_guard_count();
+ Self { _private: () }
+ }
+
+ /// Transfer this guard to a new guard.
+ /// This guard must be dropped after this function.
+ pub fn transfer_to(&self) -> Self {
+ disable_preempt()
+ }
+}
+
+impl Drop for DisablePreemptGuard {
+ fn drop(&mut self) {
+ super::cpu_local::dec_guard_count();
+ }
+}
+
+/// Disables preemption.
+pub fn disable_preempt() -> DisablePreemptGuard {
+ DisablePreemptGuard::new()
+}
diff --git /dev/null b/ostd/src/task/preempt/guard.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/task/preempt/guard.rs
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: MPL-2.0
+
+/// A guard for disable preempt.
+#[clippy::has_significant_drop]
+#[must_use]
+pub struct DisablePreemptGuard {
+ // This private field prevents user from constructing values of this type directly.
+ _private: (),
+}
+
+impl !Send for DisablePreemptGuard {}
+
+impl DisablePreemptGuard {
+ fn new() -> Self {
+ super::cpu_local::inc_guard_count();
+ Self { _private: () }
+ }
+
+ /// Transfer this guard to a new guard.
+ /// This guard must be dropped after this function.
+ pub fn transfer_to(&self) -> Self {
+ disable_preempt()
+ }
+}
+
+impl Drop for DisablePreemptGuard {
+ fn drop(&mut self) {
+ super::cpu_local::dec_guard_count();
+ }
+}
+
+/// Disables preemption.
+pub fn disable_preempt() -> DisablePreemptGuard {
+ DisablePreemptGuard::new()
+}
diff --git /dev/null b/ostd/src/task/preempt/mod.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/task/preempt/mod.rs
@@ -0,0 +1,6 @@
+// SPDX-License-Identifier: MPL-2.0
+
+pub(super) mod cpu_local;
+mod guard;
+
+pub use self::guard::{disable_preempt, DisablePreemptGuard};
diff --git /dev/null b/ostd/src/task/preempt/mod.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/task/preempt/mod.rs
@@ -0,0 +1,6 @@
+// SPDX-License-Identifier: MPL-2.0
+
+pub(super) mod cpu_local;
+mod guard;
+
+pub use self::guard::{disable_preempt, DisablePreemptGuard};
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -3,11 +3,10 @@
use alloc::sync::Arc;
use super::{
- scheduler::{fetch_task, GLOBAL_SCHEDULER},
- task::{context_switch, TaskContext},
- Task, TaskStatus,
+ preempt::cpu_local,
+ task::{context_switch, Task, TaskContext},
};
-use crate::{cpu::local::PREEMPT_LOCK_COUNT, cpu_local_cell};
+use crate::cpu_local_cell;
cpu_local_cell! {
/// The `Arc<Task>` (casted by [`Arc::into_raw`]) that is the current task.
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -3,11 +3,10 @@
use alloc::sync::Arc;
use super::{
- scheduler::{fetch_task, GLOBAL_SCHEDULER},
- task::{context_switch, TaskContext},
- Task, TaskStatus,
+ preempt::cpu_local,
+ task::{context_switch, Task, TaskContext},
};
-use crate::{cpu::local::PREEMPT_LOCK_COUNT, cpu_local_cell};
+use crate::cpu_local_cell;
cpu_local_cell! {
/// The `Arc<Task>` (casted by [`Arc::into_raw`]) that is the current task.
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -37,51 +36,21 @@ pub(super) fn current_task() -> Option<Arc<Task>> {
Some(restored)
}
-/// Calls this function to switch to other task by using GLOBAL_SCHEDULER
-pub fn schedule() {
- if let Some(task) = fetch_task() {
- switch_to_task(task);
- }
-}
-
-/// Preempts the `task`.
-///
-/// TODO: This interface of this method is error prone.
-/// The method takes an argument for the current task to optimize its efficiency,
-/// but the argument provided by the caller may not be the current task, really.
-/// Thus, this method should be removed or reworked in the future.
-pub fn preempt(task: &Arc<Task>) {
- // TODO: Refactor `preempt` and `schedule`
- // after the Atomic mode and `might_break` is enabled.
- let mut scheduler = GLOBAL_SCHEDULER.lock_irq_disabled();
- if !scheduler.should_preempt(task) {
- return;
- }
- let Some(next_task) = scheduler.dequeue() else {
- return;
- };
- drop(scheduler);
- switch_to_task(next_task);
-}
-
/// Calls this function to switch to other task
///
/// If current task is none, then it will use the default task context and it
/// will not return to this function again.
///
-/// If the current task's status not [`TaskStatus::Runnable`], it will not be
-/// added to the scheduler.
-///
/// # Panics
///
/// This function will panic if called while holding preemption locks or with
/// local IRQ disabled.
-fn switch_to_task(next_task: Arc<Task>) {
- let preemt_lock_count = PREEMPT_LOCK_COUNT.load();
- if preemt_lock_count != 0 {
+pub(super) fn switch_to_task(next_task: Arc<Task>) {
+ let guard_count = cpu_local::get_guard_count();
+ if guard_count != 0 {
panic!(
- "Calling schedule() while holding {} locks",
- preemt_lock_count
+ "Switching task with preemption disabled (nesting depth: {})",
+ guard_count
);
}
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -37,51 +36,21 @@ pub(super) fn current_task() -> Option<Arc<Task>> {
Some(restored)
}
-/// Calls this function to switch to other task by using GLOBAL_SCHEDULER
-pub fn schedule() {
- if let Some(task) = fetch_task() {
- switch_to_task(task);
- }
-}
-
-/// Preempts the `task`.
-///
-/// TODO: This interface of this method is error prone.
-/// The method takes an argument for the current task to optimize its efficiency,
-/// but the argument provided by the caller may not be the current task, really.
-/// Thus, this method should be removed or reworked in the future.
-pub fn preempt(task: &Arc<Task>) {
- // TODO: Refactor `preempt` and `schedule`
- // after the Atomic mode and `might_break` is enabled.
- let mut scheduler = GLOBAL_SCHEDULER.lock_irq_disabled();
- if !scheduler.should_preempt(task) {
- return;
- }
- let Some(next_task) = scheduler.dequeue() else {
- return;
- };
- drop(scheduler);
- switch_to_task(next_task);
-}
-
/// Calls this function to switch to other task
///
/// If current task is none, then it will use the default task context and it
/// will not return to this function again.
///
-/// If the current task's status not [`TaskStatus::Runnable`], it will not be
-/// added to the scheduler.
-///
/// # Panics
///
/// This function will panic if called while holding preemption locks or with
/// local IRQ disabled.
-fn switch_to_task(next_task: Arc<Task>) {
- let preemt_lock_count = PREEMPT_LOCK_COUNT.load();
- if preemt_lock_count != 0 {
+pub(super) fn switch_to_task(next_task: Arc<Task>) {
+ let guard_count = cpu_local::get_guard_count();
+ if guard_count != 0 {
panic!(
- "Calling schedule() while holding {} locks",
- preemt_lock_count
+ "Switching task with preemption disabled (nesting depth: {})",
+ guard_count
);
}
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -93,7 +62,6 @@ fn switch_to_task(next_task: Arc<Task>) {
let irq_guard = crate::trap::disable_local();
let current_task_ptr = CURRENT_TASK_PTR.load();
-
let current_task_ctx_ptr = if current_task_ptr.is_null() {
// SAFETY: Interrupts are disabled, so the pointer is safe to be fetched.
unsafe { BOOTSTRAP_CONTEXT.as_ptr_mut() }
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -93,7 +62,6 @@ fn switch_to_task(next_task: Arc<Task>) {
let irq_guard = crate::trap::disable_local();
let current_task_ptr = CURRENT_TASK_PTR.load();
-
let current_task_ctx_ptr = if current_task_ptr.is_null() {
// SAFETY: Interrupts are disabled, so the pointer is safe to be fetched.
unsafe { BOOTSTRAP_CONTEXT.as_ptr_mut() }
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -104,24 +72,12 @@ fn switch_to_task(next_task: Arc<Task>) {
let _ = core::mem::ManuallyDrop::new(restored.clone());
restored
};
-
let ctx_ptr = cur_task_arc.ctx().get();
- let mut task_inner = cur_task_arc.inner_exclusive_access();
-
- debug_assert_ne!(task_inner.task_status, TaskStatus::Sleeping);
- if task_inner.task_status == TaskStatus::Runnable {
- drop(task_inner);
- GLOBAL_SCHEDULER.lock().enqueue(cur_task_arc);
- } else if task_inner.task_status == TaskStatus::Sleepy {
- task_inner.task_status = TaskStatus::Sleeping;
- }
-
ctx_ptr
};
let next_task_ctx_ptr = next_task.ctx().get().cast_const();
-
if let Some(next_user_space) = next_task.user_space() {
next_user_space.vm_space().activate();
}
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -104,24 +72,12 @@ fn switch_to_task(next_task: Arc<Task>) {
let _ = core::mem::ManuallyDrop::new(restored.clone());
restored
};
-
let ctx_ptr = cur_task_arc.ctx().get();
- let mut task_inner = cur_task_arc.inner_exclusive_access();
-
- debug_assert_ne!(task_inner.task_status, TaskStatus::Sleeping);
- if task_inner.task_status == TaskStatus::Runnable {
- drop(task_inner);
- GLOBAL_SCHEDULER.lock().enqueue(cur_task_arc);
- } else if task_inner.task_status == TaskStatus::Sleepy {
- task_inner.task_status = TaskStatus::Sleeping;
- }
-
ctx_ptr
};
let next_task_ctx_ptr = next_task.ctx().get().cast_const();
-
if let Some(next_user_space) = next_task.user_space() {
next_user_space.vm_space().activate();
}
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -144,7 +100,7 @@ fn switch_to_task(next_task: Arc<Task>) {
drop(irq_guard);
// SAFETY:
- // 1. `ctx` is only used in `schedule()`. We have exclusive access to both the current task
+ // 1. `ctx` is only used in `reschedule()`. We have exclusive access to both the current task
// context and the next task context.
// 2. The next task context is a valid task context.
unsafe {
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -144,7 +100,7 @@ fn switch_to_task(next_task: Arc<Task>) {
drop(irq_guard);
// SAFETY:
- // 1. `ctx` is only used in `schedule()`. We have exclusive access to both the current task
+ // 1. `ctx` is only used in `reschedule()`. We have exclusive access to both the current task
// context and the next task context.
// 2. The next task context is a valid task context.
unsafe {
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -158,37 +114,3 @@ fn switch_to_task(next_task: Arc<Task>) {
// next task. Not dropping is just fine because the only consequence is that we delay the drop
// to the next task switching.
}
-
-/// A guard for disable preempt.
-#[clippy::has_significant_drop]
-#[must_use]
-pub struct DisablePreemptGuard {
- // This private field prevents user from constructing values of this type directly.
- _private: (),
-}
-
-impl !Send for DisablePreemptGuard {}
-
-impl DisablePreemptGuard {
- fn new() -> Self {
- PREEMPT_LOCK_COUNT.add_assign(1);
- Self { _private: () }
- }
-
- /// Transfer this guard to a new guard.
- /// This guard must be dropped after this function.
- pub fn transfer_to(&self) -> Self {
- disable_preempt()
- }
-}
-
-impl Drop for DisablePreemptGuard {
- fn drop(&mut self) {
- PREEMPT_LOCK_COUNT.sub_assign(1);
- }
-}
-
-/// Disables preemption.
-pub fn disable_preempt() -> DisablePreemptGuard {
- DisablePreemptGuard::new()
-}
diff --git a/ostd/src/task/processor.rs b/ostd/src/task/processor.rs
--- a/ostd/src/task/processor.rs
+++ b/ostd/src/task/processor.rs
@@ -158,37 +114,3 @@ fn switch_to_task(next_task: Arc<Task>) {
// next task. Not dropping is just fine because the only consequence is that we delay the drop
// to the next task switching.
}
-
-/// A guard for disable preempt.
-#[clippy::has_significant_drop]
-#[must_use]
-pub struct DisablePreemptGuard {
- // This private field prevents user from constructing values of this type directly.
- _private: (),
-}
-
-impl !Send for DisablePreemptGuard {}
-
-impl DisablePreemptGuard {
- fn new() -> Self {
- PREEMPT_LOCK_COUNT.add_assign(1);
- Self { _private: () }
- }
-
- /// Transfer this guard to a new guard.
- /// This guard must be dropped after this function.
- pub fn transfer_to(&self) -> Self {
- disable_preempt()
- }
-}
-
-impl Drop for DisablePreemptGuard {
- fn drop(&mut self) {
- PREEMPT_LOCK_COUNT.sub_assign(1);
- }
-}
-
-/// Disables preemption.
-pub fn disable_preempt() -> DisablePreemptGuard {
- DisablePreemptGuard::new()
-}
diff --git a/ostd/src/task/scheduler.rs /dev/null
--- a/ostd/src/task/scheduler.rs
+++ /dev/null
@@ -1,107 +0,0 @@
-// SPDX-License-Identifier: MPL-2.0
-
-#![allow(dead_code)]
-
-use alloc::collections::VecDeque;
-
-use crate::{prelude::*, sync::SpinLock, task::Task};
-
-static DEFAULT_SCHEDULER: FifoScheduler = FifoScheduler::new();
-pub(crate) static GLOBAL_SCHEDULER: SpinLock<GlobalScheduler> = SpinLock::new(GlobalScheduler {
- scheduler: &DEFAULT_SCHEDULER,
-});
-
-/// A scheduler for tasks.
-///
-/// An implementation of scheduler can attach scheduler-related information
-/// with the `TypeMap` returned from `task.data()`.
-pub trait Scheduler: Sync + Send {
- /// Enqueues a task to the scheduler.
- fn enqueue(&self, task: Arc<Task>);
-
- /// Dequeues a task from the scheduler.
- fn dequeue(&self) -> Option<Arc<Task>>;
-
- /// Tells whether the given task should be preempted by other tasks in the queue.
- fn should_preempt(&self, task: &Arc<Task>) -> bool;
-}
-
-pub struct GlobalScheduler {
- scheduler: &'static dyn Scheduler,
-}
-
-impl GlobalScheduler {
- pub const fn new(scheduler: &'static dyn Scheduler) -> Self {
- Self { scheduler }
- }
-
- /// dequeue a task using scheduler
- /// require the scheduler is not none
- pub fn dequeue(&mut self) -> Option<Arc<Task>> {
- self.scheduler.dequeue()
- }
- /// enqueue a task using scheduler
- /// require the scheduler is not none
- pub fn enqueue(&mut self, task: Arc<Task>) {
- self.scheduler.enqueue(task)
- }
-
- pub fn should_preempt(&self, task: &Arc<Task>) -> bool {
- self.scheduler.should_preempt(task)
- }
-}
-/// Sets the global task scheduler.
-///
-/// This must be called before invoking `Task::spawn`.
-pub fn set_scheduler(scheduler: &'static dyn Scheduler) {
- let mut global_scheduler = GLOBAL_SCHEDULER.lock_irq_disabled();
- // When setting a new scheduler, the old scheduler should be empty
- assert!(global_scheduler.dequeue().is_none());
- global_scheduler.scheduler = scheduler;
-}
-
-pub fn fetch_task() -> Option<Arc<Task>> {
- GLOBAL_SCHEDULER.lock_irq_disabled().dequeue()
-}
-
-/// Adds a task to the global scheduler.
-pub fn add_task(task: Arc<Task>) {
- GLOBAL_SCHEDULER.lock_irq_disabled().enqueue(task);
-}
-
-/// A simple FIFO (First-In-First-Out) task scheduler.
-pub struct FifoScheduler {
- /// A thread-safe queue to hold tasks waiting to be executed.
- task_queue: SpinLock<VecDeque<Arc<Task>>>,
-}
-
-impl FifoScheduler {
- /// Creates a new instance of `FifoScheduler`.
- pub const fn new() -> Self {
- FifoScheduler {
- task_queue: SpinLock::new(VecDeque::new()),
- }
- }
-}
-
-impl Default for FifoScheduler {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl Scheduler for FifoScheduler {
- /// Enqueues a task to the end of the queue.
- fn enqueue(&self, task: Arc<Task>) {
- self.task_queue.lock_irq_disabled().push_back(task);
- }
- /// Dequeues a task from the front of the queue, if any.
- fn dequeue(&self) -> Option<Arc<Task>> {
- self.task_queue.lock_irq_disabled().pop_front()
- }
- /// In this simple implementation, task preemption is not supported.
- /// Once a task starts running, it will continue to run until completion.
- fn should_preempt(&self, _task: &Arc<Task>) -> bool {
- false
- }
-}
diff --git a/ostd/src/task/scheduler.rs /dev/null
--- a/ostd/src/task/scheduler.rs
+++ /dev/null
@@ -1,107 +0,0 @@
-// SPDX-License-Identifier: MPL-2.0
-
-#![allow(dead_code)]
-
-use alloc::collections::VecDeque;
-
-use crate::{prelude::*, sync::SpinLock, task::Task};
-
-static DEFAULT_SCHEDULER: FifoScheduler = FifoScheduler::new();
-pub(crate) static GLOBAL_SCHEDULER: SpinLock<GlobalScheduler> = SpinLock::new(GlobalScheduler {
- scheduler: &DEFAULT_SCHEDULER,
-});
-
-/// A scheduler for tasks.
-///
-/// An implementation of scheduler can attach scheduler-related information
-/// with the `TypeMap` returned from `task.data()`.
-pub trait Scheduler: Sync + Send {
- /// Enqueues a task to the scheduler.
- fn enqueue(&self, task: Arc<Task>);
-
- /// Dequeues a task from the scheduler.
- fn dequeue(&self) -> Option<Arc<Task>>;
-
- /// Tells whether the given task should be preempted by other tasks in the queue.
- fn should_preempt(&self, task: &Arc<Task>) -> bool;
-}
-
-pub struct GlobalScheduler {
- scheduler: &'static dyn Scheduler,
-}
-
-impl GlobalScheduler {
- pub const fn new(scheduler: &'static dyn Scheduler) -> Self {
- Self { scheduler }
- }
-
- /// dequeue a task using scheduler
- /// require the scheduler is not none
- pub fn dequeue(&mut self) -> Option<Arc<Task>> {
- self.scheduler.dequeue()
- }
- /// enqueue a task using scheduler
- /// require the scheduler is not none
- pub fn enqueue(&mut self, task: Arc<Task>) {
- self.scheduler.enqueue(task)
- }
-
- pub fn should_preempt(&self, task: &Arc<Task>) -> bool {
- self.scheduler.should_preempt(task)
- }
-}
-/// Sets the global task scheduler.
-///
-/// This must be called before invoking `Task::spawn`.
-pub fn set_scheduler(scheduler: &'static dyn Scheduler) {
- let mut global_scheduler = GLOBAL_SCHEDULER.lock_irq_disabled();
- // When setting a new scheduler, the old scheduler should be empty
- assert!(global_scheduler.dequeue().is_none());
- global_scheduler.scheduler = scheduler;
-}
-
-pub fn fetch_task() -> Option<Arc<Task>> {
- GLOBAL_SCHEDULER.lock_irq_disabled().dequeue()
-}
-
-/// Adds a task to the global scheduler.
-pub fn add_task(task: Arc<Task>) {
- GLOBAL_SCHEDULER.lock_irq_disabled().enqueue(task);
-}
-
-/// A simple FIFO (First-In-First-Out) task scheduler.
-pub struct FifoScheduler {
- /// A thread-safe queue to hold tasks waiting to be executed.
- task_queue: SpinLock<VecDeque<Arc<Task>>>,
-}
-
-impl FifoScheduler {
- /// Creates a new instance of `FifoScheduler`.
- pub const fn new() -> Self {
- FifoScheduler {
- task_queue: SpinLock::new(VecDeque::new()),
- }
- }
-}
-
-impl Default for FifoScheduler {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl Scheduler for FifoScheduler {
- /// Enqueues a task to the end of the queue.
- fn enqueue(&self, task: Arc<Task>) {
- self.task_queue.lock_irq_disabled().push_back(task);
- }
- /// Dequeues a task from the front of the queue, if any.
- fn dequeue(&self) -> Option<Arc<Task>> {
- self.task_queue.lock_irq_disabled().pop_front()
- }
- /// In this simple implementation, task preemption is not supported.
- /// Once a task starts running, it will continue to run until completion.
- fn should_preempt(&self, _task: &Arc<Task>) -> bool {
- false
- }
-}
diff --git /dev/null b/ostd/src/task/scheduler/fifo_scheduler.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/task/scheduler/fifo_scheduler.rs
@@ -0,0 +1,125 @@
+// SPDX-License-Identifier: MPL-2.0
+
+use alloc::{boxed::Box, collections::VecDeque, sync::Arc, vec::Vec};
+
+use super::{inject_scheduler, EnqueueFlags, LocalRunQueue, Scheduler, UpdateFlags};
+use crate::{
+ cpu::{num_cpus, this_cpu},
+ sync::SpinLock,
+ task::{AtomicCpuId, Task},
+};
+
+pub fn init() {
+ let fifo_scheduler = Box::new(FifoScheduler::default());
+ let scheduler = Box::<FifoScheduler<Task>>::leak(fifo_scheduler);
+ inject_scheduler(scheduler);
+}
+
+/// A simple FIFO (First-In-First-Out) task scheduler.
+struct FifoScheduler<T: FifoSchedInfo> {
+ /// A thread-safe queue to hold tasks waiting to be executed.
+ rq: Vec<SpinLock<FifoRunQueue<T>>>,
+}
+
+impl<T: FifoSchedInfo> FifoScheduler<T> {
+ /// Creates a new instance of `FifoScheduler`.
+ fn new(nr_cpus: u32) -> Self {
+ let mut rq = Vec::new();
+ for _ in 0..nr_cpus {
+ rq.push(SpinLock::new(FifoRunQueue::new()));
+ }
+ Self { rq }
+ }
+
+ fn select_cpu(&self) -> u32 {
+ // FIXME: adopt more reasonable policy once we fully enable SMP.
+ 0
+ }
+}
+
+impl<T: FifoSchedInfo + Send + Sync> Scheduler<T> for FifoScheduler<T> {
+ fn enqueue(&self, runnable: Arc<T>, flags: EnqueueFlags) -> Option<u32> {
+ let mut still_in_rq = false;
+ let target_cpu = {
+ let mut cpu_id = self.select_cpu();
+ if let Err(task_cpu_id) = runnable.cpu().set_if_is_none(cpu_id) {
+ debug_assert!(flags != EnqueueFlags::Spawn);
+ still_in_rq = true;
+ cpu_id = task_cpu_id;
+ }
+
+ cpu_id
+ };
+
+ let mut rq = self.rq[target_cpu as usize].lock_irq_disabled();
+ if still_in_rq && let Err(_) = runnable.cpu().set_if_is_none(target_cpu) {
+ return None;
+ }
+ rq.queue.push_back(runnable);
+
+ Some(target_cpu)
+ }
+
+ fn local_rq_with(&self, f: &mut dyn FnMut(&dyn LocalRunQueue<T>)) {
+ let local_rq: &FifoRunQueue<T> = &self.rq[this_cpu() as usize].lock_irq_disabled();
+ f(local_rq);
+ }
+
+ fn local_mut_rq_with(&self, f: &mut dyn FnMut(&mut dyn LocalRunQueue<T>)) {
+ let local_rq: &mut FifoRunQueue<T> = &mut self.rq[this_cpu() as usize].lock_irq_disabled();
+ f(local_rq);
+ }
+}
+
+struct FifoRunQueue<T: FifoSchedInfo> {
+ current: Option<Arc<T>>,
+ queue: VecDeque<Arc<T>>,
+}
+
+impl<T: FifoSchedInfo> FifoRunQueue<T> {
+ pub const fn new() -> Self {
+ Self {
+ current: None,
+ queue: VecDeque::new(),
+ }
+ }
+}
+
+impl<T: FifoSchedInfo> LocalRunQueue<T> for FifoRunQueue<T> {
+ fn current(&self) -> Option<&Arc<T>> {
+ self.current.as_ref()
+ }
+
+ fn update_current(&mut self, flags: super::UpdateFlags) -> bool {
+ !matches!(flags, UpdateFlags::Tick)
+ }
+
+ fn pick_next_current(&mut self) -> Option<&Arc<T>> {
+ let next_task = self.queue.pop_front()?;
+ if let Some(prev_task) = self.current.replace(next_task) {
+ self.queue.push_back(prev_task);
+ }
+
+ self.current.as_ref()
+ }
+
+ fn dequeue_current(&mut self) -> Option<Arc<T>> {
+ self.current.take().inspect(|task| task.cpu().set_to_none())
+ }
+}
+
+impl Default for FifoScheduler<Task> {
+ fn default() -> Self {
+ Self::new(num_cpus())
+ }
+}
+
+impl FifoSchedInfo for Task {
+ fn cpu(&self) -> &AtomicCpuId {
+ self.cpu()
+ }
+}
+
+trait FifoSchedInfo {
+ fn cpu(&self) -> &AtomicCpuId;
+}
diff --git /dev/null b/ostd/src/task/scheduler/fifo_scheduler.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/task/scheduler/fifo_scheduler.rs
@@ -0,0 +1,125 @@
+// SPDX-License-Identifier: MPL-2.0
+
+use alloc::{boxed::Box, collections::VecDeque, sync::Arc, vec::Vec};
+
+use super::{inject_scheduler, EnqueueFlags, LocalRunQueue, Scheduler, UpdateFlags};
+use crate::{
+ cpu::{num_cpus, this_cpu},
+ sync::SpinLock,
+ task::{AtomicCpuId, Task},
+};
+
+pub fn init() {
+ let fifo_scheduler = Box::new(FifoScheduler::default());
+ let scheduler = Box::<FifoScheduler<Task>>::leak(fifo_scheduler);
+ inject_scheduler(scheduler);
+}
+
+/// A simple FIFO (First-In-First-Out) task scheduler.
+struct FifoScheduler<T: FifoSchedInfo> {
+ /// A thread-safe queue to hold tasks waiting to be executed.
+ rq: Vec<SpinLock<FifoRunQueue<T>>>,
+}
+
+impl<T: FifoSchedInfo> FifoScheduler<T> {
+ /// Creates a new instance of `FifoScheduler`.
+ fn new(nr_cpus: u32) -> Self {
+ let mut rq = Vec::new();
+ for _ in 0..nr_cpus {
+ rq.push(SpinLock::new(FifoRunQueue::new()));
+ }
+ Self { rq }
+ }
+
+ fn select_cpu(&self) -> u32 {
+ // FIXME: adopt more reasonable policy once we fully enable SMP.
+ 0
+ }
+}
+
+impl<T: FifoSchedInfo + Send + Sync> Scheduler<T> for FifoScheduler<T> {
+ fn enqueue(&self, runnable: Arc<T>, flags: EnqueueFlags) -> Option<u32> {
+ let mut still_in_rq = false;
+ let target_cpu = {
+ let mut cpu_id = self.select_cpu();
+ if let Err(task_cpu_id) = runnable.cpu().set_if_is_none(cpu_id) {
+ debug_assert!(flags != EnqueueFlags::Spawn);
+ still_in_rq = true;
+ cpu_id = task_cpu_id;
+ }
+
+ cpu_id
+ };
+
+ let mut rq = self.rq[target_cpu as usize].lock_irq_disabled();
+ if still_in_rq && let Err(_) = runnable.cpu().set_if_is_none(target_cpu) {
+ return None;
+ }
+ rq.queue.push_back(runnable);
+
+ Some(target_cpu)
+ }
+
+ fn local_rq_with(&self, f: &mut dyn FnMut(&dyn LocalRunQueue<T>)) {
+ let local_rq: &FifoRunQueue<T> = &self.rq[this_cpu() as usize].lock_irq_disabled();
+ f(local_rq);
+ }
+
+ fn local_mut_rq_with(&self, f: &mut dyn FnMut(&mut dyn LocalRunQueue<T>)) {
+ let local_rq: &mut FifoRunQueue<T> = &mut self.rq[this_cpu() as usize].lock_irq_disabled();
+ f(local_rq);
+ }
+}
+
+struct FifoRunQueue<T: FifoSchedInfo> {
+ current: Option<Arc<T>>,
+ queue: VecDeque<Arc<T>>,
+}
+
+impl<T: FifoSchedInfo> FifoRunQueue<T> {
+ pub const fn new() -> Self {
+ Self {
+ current: None,
+ queue: VecDeque::new(),
+ }
+ }
+}
+
+impl<T: FifoSchedInfo> LocalRunQueue<T> for FifoRunQueue<T> {
+ fn current(&self) -> Option<&Arc<T>> {
+ self.current.as_ref()
+ }
+
+ fn update_current(&mut self, flags: super::UpdateFlags) -> bool {
+ !matches!(flags, UpdateFlags::Tick)
+ }
+
+ fn pick_next_current(&mut self) -> Option<&Arc<T>> {
+ let next_task = self.queue.pop_front()?;
+ if let Some(prev_task) = self.current.replace(next_task) {
+ self.queue.push_back(prev_task);
+ }
+
+ self.current.as_ref()
+ }
+
+ fn dequeue_current(&mut self) -> Option<Arc<T>> {
+ self.current.take().inspect(|task| task.cpu().set_to_none())
+ }
+}
+
+impl Default for FifoScheduler<Task> {
+ fn default() -> Self {
+ Self::new(num_cpus())
+ }
+}
+
+impl FifoSchedInfo for Task {
+ fn cpu(&self) -> &AtomicCpuId {
+ self.cpu()
+ }
+}
+
+trait FifoSchedInfo {
+ fn cpu(&self) -> &AtomicCpuId;
+}
diff --git /dev/null b/ostd/src/task/scheduler/mod.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/task/scheduler/mod.rs
@@ -0,0 +1,241 @@
+// SPDX-License-Identifier: MPL-2.0
+
+//! Scheduling subsystem (in-OSTD part).
+//!
+//! This module defines what OSTD expects from a scheduling implementation
+//! and provides useful functions for controlling the execution flow.
+
+mod fifo_scheduler;
+
+use core::sync::atomic::{AtomicBool, Ordering};
+
+use spin::Once;
+
+use super::{preempt::cpu_local, processor, task::Task};
+use crate::{arch::timer, cpu::this_cpu, prelude::*};
+
+/// Injects a scheduler implementation into framework.
+///
+/// This function can only be called once and must be called during the initialization of kernel.
+pub fn inject_scheduler(scheduler: &'static dyn Scheduler<Task>) {
+ SCHEDULER.call_once(|| scheduler);
+
+ timer::register_callback(|| {
+ SCHEDULER.get().unwrap().local_mut_rq_with(&mut |local_rq| {
+ if local_rq.update_current(UpdateFlags::Tick) {
+ cpu_local::set_need_preempt();
+ }
+ })
+ });
+}
+
+static SCHEDULER: Once<&'static dyn Scheduler<Task>> = Once::new();
+
+/// A per-CPU task scheduler.
+pub trait Scheduler<T = Task>: Sync + Send {
+ /// Enqueues a runnable task.
+ ///
+ /// Scheduler developers can perform load-balancing or some accounting work here.
+ ///
+ /// If the `current` of a CPU needs to be preempted, this method returns the id of
+ /// that CPU.
+ fn enqueue(&self, runnable: Arc<T>, flags: EnqueueFlags) -> Option<u32>;
+
+ /// Gets an immutable access to the local runqueue of the current CPU core.
+ fn local_rq_with(&self, f: &mut dyn FnMut(&dyn LocalRunQueue<T>));
+
+ /// Gets a mutable access to the local runqueue of the current CPU core.
+ fn local_mut_rq_with(&self, f: &mut dyn FnMut(&mut dyn LocalRunQueue<T>));
+}
+
+/// The _local_ view of a per-CPU runqueue.
+///
+/// This local view provides the interface for the runqueue of a CPU core
+/// to be inspected and manipulated by the code running on this particular CPU core.
+///
+/// Conceptually, a local runqueue consists of two parts:
+/// (1) a priority queue of runnable tasks;
+/// (2) the current running task.
+/// The exact definition of "priority" is left for the concrete implementation to decide.
+pub trait LocalRunQueue<T = Task> {
+ /// Gets the current runnable task.
+ fn current(&self) -> Option<&Arc<T>>;
+
+ /// Updates the current runnable task's scheduling statistics and potentially its
+ /// position in the queue.
+ ///
+ /// If the current runnable task needs to be preempted, the method returns `true`.
+ fn update_current(&mut self, flags: UpdateFlags) -> bool;
+
+ /// Picks the next current runnable task.
+ ///
+ /// This method returns the chosen next current runnable task. If there is no
+ /// candidate for next current runnable task, this method returns `None`.
+ fn pick_next_current(&mut self) -> Option<&Arc<T>>;
+
+ /// Removes the current runnable task from runqueue.
+ ///
+ /// This method returns the current runnable task. If there is no current runnable
+ /// task, this method returns `None`.
+ fn dequeue_current(&mut self) -> Option<Arc<T>>;
+}
+
+/// Possible triggers of an `enqueue` action.
+#[derive(PartialEq, Copy, Clone)]
+pub enum EnqueueFlags {
+ /// Spawn a new task.
+ Spawn,
+ /// Wake a sleeping task.
+ Wake,
+}
+
+/// Possible triggers of an `update_current` action.
+#[derive(PartialEq, Copy, Clone)]
+pub enum UpdateFlags {
+ /// Timer interrupt.
+ Tick,
+ /// Task waiting.
+ Wait,
+ /// Task yielding.
+ Yield,
+}
+
+/// Preempts the current task.
+pub(crate) fn might_preempt() {
+ if !cpu_local::should_preempt() {
+ return;
+ }
+ yield_now();
+}
+
+/// Blocks the current task unless `has_woken` is `true`.
+pub(crate) fn park_current(has_woken: &AtomicBool) {
+ let mut current = None;
+ let mut is_first_try = true;
+ reschedule(&mut |local_rq: &mut dyn LocalRunQueue| {
+ if is_first_try {
+ if has_woken.load(Ordering::Acquire) {
+ return ReschedAction::DoNothing;
+ }
+ current = local_rq.dequeue_current();
+ local_rq.update_current(UpdateFlags::Wait);
+ }
+ if let Some(next_task) = local_rq.pick_next_current() {
+ if Arc::ptr_eq(current.as_ref().unwrap(), next_task) {
+ return ReschedAction::DoNothing;
+ }
+ ReschedAction::SwitchTo(next_task.clone())
+ } else {
+ is_first_try = false;
+ ReschedAction::Retry
+ }
+ });
+}
+
+/// Unblocks a target task.
+pub(crate) fn unpark_target(runnable: Arc<Task>) {
+ let need_preempt_info = SCHEDULER
+ .get()
+ .unwrap()
+ .enqueue(runnable, EnqueueFlags::Wake);
+ if need_preempt_info.is_some() {
+ let cpu_id = need_preempt_info.unwrap();
+ // FIXME: send IPI to set remote CPU's need_preempt if needed.
+ if cpu_id == this_cpu() {
+ cpu_local::set_need_preempt();
+ }
+ }
+}
+
+/// Enqueues a newly built task.
+///
+/// Note that the new task is not guranteed to run at once.
+pub(super) fn run_new_task(runnable: Arc<Task>) {
+ // FIXME: remove this check for `SCHEDULER`.
+ // Currently OSTD cannot know whether its user has injected a scheduler.
+ if !SCHEDULER.is_completed() {
+ fifo_scheduler::init();
+ }
+
+ let need_preempt_info = SCHEDULER
+ .get()
+ .unwrap()
+ .enqueue(runnable, EnqueueFlags::Spawn);
+ if need_preempt_info.is_some() {
+ let cpu_id = need_preempt_info.unwrap();
+ // FIXME: send IPI to set remote CPU's need_preempt if needed.
+ if cpu_id == this_cpu() {
+ cpu_local::set_need_preempt();
+ }
+ }
+
+ might_preempt();
+}
+
+/// Dequeues the current task from its runqueue.
+///
+/// This should only be called if the current is to exit.
+pub(super) fn exit_current() {
+ reschedule(&mut |local_rq: &mut dyn LocalRunQueue| {
+ let _ = local_rq.dequeue_current();
+ if let Some(next_task) = local_rq.pick_next_current() {
+ ReschedAction::SwitchTo(next_task.clone())
+ } else {
+ ReschedAction::Retry
+ }
+ })
+}
+
+/// Yields execution.
+pub(super) fn yield_now() {
+ reschedule(&mut |local_rq| {
+ local_rq.update_current(UpdateFlags::Yield);
+
+ if let Some(next_task) = local_rq.pick_next_current() {
+ ReschedAction::SwitchTo(next_task.clone())
+ } else {
+ ReschedAction::DoNothing
+ }
+ })
+}
+
+/// Do rescheduling by acting on the scheduling decision (`ReschedAction`) made by a
+/// user-given closure.
+///
+/// The closure makes the scheduling decision by taking the local runqueue has its input.
+fn reschedule<F>(f: &mut F)
+where
+ F: FnMut(&mut dyn LocalRunQueue) -> ReschedAction,
+{
+ let next_task = loop {
+ let mut action = ReschedAction::DoNothing;
+ SCHEDULER.get().unwrap().local_mut_rq_with(&mut |rq| {
+ action = f(rq);
+ });
+
+ match action {
+ ReschedAction::DoNothing => {
+ return;
+ }
+ ReschedAction::Retry => {
+ continue;
+ }
+ ReschedAction::SwitchTo(next_task) => {
+ break next_task;
+ }
+ };
+ };
+
+ cpu_local::clear_need_preempt();
+ processor::switch_to_task(next_task);
+}
+
+/// Possible actions of a rescheduling.
+enum ReschedAction {
+ /// Keep running current task and do nothing.
+ DoNothing,
+ /// Loop until finding a task to swap out the current.
+ Retry,
+ /// Switch to target task.
+ SwitchTo(Arc<Task>),
+}
diff --git /dev/null b/ostd/src/task/scheduler/mod.rs
new file mode 100644
--- /dev/null
+++ b/ostd/src/task/scheduler/mod.rs
@@ -0,0 +1,241 @@
+// SPDX-License-Identifier: MPL-2.0
+
+//! Scheduling subsystem (in-OSTD part).
+//!
+//! This module defines what OSTD expects from a scheduling implementation
+//! and provides useful functions for controlling the execution flow.
+
+mod fifo_scheduler;
+
+use core::sync::atomic::{AtomicBool, Ordering};
+
+use spin::Once;
+
+use super::{preempt::cpu_local, processor, task::Task};
+use crate::{arch::timer, cpu::this_cpu, prelude::*};
+
+/// Injects a scheduler implementation into framework.
+///
+/// This function can only be called once and must be called during the initialization of kernel.
+pub fn inject_scheduler(scheduler: &'static dyn Scheduler<Task>) {
+ SCHEDULER.call_once(|| scheduler);
+
+ timer::register_callback(|| {
+ SCHEDULER.get().unwrap().local_mut_rq_with(&mut |local_rq| {
+ if local_rq.update_current(UpdateFlags::Tick) {
+ cpu_local::set_need_preempt();
+ }
+ })
+ });
+}
+
+static SCHEDULER: Once<&'static dyn Scheduler<Task>> = Once::new();
+
+/// A per-CPU task scheduler.
+pub trait Scheduler<T = Task>: Sync + Send {
+ /// Enqueues a runnable task.
+ ///
+ /// Scheduler developers can perform load-balancing or some accounting work here.
+ ///
+ /// If the `current` of a CPU needs to be preempted, this method returns the id of
+ /// that CPU.
+ fn enqueue(&self, runnable: Arc<T>, flags: EnqueueFlags) -> Option<u32>;
+
+ /// Gets an immutable access to the local runqueue of the current CPU core.
+ fn local_rq_with(&self, f: &mut dyn FnMut(&dyn LocalRunQueue<T>));
+
+ /// Gets a mutable access to the local runqueue of the current CPU core.
+ fn local_mut_rq_with(&self, f: &mut dyn FnMut(&mut dyn LocalRunQueue<T>));
+}
+
+/// The _local_ view of a per-CPU runqueue.
+///
+/// This local view provides the interface for the runqueue of a CPU core
+/// to be inspected and manipulated by the code running on this particular CPU core.
+///
+/// Conceptually, a local runqueue consists of two parts:
+/// (1) a priority queue of runnable tasks;
+/// (2) the current running task.
+/// The exact definition of "priority" is left for the concrete implementation to decide.
+pub trait LocalRunQueue<T = Task> {
+ /// Gets the current runnable task.
+ fn current(&self) -> Option<&Arc<T>>;
+
+ /// Updates the current runnable task's scheduling statistics and potentially its
+ /// position in the queue.
+ ///
+ /// If the current runnable task needs to be preempted, the method returns `true`.
+ fn update_current(&mut self, flags: UpdateFlags) -> bool;
+
+ /// Picks the next current runnable task.
+ ///
+ /// This method returns the chosen next current runnable task. If there is no
+ /// candidate for next current runnable task, this method returns `None`.
+ fn pick_next_current(&mut self) -> Option<&Arc<T>>;
+
+ /// Removes the current runnable task from runqueue.
+ ///
+ /// This method returns the current runnable task. If there is no current runnable
+ /// task, this method returns `None`.
+ fn dequeue_current(&mut self) -> Option<Arc<T>>;
+}
+
+/// Possible triggers of an `enqueue` action.
+#[derive(PartialEq, Copy, Clone)]
+pub enum EnqueueFlags {
+ /// Spawn a new task.
+ Spawn,
+ /// Wake a sleeping task.
+ Wake,
+}
+
+/// Possible triggers of an `update_current` action.
+#[derive(PartialEq, Copy, Clone)]
+pub enum UpdateFlags {
+ /// Timer interrupt.
+ Tick,
+ /// Task waiting.
+ Wait,
+ /// Task yielding.
+ Yield,
+}
+
+/// Preempts the current task.
+pub(crate) fn might_preempt() {
+ if !cpu_local::should_preempt() {
+ return;
+ }
+ yield_now();
+}
+
+/// Blocks the current task unless `has_woken` is `true`.
+pub(crate) fn park_current(has_woken: &AtomicBool) {
+ let mut current = None;
+ let mut is_first_try = true;
+ reschedule(&mut |local_rq: &mut dyn LocalRunQueue| {
+ if is_first_try {
+ if has_woken.load(Ordering::Acquire) {
+ return ReschedAction::DoNothing;
+ }
+ current = local_rq.dequeue_current();
+ local_rq.update_current(UpdateFlags::Wait);
+ }
+ if let Some(next_task) = local_rq.pick_next_current() {
+ if Arc::ptr_eq(current.as_ref().unwrap(), next_task) {
+ return ReschedAction::DoNothing;
+ }
+ ReschedAction::SwitchTo(next_task.clone())
+ } else {
+ is_first_try = false;
+ ReschedAction::Retry
+ }
+ });
+}
+
+/// Unblocks a target task.
+pub(crate) fn unpark_target(runnable: Arc<Task>) {
+ let need_preempt_info = SCHEDULER
+ .get()
+ .unwrap()
+ .enqueue(runnable, EnqueueFlags::Wake);
+ if need_preempt_info.is_some() {
+ let cpu_id = need_preempt_info.unwrap();
+ // FIXME: send IPI to set remote CPU's need_preempt if needed.
+ if cpu_id == this_cpu() {
+ cpu_local::set_need_preempt();
+ }
+ }
+}
+
+/// Enqueues a newly built task.
+///
+/// Note that the new task is not guranteed to run at once.
+pub(super) fn run_new_task(runnable: Arc<Task>) {
+ // FIXME: remove this check for `SCHEDULER`.
+ // Currently OSTD cannot know whether its user has injected a scheduler.
+ if !SCHEDULER.is_completed() {
+ fifo_scheduler::init();
+ }
+
+ let need_preempt_info = SCHEDULER
+ .get()
+ .unwrap()
+ .enqueue(runnable, EnqueueFlags::Spawn);
+ if need_preempt_info.is_some() {
+ let cpu_id = need_preempt_info.unwrap();
+ // FIXME: send IPI to set remote CPU's need_preempt if needed.
+ if cpu_id == this_cpu() {
+ cpu_local::set_need_preempt();
+ }
+ }
+
+ might_preempt();
+}
+
+/// Dequeues the current task from its runqueue.
+///
+/// This should only be called if the current is to exit.
+pub(super) fn exit_current() {
+ reschedule(&mut |local_rq: &mut dyn LocalRunQueue| {
+ let _ = local_rq.dequeue_current();
+ if let Some(next_task) = local_rq.pick_next_current() {
+ ReschedAction::SwitchTo(next_task.clone())
+ } else {
+ ReschedAction::Retry
+ }
+ })
+}
+
+/// Yields execution.
+pub(super) fn yield_now() {
+ reschedule(&mut |local_rq| {
+ local_rq.update_current(UpdateFlags::Yield);
+
+ if let Some(next_task) = local_rq.pick_next_current() {
+ ReschedAction::SwitchTo(next_task.clone())
+ } else {
+ ReschedAction::DoNothing
+ }
+ })
+}
+
+/// Do rescheduling by acting on the scheduling decision (`ReschedAction`) made by a
+/// user-given closure.
+///
+/// The closure makes the scheduling decision by taking the local runqueue has its input.
+fn reschedule<F>(f: &mut F)
+where
+ F: FnMut(&mut dyn LocalRunQueue) -> ReschedAction,
+{
+ let next_task = loop {
+ let mut action = ReschedAction::DoNothing;
+ SCHEDULER.get().unwrap().local_mut_rq_with(&mut |rq| {
+ action = f(rq);
+ });
+
+ match action {
+ ReschedAction::DoNothing => {
+ return;
+ }
+ ReschedAction::Retry => {
+ continue;
+ }
+ ReschedAction::SwitchTo(next_task) => {
+ break next_task;
+ }
+ };
+ };
+
+ cpu_local::clear_need_preempt();
+ processor::switch_to_task(next_task);
+}
+
+/// Possible actions of a rescheduling.
+enum ReschedAction {
+ /// Keep running current task and do nothing.
+ DoNothing,
+ /// Loop until finding a task to swap out the current.
+ Retry,
+ /// Switch to target task.
+ SwitchTo(Arc<Task>),
+}
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task/mod.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task/mod.rs
@@ -4,22 +4,23 @@
// So we temporary allow missing_docs for this module.
#![allow(missing_docs)]
-use alloc::{boxed::Box, sync::Arc};
-use core::{any::Any, cell::UnsafeCell};
+mod priority;
+
+use core::{
+ any::Any,
+ cell::UnsafeCell,
+ sync::atomic::{AtomicU32, Ordering},
+};
use intrusive_collections::{intrusive_adapter, LinkedListAtomicLink};
+pub use priority::Priority;
-use super::{
- add_task,
- priority::Priority,
- processor::{current_task, schedule},
-};
+use super::{processor::current_task, scheduler};
pub(crate) use crate::arch::task::{context_switch, TaskContext};
use crate::{
cpu::CpuSet,
mm::{kspace::KERNEL_PAGE_TABLE, FrameAllocOptions, Paddr, PageFlags, Segment, PAGE_SIZE},
prelude::*,
- sync::{SpinLock, SpinLockGuard},
user::UserSpace,
};
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task/mod.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task/mod.rs
@@ -4,22 +4,23 @@
// So we temporary allow missing_docs for this module.
#![allow(missing_docs)]
-use alloc::{boxed::Box, sync::Arc};
-use core::{any::Any, cell::UnsafeCell};
+mod priority;
+
+use core::{
+ any::Any,
+ cell::UnsafeCell,
+ sync::atomic::{AtomicU32, Ordering},
+};
use intrusive_collections::{intrusive_adapter, LinkedListAtomicLink};
+pub use priority::Priority;
-use super::{
- add_task,
- priority::Priority,
- processor::{current_task, schedule},
-};
+use super::{processor::current_task, scheduler};
pub(crate) use crate::arch::task::{context_switch, TaskContext};
use crate::{
cpu::CpuSet,
mm::{kspace::KERNEL_PAGE_TABLE, FrameAllocOptions, Paddr, PageFlags, Segment, PAGE_SIZE},
prelude::*,
- sync::{SpinLock, SpinLockGuard},
user::UserSpace,
};
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task/mod.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task/mod.rs
@@ -103,6 +104,41 @@ impl Drop for KernelStack {
}
}
+/// An atomic CPUID container.
+pub struct AtomicCpuId(AtomicU32);
+
+impl AtomicCpuId {
+ /// The null value of CPUID.
+ ///
+ /// An `AtomicCpuId` with `AtomicCpuId::NONE` as its inner value is empty.
+ const NONE: u32 = u32::MAX;
+
+ fn new(cpu_id: u32) -> Self {
+ Self(AtomicU32::new(cpu_id))
+ }
+
+ /// Sets the inner value of an `AtomicCpuId` if it's empty.
+ ///
+ /// The return value is a result indicating whether the new value was written
+ /// and containing the previous value.
+ pub fn set_if_is_none(&self, cpu_id: u32) -> core::result::Result<u32, u32> {
+ self.0
+ .compare_exchange(Self::NONE, cpu_id, Ordering::Relaxed, Ordering::Relaxed)
+ }
+
+ /// Sets the inner value of an `AtomicCpuId` to `AtomicCpuId::NONE`, i.e. makes
+ /// an `AtomicCpuId` empty.
+ pub fn set_to_none(&self) {
+ self.0.store(Self::NONE, Ordering::Relaxed);
+ }
+}
+
+impl Default for AtomicCpuId {
+ fn default() -> Self {
+ Self::new(Self::NONE)
+ }
+}
+
/// A task that executes a function to the end.
///
/// Each task is associated with per-task data and an optional user space.
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task/mod.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task/mod.rs
@@ -103,6 +104,41 @@ impl Drop for KernelStack {
}
}
+/// An atomic CPUID container.
+pub struct AtomicCpuId(AtomicU32);
+
+impl AtomicCpuId {
+ /// The null value of CPUID.
+ ///
+ /// An `AtomicCpuId` with `AtomicCpuId::NONE` as its inner value is empty.
+ const NONE: u32 = u32::MAX;
+
+ fn new(cpu_id: u32) -> Self {
+ Self(AtomicU32::new(cpu_id))
+ }
+
+ /// Sets the inner value of an `AtomicCpuId` if it's empty.
+ ///
+ /// The return value is a result indicating whether the new value was written
+ /// and containing the previous value.
+ pub fn set_if_is_none(&self, cpu_id: u32) -> core::result::Result<u32, u32> {
+ self.0
+ .compare_exchange(Self::NONE, cpu_id, Ordering::Relaxed, Ordering::Relaxed)
+ }
+
+ /// Sets the inner value of an `AtomicCpuId` to `AtomicCpuId::NONE`, i.e. makes
+ /// an `AtomicCpuId` empty.
+ pub fn set_to_none(&self) {
+ self.0.store(Self::NONE, Ordering::Relaxed);
+ }
+}
+
+impl Default for AtomicCpuId {
+ fn default() -> Self {
+ Self::new(Self::NONE)
+ }
+}
+
/// A task that executes a function to the end.
///
/// Each task is associated with per-task data and an optional user space.
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task/mod.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task/mod.rs
@@ -112,11 +148,11 @@ pub struct Task {
func: Box<dyn Fn() + Send + Sync>,
data: Box<dyn Any + Send + Sync>,
user_space: Option<Arc<UserSpace>>,
- task_inner: SpinLock<TaskInner>,
ctx: UnsafeCell<TaskContext>,
/// kernel stack, note that the top is SyscallFrame/TrapFrame
kstack: KernelStack,
link: LinkedListAtomicLink,
+ cpu: AtomicCpuId,
priority: Priority,
// TODO: add multiprocessor support
#[allow(dead_code)]
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task/mod.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task/mod.rs
@@ -112,11 +148,11 @@ pub struct Task {
func: Box<dyn Fn() + Send + Sync>,
data: Box<dyn Any + Send + Sync>,
user_space: Option<Arc<UserSpace>>,
- task_inner: SpinLock<TaskInner>,
ctx: UnsafeCell<TaskContext>,
/// kernel stack, note that the top is SyscallFrame/TrapFrame
kstack: KernelStack,
link: LinkedListAtomicLink,
+ cpu: AtomicCpuId,
priority: Priority,
// TODO: add multiprocessor support
#[allow(dead_code)]
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task/mod.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task/mod.rs
@@ -130,11 +166,6 @@ intrusive_adapter!(pub TaskAdapter = Arc<Task>: Task { link: LinkedListAtomicLin
// we have exclusive access to the field.
unsafe impl Sync for Task {}
-#[derive(Debug)]
-pub(crate) struct TaskInner {
- pub task_status: TaskStatus,
-}
-
impl Task {
/// Gets the current task.
///
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task/mod.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task/mod.rs
@@ -130,11 +166,6 @@ intrusive_adapter!(pub TaskAdapter = Arc<Task>: Task { link: LinkedListAtomicLin
// we have exclusive access to the field.
unsafe impl Sync for Task {}
-#[derive(Debug)]
-pub(crate) struct TaskInner {
- pub task_status: TaskStatus,
-}
-
impl Task {
/// Gets the current task.
///
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task/mod.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task/mod.rs
@@ -143,11 +174,6 @@ impl Task {
current_task()
}
- /// Gets inner
- pub(crate) fn inner_exclusive_access(&self) -> SpinLockGuard<TaskInner> {
- self.task_inner.lock_irq_disabled()
- }
-
pub(super) fn ctx(&self) -> &UnsafeCell<TaskContext> {
&self.ctx
}
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task/mod.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task/mod.rs
@@ -143,11 +174,6 @@ impl Task {
current_task()
}
- /// Gets inner
- pub(crate) fn inner_exclusive_access(&self) -> SpinLockGuard<TaskInner> {
- self.task_inner.lock_irq_disabled()
- }
-
pub(super) fn ctx(&self) -> &UnsafeCell<TaskContext> {
&self.ctx
}
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task/mod.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task/mod.rs
@@ -157,18 +183,14 @@ impl Task {
/// Note that this method cannot be simply named "yield" as the name is
/// a Rust keyword.
pub fn yield_now() {
- schedule();
+ scheduler::yield_now()
}
/// Runs the task.
+ ///
+ /// BUG: This method highly depends on the current scheduling policy.
pub fn run(self: &Arc<Self>) {
- add_task(self.clone());
- schedule();
- }
-
- /// Returns the task status.
- pub fn status(&self) -> TaskStatus {
- self.task_inner.lock_irq_disabled().task_status
+ scheduler::run_new_task(self.clone());
}
/// Returns the task data.
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task/mod.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task/mod.rs
@@ -157,18 +183,14 @@ impl Task {
/// Note that this method cannot be simply named "yield" as the name is
/// a Rust keyword.
pub fn yield_now() {
- schedule();
+ scheduler::yield_now()
}
/// Runs the task.
+ ///
+ /// BUG: This method highly depends on the current scheduling policy.
pub fn run(self: &Arc<Self>) {
- add_task(self.clone());
- schedule();
- }
-
- /// Returns the task status.
- pub fn status(&self) -> TaskStatus {
- self.task_inner.lock_irq_disabled().task_status
+ scheduler::run_new_task(self.clone());
}
/// Returns the task data.
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task/mod.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task/mod.rs
@@ -185,6 +207,16 @@ impl Task {
}
}
+ // Returns the cpu of this task.
+ pub fn cpu(&self) -> &AtomicCpuId {
+ &self.cpu
+ }
+
+ /// Returns the priority.
+ pub fn priority(&self) -> Priority {
+ self.priority
+ }
+
/// Exits the current task.
///
/// The task `self` must be the task that is currently running.
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task/mod.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task/mod.rs
@@ -185,6 +207,16 @@ impl Task {
}
}
+ // Returns the cpu of this task.
+ pub fn cpu(&self) -> &AtomicCpuId {
+ &self.cpu
+ }
+
+ /// Returns the priority.
+ pub fn priority(&self) -> Priority {
+ self.priority
+ }
+
/// Exits the current task.
///
/// The task `self` must be the task that is currently running.
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task/mod.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task/mod.rs
@@ -192,13 +224,10 @@ impl Task {
/// **NOTE:** If there is anything left on the stack, it will be forgotten. This behavior may
/// lead to resource leakage.
fn exit(self: Arc<Self>) -> ! {
- self.inner_exclusive_access().task_status = TaskStatus::Exited;
-
// `current_task()` still holds a strong reference, so nothing is destroyed at this point,
// neither is the kernel stack.
drop(self);
-
- schedule();
+ scheduler::exit_current();
unreachable!()
}
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task/mod.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task/mod.rs
@@ -192,13 +224,10 @@ impl Task {
/// **NOTE:** If there is anything left on the stack, it will be forgotten. This behavior may
/// lead to resource leakage.
fn exit(self: Arc<Self>) -> ! {
- self.inner_exclusive_access().task_status = TaskStatus::Exited;
-
// `current_task()` still holds a strong reference, so nothing is destroyed at this point,
// neither is the kernel stack.
drop(self);
-
- schedule();
+ scheduler::exit_current();
unreachable!()
}
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task/mod.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task/mod.rs
@@ -208,19 +237,6 @@ impl Task {
}
}
-#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
-/// The status of a task.
-pub enum TaskStatus {
- /// The task is runnable.
- Runnable,
- /// The task is running in the foreground but will sleep when it goes to the background.
- Sleepy,
- /// The task is sleeping in the background.
- Sleeping,
- /// The task has exited.
- Exited,
-}
-
/// Options to create or spawn a new task.
pub struct TaskOptions {
func: Option<Box<dyn Fn() + Send + Sync>>,
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task/mod.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task/mod.rs
@@ -208,19 +237,6 @@ impl Task {
}
}
-#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
-/// The status of a task.
-pub enum TaskStatus {
- /// The task is runnable.
- Runnable,
- /// The task is running in the foreground but will sleep when it goes to the background.
- Sleepy,
- /// The task is sleeping in the background.
- Sleeping,
- /// The task has exited.
- Exited,
-}
-
/// Options to create or spawn a new task.
pub struct TaskOptions {
func: Option<Box<dyn Fn() + Send + Sync>>,
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task/mod.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task/mod.rs
@@ -236,13 +252,12 @@ impl TaskOptions {
where
F: Fn() + Send + Sync + 'static,
{
- let cpu_affinity = CpuSet::new_full();
Self {
func: Some(Box::new(func)),
data: None,
user_space: None,
priority: Priority::normal(),
- cpu_affinity,
+ cpu_affinity: CpuSet::new_full(),
}
}
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task/mod.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task/mod.rs
@@ -236,13 +252,12 @@ impl TaskOptions {
where
F: Fn() + Send + Sync + 'static,
{
- let cpu_affinity = CpuSet::new_full();
Self {
func: Some(Box::new(func)),
data: None,
user_space: None,
priority: Priority::normal(),
- cpu_affinity,
+ cpu_affinity: CpuSet::new_full(),
}
}
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task/mod.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task/mod.rs
@@ -300,11 +315,9 @@ impl TaskOptions {
func: self.func.unwrap(),
data: self.data.unwrap(),
user_space: self.user_space,
- task_inner: SpinLock::new(TaskInner {
- task_status: TaskStatus::Runnable,
- }),
ctx: UnsafeCell::new(TaskContext::default()),
kstack: KernelStack::new_with_guard_page()?,
+ cpu: AtomicCpuId::default(),
link: LinkedListAtomicLink::new(),
priority: self.priority,
cpu_affinity: self.cpu_affinity,
diff --git a/ostd/src/task/task.rs b/ostd/src/task/task/mod.rs
--- a/ostd/src/task/task.rs
+++ b/ostd/src/task/task/mod.rs
@@ -300,11 +315,9 @@ impl TaskOptions {
func: self.func.unwrap(),
data: self.data.unwrap(),
user_space: self.user_space,
- task_inner: SpinLock::new(TaskInner {
- task_status: TaskStatus::Runnable,
- }),
ctx: UnsafeCell::new(TaskContext::default()),
kstack: KernelStack::new_with_guard_page()?,
+ cpu: AtomicCpuId::default(),
link: LinkedListAtomicLink::new(),
priority: self.priority,
cpu_affinity: self.cpu_affinity,
diff --git a/ostd/src/task/priority.rs b/ostd/src/task/task/priority.rs
--- a/ostd/src/task/priority.rs
+++ b/ostd/src/task/task/priority.rs
@@ -7,7 +7,7 @@ pub const REAL_TIME_TASK_PRIORITY: u16 = 100;
/// Similar to Linux, a larger value represents a lower priority,
/// with a range of 0 to 139. Priorities ranging from 0 to 99 are considered real-time,
/// while those ranging from 100 to 139 are considered normal.
-#[derive(Copy, Clone, Debug)]
+#[derive(Copy, Clone, Eq, Ord, PartialEq, PartialOrd)]
pub struct Priority(u16);
impl Priority {
diff --git a/ostd/src/task/priority.rs b/ostd/src/task/task/priority.rs
--- a/ostd/src/task/priority.rs
+++ b/ostd/src/task/task/priority.rs
@@ -7,7 +7,7 @@ pub const REAL_TIME_TASK_PRIORITY: u16 = 100;
/// Similar to Linux, a larger value represents a lower priority,
/// with a range of 0 to 139. Priorities ranging from 0 to 99 are considered real-time,
/// while those ranging from 100 to 139 are considered normal.
-#[derive(Copy, Clone, Debug)]
+#[derive(Copy, Clone, Eq, Ord, PartialEq, PartialOrd)]
pub struct Priority(u16);
impl Priority {
|
From my point of view, I suggest removing the `RunQueue` trait and the `fn rq(&self, cpu: CpuId) -> &Arc<dyn RunQueue>` method _if_ we cannot figure out any real use cases for them in the Asterinas framework.
We can easily add them in the future if we find them useful in some way, but at least for the use cases listed in this RFC, they are not useful.
The local and remote views of run queues make sense to me, but they do not outweigh the fact that we should not add code or APIs whose usefulness cannot be justified.
|
2024-06-28T06:42:22Z
|
562e64437584279783f244edba10b512beddc81d
|
asterinas/asterinas
|
diff --git a/docs/src/ostd/a-100-line-kernel.md b/docs/src/ostd/a-100-line-kernel.md
--- a/docs/src/ostd/a-100-line-kernel.md
+++ b/docs/src/ostd/a-100-line-kernel.md
@@ -7,23 +7,7 @@ we will show a new kernel in about 100 lines of safe Rust.
Our new kernel will be able to run the following Hello World program.
```s
-.global _start # entry point
-.section .text # code section
-_start:
- mov $1, %rax # syscall number of write
- mov $1, %rdi # stdout
- mov $message, %rsi # address of message
- mov $message_end, %rdx
- sub %rsi, %rdx # calculate message len
- syscall
- mov $60, %rax # syscall number of exit, move it to rax
- mov $0, %rdi # exit code, move it to rdi
- syscall
-
-.section .rodata # read only data section
-message:
- .ascii "Hello, world\n"
-message_end:
+{{#include ../../../osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/hello.S}}
```
The assembly program above can be compiled with the following command.
diff --git a/docs/src/ostd/a-100-line-kernel.md b/docs/src/ostd/a-100-line-kernel.md
--- a/docs/src/ostd/a-100-line-kernel.md
+++ b/docs/src/ostd/a-100-line-kernel.md
@@ -42,131 +26,5 @@ Comments are added
to highlight how the APIs of Asterinas OSTD enable safe kernel development.
```rust
-#![no_std]
-
-extern crate alloc;
-
-use align_ext::AlignExt;
-use core::str;
-
-use alloc::sync::Arc;
-use alloc::vec;
-
-use ostd::cpu::UserContext;
-use ostd::prelude::*;
-use ostd::task::{Task, TaskOptions};
-use ostd::user::{ReturnReason, UserMode, UserSpace};
-use ostd::mm::{PageFlags, PAGE_SIZE, Vaddr, FrameAllocOptions, VmIo, VmMapOptions, VmSpace};
-
-/// The kernel's boot and initialization process is managed by Asterinas OSTD.
-/// After the process is done, the kernel's execution environment
-/// (e.g., stack, heap, tasks) will be ready for use and the entry function
-/// labeled as `#[ostd::main]` will be called.
-#[ostd::main]
-pub fn main() {
- let program_binary = include_bytes!("../hello_world");
- let user_space = create_user_space(program_binary);
- let user_task = create_user_task(Arc::new(user_space));
- user_task.run();
-}
-
-fn create_user_space(program: &[u8]) -> UserSpace {
- let user_pages = {
- let nframes = program.len().align_up(PAGE_SIZE) / PAGE_SIZE;
- let vm_frames = FrameAllocOptions::new(nframes).alloc().unwrap();
- // Phyiscal memory pages can be only accessed
- // via the Frame abstraction.
- vm_frames.write_bytes(0, program).unwrap();
- vm_frames
- };
- let user_address_space = {
- const MAP_ADDR: Vaddr = 0x0040_0000; // The map addr for statically-linked executable
-
- // The page table of the user space can be
- // created and manipulated safely through
- // the VmSpace abstraction.
- let vm_space = VmSpace::new();
- let mut options = VmMapOptions::new();
- options.addr(Some(MAP_ADDR)).flags(PageFlags::RWX);
- vm_space.map(user_pages, &options).unwrap();
- vm_space
- };
- let user_cpu_state = {
- const ENTRY_POINT: Vaddr = 0x0040_1000; // The entry point for statically-linked executable
-
- // The user-space CPU states can be initialized
- // to arbitrary values via the UserContext
- // abstraction.
- let mut user_cpu_state = UserContext::default();
- user_cpu_state.set_rip(ENTRY_POINT);
- user_cpu_state
- };
- UserSpace::new(user_address_space, user_cpu_state)
-}
-
-fn create_user_task(user_space: Arc<UserSpace>) -> Arc<Task> {
- fn user_task() {
- let current = Task::current();
- // Switching between user-kernel space is
- // performed via the UserMode abstraction.
- let mut user_mode = {
- let user_space = current.user_space().unwrap();
- UserMode::new(user_space)
- };
-
- loop {
- // The execute method returns when system
- // calls or CPU exceptions occur or some
- // events specified by the kernel occur.
- let return_reason = user_mode.execute(|| false);
-
- // The CPU registers of the user space
- // can be accessed and manipulated via
- // the `UserContext` abstraction.
- let user_context = user_mode.context_mut();
- if ReturnReason::UserSyscall == return_reason {
- handle_syscall(user_context, current.user_space().unwrap());
- }
- }
- }
-
- // Kernel tasks are managed by OSTD,
- // while scheduling algorithms for them can be
- // determined by the users of OSTD.
- TaskOptions::new(user_task)
- .user_space(Some(user_space))
- .data(0)
- .build()
- .unwrap()
-}
-
-fn handle_syscall(user_context: &mut UserContext, user_space: &UserSpace) {
- const SYS_WRITE: usize = 1;
- const SYS_EXIT: usize = 60;
-
- match user_context.rax() {
- SYS_WRITE => {
- // Access the user-space CPU registers safely.
- let (_, buf_addr, buf_len) =
- (user_context.rdi(), user_context.rsi(), user_context.rdx());
- let buf = {
- let mut buf = vec![0u8; buf_len];
- // Copy data from the user space without
- // unsafe pointer dereferencing.
- user_space
- .vm_space()
- .read_bytes(buf_addr, &mut buf)
- .unwrap();
- buf
- };
- // Use the console for output safely.
- println!("{}", str::from_utf8(&buf).unwrap());
- // Manipulate the user-space CPU registers safely.
- user_context.set_rax(buf_len);
- }
- SYS_EXIT => Task::current().exit(),
- _ => unimplemented!(),
- }
-}
+{{#include ../../../osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs}}
```
-
diff --git a/osdk/tests/examples_in_book/mod.rs b/osdk/tests/examples_in_book/mod.rs
--- a/osdk/tests/examples_in_book/mod.rs
+++ b/osdk/tests/examples_in_book/mod.rs
@@ -5,3 +5,4 @@
mod create_os_projects;
mod test_and_run_projects;
mod work_in_workspace;
+mod write_a_kernel_in_100_lines;
diff --git a/osdk/tests/examples_in_book/work_in_workspace.rs b/osdk/tests/examples_in_book/work_in_workspace.rs
--- a/osdk/tests/examples_in_book/work_in_workspace.rs
+++ b/osdk/tests/examples_in_book/work_in_workspace.rs
@@ -1,7 +1,6 @@
// SPDX-License-Identifier: MPL-2.0
use std::{
- env,
fs::{self, OpenOptions},
io::Write,
path::PathBuf,
diff --git a/osdk/tests/examples_in_book/work_in_workspace.rs b/osdk/tests/examples_in_book/work_in_workspace.rs
--- a/osdk/tests/examples_in_book/work_in_workspace.rs
+++ b/osdk/tests/examples_in_book/work_in_workspace.rs
@@ -21,7 +20,6 @@ fn work_in_workspace() {
}
fs::create_dir_all(&workspace_dir).unwrap();
- env::set_current_dir(&workspace_dir).unwrap();
let workspace_toml = include_str!("work_in_workspace_templates/Cargo.toml");
fs::write(workspace_dir.join("Cargo.toml"), workspace_toml).unwrap();
diff --git a/osdk/tests/examples_in_book/work_in_workspace.rs b/osdk/tests/examples_in_book/work_in_workspace.rs
--- a/osdk/tests/examples_in_book/work_in_workspace.rs
+++ b/osdk/tests/examples_in_book/work_in_workspace.rs
@@ -29,8 +27,14 @@ fn work_in_workspace() {
// Create a kernel project and a library project
let kernel = "myos";
let module = "mylib";
- cargo_osdk(&["new", "--kernel", kernel]).ok().unwrap();
- cargo_osdk(&["new", module]).ok().unwrap();
+ cargo_osdk(&["new", "--kernel", kernel])
+ .current_dir(&workspace_dir)
+ .ok()
+ .unwrap();
+ cargo_osdk(&["new", module])
+ .current_dir(&workspace_dir)
+ .ok()
+ .unwrap();
// Add a test function to mylib/src/lib.rs
let module_src_path = workspace_dir.join(module).join("src").join("lib.rs");
diff --git a/osdk/tests/examples_in_book/work_in_workspace.rs b/osdk/tests/examples_in_book/work_in_workspace.rs
--- a/osdk/tests/examples_in_book/work_in_workspace.rs
+++ b/osdk/tests/examples_in_book/work_in_workspace.rs
@@ -75,13 +79,22 @@ fn work_in_workspace() {
.unwrap();
// Run subcommand build & run
- cargo_osdk(&["build"]).ok().unwrap();
- let output = cargo_osdk(&["run"]).output().unwrap();
+ cargo_osdk(&["build"])
+ .current_dir(&workspace_dir)
+ .ok()
+ .unwrap();
+ let output = cargo_osdk(&["run"])
+ .current_dir(&workspace_dir)
+ .output()
+ .unwrap();
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
assert!(stdout.contains("The available memory is"));
// Run subcommand test
- cargo_osdk(&["test"]).ok().unwrap();
+ cargo_osdk(&["test"])
+ .current_dir(&workspace_dir)
+ .ok()
+ .unwrap();
// Remove the directory
fs::remove_dir_all(&workspace_dir).unwrap();
diff --git /dev/null b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines.rs
new file mode 100644
--- /dev/null
+++ b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines.rs
@@ -0,0 +1,65 @@
+// SPDX-License-Identifier: MPL-2.0
+
+use std::{fs, path::PathBuf, process::Command};
+
+use assert_cmd::output::OutputOkExt;
+
+use crate::util::{cargo_osdk, depends_on_local_ostd};
+
+#[test]
+fn write_a_kernel_in_100_lines() {
+ let workdir = "/tmp";
+ let os_name = "kernel_in_100_lines";
+
+ let os_dir = PathBuf::from(workdir).join(os_name);
+
+ if os_dir.exists() {
+ fs::remove_dir_all(&os_dir).unwrap()
+ }
+
+ // Creates a new kernel project
+ cargo_osdk(&["new", "--kernel", os_name])
+ .current_dir(&workdir)
+ .ok()
+ .unwrap();
+
+ // Depends on local OSTD
+ let manifest_path = os_dir.join("Cargo.toml");
+ depends_on_local_ostd(manifest_path);
+
+ // Copies the kernel content
+ let kernel_contents = include_str!("write_a_kernel_in_100_lines_templates/lib.rs");
+ fs::write(os_dir.join("src").join("lib.rs"), kernel_contents).unwrap();
+
+ // Copies and compiles the user program
+ let user_program_contents = include_str!("write_a_kernel_in_100_lines_templates/hello.S");
+ fs::write(os_dir.join("hello.S"), user_program_contents).unwrap();
+ Command::new("gcc")
+ .args(&["-static", "-nostdlib", "hello.S", "-o", "hello"])
+ .current_dir(&os_dir)
+ .ok()
+ .unwrap();
+
+ // Adds align ext as the dependency
+ let file_contents = fs::read_to_string(os_dir.join("Cargo.toml")).unwrap();
+ let mut manifest: toml::Table = toml::from_str(&file_contents).unwrap();
+ let dependencies = manifest
+ .get_mut("dependencies")
+ .unwrap()
+ .as_table_mut()
+ .unwrap();
+ dependencies.insert(
+ "align_ext".to_string(),
+ toml::Value::String("0.1.0".to_string()),
+ );
+
+ let new_file_content = manifest.to_string();
+ fs::write(os_dir.join("Cargo.toml"), new_file_content).unwrap();
+
+ // Runs the kernel
+ let output = cargo_osdk(&["run"]).current_dir(&os_dir).ok().unwrap();
+ let stdout = std::str::from_utf8(&output.stdout).unwrap();
+ println!("stdout = {}", stdout);
+
+ fs::remove_dir_all(&os_dir).unwrap();
+}
diff --git /dev/null b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/hello.S
new file mode 100644
--- /dev/null
+++ b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/hello.S
@@ -0,0 +1,19 @@
+# SPDX-License-Identifier: MPL-2.0
+
+.global _start # entry point
+.section .text # code section
+_start:
+ mov $1, %rax # syscall number of write
+ mov $1, %rdi # stdout
+ mov $message, %rsi # address of message
+ mov $message_end, %rdx
+ sub %rsi, %rdx # calculate message len
+ syscall
+ mov $60, %rax # syscall number of exit, move it to rax
+ mov $0, %rdi # exit code, move it to rdi
+ syscall
+
+.section .rodata # read only data section
+message:
+ .ascii "Hello, world\n"
+message_end:
\ No newline at end of file
diff --git /dev/null b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
new file mode 100644
--- /dev/null
+++ b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
@@ -0,0 +1,132 @@
+// SPDX-License-Identifier: MPL-2.0
+
+#![no_std]
+
+extern crate alloc;
+
+use align_ext::AlignExt;
+use core::str;
+
+use alloc::sync::Arc;
+use alloc::vec;
+
+use ostd::arch::qemu::{exit_qemu, QemuExitCode};
+use ostd::cpu::UserContext;
+use ostd::mm::{
+ FrameAllocOptions, PageFlags, Vaddr, VmIo, VmMapOptions, VmSpace, VmWriter, PAGE_SIZE,
+};
+use ostd::prelude::*;
+use ostd::task::{Task, TaskOptions};
+use ostd::user::{ReturnReason, UserMode, UserSpace};
+
+/// The kernel's boot and initialization process is managed by OSTD.
+/// After the process is done, the kernel's execution environment
+/// (e.g., stack, heap, tasks) will be ready for use and the entry function
+/// labeled as `#[ostd::main]` will be called.
+#[ostd::main]
+pub fn main() {
+ let program_binary = include_bytes!("../hello");
+ let user_space = create_user_space(program_binary);
+ let user_task = create_user_task(Arc::new(user_space));
+ user_task.run();
+}
+
+fn create_user_space(program: &[u8]) -> UserSpace {
+ let user_pages = {
+ let nframes = program.len().align_up(PAGE_SIZE) / PAGE_SIZE;
+ let vm_frames = FrameAllocOptions::new(nframes).alloc().unwrap();
+ // Phyiscal memory pages can be only accessed
+ // via the Frame abstraction.
+ vm_frames.write_bytes(0, program).unwrap();
+ vm_frames
+ };
+ let user_address_space = {
+ const MAP_ADDR: Vaddr = 0x0040_0000; // The map addr for statically-linked executable
+
+ // The page table of the user space can be
+ // created and manipulated safely through
+ // the VmSpace abstraction.
+ let vm_space = VmSpace::new();
+ let mut options = VmMapOptions::new();
+ options.addr(Some(MAP_ADDR)).flags(PageFlags::RWX);
+ vm_space.map(user_pages, &options).unwrap();
+ Arc::new(vm_space)
+ };
+ let user_cpu_state = {
+ const ENTRY_POINT: Vaddr = 0x0040_1000; // The entry point for statically-linked executable
+
+ // The user-space CPU states can be initialized
+ // to arbitrary values via the UserContext
+ // abstraction.
+ let mut user_cpu_state = UserContext::default();
+ user_cpu_state.set_rip(ENTRY_POINT);
+ user_cpu_state
+ };
+ UserSpace::new(user_address_space, user_cpu_state)
+}
+
+fn create_user_task(user_space: Arc<UserSpace>) -> Arc<Task> {
+ fn user_task() {
+ let current = Task::current();
+ // Switching between user-kernel space is
+ // performed via the UserMode abstraction.
+ let mut user_mode = {
+ let user_space = current.user_space().unwrap();
+ UserMode::new(user_space)
+ };
+
+ loop {
+ // The execute method returns when system
+ // calls or CPU exceptions occur or some
+ // events specified by the kernel occur.
+ let return_reason = user_mode.execute(|| false);
+
+ // The CPU registers of the user space
+ // can be accessed and manipulated via
+ // the `UserContext` abstraction.
+ let user_context = user_mode.context_mut();
+ if ReturnReason::UserSyscall == return_reason {
+ handle_syscall(user_context, current.user_space().unwrap());
+ }
+ }
+ }
+
+ // Kernel tasks are managed by the Framework,
+ // while scheduling algorithms for them can be
+ // determined by the users of the Framework.
+ TaskOptions::new(user_task)
+ .user_space(Some(user_space))
+ .data(0)
+ .build()
+ .unwrap()
+}
+
+fn handle_syscall(user_context: &mut UserContext, user_space: &UserSpace) {
+ const SYS_WRITE: usize = 1;
+ const SYS_EXIT: usize = 60;
+
+ match user_context.rax() {
+ SYS_WRITE => {
+ // Access the user-space CPU registers safely.
+ let (_, buf_addr, buf_len) =
+ (user_context.rdi(), user_context.rsi(), user_context.rdx());
+ let buf = {
+ let mut buf = vec![0u8; buf_len];
+ // Copy data from the user space without
+ // unsafe pointer dereferencing.
+ let current_vm_space = user_space.vm_space();
+ let mut reader = current_vm_space.reader(buf_addr, buf_len).unwrap();
+ reader
+ .read_fallible(&mut VmWriter::from(&mut buf as &mut [u8]))
+ .unwrap();
+ buf
+ };
+ // Use the console for output safely.
+ println!("{}", str::from_utf8(&buf).unwrap());
+ // Manipulate the user-space CPU registers safely.
+ user_context.set_rax(buf_len);
+ }
+ SYS_EXIT => exit_qemu(QemuExitCode::Success),
+ _ => unimplemented!(),
+ }
+}
|
[
"871"
] |
0.5
|
cd2b305fa890bca9c4374ccd83c9ccb24bf8dda3
|
"[ERROR]: Uncaught panic!" when running the 100-line kernel example in the asterinas book.
When running the 100-line kernel example in the asterinas book [https://asterinas.github.io/book/framework/a-100-line-kernel.html ](url), the following error is reported:
```
Drive current: -outdev 'stdio:/root/workspace/asterinas/target/osdk/myos-osdk-bin.iso'
Media current: stdio file, overwriteable
Media status : is blank
Media summary: 0 sessions, 0 data blocks, 0 data, 931g free
Added to ISO image: directory '/'='/tmp/grub.CQmOUp'
xorriso : UPDATE : 341 files added in 1 seconds
Added to ISO image: directory '/'='/root/workspace/asterinas/target/osdk/iso_root'
xorriso : UPDATE : 346 files added in 1 seconds
xorriso : UPDATE : 0.00% done
BdsDxe: loading Boot0001 "UEFI QEMU DVD-ROM QM00005 " from PciRoot(0x0)/Pci(0x1F,0x2)/Sata(0x2,0xFFFF,0x0)
BdsDxe: starting Boot0001 "UEFI QEMU DVD-ROM QM00005 " from PciRoot(0x0)/Pci(0x1F,0x2)/Sata(0x2,0xFFFF,0x0)
WARNING: no console will be available to OS
error: no suitable video mode found.
[ERROR]: Uncaught panic!
panicked at /root/workspace/asterinas/framework/aster-frame/src/task/scheduler.rs:44:24:
called `Option::unwrap()` on a `None` value
printing stack trace:
1: fn 0xffffffff8809f660 - pc 0xffffffff8809f678 / registers:
rax 0x1; rdx 0xffffffff881a43f0; rcx 0x16; rbx 0xffffffff80000000;
rsi 0xffffffff881a4358; rdi 0xffffffff880479e8; rbp 0x0; rsp 0xffffffff88047820;
2: fn 0xffffffff8809f160 - pc 0xffffffff8809f617 / registers:
rax 0x1; rdx 0xffffffff881a43f0; rcx 0x16; rbx 0xffffffff80000000;
rsi 0xffffffff881a4358; rdi 0xffffffff880479e8; rbp 0x0; rsp 0xffffffff88047830;
3: fn 0xffffffff88048030 - pc 0xffffffff8804803a / registers:
rax 0x1; rdx 0xffffffff881a43f0; rcx 0x16; rbx 0xffffffff80000000;
rsi 0xffffffff881a4358; rdi 0xffffffff880479e8; rbp 0x0; rsp 0xffffffff88047a80;
4: fn 0xffffffff8818f4a0 - pc 0xffffffff8818f4ef / registers:
rax 0x1; rdx 0xffffffff881a43f0; rcx 0x16; rbx 0xffffffff80000000;
rsi 0xffffffff881a4358; rdi 0xffffffff880479e8; rbp 0x0; rsp 0xffffffff88047a90;
5: fn 0xffffffff8818f5d0 - pc 0xffffffff8818f615 / registers:
rax 0x1; rdx 0xffffffff881a43f0; rcx 0x16; rbx 0xffffffff80000000;
rsi 0xffffffff881a4358; rdi 0xffffffff880479e8; rbp 0x0; rsp 0xffffffff88047ae0;
6: fn 0xffffffff88124fd0 - pc 0xffffffff88125011 / registers:
rax 0x1; rdx 0xffffffff881a43f0; rcx 0x16; rbx 0xffffffff80000000;
rsi 0xffffffff881a4358; rdi 0xffffffff880479e8; rbp 0x0; rsp 0xffffffff88047b50;
7: fn 0xffffffff8806efa0 - pc 0xffffffff8806efce / registers:
rax 0x1; rdx 0xffffffff881a43f0; rcx 0x16; rbx 0xffffffff80000000;
rsi 0xffffffff881a4358; rdi 0xffffffff880479e8; rbp 0x0; rsp 0xffffffff88047b80;
8: fn 0xffffffff8806f0c0 - pc 0xffffffff8806f16e / registers:
rax 0x1; rdx 0xffffffff881a43f0; rcx 0x16; rbx 0xffffffff80000000;
rsi 0xffffffff881a4358; rdi 0xffffffff880479e8; rbp 0x0; rsp 0xffffffff88047bc0;
9: fn 0xffffffff8806e450 - pc 0xffffffff8806e462 / registers:
rax 0x1; rdx 0xffffffff881a43f0; rcx 0x16; rbx 0xffffffff80000000;
rsi 0xffffffff881a4358; rdi 0xffffffff880479e8; rbp 0x0; rsp 0xffffffff88047c20;
10: fn 0xffffffff880489e0 - pc 0xffffffff88048a30 / registers:
rax 0x1; rdx 0xffffffff881a43f0; rcx 0x16; rbx 0xffffffff80000000;
rsi 0xffffffff881a4358; rdi 0xffffffff880479e8; rbp 0x0; rsp 0xffffffff88047c30;
11: fn 0xffffffff880489d0 - pc 0xffffffff880489db / registers:
rax 0x1; rdx 0xffffffff881a43f0; rcx 0x16; rbx 0xffffffff80000000;
rsi 0xffffffff881a4358; rdi 0xffffffff880479e8; rbp 0x0; rsp 0xffffffff88047f50;
12: fn 0xffffffff880a3b00 - pc 0xffffffff880a3b06 / registers:
rax 0x1; rdx 0xffffffff881a43f0; rcx 0x16; rbx 0xffffffff80000000;
rsi 0xffffffff881a4358; rdi 0xffffffff880479e8; rbp 0x0; rsp 0xffffffff88047f60;
13: fn 0xffffffff8810d3b0 - pc 0xffffffff8810d477 / registers:
rax 0x1; rdx 0xffffffff881a43f0; rcx 0x16; rbx 0xffffffff80000000;
rsi 0xffffffff881a4358; rdi 0xffffffff880479e8; rbp 0x0; rsp 0xffffffff88047f70;
14: fn 0x0 - pc 0xffffffff880ad052 / registers:
rax 0x1; rdx 0xffffffff881a43f0; rcx 0x16; rbx 0xffffffff80000000;
rsi 0xffffffff881a4358; rdi 0xffffffff880479e8; rbp 0x0; rsp 0xffffffff88048000;
```
|
asterinas__asterinas-954
| 954
|
diff --git a/docs/src/ostd/a-100-line-kernel.md b/docs/src/ostd/a-100-line-kernel.md
--- a/docs/src/ostd/a-100-line-kernel.md
+++ b/docs/src/ostd/a-100-line-kernel.md
@@ -7,23 +7,7 @@ we will show a new kernel in about 100 lines of safe Rust.
Our new kernel will be able to run the following Hello World program.
```s
-.global _start # entry point
-.section .text # code section
-_start:
- mov $1, %rax # syscall number of write
- mov $1, %rdi # stdout
- mov $message, %rsi # address of message
- mov $message_end, %rdx
- sub %rsi, %rdx # calculate message len
- syscall
- mov $60, %rax # syscall number of exit, move it to rax
- mov $0, %rdi # exit code, move it to rdi
- syscall
-
-.section .rodata # read only data section
-message:
- .ascii "Hello, world\n"
-message_end:
+{{#include ../../../osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/hello.S}}
```
The assembly program above can be compiled with the following command.
diff --git a/docs/src/ostd/a-100-line-kernel.md b/docs/src/ostd/a-100-line-kernel.md
--- a/docs/src/ostd/a-100-line-kernel.md
+++ b/docs/src/ostd/a-100-line-kernel.md
@@ -42,131 +26,5 @@ Comments are added
to highlight how the APIs of Asterinas OSTD enable safe kernel development.
```rust
-#![no_std]
-
-extern crate alloc;
-
-use align_ext::AlignExt;
-use core::str;
-
-use alloc::sync::Arc;
-use alloc::vec;
-
-use ostd::cpu::UserContext;
-use ostd::prelude::*;
-use ostd::task::{Task, TaskOptions};
-use ostd::user::{ReturnReason, UserMode, UserSpace};
-use ostd::mm::{PageFlags, PAGE_SIZE, Vaddr, FrameAllocOptions, VmIo, VmMapOptions, VmSpace};
-
-/// The kernel's boot and initialization process is managed by Asterinas OSTD.
-/// After the process is done, the kernel's execution environment
-/// (e.g., stack, heap, tasks) will be ready for use and the entry function
-/// labeled as `#[ostd::main]` will be called.
-#[ostd::main]
-pub fn main() {
- let program_binary = include_bytes!("../hello_world");
- let user_space = create_user_space(program_binary);
- let user_task = create_user_task(Arc::new(user_space));
- user_task.run();
-}
-
-fn create_user_space(program: &[u8]) -> UserSpace {
- let user_pages = {
- let nframes = program.len().align_up(PAGE_SIZE) / PAGE_SIZE;
- let vm_frames = FrameAllocOptions::new(nframes).alloc().unwrap();
- // Phyiscal memory pages can be only accessed
- // via the Frame abstraction.
- vm_frames.write_bytes(0, program).unwrap();
- vm_frames
- };
- let user_address_space = {
- const MAP_ADDR: Vaddr = 0x0040_0000; // The map addr for statically-linked executable
-
- // The page table of the user space can be
- // created and manipulated safely through
- // the VmSpace abstraction.
- let vm_space = VmSpace::new();
- let mut options = VmMapOptions::new();
- options.addr(Some(MAP_ADDR)).flags(PageFlags::RWX);
- vm_space.map(user_pages, &options).unwrap();
- vm_space
- };
- let user_cpu_state = {
- const ENTRY_POINT: Vaddr = 0x0040_1000; // The entry point for statically-linked executable
-
- // The user-space CPU states can be initialized
- // to arbitrary values via the UserContext
- // abstraction.
- let mut user_cpu_state = UserContext::default();
- user_cpu_state.set_rip(ENTRY_POINT);
- user_cpu_state
- };
- UserSpace::new(user_address_space, user_cpu_state)
-}
-
-fn create_user_task(user_space: Arc<UserSpace>) -> Arc<Task> {
- fn user_task() {
- let current = Task::current();
- // Switching between user-kernel space is
- // performed via the UserMode abstraction.
- let mut user_mode = {
- let user_space = current.user_space().unwrap();
- UserMode::new(user_space)
- };
-
- loop {
- // The execute method returns when system
- // calls or CPU exceptions occur or some
- // events specified by the kernel occur.
- let return_reason = user_mode.execute(|| false);
-
- // The CPU registers of the user space
- // can be accessed and manipulated via
- // the `UserContext` abstraction.
- let user_context = user_mode.context_mut();
- if ReturnReason::UserSyscall == return_reason {
- handle_syscall(user_context, current.user_space().unwrap());
- }
- }
- }
-
- // Kernel tasks are managed by OSTD,
- // while scheduling algorithms for them can be
- // determined by the users of OSTD.
- TaskOptions::new(user_task)
- .user_space(Some(user_space))
- .data(0)
- .build()
- .unwrap()
-}
-
-fn handle_syscall(user_context: &mut UserContext, user_space: &UserSpace) {
- const SYS_WRITE: usize = 1;
- const SYS_EXIT: usize = 60;
-
- match user_context.rax() {
- SYS_WRITE => {
- // Access the user-space CPU registers safely.
- let (_, buf_addr, buf_len) =
- (user_context.rdi(), user_context.rsi(), user_context.rdx());
- let buf = {
- let mut buf = vec![0u8; buf_len];
- // Copy data from the user space without
- // unsafe pointer dereferencing.
- user_space
- .vm_space()
- .read_bytes(buf_addr, &mut buf)
- .unwrap();
- buf
- };
- // Use the console for output safely.
- println!("{}", str::from_utf8(&buf).unwrap());
- // Manipulate the user-space CPU registers safely.
- user_context.set_rax(buf_len);
- }
- SYS_EXIT => Task::current().exit(),
- _ => unimplemented!(),
- }
-}
+{{#include ../../../osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs}}
```
-
diff --git a/osdk/src/commands/build/bin.rs b/osdk/src/commands/build/bin.rs
--- a/osdk/src/commands/build/bin.rs
+++ b/osdk/src/commands/build/bin.rs
@@ -158,7 +158,9 @@ fn install_setup_with_arch(
cmd.arg("--force");
cmd.arg("--root").arg(install_dir.as_ref());
cmd.arg("--git").arg(crate::util::ASTER_GIT_LINK);
- cmd.arg("--tag").arg(crate::util::ASTER_GIT_TAG);
+ // FIXME: Uses a fixed tag instaed of relies on remote branch
+ cmd.arg("--tag").arg("v0.5.1");
+ // cmd.arg("--tag").arg(crate::util::ASTER_GIT_TAG);
cmd.arg("--target").arg(match arch {
SetupInstallArch::X86_64 => "x86_64-unknown-none",
SetupInstallArch::Other(path) => path.to_str().unwrap(),
diff --git a/osdk/src/commands/build/bin.rs b/osdk/src/commands/build/bin.rs
--- a/osdk/src/commands/build/bin.rs
+++ b/osdk/src/commands/build/bin.rs
@@ -158,7 +158,9 @@ fn install_setup_with_arch(
cmd.arg("--force");
cmd.arg("--root").arg(install_dir.as_ref());
cmd.arg("--git").arg(crate::util::ASTER_GIT_LINK);
- cmd.arg("--tag").arg(crate::util::ASTER_GIT_TAG);
+ // FIXME: Uses a fixed tag instaed of relies on remote branch
+ cmd.arg("--tag").arg("v0.5.1");
+ // cmd.arg("--tag").arg(crate::util::ASTER_GIT_TAG);
cmd.arg("--target").arg(match arch {
SetupInstallArch::X86_64 => "x86_64-unknown-none",
SetupInstallArch::Other(path) => path.to_str().unwrap(),
diff --git a/osdk/tests/examples_in_book/mod.rs b/osdk/tests/examples_in_book/mod.rs
--- a/osdk/tests/examples_in_book/mod.rs
+++ b/osdk/tests/examples_in_book/mod.rs
@@ -5,3 +5,4 @@
mod create_os_projects;
mod test_and_run_projects;
mod work_in_workspace;
+mod write_a_kernel_in_100_lines;
diff --git a/osdk/tests/examples_in_book/work_in_workspace.rs b/osdk/tests/examples_in_book/work_in_workspace.rs
--- a/osdk/tests/examples_in_book/work_in_workspace.rs
+++ b/osdk/tests/examples_in_book/work_in_workspace.rs
@@ -1,7 +1,6 @@
// SPDX-License-Identifier: MPL-2.0
use std::{
- env,
fs::{self, OpenOptions},
io::Write,
path::PathBuf,
diff --git a/osdk/tests/examples_in_book/work_in_workspace.rs b/osdk/tests/examples_in_book/work_in_workspace.rs
--- a/osdk/tests/examples_in_book/work_in_workspace.rs
+++ b/osdk/tests/examples_in_book/work_in_workspace.rs
@@ -21,7 +20,6 @@ fn work_in_workspace() {
}
fs::create_dir_all(&workspace_dir).unwrap();
- env::set_current_dir(&workspace_dir).unwrap();
let workspace_toml = include_str!("work_in_workspace_templates/Cargo.toml");
fs::write(workspace_dir.join("Cargo.toml"), workspace_toml).unwrap();
diff --git a/osdk/tests/examples_in_book/work_in_workspace.rs b/osdk/tests/examples_in_book/work_in_workspace.rs
--- a/osdk/tests/examples_in_book/work_in_workspace.rs
+++ b/osdk/tests/examples_in_book/work_in_workspace.rs
@@ -29,8 +27,14 @@ fn work_in_workspace() {
// Create a kernel project and a library project
let kernel = "myos";
let module = "mylib";
- cargo_osdk(&["new", "--kernel", kernel]).ok().unwrap();
- cargo_osdk(&["new", module]).ok().unwrap();
+ cargo_osdk(&["new", "--kernel", kernel])
+ .current_dir(&workspace_dir)
+ .ok()
+ .unwrap();
+ cargo_osdk(&["new", module])
+ .current_dir(&workspace_dir)
+ .ok()
+ .unwrap();
// Add a test function to mylib/src/lib.rs
let module_src_path = workspace_dir.join(module).join("src").join("lib.rs");
diff --git a/osdk/tests/examples_in_book/work_in_workspace.rs b/osdk/tests/examples_in_book/work_in_workspace.rs
--- a/osdk/tests/examples_in_book/work_in_workspace.rs
+++ b/osdk/tests/examples_in_book/work_in_workspace.rs
@@ -75,13 +79,22 @@ fn work_in_workspace() {
.unwrap();
// Run subcommand build & run
- cargo_osdk(&["build"]).ok().unwrap();
- let output = cargo_osdk(&["run"]).output().unwrap();
+ cargo_osdk(&["build"])
+ .current_dir(&workspace_dir)
+ .ok()
+ .unwrap();
+ let output = cargo_osdk(&["run"])
+ .current_dir(&workspace_dir)
+ .output()
+ .unwrap();
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
assert!(stdout.contains("The available memory is"));
// Run subcommand test
- cargo_osdk(&["test"]).ok().unwrap();
+ cargo_osdk(&["test"])
+ .current_dir(&workspace_dir)
+ .ok()
+ .unwrap();
// Remove the directory
fs::remove_dir_all(&workspace_dir).unwrap();
diff --git /dev/null b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines.rs
new file mode 100644
--- /dev/null
+++ b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines.rs
@@ -0,0 +1,65 @@
+// SPDX-License-Identifier: MPL-2.0
+
+use std::{fs, path::PathBuf, process::Command};
+
+use assert_cmd::output::OutputOkExt;
+
+use crate::util::{cargo_osdk, depends_on_local_ostd};
+
+#[test]
+fn write_a_kernel_in_100_lines() {
+ let workdir = "/tmp";
+ let os_name = "kernel_in_100_lines";
+
+ let os_dir = PathBuf::from(workdir).join(os_name);
+
+ if os_dir.exists() {
+ fs::remove_dir_all(&os_dir).unwrap()
+ }
+
+ // Creates a new kernel project
+ cargo_osdk(&["new", "--kernel", os_name])
+ .current_dir(&workdir)
+ .ok()
+ .unwrap();
+
+ // Depends on local OSTD
+ let manifest_path = os_dir.join("Cargo.toml");
+ depends_on_local_ostd(manifest_path);
+
+ // Copies the kernel content
+ let kernel_contents = include_str!("write_a_kernel_in_100_lines_templates/lib.rs");
+ fs::write(os_dir.join("src").join("lib.rs"), kernel_contents).unwrap();
+
+ // Copies and compiles the user program
+ let user_program_contents = include_str!("write_a_kernel_in_100_lines_templates/hello.S");
+ fs::write(os_dir.join("hello.S"), user_program_contents).unwrap();
+ Command::new("gcc")
+ .args(&["-static", "-nostdlib", "hello.S", "-o", "hello"])
+ .current_dir(&os_dir)
+ .ok()
+ .unwrap();
+
+ // Adds align ext as the dependency
+ let file_contents = fs::read_to_string(os_dir.join("Cargo.toml")).unwrap();
+ let mut manifest: toml::Table = toml::from_str(&file_contents).unwrap();
+ let dependencies = manifest
+ .get_mut("dependencies")
+ .unwrap()
+ .as_table_mut()
+ .unwrap();
+ dependencies.insert(
+ "align_ext".to_string(),
+ toml::Value::String("0.1.0".to_string()),
+ );
+
+ let new_file_content = manifest.to_string();
+ fs::write(os_dir.join("Cargo.toml"), new_file_content).unwrap();
+
+ // Runs the kernel
+ let output = cargo_osdk(&["run"]).current_dir(&os_dir).ok().unwrap();
+ let stdout = std::str::from_utf8(&output.stdout).unwrap();
+ println!("stdout = {}", stdout);
+
+ fs::remove_dir_all(&os_dir).unwrap();
+}
diff --git /dev/null b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/hello.S
new file mode 100644
--- /dev/null
+++ b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/hello.S
@@ -0,0 +1,19 @@
+# SPDX-License-Identifier: MPL-2.0
+
+.global _start # entry point
+.section .text # code section
+_start:
+ mov $1, %rax # syscall number of write
+ mov $1, %rdi # stdout
+ mov $message, %rsi # address of message
+ mov $message_end, %rdx
+ sub %rsi, %rdx # calculate message len
+ syscall
+ mov $60, %rax # syscall number of exit, move it to rax
+ mov $0, %rdi # exit code, move it to rdi
+ syscall
+
+.section .rodata # read only data section
+message:
+ .ascii "Hello, world\n"
+message_end:
\ No newline at end of file
diff --git /dev/null b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
new file mode 100644
--- /dev/null
+++ b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs
@@ -0,0 +1,132 @@
+// SPDX-License-Identifier: MPL-2.0
+
+#![no_std]
+
+extern crate alloc;
+
+use align_ext::AlignExt;
+use core::str;
+
+use alloc::sync::Arc;
+use alloc::vec;
+
+use ostd::arch::qemu::{exit_qemu, QemuExitCode};
+use ostd::cpu::UserContext;
+use ostd::mm::{
+ FrameAllocOptions, PageFlags, Vaddr, VmIo, VmMapOptions, VmSpace, VmWriter, PAGE_SIZE,
+};
+use ostd::prelude::*;
+use ostd::task::{Task, TaskOptions};
+use ostd::user::{ReturnReason, UserMode, UserSpace};
+
+/// The kernel's boot and initialization process is managed by OSTD.
+/// After the process is done, the kernel's execution environment
+/// (e.g., stack, heap, tasks) will be ready for use and the entry function
+/// labeled as `#[ostd::main]` will be called.
+#[ostd::main]
+pub fn main() {
+ let program_binary = include_bytes!("../hello");
+ let user_space = create_user_space(program_binary);
+ let user_task = create_user_task(Arc::new(user_space));
+ user_task.run();
+}
+
+fn create_user_space(program: &[u8]) -> UserSpace {
+ let user_pages = {
+ let nframes = program.len().align_up(PAGE_SIZE) / PAGE_SIZE;
+ let vm_frames = FrameAllocOptions::new(nframes).alloc().unwrap();
+ // Phyiscal memory pages can be only accessed
+ // via the Frame abstraction.
+ vm_frames.write_bytes(0, program).unwrap();
+ vm_frames
+ };
+ let user_address_space = {
+ const MAP_ADDR: Vaddr = 0x0040_0000; // The map addr for statically-linked executable
+
+ // The page table of the user space can be
+ // created and manipulated safely through
+ // the VmSpace abstraction.
+ let vm_space = VmSpace::new();
+ let mut options = VmMapOptions::new();
+ options.addr(Some(MAP_ADDR)).flags(PageFlags::RWX);
+ vm_space.map(user_pages, &options).unwrap();
+ Arc::new(vm_space)
+ };
+ let user_cpu_state = {
+ const ENTRY_POINT: Vaddr = 0x0040_1000; // The entry point for statically-linked executable
+
+ // The user-space CPU states can be initialized
+ // to arbitrary values via the UserContext
+ // abstraction.
+ let mut user_cpu_state = UserContext::default();
+ user_cpu_state.set_rip(ENTRY_POINT);
+ user_cpu_state
+ };
+ UserSpace::new(user_address_space, user_cpu_state)
+}
+
+fn create_user_task(user_space: Arc<UserSpace>) -> Arc<Task> {
+ fn user_task() {
+ let current = Task::current();
+ // Switching between user-kernel space is
+ // performed via the UserMode abstraction.
+ let mut user_mode = {
+ let user_space = current.user_space().unwrap();
+ UserMode::new(user_space)
+ };
+
+ loop {
+ // The execute method returns when system
+ // calls or CPU exceptions occur or some
+ // events specified by the kernel occur.
+ let return_reason = user_mode.execute(|| false);
+
+ // The CPU registers of the user space
+ // can be accessed and manipulated via
+ // the `UserContext` abstraction.
+ let user_context = user_mode.context_mut();
+ if ReturnReason::UserSyscall == return_reason {
+ handle_syscall(user_context, current.user_space().unwrap());
+ }
+ }
+ }
+
+ // Kernel tasks are managed by the Framework,
+ // while scheduling algorithms for them can be
+ // determined by the users of the Framework.
+ TaskOptions::new(user_task)
+ .user_space(Some(user_space))
+ .data(0)
+ .build()
+ .unwrap()
+}
+
+fn handle_syscall(user_context: &mut UserContext, user_space: &UserSpace) {
+ const SYS_WRITE: usize = 1;
+ const SYS_EXIT: usize = 60;
+
+ match user_context.rax() {
+ SYS_WRITE => {
+ // Access the user-space CPU registers safely.
+ let (_, buf_addr, buf_len) =
+ (user_context.rdi(), user_context.rsi(), user_context.rdx());
+ let buf = {
+ let mut buf = vec![0u8; buf_len];
+ // Copy data from the user space without
+ // unsafe pointer dereferencing.
+ let current_vm_space = user_space.vm_space();
+ let mut reader = current_vm_space.reader(buf_addr, buf_len).unwrap();
+ reader
+ .read_fallible(&mut VmWriter::from(&mut buf as &mut [u8]))
+ .unwrap();
+ buf
+ };
+ // Use the console for output safely.
+ println!("{}", str::from_utf8(&buf).unwrap());
+ // Manipulate the user-space CPU registers safely.
+ user_context.set_rax(buf_len);
+ }
+ SYS_EXIT => exit_qemu(QemuExitCode::Success),
+ _ => unimplemented!(),
+ }
+}
|
It seems that the scheduler is not set. And the guide does not mention that.
```rust
use aster_frame::task::{set_scheduler, FifoScheduler, Scheduler};
let simple_scheduler = Box::new(FifoScheduler::new());
let static_scheduler: &'static dyn Scheduler = Box::leak(simple_scheduler);
set_scheduler(static_scheduler);
```
Could you please check if this works? If so you can help us improve the guide!
Thanks. After adding your code into the example, the program runs successfully and outputs "Hello, world". However, the below error message follows. Is this normal?
```
WARNING: no console will be available to OS
error: no suitable video mode found.
Hello, world
[ERROR]: Uncaught panic!
panicked at /root/workspace/asterinas/framework/aster-frame/src/task/task.rs:191:9:
internal error: entered unreachable code
printing stack trace:
1: fn 0xffffffff880a1840 - pc 0xffffffff880a1858 / registers:
rax 0x1; rdx 0xffffffff881a6db0; rcx 0x16; rbx 0x0;
rsi 0xffffffff881a6d18; rdi 0xffff8000083c0898; rbp 0x0; rsp 0xffff8000083c06d0;
2: fn 0xffffffff880a1340 - pc 0xffffffff880a17f7 / registers:
rax 0x1; rdx 0xffffffff881a6db0; rcx 0x16; rbx 0x0;
rsi 0xffffffff881a6d18; rdi 0xffff8000083c0898; rbp 0x0; rsp 0xffff8000083c06e0;
3: fn 0xffffffff88048030 - pc 0xffffffff8804803a / registers:
rax 0x1; rdx 0xffffffff881a6db0; rcx 0x16; rbx 0x0;
rsi 0xffffffff881a6d18; rdi 0xffff8000083c0898; rbp 0x0; rsp 0xffff8000083c0930;
4: fn 0xffffffff88191e30 - pc 0xffffffff88191e7f / registers:
rax 0x1; rdx 0xffffffff881a6db0; rcx 0x16; rbx 0x0;
rsi 0xffffffff881a6d18; rdi 0xffff8000083c0898; rbp 0x0; rsp 0xffff8000083c0940;
5: fn 0xffffffff88191f60 - pc 0xffffffff88191fa5 / registers:
rax 0x1; rdx 0xffffffff881a6db0; rcx 0x16; rbx 0x0;
rsi 0xffffffff881a6d18; rdi 0xffff8000083c0898; rbp 0x0; rsp 0xffff8000083c0990;
6: fn 0xffffffff8806ee80 - pc 0xffffffff8806eef9 / registers:
rax 0x1; rdx 0xffffffff881a6db0; rcx 0x16; rbx 0x0;
rsi 0xffffffff881a6d18; rdi 0xffff8000083c0898; rbp 0x0; rsp 0xffff8000083c0a00;
7: fn 0xffffffff88048660 - pc 0xffffffff880489c7 / registers:
rax 0x1; rdx 0xffffffff881a6db0; rcx 0x16; rbx 0x0;
rsi 0xffffffff881a6d18; rdi 0xffff8000083c0898; rbp 0x0; rsp 0xffff8000083c0a40;
8: fn 0xffffffff880484d0 - pc 0xffffffff8804863c / registers:
rax 0x1; rdx 0xffffffff881a6db0; rcx 0x16; rbx 0x0;
rsi 0xffffffff881a6d18; rdi 0xffff8000083c0898; rbp 0x0; rsp 0xffff8000083c0c10;
9: fn 0xffffffff88049e60 - pc 0xffffffff88049e6e / registers:
rax 0x1; rdx 0xffffffff881a6db0; rcx 0x16; rbx 0x0;
rsi 0xffffffff881a6d18; rdi 0xffff8000083c0898; rbp 0x0; rsp 0xffff8000083c0f90;
10: fn 0xffffffff880bae20 - pc 0xffffffff880bae36 / registers:
rax 0x1; rdx 0xffffffff881a6db0; rcx 0x16; rbx 0x0;
rsi 0xffffffff881a6d18; rdi 0xffff8000083c0898; rbp 0x0; rsp 0xffff8000083c0fb0;
11: fn 0xffffffff8806f710 - pc 0xffffffff8806f774 / registers:
rax 0x1; rdx 0xffffffff881a6db0; rcx 0x16; rbx 0x0;
rsi 0xffffffff881a6d18; rdi 0xffff8000083c0898; rbp 0x0; rsp 0xffff8000083c0fd0;
```
Yes it is normal and the scheduler expect that the main task of the kernel will never return.
So a well formed hello world kernel may shut the system down after printing.
However we do not have ACPI shutdown at this moment. Here is a debug fix.
```rust
#[aster_main]
pub fn main() {
let program_binary = include_bytes!("../hello_world");
let user_space = create_user_space(program_binary);
let user_task = create_user_task(Arc::new(user_space));
user_task.run();
use aster_frame::arch::qemu::{exit_qemu, QemuExitCode};
exit_qemu(QemuExitCode::Success);
}
```
Ok! Thanks again.
> It seems that the scheduler is not set. And the guide does not mention that.
>
> ```rust
> use aster_frame::task::{set_scheduler, FifoScheduler, Scheduler};
> let simple_scheduler = Box::new(FifoScheduler::new());
> let static_scheduler: &'static dyn Scheduler = Box::leak(simple_scheduler);
> set_scheduler(static_scheduler);
> ```
>
> Could you please check if this works? If so you can help us improve the guide!
#748 introduces such a scheduler initialization for `ktest`. Maybe it will be better to set the scheduler in `aster_frame::init()` and it will work for both.
|
2024-06-20T08:52:42Z
|
cd2b305fa890bca9c4374ccd83c9ccb24bf8dda3
|
asterinas/asterinas
|
diff --git a/framework/aster-frame/src/mm/kspace.rs b/framework/aster-frame/src/mm/kspace.rs
--- a/framework/aster-frame/src/mm/kspace.rs
+++ b/framework/aster-frame/src/mm/kspace.rs
@@ -52,7 +55,10 @@ use super::{
page_table::{boot_pt::BootPageTable, KernelMode, PageTable},
MemoryRegionType, Paddr, PagingConstsTrait, Vaddr, PAGE_SIZE,
};
-use crate::arch::mm::{PageTableEntry, PagingConsts};
+use crate::{
+ arch::mm::{PageTableEntry, PagingConsts},
+ sync::SpinLock,
+};
/// The shortest supported address width is 39 bits. And the literal
/// values are written for 48 bits address width. Adjust the values
diff --git a/framework/aster-frame/src/mm/page_table/boot_pt.rs b/framework/aster-frame/src/mm/page_table/boot_pt.rs
--- a/framework/aster-frame/src/mm/page_table/boot_pt.rs
+++ b/framework/aster-frame/src/mm/page_table/boot_pt.rs
@@ -85,43 +151,19 @@ impl<E: PageTableEntryTrait, C: PagingConstsTrait> BootPageTable<E, C> {
unsafe { core::ptr::write_bytes(vaddr, 0, PAGE_SIZE) };
frame
}
-
- /// Retires this boot-stage page table.
- ///
- /// Do not drop a boot-stage page table. Instead, retire it.
- ///
- /// # Safety
- ///
- /// This method can only be called when this boot-stage page table is no longer in use,
- /// e.g., after the permanent kernel page table has been activated.
- pub unsafe fn retire(mut self) {
- // Manually free all heap and frame memory allocated.
- let frames = core::mem::take(&mut self.frames);
- for frame in frames {
- FRAME_ALLOCATOR.get().unwrap().lock().dealloc(frame, 1);
- }
- // We do not want or need to trigger drop.
- core::mem::forget(self);
- // FIXME: an empty `Vec` is leaked on the heap here since the drop is not called
- // and we have no ways to free it.
- // The best solution to recycle the boot-phase page table is to initialize all
- // page table page metadata of the boot page table by page walk after the metadata
- // pages are mapped. Therefore the boot page table can be recycled or dropped by
- // the routines in the [`super::node`] module. There's even without a need of
- // `first_activate` concept if the boot page table can be managed by page table
- // pages.
- }
}
impl<E: PageTableEntryTrait, C: PagingConstsTrait> Drop for BootPageTable<E, C> {
fn drop(&mut self) {
- panic!("the boot page table is dropped rather than retired.");
+ for frame in &self.frames {
+ FRAME_ALLOCATOR.get().unwrap().lock().dealloc(*frame, 1);
+ }
}
}
#[cfg(ktest)]
#[ktest]
-fn test_boot_pt() {
+fn test_boot_pt_map_protect() {
use super::page_walk;
use crate::{
arch::mm::{PageTableEntry, PagingConsts},
diff --git a/framework/aster-frame/src/mm/page_table/boot_pt.rs b/framework/aster-frame/src/mm/page_table/boot_pt.rs
--- a/framework/aster-frame/src/mm/page_table/boot_pt.rs
+++ b/framework/aster-frame/src/mm/page_table/boot_pt.rs
@@ -140,20 +182,34 @@ fn test_boot_pt() {
let from1 = 0x1000;
let to1 = 0x2;
let prop1 = PageProperty::new(PageFlags::RW, CachePolicy::Writeback);
- boot_pt.map_base_page(from1, to1, prop1);
+ unsafe { boot_pt.map_base_page(from1, to1, prop1) };
assert_eq!(
unsafe { page_walk::<PageTableEntry, PagingConsts>(root_paddr, from1 + 1) },
Some((to1 * PAGE_SIZE + 1, prop1))
);
+ unsafe { boot_pt.protect_base_page(from1, |prop| prop.flags = PageFlags::RX) };
+ assert_eq!(
+ unsafe { page_walk::<PageTableEntry, PagingConsts>(root_paddr, from1 + 1) },
+ Some((
+ to1 * PAGE_SIZE + 1,
+ PageProperty::new(PageFlags::RX, CachePolicy::Writeback)
+ ))
+ );
let from2 = 0x2000;
let to2 = 0x3;
let prop2 = PageProperty::new(PageFlags::RX, CachePolicy::Uncacheable);
- boot_pt.map_base_page(from2, to2, prop2);
+ unsafe { boot_pt.map_base_page(from2, to2, prop2) };
assert_eq!(
unsafe { page_walk::<PageTableEntry, PagingConsts>(root_paddr, from2 + 2) },
Some((to2 * PAGE_SIZE + 2, prop2))
);
-
- unsafe { boot_pt.retire() }
+ unsafe { boot_pt.protect_base_page(from2, |prop| prop.flags = PageFlags::RW) };
+ assert_eq!(
+ unsafe { page_walk::<PageTableEntry, PagingConsts>(root_paddr, from2 + 2) },
+ Some((
+ to2 * PAGE_SIZE + 2,
+ PageProperty::new(PageFlags::RW, CachePolicy::Uncacheable)
+ ))
+ );
}
|
[
"906"
] |
0.4
|
e210e68920481c911f62f03ade0a780f96e48e24
|
[TDX BUG] The TDX SHARED bit can‘t be set in the page table during IOAPIC initialization.
In `framework/aster-frame/src/arch/x86/tdx_guest.rs`:
```rust
trap::init();
arch::after_all_init();
bus::init();
mm::kspace::init_kernel_page_table(boot_pt, meta_pages);
```
The kernel page table is initialized and activated in the `init_kernel_page_table` function. This step occurs after ioapic is initialized (via `after_all_init` function).
However, we should set the ioapic MMIO space as shared page in TDX env, this process manipulates the page table, but the page table is not yet activated.
|
asterinas__asterinas-928
| 928
|
diff --git a/framework/aster-frame/src/arch/x86/mm/mod.rs b/framework/aster-frame/src/arch/x86/mm/mod.rs
--- a/framework/aster-frame/src/arch/x86/mm/mod.rs
+++ b/framework/aster-frame/src/arch/x86/mm/mod.rs
@@ -161,13 +161,6 @@ impl PageTableEntryTrait for PageTableEntry {
let flags = PageTableFlags::PRESENT.bits()
| PageTableFlags::WRITABLE.bits()
| PageTableFlags::USER.bits();
- #[cfg(feature = "intel_tdx")]
- let flags = flags
- | parse_flags!(
- prop.priv_flags.bits(),
- PrivFlags::SHARED,
- PageTableFlags::SHARED
- );
Self(paddr & Self::PHYS_ADDR_MASK | flags)
}
diff --git a/framework/aster-frame/src/arch/x86/mm/mod.rs b/framework/aster-frame/src/arch/x86/mm/mod.rs
--- a/framework/aster-frame/src/arch/x86/mm/mod.rs
+++ b/framework/aster-frame/src/arch/x86/mm/mod.rs
@@ -161,13 +161,6 @@ impl PageTableEntryTrait for PageTableEntry {
let flags = PageTableFlags::PRESENT.bits()
| PageTableFlags::WRITABLE.bits()
| PageTableFlags::USER.bits();
- #[cfg(feature = "intel_tdx")]
- let flags = flags
- | parse_flags!(
- prop.priv_flags.bits(),
- PrivFlags::SHARED,
- PageTableFlags::SHARED
- );
Self(paddr & Self::PHYS_ADDR_MASK | flags)
}
diff --git a/framework/aster-frame/src/arch/x86/tdx_guest.rs b/framework/aster-frame/src/arch/x86/tdx_guest.rs
--- a/framework/aster-frame/src/arch/x86/tdx_guest.rs
+++ b/framework/aster-frame/src/arch/x86/tdx_guest.rs
@@ -11,15 +11,12 @@ use tdx_guest::{
};
use trapframe::TrapFrame;
-use crate::{
- arch::mm::PageTableFlags,
- mm::{
- kspace::KERNEL_PAGE_TABLE,
- paddr_to_vaddr,
- page_prop::{CachePolicy, PageProperty, PrivilegedPageFlags as PrivFlags},
- page_table::PageTableError,
- KERNEL_BASE_VADDR, KERNEL_END_VADDR, PAGE_SIZE,
- },
+use crate::mm::{
+ kspace::{BOOT_PAGE_TABLE, KERNEL_BASE_VADDR, KERNEL_END_VADDR, KERNEL_PAGE_TABLE},
+ paddr_to_vaddr,
+ page_prop::{PageProperty, PrivilegedPageFlags as PrivFlags},
+ page_table::PageTableError,
+ PAGE_SIZE,
};
const SHARED_BIT: u8 = 51;
diff --git a/framework/aster-frame/src/arch/x86/tdx_guest.rs b/framework/aster-frame/src/arch/x86/tdx_guest.rs
--- a/framework/aster-frame/src/arch/x86/tdx_guest.rs
+++ b/framework/aster-frame/src/arch/x86/tdx_guest.rs
@@ -11,15 +11,12 @@ use tdx_guest::{
};
use trapframe::TrapFrame;
-use crate::{
- arch::mm::PageTableFlags,
- mm::{
- kspace::KERNEL_PAGE_TABLE,
- paddr_to_vaddr,
- page_prop::{CachePolicy, PageProperty, PrivilegedPageFlags as PrivFlags},
- page_table::PageTableError,
- KERNEL_BASE_VADDR, KERNEL_END_VADDR, PAGE_SIZE,
- },
+use crate::mm::{
+ kspace::{BOOT_PAGE_TABLE, KERNEL_BASE_VADDR, KERNEL_END_VADDR, KERNEL_PAGE_TABLE},
+ paddr_to_vaddr,
+ page_prop::{PageProperty, PrivilegedPageFlags as PrivFlags},
+ page_table::PageTableError,
+ PAGE_SIZE,
};
const SHARED_BIT: u8 = 51;
diff --git a/framework/aster-frame/src/arch/x86/tdx_guest.rs b/framework/aster-frame/src/arch/x86/tdx_guest.rs
--- a/framework/aster-frame/src/arch/x86/tdx_guest.rs
+++ b/framework/aster-frame/src/arch/x86/tdx_guest.rs
@@ -416,16 +413,28 @@ pub unsafe fn unprotect_gpa_range(gpa: TdxGpa, page_num: usize) -> Result<(), Pa
if gpa & PAGE_MASK != 0 {
warn!("Misaligned address: {:x}", gpa);
}
- let vaddr = paddr_to_vaddr(gpa);
+ // Protect the page in the kernel page table.
let pt = KERNEL_PAGE_TABLE.get().unwrap();
- pt.protect(&(vaddr..page_num * PAGE_SIZE), |prop| {
- prop = PageProperty {
+ let protect_op = |prop: &mut PageProperty| {
+ *prop = PageProperty {
flags: prop.flags,
cache: prop.cache,
priv_flags: prop.priv_flags | PrivFlags::SHARED,
}
- })
- .map_err(PageConvertError::PageTableError)?;
+ };
+ let vaddr = paddr_to_vaddr(gpa);
+ pt.protect(&(vaddr..page_num * PAGE_SIZE), protect_op)
+ .map_err(PageConvertError::PageTableError)?;
+ // Protect the page in the boot page table if in the boot phase.
+ {
+ let mut boot_pt_lock = BOOT_PAGE_TABLE.lock();
+ if let Some(boot_pt) = boot_pt_lock.as_mut() {
+ for i in 0..page_num {
+ let vaddr = paddr_to_vaddr(gpa + i * PAGE_SIZE);
+ boot_pt.protect_base_page(vaddr, protect_op);
+ }
+ }
+ }
map_gpa(
(gpa & (!PAGE_MASK)) as u64 | SHARED_MASK,
(page_num * PAGE_SIZE) as u64,
diff --git a/framework/aster-frame/src/arch/x86/tdx_guest.rs b/framework/aster-frame/src/arch/x86/tdx_guest.rs
--- a/framework/aster-frame/src/arch/x86/tdx_guest.rs
+++ b/framework/aster-frame/src/arch/x86/tdx_guest.rs
@@ -416,16 +413,28 @@ pub unsafe fn unprotect_gpa_range(gpa: TdxGpa, page_num: usize) -> Result<(), Pa
if gpa & PAGE_MASK != 0 {
warn!("Misaligned address: {:x}", gpa);
}
- let vaddr = paddr_to_vaddr(gpa);
+ // Protect the page in the kernel page table.
let pt = KERNEL_PAGE_TABLE.get().unwrap();
- pt.protect(&(vaddr..page_num * PAGE_SIZE), |prop| {
- prop = PageProperty {
+ let protect_op = |prop: &mut PageProperty| {
+ *prop = PageProperty {
flags: prop.flags,
cache: prop.cache,
priv_flags: prop.priv_flags | PrivFlags::SHARED,
}
- })
- .map_err(PageConvertError::PageTableError)?;
+ };
+ let vaddr = paddr_to_vaddr(gpa);
+ pt.protect(&(vaddr..page_num * PAGE_SIZE), protect_op)
+ .map_err(PageConvertError::PageTableError)?;
+ // Protect the page in the boot page table if in the boot phase.
+ {
+ let mut boot_pt_lock = BOOT_PAGE_TABLE.lock();
+ if let Some(boot_pt) = boot_pt_lock.as_mut() {
+ for i in 0..page_num {
+ let vaddr = paddr_to_vaddr(gpa + i * PAGE_SIZE);
+ boot_pt.protect_base_page(vaddr, protect_op);
+ }
+ }
+ }
map_gpa(
(gpa & (!PAGE_MASK)) as u64 | SHARED_MASK,
(page_num * PAGE_SIZE) as u64,
diff --git a/framework/aster-frame/src/arch/x86/tdx_guest.rs b/framework/aster-frame/src/arch/x86/tdx_guest.rs
--- a/framework/aster-frame/src/arch/x86/tdx_guest.rs
+++ b/framework/aster-frame/src/arch/x86/tdx_guest.rs
@@ -452,16 +461,28 @@ pub unsafe fn protect_gpa_range(gpa: TdxGpa, page_num: usize) -> Result<(), Page
if gpa & !PAGE_MASK == 0 {
warn!("Misaligned address: {:x}", gpa);
}
- let vaddr = paddr_to_vaddr(gpa);
+ // Protect the page in the kernel page table.
let pt = KERNEL_PAGE_TABLE.get().unwrap();
- pt.protect(&(vaddr..page_num * PAGE_SIZE), |prop| {
- prop = PageProperty {
+ let protect_op = |prop: &mut PageProperty| {
+ *prop = PageProperty {
flags: prop.flags,
cache: prop.cache,
priv_flags: prop.priv_flags - PrivFlags::SHARED,
}
- })
- .map_err(PageConvertError::PageTableError)?;
+ };
+ let vaddr = paddr_to_vaddr(gpa);
+ pt.protect(&(vaddr..page_num * PAGE_SIZE), protect_op)
+ .map_err(PageConvertError::PageTableError)?;
+ // Protect the page in the boot page table if in the boot phase.
+ {
+ let mut boot_pt_lock = BOOT_PAGE_TABLE.lock();
+ if let Some(boot_pt) = boot_pt_lock.as_mut() {
+ for i in 0..page_num {
+ let vaddr = paddr_to_vaddr(gpa + i * PAGE_SIZE);
+ boot_pt.protect_base_page(vaddr, protect_op);
+ }
+ }
+ }
map_gpa((gpa & PAGE_MASK) as u64, (page_num * PAGE_SIZE) as u64)
.map_err(PageConvertError::TdVmcallError)?;
for i in 0..page_num {
diff --git a/framework/aster-frame/src/arch/x86/tdx_guest.rs b/framework/aster-frame/src/arch/x86/tdx_guest.rs
--- a/framework/aster-frame/src/arch/x86/tdx_guest.rs
+++ b/framework/aster-frame/src/arch/x86/tdx_guest.rs
@@ -452,16 +461,28 @@ pub unsafe fn protect_gpa_range(gpa: TdxGpa, page_num: usize) -> Result<(), Page
if gpa & !PAGE_MASK == 0 {
warn!("Misaligned address: {:x}", gpa);
}
- let vaddr = paddr_to_vaddr(gpa);
+ // Protect the page in the kernel page table.
let pt = KERNEL_PAGE_TABLE.get().unwrap();
- pt.protect(&(vaddr..page_num * PAGE_SIZE), |prop| {
- prop = PageProperty {
+ let protect_op = |prop: &mut PageProperty| {
+ *prop = PageProperty {
flags: prop.flags,
cache: prop.cache,
priv_flags: prop.priv_flags - PrivFlags::SHARED,
}
- })
- .map_err(PageConvertError::PageTableError)?;
+ };
+ let vaddr = paddr_to_vaddr(gpa);
+ pt.protect(&(vaddr..page_num * PAGE_SIZE), protect_op)
+ .map_err(PageConvertError::PageTableError)?;
+ // Protect the page in the boot page table if in the boot phase.
+ {
+ let mut boot_pt_lock = BOOT_PAGE_TABLE.lock();
+ if let Some(boot_pt) = boot_pt_lock.as_mut() {
+ for i in 0..page_num {
+ let vaddr = paddr_to_vaddr(gpa + i * PAGE_SIZE);
+ boot_pt.protect_base_page(vaddr, protect_op);
+ }
+ }
+ }
map_gpa((gpa & PAGE_MASK) as u64, (page_num * PAGE_SIZE) as u64)
.map_err(PageConvertError::TdVmcallError)?;
for i in 0..page_num {
diff --git a/framework/aster-frame/src/arch/x86/trap.rs b/framework/aster-frame/src/arch/x86/trap.rs
--- a/framework/aster-frame/src/arch/x86/trap.rs
+++ b/framework/aster-frame/src/arch/x86/trap.rs
@@ -11,11 +11,7 @@ use tdx_guest::tdcall;
use trapframe::TrapFrame;
#[cfg(feature = "intel_tdx")]
-use crate::arch::{
- cpu::VIRTUALIZATION_EXCEPTION,
- mm::PageTableFlags,
- tdx_guest::{handle_virtual_exception, TdxTrapFrame},
-};
+use crate::arch::{cpu::VIRTUALIZATION_EXCEPTION, tdx_guest::handle_virtual_exception};
use crate::{
cpu::{CpuException, PageFaultErrorCode, PAGE_FAULT},
cpu_local,
diff --git a/framework/aster-frame/src/arch/x86/trap.rs b/framework/aster-frame/src/arch/x86/trap.rs
--- a/framework/aster-frame/src/arch/x86/trap.rs
+++ b/framework/aster-frame/src/arch/x86/trap.rs
@@ -11,11 +11,7 @@ use tdx_guest::tdcall;
use trapframe::TrapFrame;
#[cfg(feature = "intel_tdx")]
-use crate::arch::{
- cpu::VIRTUALIZATION_EXCEPTION,
- mm::PageTableFlags,
- tdx_guest::{handle_virtual_exception, TdxTrapFrame},
-};
+use crate::arch::{cpu::VIRTUALIZATION_EXCEPTION, tdx_guest::handle_virtual_exception};
use crate::{
cpu::{CpuException, PageFaultErrorCode, PAGE_FAULT},
cpu_local,
diff --git a/framework/aster-frame/src/lib.rs b/framework/aster-frame/src/lib.rs
--- a/framework/aster-frame/src/lib.rs
+++ b/framework/aster-frame/src/lib.rs
@@ -76,15 +76,15 @@ pub fn init() {
boot::init();
mm::page::allocator::init();
- let mut boot_pt = mm::get_boot_pt();
- let meta_pages = mm::init_page_meta(&mut boot_pt);
+ mm::kspace::init_boot_page_table();
+ mm::kspace::init_kernel_page_table(mm::init_page_meta());
mm::misc_init();
trap::init();
arch::after_all_init();
bus::init();
- mm::kspace::init_kernel_page_table(boot_pt, meta_pages);
+ mm::kspace::activate_kernel_page_table();
invoke_ffi_init_funcs();
}
diff --git a/framework/aster-frame/src/lib.rs b/framework/aster-frame/src/lib.rs
--- a/framework/aster-frame/src/lib.rs
+++ b/framework/aster-frame/src/lib.rs
@@ -76,15 +76,15 @@ pub fn init() {
boot::init();
mm::page::allocator::init();
- let mut boot_pt = mm::get_boot_pt();
- let meta_pages = mm::init_page_meta(&mut boot_pt);
+ mm::kspace::init_boot_page_table();
+ mm::kspace::init_kernel_page_table(mm::init_page_meta());
mm::misc_init();
trap::init();
arch::after_all_init();
bus::init();
- mm::kspace::init_kernel_page_table(boot_pt, meta_pages);
+ mm::kspace::activate_kernel_page_table();
invoke_ffi_init_funcs();
}
diff --git a/framework/aster-frame/src/mm/kspace.rs b/framework/aster-frame/src/mm/kspace.rs
--- a/framework/aster-frame/src/mm/kspace.rs
+++ b/framework/aster-frame/src/mm/kspace.rs
@@ -7,24 +7,27 @@
//! The kernel memory space is currently managed as follows, if the
//! address width is 48 bits (with 47 bits kernel space).
//!
+//! TODO: the cap of linear mapping (the start of vm alloc) are raised
+//! to workaround for high IO in TDX. We need actual vm alloc API to have
+//! a proper fix.
+//!
//! ```text
//! +-+ <- the highest used address (0xffff_ffff_ffff_0000)
//! | | For the kernel code, 1 GiB. Mapped frames are untracked.
//! +-+ <- 0xffff_ffff_8000_0000
//! | |
//! | | Unused hole.
-//! +-+ <- 0xffff_e100_0000_0000
-//! | | For frame metadata, 1 TiB. Mapped frames are untracked.
-//! +-+ <- 0xffff_e000_0000_0000
-//! | |
-//! | | For vm alloc/io mappings, 32 TiB.
+//! +-+ <- 0xffff_ff00_0000_0000
+//! | | For frame metadata, 1 TiB.
+//! | | Mapped frames are untracked.
+//! +-+ <- 0xffff_fe00_0000_0000
+//! | | For vm alloc/io mappings, 1 TiB.
//! | | Mapped frames are tracked with handles.
+//! +-+ <- 0xffff_fd00_0000_0000
//! | |
-//! +-+ <- the middle of the higher half (0xffff_c000_0000_0000)
//! | |
//! | |
-//! | |
-//! | | For linear mappings, 64 TiB.
+//! | | For linear mappings.
//! | | Mapped physical addresses are untracked.
//! | |
//! | |
diff --git a/framework/aster-frame/src/mm/kspace.rs b/framework/aster-frame/src/mm/kspace.rs
--- a/framework/aster-frame/src/mm/kspace.rs
+++ b/framework/aster-frame/src/mm/kspace.rs
@@ -7,24 +7,27 @@
//! The kernel memory space is currently managed as follows, if the
//! address width is 48 bits (with 47 bits kernel space).
//!
+//! TODO: the cap of linear mapping (the start of vm alloc) are raised
+//! to workaround for high IO in TDX. We need actual vm alloc API to have
+//! a proper fix.
+//!
//! ```text
//! +-+ <- the highest used address (0xffff_ffff_ffff_0000)
//! | | For the kernel code, 1 GiB. Mapped frames are untracked.
//! +-+ <- 0xffff_ffff_8000_0000
//! | |
//! | | Unused hole.
-//! +-+ <- 0xffff_e100_0000_0000
-//! | | For frame metadata, 1 TiB. Mapped frames are untracked.
-//! +-+ <- 0xffff_e000_0000_0000
-//! | |
-//! | | For vm alloc/io mappings, 32 TiB.
+//! +-+ <- 0xffff_ff00_0000_0000
+//! | | For frame metadata, 1 TiB.
+//! | | Mapped frames are untracked.
+//! +-+ <- 0xffff_fe00_0000_0000
+//! | | For vm alloc/io mappings, 1 TiB.
//! | | Mapped frames are tracked with handles.
+//! +-+ <- 0xffff_fd00_0000_0000
//! | |
-//! +-+ <- the middle of the higher half (0xffff_c000_0000_0000)
//! | |
//! | |
-//! | |
-//! | | For linear mappings, 64 TiB.
+//! | | For linear mappings.
//! | | Mapped physical addresses are untracked.
//! | |
//! | |
diff --git a/framework/aster-frame/src/mm/kspace.rs b/framework/aster-frame/src/mm/kspace.rs
--- a/framework/aster-frame/src/mm/kspace.rs
+++ b/framework/aster-frame/src/mm/kspace.rs
@@ -36,7 +39,7 @@
//! 39 bits or 57 bits, the memory space just adjust porportionally.
use alloc::vec::Vec;
-use core::ops::Range;
+use core::{mem::ManuallyDrop, ops::Range};
use align_ext::AlignExt;
use log::info;
diff --git a/framework/aster-frame/src/mm/kspace.rs b/framework/aster-frame/src/mm/kspace.rs
--- a/framework/aster-frame/src/mm/kspace.rs
+++ b/framework/aster-frame/src/mm/kspace.rs
@@ -36,7 +39,7 @@
//! 39 bits or 57 bits, the memory space just adjust porportionally.
use alloc::vec::Vec;
-use core::ops::Range;
+use core::{mem::ManuallyDrop, ops::Range};
use align_ext::AlignExt;
use log::info;
diff --git a/framework/aster-frame/src/mm/kspace.rs b/framework/aster-frame/src/mm/kspace.rs
--- a/framework/aster-frame/src/mm/kspace.rs
+++ b/framework/aster-frame/src/mm/kspace.rs
@@ -52,7 +55,10 @@ use super::{
page_table::{boot_pt::BootPageTable, KernelMode, PageTable},
MemoryRegionType, Paddr, PagingConstsTrait, Vaddr, PAGE_SIZE,
};
-use crate::arch::mm::{PageTableEntry, PagingConsts};
+use crate::{
+ arch::mm::{PageTableEntry, PagingConsts},
+ sync::SpinLock,
+};
/// The shortest supported address width is 39 bits. And the literal
/// values are written for 48 bits address width. Adjust the values
diff --git a/framework/aster-frame/src/mm/kspace.rs b/framework/aster-frame/src/mm/kspace.rs
--- a/framework/aster-frame/src/mm/kspace.rs
+++ b/framework/aster-frame/src/mm/kspace.rs
@@ -76,12 +82,12 @@ pub fn kernel_loaded_offset() -> usize {
const KERNEL_CODE_BASE_VADDR: usize = 0xffff_ffff_8000_0000 << ADDR_WIDTH_SHIFT;
-const FRAME_METADATA_CAP_VADDR: Vaddr = 0xffff_e100_0000_0000 << ADDR_WIDTH_SHIFT;
-const FRAME_METADATA_BASE_VADDR: Vaddr = 0xffff_e000_0000_0000 << ADDR_WIDTH_SHIFT;
+const FRAME_METADATA_CAP_VADDR: Vaddr = 0xffff_ff00_0000_0000 << ADDR_WIDTH_SHIFT;
+const FRAME_METADATA_BASE_VADDR: Vaddr = 0xffff_fe00_0000_0000 << ADDR_WIDTH_SHIFT;
pub(in crate::mm) const FRAME_METADATA_RANGE: Range<Vaddr> =
FRAME_METADATA_BASE_VADDR..FRAME_METADATA_CAP_VADDR;
-const VMALLOC_BASE_VADDR: Vaddr = 0xffff_c000_0000_0000 << ADDR_WIDTH_SHIFT;
+const VMALLOC_BASE_VADDR: Vaddr = 0xffff_fd00_0000_0000 << ADDR_WIDTH_SHIFT;
pub const VMALLOC_VADDR_RANGE: Range<Vaddr> = VMALLOC_BASE_VADDR..FRAME_METADATA_BASE_VADDR;
/// The base address of the linear mapping of all physical
diff --git a/framework/aster-frame/src/mm/kspace.rs b/framework/aster-frame/src/mm/kspace.rs
--- a/framework/aster-frame/src/mm/kspace.rs
+++ b/framework/aster-frame/src/mm/kspace.rs
@@ -76,12 +82,12 @@ pub fn kernel_loaded_offset() -> usize {
const KERNEL_CODE_BASE_VADDR: usize = 0xffff_ffff_8000_0000 << ADDR_WIDTH_SHIFT;
-const FRAME_METADATA_CAP_VADDR: Vaddr = 0xffff_e100_0000_0000 << ADDR_WIDTH_SHIFT;
-const FRAME_METADATA_BASE_VADDR: Vaddr = 0xffff_e000_0000_0000 << ADDR_WIDTH_SHIFT;
+const FRAME_METADATA_CAP_VADDR: Vaddr = 0xffff_ff00_0000_0000 << ADDR_WIDTH_SHIFT;
+const FRAME_METADATA_BASE_VADDR: Vaddr = 0xffff_fe00_0000_0000 << ADDR_WIDTH_SHIFT;
pub(in crate::mm) const FRAME_METADATA_RANGE: Range<Vaddr> =
FRAME_METADATA_BASE_VADDR..FRAME_METADATA_CAP_VADDR;
-const VMALLOC_BASE_VADDR: Vaddr = 0xffff_c000_0000_0000 << ADDR_WIDTH_SHIFT;
+const VMALLOC_BASE_VADDR: Vaddr = 0xffff_fd00_0000_0000 << ADDR_WIDTH_SHIFT;
pub const VMALLOC_VADDR_RANGE: Range<Vaddr> = VMALLOC_BASE_VADDR..FRAME_METADATA_BASE_VADDR;
/// The base address of the linear mapping of all physical
diff --git a/framework/aster-frame/src/mm/kspace.rs b/framework/aster-frame/src/mm/kspace.rs
--- a/framework/aster-frame/src/mm/kspace.rs
+++ b/framework/aster-frame/src/mm/kspace.rs
@@ -95,9 +101,25 @@ pub fn paddr_to_vaddr(pa: Paddr) -> usize {
pa + LINEAR_MAPPING_BASE_VADDR
}
+/// The boot page table instance.
+///
+/// It is used in the initialization phase before [`KERNEL_PAGE_TABLE`] is activated.
+/// Since we want dropping the boot page table unsafe, it is wrapped in a [`ManuallyDrop`].
+pub static BOOT_PAGE_TABLE: SpinLock<Option<ManuallyDrop<BootPageTable>>> = SpinLock::new(None);
+
+/// The kernel page table instance.
+///
+/// It manages the kernel mapping of all address spaces by sharing the kernel part. And it
+/// is unlikely to be activated.
pub static KERNEL_PAGE_TABLE: Once<PageTable<KernelMode, PageTableEntry, PagingConsts>> =
Once::new();
+/// Initializes the boot page table.
+pub(crate) fn init_boot_page_table() {
+ let boot_pt = BootPageTable::from_current_pt();
+ *BOOT_PAGE_TABLE.lock() = Some(ManuallyDrop::new(boot_pt));
+}
+
/// Initializes the kernel page table.
///
/// This function should be called after:
diff --git a/framework/aster-frame/src/mm/kspace.rs b/framework/aster-frame/src/mm/kspace.rs
--- a/framework/aster-frame/src/mm/kspace.rs
+++ b/framework/aster-frame/src/mm/kspace.rs
@@ -95,9 +101,25 @@ pub fn paddr_to_vaddr(pa: Paddr) -> usize {
pa + LINEAR_MAPPING_BASE_VADDR
}
+/// The boot page table instance.
+///
+/// It is used in the initialization phase before [`KERNEL_PAGE_TABLE`] is activated.
+/// Since we want dropping the boot page table unsafe, it is wrapped in a [`ManuallyDrop`].
+pub static BOOT_PAGE_TABLE: SpinLock<Option<ManuallyDrop<BootPageTable>>> = SpinLock::new(None);
+
+/// The kernel page table instance.
+///
+/// It manages the kernel mapping of all address spaces by sharing the kernel part. And it
+/// is unlikely to be activated.
pub static KERNEL_PAGE_TABLE: Once<PageTable<KernelMode, PageTableEntry, PagingConsts>> =
Once::new();
+/// Initializes the boot page table.
+pub(crate) fn init_boot_page_table() {
+ let boot_pt = BootPageTable::from_current_pt();
+ *BOOT_PAGE_TABLE.lock() = Some(ManuallyDrop::new(boot_pt));
+}
+
/// Initializes the kernel page table.
///
/// This function should be called after:
diff --git a/framework/aster-frame/src/mm/kspace.rs b/framework/aster-frame/src/mm/kspace.rs
--- a/framework/aster-frame/src/mm/kspace.rs
+++ b/framework/aster-frame/src/mm/kspace.rs
@@ -106,10 +128,7 @@ pub static KERNEL_PAGE_TABLE: Once<PageTable<KernelMode, PageTableEntry, PagingC
///
/// This function should be called before:
/// - any initializer that modifies the kernel page table.
-pub fn init_kernel_page_table(
- boot_pt: BootPageTable<PageTableEntry, PagingConsts>,
- meta_pages: Vec<Range<Paddr>>,
-) {
+pub fn init_kernel_page_table(meta_pages: Vec<Range<Paddr>>) {
info!("Initializing the kernel page table");
let regions = crate::boot::memory_regions();
diff --git a/framework/aster-frame/src/mm/kspace.rs b/framework/aster-frame/src/mm/kspace.rs
--- a/framework/aster-frame/src/mm/kspace.rs
+++ b/framework/aster-frame/src/mm/kspace.rs
@@ -106,10 +128,7 @@ pub static KERNEL_PAGE_TABLE: Once<PageTable<KernelMode, PageTableEntry, PagingC
///
/// This function should be called before:
/// - any initializer that modifies the kernel page table.
-pub fn init_kernel_page_table(
- boot_pt: BootPageTable<PageTableEntry, PagingConsts>,
- meta_pages: Vec<Range<Paddr>>,
-) {
+pub fn init_kernel_page_table(meta_pages: Vec<Range<Paddr>>) {
info!("Initializing the kernel page table");
let regions = crate::boot::memory_regions();
diff --git a/framework/aster-frame/src/mm/kspace.rs b/framework/aster-frame/src/mm/kspace.rs
--- a/framework/aster-frame/src/mm/kspace.rs
+++ b/framework/aster-frame/src/mm/kspace.rs
@@ -201,15 +220,21 @@ pub fn init_kernel_page_table(
}
}
+ KERNEL_PAGE_TABLE.call_once(|| kpt);
+}
+
+pub fn activate_kernel_page_table() {
+ let kpt = KERNEL_PAGE_TABLE
+ .get()
+ .expect("The kernel page table is not initialized yet");
// SAFETY: the kernel page table is initialized properly.
unsafe {
kpt.first_activate_unchecked();
crate::arch::mm::tlb_flush_all_including_global();
}
- KERNEL_PAGE_TABLE.call_once(|| kpt);
-
- // SAFETY: the boot page table is OK to be retired now since
+ // SAFETY: the boot page table is OK to be dropped now since
// the kernel page table is activated.
- unsafe { boot_pt.retire() };
+ let mut boot_pt = BOOT_PAGE_TABLE.lock().take().unwrap();
+ unsafe { ManuallyDrop::drop(&mut boot_pt) };
}
diff --git a/framework/aster-frame/src/mm/kspace.rs b/framework/aster-frame/src/mm/kspace.rs
--- a/framework/aster-frame/src/mm/kspace.rs
+++ b/framework/aster-frame/src/mm/kspace.rs
@@ -201,15 +220,21 @@ pub fn init_kernel_page_table(
}
}
+ KERNEL_PAGE_TABLE.call_once(|| kpt);
+}
+
+pub fn activate_kernel_page_table() {
+ let kpt = KERNEL_PAGE_TABLE
+ .get()
+ .expect("The kernel page table is not initialized yet");
// SAFETY: the kernel page table is initialized properly.
unsafe {
kpt.first_activate_unchecked();
crate::arch::mm::tlb_flush_all_including_global();
}
- KERNEL_PAGE_TABLE.call_once(|| kpt);
-
- // SAFETY: the boot page table is OK to be retired now since
+ // SAFETY: the boot page table is OK to be dropped now since
// the kernel page table is activated.
- unsafe { boot_pt.retire() };
+ let mut boot_pt = BOOT_PAGE_TABLE.lock().take().unwrap();
+ unsafe { ManuallyDrop::drop(&mut boot_pt) };
}
diff --git a/framework/aster-frame/src/mm/mod.rs b/framework/aster-frame/src/mm/mod.rs
--- a/framework/aster-frame/src/mm/mod.rs
+++ b/framework/aster-frame/src/mm/mod.rs
@@ -131,7 +131,3 @@ pub(crate) fn misc_init() {
}
FRAMEBUFFER_REGIONS.call_once(|| framebuffer_regions);
}
-
-pub(crate) fn get_boot_pt() -> page_table::boot_pt::BootPageTable {
- unsafe { page_table::boot_pt::BootPageTable::from_current_pt() }
-}
diff --git a/framework/aster-frame/src/mm/mod.rs b/framework/aster-frame/src/mm/mod.rs
--- a/framework/aster-frame/src/mm/mod.rs
+++ b/framework/aster-frame/src/mm/mod.rs
@@ -131,7 +131,3 @@ pub(crate) fn misc_init() {
}
FRAMEBUFFER_REGIONS.call_once(|| framebuffer_regions);
}
-
-pub(crate) fn get_boot_pt() -> page_table::boot_pt::BootPageTable {
- unsafe { page_table::boot_pt::BootPageTable::from_current_pt() }
-}
diff --git a/framework/aster-frame/src/mm/page/meta.rs b/framework/aster-frame/src/mm/page/meta.rs
--- a/framework/aster-frame/src/mm/page/meta.rs
+++ b/framework/aster-frame/src/mm/page/meta.rs
@@ -53,12 +53,9 @@ use super::Page;
use crate::{
arch::mm::{PageTableEntry, PagingConsts},
mm::{
- paddr_to_vaddr,
- page::allocator::FRAME_ALLOCATOR,
- page_size,
- page_table::{boot_pt::BootPageTable, PageTableEntryTrait},
- CachePolicy, Paddr, PageFlags, PageProperty, PagingConstsTrait, PagingLevel,
- PrivilegedPageFlags, PAGE_SIZE,
+ kspace::BOOT_PAGE_TABLE, paddr_to_vaddr, page::allocator::FRAME_ALLOCATOR, page_size,
+ page_table::PageTableEntryTrait, CachePolicy, Paddr, PageFlags, PageProperty,
+ PagingConstsTrait, PagingLevel, PrivilegedPageFlags, PAGE_SIZE,
},
};
diff --git a/framework/aster-frame/src/mm/page/meta.rs b/framework/aster-frame/src/mm/page/meta.rs
--- a/framework/aster-frame/src/mm/page/meta.rs
+++ b/framework/aster-frame/src/mm/page/meta.rs
@@ -53,12 +53,9 @@ use super::Page;
use crate::{
arch::mm::{PageTableEntry, PagingConsts},
mm::{
- paddr_to_vaddr,
- page::allocator::FRAME_ALLOCATOR,
- page_size,
- page_table::{boot_pt::BootPageTable, PageTableEntryTrait},
- CachePolicy, Paddr, PageFlags, PageProperty, PagingConstsTrait, PagingLevel,
- PrivilegedPageFlags, PAGE_SIZE,
+ kspace::BOOT_PAGE_TABLE, paddr_to_vaddr, page::allocator::FRAME_ALLOCATOR, page_size,
+ page_table::PageTableEntryTrait, CachePolicy, Paddr, PageFlags, PageProperty,
+ PagingConstsTrait, PagingLevel, PrivilegedPageFlags, PAGE_SIZE,
},
};
diff --git a/framework/aster-frame/src/mm/page/meta.rs b/framework/aster-frame/src/mm/page/meta.rs
--- a/framework/aster-frame/src/mm/page/meta.rs
+++ b/framework/aster-frame/src/mm/page/meta.rs
@@ -191,7 +188,7 @@ impl PageMeta for KernelMeta {
/// Initializes the metadata of all physical pages.
///
/// The function returns a list of `Page`s containing the metadata.
-pub(crate) fn init(boot_pt: &mut BootPageTable) -> Vec<Range<Paddr>> {
+pub(crate) fn init() -> Vec<Range<Paddr>> {
let max_paddr = {
let regions = crate::boot::memory_regions();
regions.iter().map(|r| r.base() + r.len()).max().unwrap()
diff --git a/framework/aster-frame/src/mm/page/meta.rs b/framework/aster-frame/src/mm/page/meta.rs
--- a/framework/aster-frame/src/mm/page/meta.rs
+++ b/framework/aster-frame/src/mm/page/meta.rs
@@ -191,7 +188,7 @@ impl PageMeta for KernelMeta {
/// Initializes the metadata of all physical pages.
///
/// The function returns a list of `Page`s containing the metadata.
-pub(crate) fn init(boot_pt: &mut BootPageTable) -> Vec<Range<Paddr>> {
+pub(crate) fn init() -> Vec<Range<Paddr>> {
let max_paddr = {
let regions = crate::boot::memory_regions();
regions.iter().map(|r| r.base() + r.len()).max().unwrap()
diff --git a/framework/aster-frame/src/mm/page/meta.rs b/framework/aster-frame/src/mm/page/meta.rs
--- a/framework/aster-frame/src/mm/page/meta.rs
+++ b/framework/aster-frame/src/mm/page/meta.rs
@@ -207,8 +204,11 @@ pub(crate) fn init(boot_pt: &mut BootPageTable) -> Vec<Range<Paddr>> {
let num_pages = max_paddr / page_size::<PagingConsts>(1);
let num_meta_pages = (num_pages * size_of::<MetaSlot>()).div_ceil(PAGE_SIZE);
let meta_pages = alloc_meta_pages(num_meta_pages);
-
// Map the metadata pages.
+ let mut boot_pt_lock = BOOT_PAGE_TABLE.lock();
+ let boot_pt = boot_pt_lock
+ .as_mut()
+ .expect("boot page table not initialized");
for (i, frame_paddr) in meta_pages.iter().enumerate() {
let vaddr = mapping::page_to_meta::<PagingConsts>(0) + i * PAGE_SIZE;
let prop = PageProperty {
diff --git a/framework/aster-frame/src/mm/page/meta.rs b/framework/aster-frame/src/mm/page/meta.rs
--- a/framework/aster-frame/src/mm/page/meta.rs
+++ b/framework/aster-frame/src/mm/page/meta.rs
@@ -207,8 +204,11 @@ pub(crate) fn init(boot_pt: &mut BootPageTable) -> Vec<Range<Paddr>> {
let num_pages = max_paddr / page_size::<PagingConsts>(1);
let num_meta_pages = (num_pages * size_of::<MetaSlot>()).div_ceil(PAGE_SIZE);
let meta_pages = alloc_meta_pages(num_meta_pages);
-
// Map the metadata pages.
+ let mut boot_pt_lock = BOOT_PAGE_TABLE.lock();
+ let boot_pt = boot_pt_lock
+ .as_mut()
+ .expect("boot page table not initialized");
for (i, frame_paddr) in meta_pages.iter().enumerate() {
let vaddr = mapping::page_to_meta::<PagingConsts>(0) + i * PAGE_SIZE;
let prop = PageProperty {
diff --git a/framework/aster-frame/src/mm/page/meta.rs b/framework/aster-frame/src/mm/page/meta.rs
--- a/framework/aster-frame/src/mm/page/meta.rs
+++ b/framework/aster-frame/src/mm/page/meta.rs
@@ -216,9 +216,9 @@ pub(crate) fn init(boot_pt: &mut BootPageTable) -> Vec<Range<Paddr>> {
cache: CachePolicy::Writeback,
priv_flags: PrivilegedPageFlags::GLOBAL,
};
- boot_pt.map_base_page(vaddr, frame_paddr / PAGE_SIZE, prop);
+ // SAFETY: we are doing the metadata mappings for the kernel.
+ unsafe { boot_pt.map_base_page(vaddr, frame_paddr / PAGE_SIZE, prop) };
}
-
// Now the metadata pages are mapped, we can initialize the metadata.
meta_pages
.into_iter()
diff --git a/framework/aster-frame/src/mm/page/meta.rs b/framework/aster-frame/src/mm/page/meta.rs
--- a/framework/aster-frame/src/mm/page/meta.rs
+++ b/framework/aster-frame/src/mm/page/meta.rs
@@ -216,9 +216,9 @@ pub(crate) fn init(boot_pt: &mut BootPageTable) -> Vec<Range<Paddr>> {
cache: CachePolicy::Writeback,
priv_flags: PrivilegedPageFlags::GLOBAL,
};
- boot_pt.map_base_page(vaddr, frame_paddr / PAGE_SIZE, prop);
+ // SAFETY: we are doing the metadata mappings for the kernel.
+ unsafe { boot_pt.map_base_page(vaddr, frame_paddr / PAGE_SIZE, prop) };
}
-
// Now the metadata pages are mapped, we can initialize the metadata.
meta_pages
.into_iter()
diff --git a/framework/aster-frame/src/mm/page_table/boot_pt.rs b/framework/aster-frame/src/mm/page_table/boot_pt.rs
--- a/framework/aster-frame/src/mm/page_table/boot_pt.rs
+++ b/framework/aster-frame/src/mm/page_table/boot_pt.rs
@@ -10,8 +10,8 @@ use super::{pte_index, PageTableEntryTrait};
use crate::{
arch::mm::{PageTableEntry, PagingConsts},
mm::{
- paddr_to_vaddr, page::allocator::FRAME_ALLOCATOR, PageProperty, PagingConstsTrait, Vaddr,
- PAGE_SIZE,
+ nr_subpage_per_huge, paddr_to_vaddr, page::allocator::FRAME_ALLOCATOR, PageProperty,
+ PagingConstsTrait, Vaddr, PAGE_SIZE,
},
};
diff --git a/framework/aster-frame/src/mm/page_table/boot_pt.rs b/framework/aster-frame/src/mm/page_table/boot_pt.rs
--- a/framework/aster-frame/src/mm/page_table/boot_pt.rs
+++ b/framework/aster-frame/src/mm/page_table/boot_pt.rs
@@ -10,8 +10,8 @@ use super::{pte_index, PageTableEntryTrait};
use crate::{
arch::mm::{PageTableEntry, PagingConsts},
mm::{
- paddr_to_vaddr, page::allocator::FRAME_ALLOCATOR, PageProperty, PagingConstsTrait, Vaddr,
- PAGE_SIZE,
+ nr_subpage_per_huge, paddr_to_vaddr, page::allocator::FRAME_ALLOCATOR, PageProperty,
+ PagingConstsTrait, Vaddr, PAGE_SIZE,
},
};
diff --git a/framework/aster-frame/src/mm/page_table/boot_pt.rs b/framework/aster-frame/src/mm/page_table/boot_pt.rs
--- a/framework/aster-frame/src/mm/page_table/boot_pt.rs
+++ b/framework/aster-frame/src/mm/page_table/boot_pt.rs
@@ -34,10 +34,7 @@ pub struct BootPageTable<
impl<E: PageTableEntryTrait, C: PagingConstsTrait> BootPageTable<E, C> {
/// Creates a new boot page table from the current page table root physical address.
- ///
- /// The caller must ensure that the current page table may be set up by the firmware,
- /// loader or the setup code.
- pub unsafe fn from_current_pt() -> Self {
+ pub fn from_current_pt() -> Self {
let root_paddr = crate::arch::mm::current_page_table_paddr();
Self {
root_pt: root_paddr / C::BASE_PAGE_SIZE,
diff --git a/framework/aster-frame/src/mm/page_table/boot_pt.rs b/framework/aster-frame/src/mm/page_table/boot_pt.rs
--- a/framework/aster-frame/src/mm/page_table/boot_pt.rs
+++ b/framework/aster-frame/src/mm/page_table/boot_pt.rs
@@ -34,10 +34,7 @@ pub struct BootPageTable<
impl<E: PageTableEntryTrait, C: PagingConstsTrait> BootPageTable<E, C> {
/// Creates a new boot page table from the current page table root physical address.
- ///
- /// The caller must ensure that the current page table may be set up by the firmware,
- /// loader or the setup code.
- pub unsafe fn from_current_pt() -> Self {
+ pub fn from_current_pt() -> Self {
let root_paddr = crate::arch::mm::current_page_table_paddr();
Self {
root_pt: root_paddr / C::BASE_PAGE_SIZE,
diff --git a/framework/aster-frame/src/mm/page_table/boot_pt.rs b/framework/aster-frame/src/mm/page_table/boot_pt.rs
--- a/framework/aster-frame/src/mm/page_table/boot_pt.rs
+++ b/framework/aster-frame/src/mm/page_table/boot_pt.rs
@@ -47,8 +44,16 @@ impl<E: PageTableEntryTrait, C: PagingConstsTrait> BootPageTable<E, C> {
}
/// Maps a base page to a frame.
+ ///
+ /// # Panics
+ ///
/// This function will panic if the page is already mapped.
- pub fn map_base_page(&mut self, from: Vaddr, to: FrameNumber, prop: PageProperty) {
+ ///
+ /// # Safety
+ ///
+ /// This function is unsafe because it can cause undefined behavior if the caller
+ /// maps a page in the kernel address space.
+ pub unsafe fn map_base_page(&mut self, from: Vaddr, to: FrameNumber, prop: PageProperty) {
let mut pt = self.root_pt;
let mut level = C::NR_LEVELS;
// Walk to the last level of the page table.
diff --git a/framework/aster-frame/src/mm/page_table/boot_pt.rs b/framework/aster-frame/src/mm/page_table/boot_pt.rs
--- a/framework/aster-frame/src/mm/page_table/boot_pt.rs
+++ b/framework/aster-frame/src/mm/page_table/boot_pt.rs
@@ -47,8 +44,16 @@ impl<E: PageTableEntryTrait, C: PagingConstsTrait> BootPageTable<E, C> {
}
/// Maps a base page to a frame.
+ ///
+ /// # Panics
+ ///
/// This function will panic if the page is already mapped.
- pub fn map_base_page(&mut self, from: Vaddr, to: FrameNumber, prop: PageProperty) {
+ ///
+ /// # Safety
+ ///
+ /// This function is unsafe because it can cause undefined behavior if the caller
+ /// maps a page in the kernel address space.
+ pub unsafe fn map_base_page(&mut self, from: Vaddr, to: FrameNumber, prop: PageProperty) {
let mut pt = self.root_pt;
let mut level = C::NR_LEVELS;
// Walk to the last level of the page table.
diff --git a/framework/aster-frame/src/mm/page_table/boot_pt.rs b/framework/aster-frame/src/mm/page_table/boot_pt.rs
--- a/framework/aster-frame/src/mm/page_table/boot_pt.rs
+++ b/framework/aster-frame/src/mm/page_table/boot_pt.rs
@@ -77,6 +82,67 @@ impl<E: PageTableEntryTrait, C: PagingConstsTrait> BootPageTable<E, C> {
unsafe { pte_ptr.write(E::new_frame(to * C::BASE_PAGE_SIZE, 1, prop)) };
}
+ /// Maps a base page to a frame.
+ ///
+ /// This function may split a huge page into base pages, causing page allocations
+ /// if the original mapping is a huge page.
+ ///
+ /// # Panics
+ ///
+ /// This function will panic if the page is already mapped.
+ ///
+ /// # Safety
+ ///
+ /// This function is unsafe because it can cause undefined behavior if the caller
+ /// maps a page in the kernel address space.
+ pub unsafe fn protect_base_page(
+ &mut self,
+ virt_addr: Vaddr,
+ mut op: impl FnMut(&mut PageProperty),
+ ) {
+ let mut pt = self.root_pt;
+ let mut level = C::NR_LEVELS;
+ // Walk to the last level of the page table.
+ while level > 1 {
+ let index = pte_index::<C>(virt_addr, level);
+ let pte_ptr = unsafe { (paddr_to_vaddr(pt * C::BASE_PAGE_SIZE) as *mut E).add(index) };
+ let pte = unsafe { pte_ptr.read() };
+ pt = if !pte.is_present() {
+ panic!("protecting an unmapped page in the boot page table");
+ } else if pte.is_last(level) {
+ // Split the huge page.
+ let frame = self.alloc_frame();
+ let huge_pa = pte.paddr();
+ for i in 0..nr_subpage_per_huge::<C>() {
+ let nxt_ptr =
+ unsafe { (paddr_to_vaddr(frame * C::BASE_PAGE_SIZE) as *mut E).add(i) };
+ unsafe {
+ nxt_ptr.write(E::new_frame(
+ huge_pa + i * C::BASE_PAGE_SIZE,
+ level - 1,
+ pte.prop(),
+ ))
+ };
+ }
+ unsafe { pte_ptr.write(E::new_pt(frame * C::BASE_PAGE_SIZE)) };
+ frame
+ } else {
+ pte.paddr() / C::BASE_PAGE_SIZE
+ };
+ level -= 1;
+ }
+ // Do protection in the last level page table.
+ let index = pte_index::<C>(virt_addr, 1);
+ let pte_ptr = unsafe { (paddr_to_vaddr(pt * C::BASE_PAGE_SIZE) as *mut E).add(index) };
+ let pte = unsafe { pte_ptr.read() };
+ if !pte.is_present() {
+ panic!("protecting an unmapped page in the boot page table");
+ }
+ let mut prop = pte.prop();
+ op(&mut prop);
+ unsafe { pte_ptr.write(E::new_frame(pte.paddr(), 1, prop)) };
+ }
+
fn alloc_frame(&mut self) -> FrameNumber {
let frame = FRAME_ALLOCATOR.get().unwrap().lock().alloc(1).unwrap();
self.frames.push(frame);
diff --git a/framework/aster-frame/src/mm/page_table/boot_pt.rs b/framework/aster-frame/src/mm/page_table/boot_pt.rs
--- a/framework/aster-frame/src/mm/page_table/boot_pt.rs
+++ b/framework/aster-frame/src/mm/page_table/boot_pt.rs
@@ -77,6 +82,67 @@ impl<E: PageTableEntryTrait, C: PagingConstsTrait> BootPageTable<E, C> {
unsafe { pte_ptr.write(E::new_frame(to * C::BASE_PAGE_SIZE, 1, prop)) };
}
+ /// Maps a base page to a frame.
+ ///
+ /// This function may split a huge page into base pages, causing page allocations
+ /// if the original mapping is a huge page.
+ ///
+ /// # Panics
+ ///
+ /// This function will panic if the page is already mapped.
+ ///
+ /// # Safety
+ ///
+ /// This function is unsafe because it can cause undefined behavior if the caller
+ /// maps a page in the kernel address space.
+ pub unsafe fn protect_base_page(
+ &mut self,
+ virt_addr: Vaddr,
+ mut op: impl FnMut(&mut PageProperty),
+ ) {
+ let mut pt = self.root_pt;
+ let mut level = C::NR_LEVELS;
+ // Walk to the last level of the page table.
+ while level > 1 {
+ let index = pte_index::<C>(virt_addr, level);
+ let pte_ptr = unsafe { (paddr_to_vaddr(pt * C::BASE_PAGE_SIZE) as *mut E).add(index) };
+ let pte = unsafe { pte_ptr.read() };
+ pt = if !pte.is_present() {
+ panic!("protecting an unmapped page in the boot page table");
+ } else if pte.is_last(level) {
+ // Split the huge page.
+ let frame = self.alloc_frame();
+ let huge_pa = pte.paddr();
+ for i in 0..nr_subpage_per_huge::<C>() {
+ let nxt_ptr =
+ unsafe { (paddr_to_vaddr(frame * C::BASE_PAGE_SIZE) as *mut E).add(i) };
+ unsafe {
+ nxt_ptr.write(E::new_frame(
+ huge_pa + i * C::BASE_PAGE_SIZE,
+ level - 1,
+ pte.prop(),
+ ))
+ };
+ }
+ unsafe { pte_ptr.write(E::new_pt(frame * C::BASE_PAGE_SIZE)) };
+ frame
+ } else {
+ pte.paddr() / C::BASE_PAGE_SIZE
+ };
+ level -= 1;
+ }
+ // Do protection in the last level page table.
+ let index = pte_index::<C>(virt_addr, 1);
+ let pte_ptr = unsafe { (paddr_to_vaddr(pt * C::BASE_PAGE_SIZE) as *mut E).add(index) };
+ let pte = unsafe { pte_ptr.read() };
+ if !pte.is_present() {
+ panic!("protecting an unmapped page in the boot page table");
+ }
+ let mut prop = pte.prop();
+ op(&mut prop);
+ unsafe { pte_ptr.write(E::new_frame(pte.paddr(), 1, prop)) };
+ }
+
fn alloc_frame(&mut self) -> FrameNumber {
let frame = FRAME_ALLOCATOR.get().unwrap().lock().alloc(1).unwrap();
self.frames.push(frame);
diff --git a/framework/aster-frame/src/mm/page_table/boot_pt.rs b/framework/aster-frame/src/mm/page_table/boot_pt.rs
--- a/framework/aster-frame/src/mm/page_table/boot_pt.rs
+++ b/framework/aster-frame/src/mm/page_table/boot_pt.rs
@@ -85,43 +151,19 @@ impl<E: PageTableEntryTrait, C: PagingConstsTrait> BootPageTable<E, C> {
unsafe { core::ptr::write_bytes(vaddr, 0, PAGE_SIZE) };
frame
}
-
- /// Retires this boot-stage page table.
- ///
- /// Do not drop a boot-stage page table. Instead, retire it.
- ///
- /// # Safety
- ///
- /// This method can only be called when this boot-stage page table is no longer in use,
- /// e.g., after the permanent kernel page table has been activated.
- pub unsafe fn retire(mut self) {
- // Manually free all heap and frame memory allocated.
- let frames = core::mem::take(&mut self.frames);
- for frame in frames {
- FRAME_ALLOCATOR.get().unwrap().lock().dealloc(frame, 1);
- }
- // We do not want or need to trigger drop.
- core::mem::forget(self);
- // FIXME: an empty `Vec` is leaked on the heap here since the drop is not called
- // and we have no ways to free it.
- // The best solution to recycle the boot-phase page table is to initialize all
- // page table page metadata of the boot page table by page walk after the metadata
- // pages are mapped. Therefore the boot page table can be recycled or dropped by
- // the routines in the [`super::node`] module. There's even without a need of
- // `first_activate` concept if the boot page table can be managed by page table
- // pages.
- }
}
impl<E: PageTableEntryTrait, C: PagingConstsTrait> Drop for BootPageTable<E, C> {
fn drop(&mut self) {
- panic!("the boot page table is dropped rather than retired.");
+ for frame in &self.frames {
+ FRAME_ALLOCATOR.get().unwrap().lock().dealloc(*frame, 1);
+ }
}
}
#[cfg(ktest)]
#[ktest]
-fn test_boot_pt() {
+fn test_boot_pt_map_protect() {
use super::page_walk;
use crate::{
arch::mm::{PageTableEntry, PagingConsts},
diff --git a/framework/aster-frame/src/mm/page_table/boot_pt.rs b/framework/aster-frame/src/mm/page_table/boot_pt.rs
--- a/framework/aster-frame/src/mm/page_table/boot_pt.rs
+++ b/framework/aster-frame/src/mm/page_table/boot_pt.rs
@@ -140,20 +182,34 @@ fn test_boot_pt() {
let from1 = 0x1000;
let to1 = 0x2;
let prop1 = PageProperty::new(PageFlags::RW, CachePolicy::Writeback);
- boot_pt.map_base_page(from1, to1, prop1);
+ unsafe { boot_pt.map_base_page(from1, to1, prop1) };
assert_eq!(
unsafe { page_walk::<PageTableEntry, PagingConsts>(root_paddr, from1 + 1) },
Some((to1 * PAGE_SIZE + 1, prop1))
);
+ unsafe { boot_pt.protect_base_page(from1, |prop| prop.flags = PageFlags::RX) };
+ assert_eq!(
+ unsafe { page_walk::<PageTableEntry, PagingConsts>(root_paddr, from1 + 1) },
+ Some((
+ to1 * PAGE_SIZE + 1,
+ PageProperty::new(PageFlags::RX, CachePolicy::Writeback)
+ ))
+ );
let from2 = 0x2000;
let to2 = 0x3;
let prop2 = PageProperty::new(PageFlags::RX, CachePolicy::Uncacheable);
- boot_pt.map_base_page(from2, to2, prop2);
+ unsafe { boot_pt.map_base_page(from2, to2, prop2) };
assert_eq!(
unsafe { page_walk::<PageTableEntry, PagingConsts>(root_paddr, from2 + 2) },
Some((to2 * PAGE_SIZE + 2, prop2))
);
-
- unsafe { boot_pt.retire() }
+ unsafe { boot_pt.protect_base_page(from2, |prop| prop.flags = PageFlags::RW) };
+ assert_eq!(
+ unsafe { page_walk::<PageTableEntry, PagingConsts>(root_paddr, from2 + 2) },
+ Some((
+ to2 * PAGE_SIZE + 2,
+ PageProperty::new(PageFlags::RW, CachePolicy::Uncacheable)
+ ))
+ );
}
|
2024-06-12T07:29:38Z
|
e210e68920481c911f62f03ade0a780f96e48e24
|
|
asterinas/asterinas
|
diff --git a/regression/apps/Makefile b/regression/apps/Makefile
--- a/regression/apps/Makefile
+++ b/regression/apps/Makefile
@@ -10,6 +10,7 @@ REGRESSION_BUILD_DIR ?= $(INITRAMFS)/regression
# These test apps are sorted by name
TEST_APPS := \
+ alarm \
clone3 \
eventfd2 \
execve \
diff --git /dev/null b/regression/apps/alarm/Makefile
new file mode 100644
--- /dev/null
+++ b/regression/apps/alarm/Makefile
@@ -0,0 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
+include ../test_common.mk
+
+EXTRA_C_FLAGS := -static
|
[
"774",
"790"
] |
0.4
|
34e9d71fe4501bf4cac4d8263ccb568a814ac4b7
|
Deliver POSIX signals for busy-loop user code
## Problem
Currently, the POSIX signals are handled in the main loop of user tasks, after `UserMode::execute` returns.
```rust
pub fn create_new_user_task(user_space: Arc<UserSpace>, thread_ref: Weak<Thread>) -> Arc<Task> {
fn user_task_entry() {
loop {
let user_event = user_mode.execute();
let context = user_mode.context_mut();
handle_user_event(user_event, context);
let current_thread = current_thread!();
if current_thread.status().lock().is_exited() {
break;
}
// POSIX signals are handled here!
handle_pending_signal(context).unwrap();
// ...
}
}
TaskOptions::new(user_task_entry)
.data(thread_ref)
.user_space(Some(user_space))
.build()
.expect("spawn task failed")
}
```
This means that if `UserMode::execute` does not returns, then the kernel has no chance to handle signals. Consider the following simple user program in C.
```rust
int main() {
// When the one second elapses, a SIGALRM will be triggered.
// The default behavior of a process when receiving SIGALRM
// is to terminate the process.
alarm(1);
// But currently, the busy loop will prevent the program
// from being terminated!
while (1) { }
return 0;
}
```
Of course. The `SIGALRM` shall never be delivered to the process by Asterinas as the kernel can only handles POSIX signals when the user code requests system calls.
## Analysis
To figure out a solution, let's dig into the `UserMode::execute` function, which calls `UserContext::execute` to do the real job.
```rust
fn execute(&mut self) -> crate::user::UserEvent {
// ...
loop {
self.user_context.run();
match CpuException::to_cpu_exception(self.user_context.trap_num as u16) {
Some(exception) => {
if exception.typ == CpuExceptionType::FaultOrTrap
|| exception.typ == CpuExceptionType::Fault
|| exception.typ == CpuExceptionType::Trap
{
break;
}
}
None => {
if self.user_context.trap_num as u16 == SYSCALL_TRAPNUM {
break;
}
}
};
call_irq_callback_functions(&self.as_trap_frame());
}
if self.user_context.trap_num as u16 != SYSCALL_TRAPNUM {
// ...
UserEvent::Exception
} else {
UserEvent::Syscall
}
}
```
If the periodic timer interrupt is triggered while the CPU is running in the user mode, then `self.user_context.run()` returns and the interrupt is handled by the `call_irq_callback_functions` function.
So the control of the CPU does return to the kernel at regular intervals. However, a significant issue arises with the `UserContext::execute` method from the Asterinas Framework—it lacks awareness and handling of POSIX signals, and appropriately so.
## Solution
### Major changes to `aster-frame`
So this issue proposes to extend the API of the `UserMode::execute` method as well as that of `UserContext::execute` so that the two methods would return the control of the CPU to its caller (e.g., the `aster-nix` crate) if there are pending events (e.g., POSIX signals).
The new interface is as shown below.
```rust
impl<'a> UserMode<'a> {
/// Starts executing in the user mode. Make sure current task is the task in `UserMode`.
///
/// The method returns for one of three possible reasons indicated by `ReturnReason`.
/// 1. A system call is issued by the user space;
/// 2. A CPU exception is triggered by the user space;
/// 3. A kernel event is pending, as indicated by the given closure.
///
/// After handling whatever user or kernel events that
/// cause the method to return
/// and updating the user-mode CPU context,
/// this method can be invoked again to go back to the user space.
fn execute<F>(&mut self, mut has_kernel_event: F) -> ReturnReason
where
F: FnMut() -> bool,
{
// ...
}
}
```
The new `ReturnReason` replaces the old `UserEvent`.
```rust
/// A reason as to why the control of the CPU is returned from
/// the user space to the kernel.
#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum ReturnReason {
/// A system call is issued by the user space.
UserSyscall,
/// A CPU exception is triggered by the user space.
UserException,
/// A kernel event is pending
KernelEvent,
}
```
### Major changes to `aster-nix`
The main loop of a user task is modifed to utilize the extended interface of `UserMode::execute`.
```rust
fn execute(&mut self) -> crate::user::UserEvent {
// ...
fn user_task_entry() {
let has_kernel_events_fn = {
let current = current!();
let current_thread = current_thread!();
|| {
current.has_pending_signals()
}
};
loop {
let return_reason = user_mode.execute(has_kernel_events_fn);
let context = user_mode.context_mut();
match user_event {
ReturnReason::UserSyscall => handle_syscall(context),
ReturnReason::UserException => handle_exception(context),
_ =>,
}
let current_thread = current_thread!();
if current_thread.status().lock().is_exited() {
break;
}
handle_pending_signal(context).unwrap();
// ...
}
}
// ...
}
```
`ThreadOptions` is not fully used while creating new kernel thread
Here is the `aster-nix::thread::kernel_thread::ThreadOptions`.
```rust
/// Options to create or spawn a new thread.
pub struct ThreadOptions {
func: Option<Box<dyn Fn() + Send + Sync>>,
priority: Priority,
cpu_affinity: CpuSet,
}
```
It has fields representing priority and cpu affinity. But when we create new kernel thread in the code below,
```rust
fn new_kernel_thread(mut thread_options: ThreadOptions) -> Arc<Self> {
let task_fn = thread_options.take_func();
let thread_fn = move || {
task_fn();
let current_thread = current_thread!();
// ensure the thread is exit
current_thread.exit();
};
let tid = allocate_tid();
let thread = Arc::new_cyclic(|thread_ref| {
let weal_thread = thread_ref.clone();
let task = TaskOptions::new(thread_fn)
.data(weal_thread)
.build()
.unwrap();
let status = ThreadStatus::Init;
let kernel_thread = KernelThread;
Thread::new(tid, task, kernel_thread, status)
});
thread_table::add_thread(thread.clone());
thread
}
```
we never use this two fields to construct `TaskOptions`, therefore the bound task is always of default configuration.
One problem caused by this issue is that all `Worker`s in `WORKERPOOL_HIGH_PRI` are of normal priority instead of real-time priority, which is incorrect and can cause starvation in some specific cases.
|
asterinas__asterinas-782
| 782
|
diff --git a/docs/src/framework/a-100-line-kernel.md b/docs/src/framework/a-100-line-kernel.md
--- a/docs/src/framework/a-100-line-kernel.md
+++ b/docs/src/framework/a-100-line-kernel.md
@@ -55,7 +55,7 @@ use alloc::vec;
use aster_frame::cpu::UserContext;
use aster_frame::prelude::*;
use aster_frame::task::{Task, TaskOptions};
-use aster_frame::user::{UserEvent, UserMode, UserSpace};
+use aster_frame::user::{ReturnReason, UserMode, UserSpace};
use aster_frame::vm::{PageFlags, PAGE_SIZE, Vaddr, VmAllocOptions, VmIo, VmMapOptions, VmSpace};
/// The kernel's boot and initialization process is managed by Asterinas Framework.
diff --git a/docs/src/framework/a-100-line-kernel.md b/docs/src/framework/a-100-line-kernel.md
--- a/docs/src/framework/a-100-line-kernel.md
+++ b/docs/src/framework/a-100-line-kernel.md
@@ -55,7 +55,7 @@ use alloc::vec;
use aster_frame::cpu::UserContext;
use aster_frame::prelude::*;
use aster_frame::task::{Task, TaskOptions};
-use aster_frame::user::{UserEvent, UserMode, UserSpace};
+use aster_frame::user::{ReturnReason, UserMode, UserSpace};
use aster_frame::vm::{PageFlags, PAGE_SIZE, Vaddr, VmAllocOptions, VmIo, VmMapOptions, VmSpace};
/// The kernel's boot and initialization process is managed by Asterinas Framework.
diff --git a/docs/src/framework/a-100-line-kernel.md b/docs/src/framework/a-100-line-kernel.md
--- a/docs/src/framework/a-100-line-kernel.md
+++ b/docs/src/framework/a-100-line-kernel.md
@@ -116,13 +116,15 @@ fn create_user_task(user_space: Arc<UserSpace>) -> Arc<Task> {
loop {
// The execute method returns when system
- // calls or CPU exceptions occur.
- let user_event = user_mode.execute();
+ // calls or CPU exceptions occur or some
+ // events specified by the kernel occur.
+ let return_reason = user_mode.execute(|| false);
+
// The CPU registers of the user space
// can be accessed and manipulated via
// the `UserContext` abstraction.
let user_context = user_mode.context_mut();
- if UserEvent::Syscall == user_event {
+ if ReturnReason::UserSyscall == return_reason {
handle_syscall(user_context, current.user_space().unwrap());
}
}
diff --git a/docs/src/framework/a-100-line-kernel.md b/docs/src/framework/a-100-line-kernel.md
--- a/docs/src/framework/a-100-line-kernel.md
+++ b/docs/src/framework/a-100-line-kernel.md
@@ -116,13 +116,15 @@ fn create_user_task(user_space: Arc<UserSpace>) -> Arc<Task> {
loop {
// The execute method returns when system
- // calls or CPU exceptions occur.
- let user_event = user_mode.execute();
+ // calls or CPU exceptions occur or some
+ // events specified by the kernel occur.
+ let return_reason = user_mode.execute(|| false);
+
// The CPU registers of the user space
// can be accessed and manipulated via
// the `UserContext` abstraction.
let user_context = user_mode.context_mut();
- if UserEvent::Syscall == user_event {
+ if ReturnReason::UserSyscall == return_reason {
handle_syscall(user_context, current.user_space().unwrap());
}
}
diff --git a/framework/aster-frame/src/arch/x86/cpu.rs b/framework/aster-frame/src/arch/x86/cpu.rs
--- a/framework/aster-frame/src/arch/x86/cpu.rs
+++ b/framework/aster-frame/src/arch/x86/cpu.rs
@@ -23,7 +23,7 @@ use x86_64::registers::rflags::RFlags;
use crate::arch::tdx_guest::{handle_virtual_exception, TdxTrapFrame};
use crate::{
trap::call_irq_callback_functions,
- user::{UserContextApi, UserContextApiInternal, UserEvent},
+ user::{ReturnReason, UserContextApi, UserContextApiInternal},
};
/// Returns the number of CPUs.
diff --git a/framework/aster-frame/src/arch/x86/cpu.rs b/framework/aster-frame/src/arch/x86/cpu.rs
--- a/framework/aster-frame/src/arch/x86/cpu.rs
+++ b/framework/aster-frame/src/arch/x86/cpu.rs
@@ -23,7 +23,7 @@ use x86_64::registers::rflags::RFlags;
use crate::arch::tdx_guest::{handle_virtual_exception, TdxTrapFrame};
use crate::{
trap::call_irq_callback_functions,
- user::{UserContextApi, UserContextApiInternal, UserEvent},
+ user::{ReturnReason, UserContextApi, UserContextApiInternal},
};
/// Returns the number of CPUs.
diff --git a/framework/aster-frame/src/arch/x86/cpu.rs b/framework/aster-frame/src/arch/x86/cpu.rs
--- a/framework/aster-frame/src/arch/x86/cpu.rs
+++ b/framework/aster-frame/src/arch/x86/cpu.rs
@@ -257,11 +257,15 @@ impl UserContext {
}
impl UserContextApiInternal for UserContext {
- fn execute(&mut self) -> crate::user::UserEvent {
+ fn execute<F>(&mut self, mut has_kernel_event: F) -> ReturnReason
+ where
+ F: FnMut() -> bool,
+ {
// set interrupt flag so that in user mode it can receive external interrupts
// set ID flag which means cpu support CPUID instruction
self.user_context.general.rflags |= (RFlags::INTERRUPT_FLAG | RFlags::ID).bits() as usize;
+ let return_reason: ReturnReason;
const SYSCALL_TRAPNUM: u16 = 0x100;
let mut user_preemption = UserPreemption::new();
diff --git a/framework/aster-frame/src/arch/x86/cpu.rs b/framework/aster-frame/src/arch/x86/cpu.rs
--- a/framework/aster-frame/src/arch/x86/cpu.rs
+++ b/framework/aster-frame/src/arch/x86/cpu.rs
@@ -257,11 +257,15 @@ impl UserContext {
}
impl UserContextApiInternal for UserContext {
- fn execute(&mut self) -> crate::user::UserEvent {
+ fn execute<F>(&mut self, mut has_kernel_event: F) -> ReturnReason
+ where
+ F: FnMut() -> bool,
+ {
// set interrupt flag so that in user mode it can receive external interrupts
// set ID flag which means cpu support CPUID instruction
self.user_context.general.rflags |= (RFlags::INTERRUPT_FLAG | RFlags::ID).bits() as usize;
+ let return_reason: ReturnReason;
const SYSCALL_TRAPNUM: u16 = 0x100;
let mut user_preemption = UserPreemption::new();
diff --git a/framework/aster-frame/src/arch/x86/cpu.rs b/framework/aster-frame/src/arch/x86/cpu.rs
--- a/framework/aster-frame/src/arch/x86/cpu.rs
+++ b/framework/aster-frame/src/arch/x86/cpu.rs
@@ -281,31 +285,36 @@ impl UserContextApiInternal for UserContext {
|| exception.typ == CpuExceptionType::Fault
|| exception.typ == CpuExceptionType::Trap
{
+ return_reason = ReturnReason::UserException;
break;
}
}
None => {
if self.user_context.trap_num as u16 == SYSCALL_TRAPNUM {
+ return_reason = ReturnReason::UserSyscall;
break;
}
}
};
call_irq_callback_functions(&self.as_trap_frame());
+ if has_kernel_event() {
+ return_reason = ReturnReason::KernelEvent;
+ break;
+ }
user_preemption.might_preempt();
}
crate::arch::irq::enable_local();
- if self.user_context.trap_num as u16 != SYSCALL_TRAPNUM {
+ if return_reason == ReturnReason::UserException {
self.cpu_exception_info = CpuExceptionInfo {
page_fault_addr: unsafe { x86::controlregs::cr2() },
id: self.user_context.trap_num,
error_code: self.user_context.error_code,
};
- UserEvent::Exception
- } else {
- UserEvent::Syscall
}
+
+ return_reason
}
fn as_trap_frame(&self) -> trapframe::TrapFrame {
diff --git a/framework/aster-frame/src/arch/x86/cpu.rs b/framework/aster-frame/src/arch/x86/cpu.rs
--- a/framework/aster-frame/src/arch/x86/cpu.rs
+++ b/framework/aster-frame/src/arch/x86/cpu.rs
@@ -281,31 +285,36 @@ impl UserContextApiInternal for UserContext {
|| exception.typ == CpuExceptionType::Fault
|| exception.typ == CpuExceptionType::Trap
{
+ return_reason = ReturnReason::UserException;
break;
}
}
None => {
if self.user_context.trap_num as u16 == SYSCALL_TRAPNUM {
+ return_reason = ReturnReason::UserSyscall;
break;
}
}
};
call_irq_callback_functions(&self.as_trap_frame());
+ if has_kernel_event() {
+ return_reason = ReturnReason::KernelEvent;
+ break;
+ }
user_preemption.might_preempt();
}
crate::arch::irq::enable_local();
- if self.user_context.trap_num as u16 != SYSCALL_TRAPNUM {
+ if return_reason == ReturnReason::UserException {
self.cpu_exception_info = CpuExceptionInfo {
page_fault_addr: unsafe { x86::controlregs::cr2() },
id: self.user_context.trap_num,
error_code: self.user_context.error_code,
};
- UserEvent::Exception
- } else {
- UserEvent::Syscall
}
+
+ return_reason
}
fn as_trap_frame(&self) -> trapframe::TrapFrame {
diff --git a/framework/aster-frame/src/user.rs b/framework/aster-frame/src/user.rs
--- a/framework/aster-frame/src/user.rs
+++ b/framework/aster-frame/src/user.rs
@@ -51,7 +51,9 @@ impl UserSpace {
/// Only visible in aster-frame
pub(crate) trait UserContextApiInternal {
/// Starts executing in the user mode.
- fn execute(&mut self) -> UserEvent;
+ fn execute<F>(&mut self, has_kernel_event: F) -> ReturnReason
+ where
+ F: FnMut() -> bool;
/// Use the information inside CpuContext to build a trapframe
fn as_trap_frame(&self) -> TrapFrame;
diff --git a/framework/aster-frame/src/user.rs b/framework/aster-frame/src/user.rs
--- a/framework/aster-frame/src/user.rs
+++ b/framework/aster-frame/src/user.rs
@@ -51,7 +51,9 @@ impl UserSpace {
/// Only visible in aster-frame
pub(crate) trait UserContextApiInternal {
/// Starts executing in the user mode.
- fn execute(&mut self) -> UserEvent;
+ fn execute<F>(&mut self, has_kernel_event: F) -> ReturnReason
+ where
+ F: FnMut() -> bool;
/// Use the information inside CpuContext to build a trapframe
fn as_trap_frame(&self) -> TrapFrame;
diff --git a/framework/aster-frame/src/user.rs b/framework/aster-frame/src/user.rs
--- a/framework/aster-frame/src/user.rs
+++ b/framework/aster-frame/src/user.rs
@@ -93,9 +95,9 @@ pub trait UserContextApi {
/// .expect("the current task is associated with a user space");
/// let mut user_mode = user_space.user_mode();
/// loop {
-/// // Execute in the user space until some interesting user event occurs
-/// let user_event = user_mode.execute();
-/// todo!("handle the user event, e.g., syscall");
+/// // Execute in the user space until some interesting events occur.
+/// let return_reason = user_mode.execute(|| false);
+/// todo!("handle the event, e.g., syscall");
/// }
/// ```
pub struct UserMode<'a> {
diff --git a/framework/aster-frame/src/user.rs b/framework/aster-frame/src/user.rs
--- a/framework/aster-frame/src/user.rs
+++ b/framework/aster-frame/src/user.rs
@@ -93,9 +95,9 @@ pub trait UserContextApi {
/// .expect("the current task is associated with a user space");
/// let mut user_mode = user_space.user_mode();
/// loop {
-/// // Execute in the user space until some interesting user event occurs
-/// let user_event = user_mode.execute();
-/// todo!("handle the user event, e.g., syscall");
+/// // Execute in the user space until some interesting events occur.
+/// let return_reason = user_mode.execute(|| false);
+/// todo!("handle the event, e.g., syscall");
/// }
/// ```
pub struct UserMode<'a> {
diff --git a/framework/aster-frame/src/user.rs b/framework/aster-frame/src/user.rs
--- a/framework/aster-frame/src/user.rs
+++ b/framework/aster-frame/src/user.rs
@@ -118,17 +120,22 @@ impl<'a> UserMode<'a> {
/// Starts executing in the user mode. Make sure current task is the task in `UserMode`.
///
- /// The method returns for one of three possible reasons indicated by `UserEvent`.
- /// 1. The user invokes a system call;
- /// 2. The user triggers an exception;
- /// 3. The user triggers a fault.
+ /// The method returns for one of three possible reasons indicated by `ReturnReason`.
+ /// 1. A system call is issued by the user space;
+ /// 2. A CPU exception is triggered by the user space;
+ /// 3. A kernel event is pending, as indicated by the given closure.
///
- /// After handling the user event and updating the user-mode CPU context,
+ /// After handling whatever user or kernel events that
+ /// cause the method to return
+ /// and updating the user-mode CPU context,
/// this method can be invoked again to go back to the user space.
- pub fn execute(&mut self) -> UserEvent {
+ pub fn execute<F>(&mut self, has_kernel_event: F) -> ReturnReason
+ where
+ F: FnMut() -> bool,
+ {
self.user_space.vm_space().activate();
debug_assert!(Arc::ptr_eq(&self.current, &Task::current()));
- self.context.execute()
+ self.context.execute(has_kernel_event)
}
/// Returns an immutable reference the user-mode CPU context.
diff --git a/framework/aster-frame/src/user.rs b/framework/aster-frame/src/user.rs
--- a/framework/aster-frame/src/user.rs
+++ b/framework/aster-frame/src/user.rs
@@ -118,17 +120,22 @@ impl<'a> UserMode<'a> {
/// Starts executing in the user mode. Make sure current task is the task in `UserMode`.
///
- /// The method returns for one of three possible reasons indicated by `UserEvent`.
- /// 1. The user invokes a system call;
- /// 2. The user triggers an exception;
- /// 3. The user triggers a fault.
+ /// The method returns for one of three possible reasons indicated by `ReturnReason`.
+ /// 1. A system call is issued by the user space;
+ /// 2. A CPU exception is triggered by the user space;
+ /// 3. A kernel event is pending, as indicated by the given closure.
///
- /// After handling the user event and updating the user-mode CPU context,
+ /// After handling whatever user or kernel events that
+ /// cause the method to return
+ /// and updating the user-mode CPU context,
/// this method can be invoked again to go back to the user space.
- pub fn execute(&mut self) -> UserEvent {
+ pub fn execute<F>(&mut self, has_kernel_event: F) -> ReturnReason
+ where
+ F: FnMut() -> bool,
+ {
self.user_space.vm_space().activate();
debug_assert!(Arc::ptr_eq(&self.current, &Task::current()));
- self.context.execute()
+ self.context.execute(has_kernel_event)
}
/// Returns an immutable reference the user-mode CPU context.
diff --git a/framework/aster-frame/src/user.rs b/framework/aster-frame/src/user.rs
--- a/framework/aster-frame/src/user.rs
+++ b/framework/aster-frame/src/user.rs
@@ -143,14 +150,13 @@ impl<'a> UserMode<'a> {
}
#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
-/// A user event is what brings back the control of the CPU back from
-/// the user space to the kernel space.
-///
-/// Note that hardware interrupts are not considered user events as they
-/// are triggered by devices and not visible to user programs.
-/// To handle interrupts, one should register callback funtions for
-/// IRQ lines (`IrqLine`).
-pub enum UserEvent {
- Syscall,
- Exception,
+/// A reason as to why the control of the CPU is returned from
+/// the user space to the kernel.
+pub enum ReturnReason {
+ /// A system call is issued by the user space.
+ UserSyscall,
+ /// A CPU exception is triggered by the user space.
+ UserException,
+ /// A kernel event is pending
+ KernelEvent,
}
diff --git a/framework/aster-frame/src/user.rs b/framework/aster-frame/src/user.rs
--- a/framework/aster-frame/src/user.rs
+++ b/framework/aster-frame/src/user.rs
@@ -143,14 +150,13 @@ impl<'a> UserMode<'a> {
}
#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
-/// A user event is what brings back the control of the CPU back from
-/// the user space to the kernel space.
-///
-/// Note that hardware interrupts are not considered user events as they
-/// are triggered by devices and not visible to user programs.
-/// To handle interrupts, one should register callback funtions for
-/// IRQ lines (`IrqLine`).
-pub enum UserEvent {
- Syscall,
- Exception,
+/// A reason as to why the control of the CPU is returned from
+/// the user space to the kernel.
+pub enum ReturnReason {
+ /// A system call is issued by the user space.
+ UserSyscall,
+ /// A CPU exception is triggered by the user space.
+ UserException,
+ /// A kernel event is pending
+ KernelEvent,
}
diff --git a/kernel/aster-nix/src/thread/kernel_thread.rs b/kernel/aster-nix/src/thread/kernel_thread.rs
--- a/kernel/aster-nix/src/thread/kernel_thread.rs
+++ b/kernel/aster-nix/src/thread/kernel_thread.rs
@@ -44,6 +44,8 @@ impl KernelThreadExt for Thread {
let weal_thread = thread_ref.clone();
let task = TaskOptions::new(thread_fn)
.data(weal_thread)
+ .priority(thread_options.priority)
+ .cpu_affinity(thread_options.cpu_affinity)
.build()
.unwrap();
let status = ThreadStatus::Init;
diff --git a/kernel/aster-nix/src/thread/kernel_thread.rs b/kernel/aster-nix/src/thread/kernel_thread.rs
--- a/kernel/aster-nix/src/thread/kernel_thread.rs
+++ b/kernel/aster-nix/src/thread/kernel_thread.rs
@@ -44,6 +44,8 @@ impl KernelThreadExt for Thread {
let weal_thread = thread_ref.clone();
let task = TaskOptions::new(thread_fn)
.data(weal_thread)
+ .priority(thread_options.priority)
+ .cpu_affinity(thread_options.cpu_affinity)
.build()
.unwrap();
let status = ThreadStatus::Init;
diff --git a/kernel/aster-nix/src/thread/task.rs b/kernel/aster-nix/src/thread/task.rs
--- a/kernel/aster-nix/src/thread/task.rs
+++ b/kernel/aster-nix/src/thread/task.rs
@@ -1,20 +1,27 @@
// SPDX-License-Identifier: MPL-2.0
use aster_frame::{
- cpu::UserContext,
task::{preempt, Task, TaskOptions},
- user::{UserContextApi, UserEvent, UserMode, UserSpace},
+ user::{ReturnReason, UserContextApi, UserMode, UserSpace},
};
use super::Thread;
use crate::{
- cpu::LinuxAbi, prelude::*, process::signal::handle_pending_signal, syscall::handle_syscall,
+ cpu::LinuxAbi,
+ prelude::*,
+ process::{posix_thread::PosixThreadExt, signal::handle_pending_signal},
+ syscall::handle_syscall,
thread::exception::handle_exception,
};
/// create new task with userspace and parent process
pub fn create_new_user_task(user_space: Arc<UserSpace>, thread_ref: Weak<Thread>) -> Arc<Task> {
fn user_task_entry() {
+ fn has_pending_signal(current_thread: &Arc<Thread>) -> bool {
+ let posix_thread = current_thread.as_posix_thread().unwrap();
+ posix_thread.has_pending_signal()
+ }
+
let current_thread = current_thread!();
let current_task = current_thread.task();
let user_space = current_task
diff --git a/kernel/aster-nix/src/thread/task.rs b/kernel/aster-nix/src/thread/task.rs
--- a/kernel/aster-nix/src/thread/task.rs
+++ b/kernel/aster-nix/src/thread/task.rs
@@ -1,20 +1,27 @@
// SPDX-License-Identifier: MPL-2.0
use aster_frame::{
- cpu::UserContext,
task::{preempt, Task, TaskOptions},
- user::{UserContextApi, UserEvent, UserMode, UserSpace},
+ user::{ReturnReason, UserContextApi, UserMode, UserSpace},
};
use super::Thread;
use crate::{
- cpu::LinuxAbi, prelude::*, process::signal::handle_pending_signal, syscall::handle_syscall,
+ cpu::LinuxAbi,
+ prelude::*,
+ process::{posix_thread::PosixThreadExt, signal::handle_pending_signal},
+ syscall::handle_syscall,
thread::exception::handle_exception,
};
/// create new task with userspace and parent process
pub fn create_new_user_task(user_space: Arc<UserSpace>, thread_ref: Weak<Thread>) -> Arc<Task> {
fn user_task_entry() {
+ fn has_pending_signal(current_thread: &Arc<Thread>) -> bool {
+ let posix_thread = current_thread.as_posix_thread().unwrap();
+ posix_thread.has_pending_signal()
+ }
+
let current_thread = current_thread!();
let current_task = current_thread.task();
let user_space = current_task
diff --git a/kernel/aster-nix/src/thread/task.rs b/kernel/aster-nix/src/thread/task.rs
--- a/kernel/aster-nix/src/thread/task.rs
+++ b/kernel/aster-nix/src/thread/task.rs
@@ -34,11 +41,17 @@ pub fn create_new_user_task(user_space: Arc<UserSpace>, thread_ref: Weak<Thread>
user_mode.context().syscall_ret()
);
+ #[allow(clippy::redundant_closure)]
+ let has_kernel_event_fn = || has_pending_signal(¤t_thread);
loop {
- let user_event = user_mode.execute();
+ let return_reason = user_mode.execute(has_kernel_event_fn);
let context = user_mode.context_mut();
// handle user event:
- handle_user_event(user_event, context);
+ match return_reason {
+ ReturnReason::UserException => handle_exception(context),
+ ReturnReason::UserSyscall => handle_syscall(context),
+ ReturnReason::KernelEvent => {}
+ };
// should be do this comparison before handle signal?
if current_thread.status().is_exited() {
break;
diff --git a/kernel/aster-nix/src/thread/task.rs b/kernel/aster-nix/src/thread/task.rs
--- a/kernel/aster-nix/src/thread/task.rs
+++ b/kernel/aster-nix/src/thread/task.rs
@@ -34,11 +41,17 @@ pub fn create_new_user_task(user_space: Arc<UserSpace>, thread_ref: Weak<Thread>
user_mode.context().syscall_ret()
);
+ #[allow(clippy::redundant_closure)]
+ let has_kernel_event_fn = || has_pending_signal(¤t_thread);
loop {
- let user_event = user_mode.execute();
+ let return_reason = user_mode.execute(has_kernel_event_fn);
let context = user_mode.context_mut();
// handle user event:
- handle_user_event(user_event, context);
+ match return_reason {
+ ReturnReason::UserException => handle_exception(context),
+ ReturnReason::UserSyscall => handle_syscall(context),
+ ReturnReason::KernelEvent => {}
+ };
// should be do this comparison before handle signal?
if current_thread.status().is_exited() {
break;
diff --git a/kernel/aster-nix/src/thread/task.rs b/kernel/aster-nix/src/thread/task.rs
--- a/kernel/aster-nix/src/thread/task.rs
+++ b/kernel/aster-nix/src/thread/task.rs
@@ -68,10 +81,3 @@ pub fn create_new_user_task(user_space: Arc<UserSpace>, thread_ref: Weak<Thread>
.build()
.expect("spawn task failed")
}
-
-fn handle_user_event(user_event: UserEvent, context: &mut UserContext) {
- match user_event {
- UserEvent::Syscall => handle_syscall(context),
- UserEvent::Exception => handle_exception(context),
- }
-}
diff --git a/kernel/aster-nix/src/thread/task.rs b/kernel/aster-nix/src/thread/task.rs
--- a/kernel/aster-nix/src/thread/task.rs
+++ b/kernel/aster-nix/src/thread/task.rs
@@ -68,10 +81,3 @@ pub fn create_new_user_task(user_space: Arc<UserSpace>, thread_ref: Weak<Thread>
.build()
.expect("spawn task failed")
}
-
-fn handle_user_event(user_event: UserEvent, context: &mut UserContext) {
- match user_event {
- UserEvent::Syscall => handle_syscall(context),
- UserEvent::Exception => handle_exception(context),
- }
-}
diff --git a/regression/apps/Makefile b/regression/apps/Makefile
--- a/regression/apps/Makefile
+++ b/regression/apps/Makefile
@@ -10,6 +10,7 @@ REGRESSION_BUILD_DIR ?= $(INITRAMFS)/regression
# These test apps are sorted by name
TEST_APPS := \
+ alarm \
clone3 \
eventfd2 \
execve \
diff --git /dev/null b/regression/apps/alarm/Makefile
new file mode 100644
--- /dev/null
+++ b/regression/apps/alarm/Makefile
@@ -0,0 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
+include ../test_common.mk
+
+EXTRA_C_FLAGS := -static
diff --git /dev/null b/regression/apps/alarm/alarm.c
new file mode 100644
--- /dev/null
+++ b/regression/apps/alarm/alarm.c
@@ -0,0 +1,11 @@
+// SPDX-License-Identifier: MPL-2.0
+
+#include <unistd.h>
+
+int main()
+{
+ alarm(3);
+ while (1) {
+ }
+ return 0;
+}
diff --git /dev/null b/regression/apps/alarm/alarm.c
new file mode 100644
--- /dev/null
+++ b/regression/apps/alarm/alarm.c
@@ -0,0 +1,11 @@
+// SPDX-License-Identifier: MPL-2.0
+
+#include <unistd.h>
+
+int main()
+{
+ alarm(3);
+ while (1) {
+ }
+ return 0;
+}
|
I made some modification in #782 to enable timely delivery of POSIX signals based on the solution you proposed. But as to this specific MRE that you mentioned,
```c
int main() {
// When the one second elapses, a SIGALRM will be triggered.
// The default behavior of a process when receiving SIGALRM
// is to terminate the process.
alarm(1);
// But currently, the busy loop will prevent the program
// from being terminated!
while (1) { }
return 0;
}
```
I'm afraid that's not enough.
Under current implementation of alarm syscall, the actual callback, in which we enqueue the `SIGALRM` to corresponding `posix_thread`'s `sig_queues`, is submitted to the global workqueue once the timer expires. However, our scheduler doesn't support preemption, therefore the submitted workitem will never be executed.
> Under current implementation of alarm syscall, the actual callback, in which we enqueue the SIGALRM to corresponding posix_thread's sig_queues, is submitted to the global workqueue once the timer expires. However, our scheduler doesn't support preemption, therefore the submitted workitem will never be executed.
@jellllly420, there's a preemption point in the main loop of `user_task_entry`, after handling pending signal. So the workqueue thread should be scheduled to run after some signal is submitted to the work queue?
But I'm not sure whether we need to trigger preemtion before handling irq or after handling irq.
> > Under current implementation of alarm syscall, the actual callback, in which we enqueue the SIGALRM to corresponding posix_thread's sig_queues, is submitted to the global workqueue once the timer expires. However, our scheduler doesn't support preemption, therefore the submitted workitem will never be executed.
>
> @jellllly420, there's a preemption point in the main loop of `user_task_entry`, after handling pending signal. So the workqueue thread should be scheduled to run after some signal is submitted the the work queue?
Will the `Usermode::execute` in `user_task_entry` ever return once we enter the `while(1)` busy-looping?
> Will the Usermode::execute in user_task_entry ever return once we enter the while(1) busy-looping?
Currently, it won't. Maybe the `has_kernel_events_fn` should also check whether there are any pending workitems, and if any, `Usermode.execute` should also return to `aster-nix` to enable workqueue thread run.
I'm not sure whether it's suitable to do so.
> However, our scheduler doesn't support preemption, therefore the submitted workitem will never be executed.
@jellllly420 The following small change should be enough to address the issue you raised.
### The change
The `aster_frame::task::preempt` function should be made private and called internally in `UserMode::execute`. This way, the Framework ensures that the user-kernel switching is always a preemption point.
### The rationale
Preemptive scheduling, as opposite to cooperative scheduling, is by definition transparent to the tasks that are subject to scheduling. In other words, Asterinas Framework must enforce preemption, without cooperation from the users of Asterinas Framework.
But in our current implementation, the `preempt` method from `aster-frame` is explicitly called by its user.
```rust
pub fn create_new_user_task(user_space: Arc<UserSpace>, thread_ref: Weak<Thread>) -> Arc<Task> {
fn user_task_entry() {
loop {
let user_event = user_mode.execute();
let context = user_mode.context_mut();
handle_user_event(user_event, context);
// ...
// a preemption point after handling user event.
preempt();
}
// ...
}
// ...
}
```
The proposed change can address this problem.
Thanks for your advice.
I have some question about how the `WorkQueue` mechanism works after we submit some `WorkItem`s. If I understood correctly, the `Monitor` of `WorkerPool` should be scheduled to run first and the `Monitor` will `wake_worker` or `add_worker`, then we should wait for the running worker to be scheduled and the `Worker` will pick a `WorkItem` to run if there is any.
If that is the case, how can a `Monitor` of `normal` priority `preempt` a running thread in current `PriorityScheduler`? Calling `schedule` instead of `preempt` may be a workaround, though logically incorrect (because the user loop should not explicitly give up cpu).
Update:
When I replaced `preempt` with `schedule`, the `Monitor` can be scheduled to run. However, `Workers` waken by `Monitor` still cannot be scheduled even though they are supposed to be of real-time priority. It's caused by #790.
After fixing that issue, the `SIGALRM` signal can finally be correctly enqueued. I expected that the `while(1)` thread would be rescheduled to run and the signal would be handled in next timer interrupt. The `while(1)` did get on the cpu. However, this time the `UserContext::run` never returned. I'm not that familiar with this part and need to dig in more to find out what happened.
> When I replaced `preempt` with `schedule`, the `Monitor` can be scheduled to run. However, `Workers` waken by `Monitor` still cannot be scheduled even though they are supposed to be of real-time priority. It's caused by #790.
Good point 👍
@jellllly420 Good job on spotting the bug. Could you try to fix it?
|
2024-04-23T16:18:28Z
|
e210e68920481c911f62f03ade0a780f96e48e24
|
asterinas/asterinas
|
diff --git a/kernel/aster-nix/src/vm/vmar/options.rs b/kernel/aster-nix/src/vm/vmar/options.rs
--- a/kernel/aster-nix/src/vm/vmar/options.rs
+++ b/kernel/aster-nix/src/vm/vmar/options.rs
@@ -142,14 +142,14 @@ mod test {
use crate::vm::{
page_fault_handler::PageFaultHandler,
perms::VmPerms,
- vmar::ROOT_VMAR_HIGHEST_ADDR,
+ vmar::ROOT_VMAR_CAP_ADDR,
vmo::{VmoOptions, VmoRightsOp},
};
#[ktest]
fn root_vmar() {
let vmar = Vmar::<Full>::new_root();
- assert!(vmar.size() == ROOT_VMAR_HIGHEST_ADDR);
+ assert!(vmar.size() == ROOT_VMAR_CAP_ADDR);
}
#[ktest]
|
[
"666"
] |
0.4
|
dede22843a99f6d19c8a2dddcfc7ef0ad45ce815
|
[BUG] Uncaught panic happened in heap_allocator
I run 416.gamess , one of spec CPU 2006 test items, but a pacnic happened:
```
~ # ./gamess_base.amd64-m64-gcc41-nn < exam29.config
[ERROR]: Uncaught panic!
panicked at framework/aster-frame/src/vm/heap_allocator.rs:24:5:
Heap allocation error, layout = Layout { size: 659468632, align: 1 (1 << 0) }
```
This pacnic alse happened when I run 434.zeusmp.
the file of 434.zeusmp and 416.gamess: [https://github.com/skpupil/my_spec_test](url)
|
asterinas__asterinas-679
| 679
|
diff --git a/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs b/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs
--- a/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs
@@ -15,8 +15,7 @@ use crate::{
memory_region::{non_overlapping_regions_from, MemoryRegion, MemoryRegionType},
BootloaderAcpiArg, BootloaderFramebufferArg,
},
- config::PHYS_OFFSET,
- vm::paddr_to_vaddr,
+ vm::{paddr_to_vaddr, PHYS_MEM_BASE_VADDR},
};
static BOOT_PARAMS: Once<BootParams> = Once::new();
diff --git a/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs b/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs
--- a/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs
@@ -15,8 +15,7 @@ use crate::{
memory_region::{non_overlapping_regions_from, MemoryRegion, MemoryRegionType},
BootloaderAcpiArg, BootloaderFramebufferArg,
},
- config::PHYS_OFFSET,
- vm::paddr_to_vaddr,
+ vm::{paddr_to_vaddr, PHYS_MEM_BASE_VADDR},
};
static BOOT_PARAMS: Once<BootParams> = Once::new();
diff --git a/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs b/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs
--- a/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs
@@ -71,7 +70,7 @@ fn init_initramfs(initramfs: &'static Once<&'static [u8]>) {
let hdr = &BOOT_PARAMS.get().unwrap().hdr;
let ptr = hdr.ramdisk_image as usize;
// We must return a slice composed by VA since kernel should read everything in VA.
- let base_va = if ptr < PHYS_OFFSET {
+ let base_va = if ptr < PHYS_MEM_BASE_VADDR {
paddr_to_vaddr(ptr)
} else {
ptr
diff --git a/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs b/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs
--- a/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs
@@ -71,7 +70,7 @@ fn init_initramfs(initramfs: &'static Once<&'static [u8]>) {
let hdr = &BOOT_PARAMS.get().unwrap().hdr;
let ptr = hdr.ramdisk_image as usize;
// We must return a slice composed by VA since kernel should read everything in VA.
- let base_va = if ptr < PHYS_OFFSET {
+ let base_va = if ptr < PHYS_MEM_BASE_VADDR {
paddr_to_vaddr(ptr)
} else {
ptr
diff --git a/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs b/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs
--- a/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs
@@ -12,8 +12,7 @@ use crate::{
memory_region::{non_overlapping_regions_from, MemoryRegion, MemoryRegionType},
BootloaderAcpiArg, BootloaderFramebufferArg,
},
- config::PHYS_OFFSET,
- vm::paddr_to_vaddr,
+ vm::{paddr_to_vaddr, PHYS_MEM_BASE_VADDR},
};
global_asm!(include_str!("header.S"));
diff --git a/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs b/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs
--- a/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs
@@ -12,8 +12,7 @@ use crate::{
memory_region::{non_overlapping_regions_from, MemoryRegion, MemoryRegionType},
BootloaderAcpiArg, BootloaderFramebufferArg,
},
- config::PHYS_OFFSET,
- vm::paddr_to_vaddr,
+ vm::{paddr_to_vaddr, PHYS_MEM_BASE_VADDR},
};
global_asm!(include_str!("header.S"));
diff --git a/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs b/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs
--- a/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs
@@ -77,7 +76,7 @@ fn init_initramfs(initramfs: &'static Once<&'static [u8]>) {
)
};
// We must return a slice composed by VA since kernel should read every in VA.
- let base_va = if start < PHYS_OFFSET {
+ let base_va = if start < PHYS_MEM_BASE_VADDR {
paddr_to_vaddr(start)
} else {
start
diff --git a/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs b/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs
--- a/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs
@@ -77,7 +76,7 @@ fn init_initramfs(initramfs: &'static Once<&'static [u8]>) {
)
};
// We must return a slice composed by VA since kernel should read every in VA.
- let base_va = if start < PHYS_OFFSET {
+ let base_va = if start < PHYS_MEM_BASE_VADDR {
paddr_to_vaddr(start)
} else {
start
diff --git a/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs b/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs
--- a/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs
@@ -17,7 +17,7 @@ use crate::boot::{
global_asm!(include_str!("header.S"));
-use crate::{config::PHYS_OFFSET, vm::paddr_to_vaddr};
+use crate::vm::{paddr_to_vaddr, PHYS_MEM_BASE_VADDR};
pub(super) const MULTIBOOT2_ENTRY_MAGIC: u32 = 0x36d76289;
diff --git a/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs b/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs
--- a/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs
@@ -17,7 +17,7 @@ use crate::boot::{
global_asm!(include_str!("header.S"));
-use crate::{config::PHYS_OFFSET, vm::paddr_to_vaddr};
+use crate::vm::{paddr_to_vaddr, PHYS_MEM_BASE_VADDR};
pub(super) const MULTIBOOT2_ENTRY_MAGIC: u32 = 0x36d76289;
diff --git a/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs b/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs
--- a/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs
@@ -58,7 +58,7 @@ fn init_initramfs(initramfs: &'static Once<&'static [u8]>) {
.expect("No Multiboot2 modules found!");
let base_addr = mb2_module_tag.start_address() as usize;
// We must return a slice composed by VA since kernel should read every in VA.
- let base_va = if base_addr < PHYS_OFFSET {
+ let base_va = if base_addr < PHYS_MEM_BASE_VADDR {
paddr_to_vaddr(base_addr)
} else {
base_addr
diff --git a/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs b/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs
--- a/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs
@@ -58,7 +58,7 @@ fn init_initramfs(initramfs: &'static Once<&'static [u8]>) {
.expect("No Multiboot2 modules found!");
let base_addr = mb2_module_tag.start_address() as usize;
// We must return a slice composed by VA since kernel should read every in VA.
- let base_va = if base_addr < PHYS_OFFSET {
+ let base_va = if base_addr < PHYS_MEM_BASE_VADDR {
paddr_to_vaddr(base_addr)
} else {
base_addr
diff --git a/framework/aster-frame/src/arch/x86/iommu/second_stage.rs b/framework/aster-frame/src/arch/x86/iommu/second_stage.rs
--- a/framework/aster-frame/src/arch/x86/iommu/second_stage.rs
+++ b/framework/aster-frame/src/arch/x86/iommu/second_stage.rs
@@ -3,7 +3,7 @@
use pod::Pod;
use crate::{
- config::ENTRY_COUNT,
+ arch::x86::mm::NR_ENTRIES_PER_PAGE,
vm::page_table::{PageTableEntryTrait, PageTableFlagsTrait},
};
diff --git a/framework/aster-frame/src/arch/x86/iommu/second_stage.rs b/framework/aster-frame/src/arch/x86/iommu/second_stage.rs
--- a/framework/aster-frame/src/arch/x86/iommu/second_stage.rs
+++ b/framework/aster-frame/src/arch/x86/iommu/second_stage.rs
@@ -3,7 +3,7 @@
use pod::Pod;
use crate::{
- config::ENTRY_COUNT,
+ arch::x86::mm::NR_ENTRIES_PER_PAGE,
vm::page_table::{PageTableEntryTrait, PageTableFlagsTrait},
};
diff --git a/framework/aster-frame/src/arch/x86/iommu/second_stage.rs b/framework/aster-frame/src/arch/x86/iommu/second_stage.rs
--- a/framework/aster-frame/src/arch/x86/iommu/second_stage.rs
+++ b/framework/aster-frame/src/arch/x86/iommu/second_stage.rs
@@ -153,6 +153,6 @@ impl PageTableEntryTrait for PageTableEntry {
fn page_index(va: crate::vm::Vaddr, level: usize) -> usize {
debug_assert!((1..=5).contains(&level));
- va >> (12 + 9 * (level - 1)) & (ENTRY_COUNT - 1)
+ va >> (12 + 9 * (level - 1)) & (NR_ENTRIES_PER_PAGE - 1)
}
}
diff --git a/framework/aster-frame/src/arch/x86/iommu/second_stage.rs b/framework/aster-frame/src/arch/x86/iommu/second_stage.rs
--- a/framework/aster-frame/src/arch/x86/iommu/second_stage.rs
+++ b/framework/aster-frame/src/arch/x86/iommu/second_stage.rs
@@ -153,6 +153,6 @@ impl PageTableEntryTrait for PageTableEntry {
fn page_index(va: crate::vm::Vaddr, level: usize) -> usize {
debug_assert!((1..=5).contains(&level));
- va >> (12 + 9 * (level - 1)) & (ENTRY_COUNT - 1)
+ va >> (12 + 9 * (level - 1)) & (NR_ENTRIES_PER_PAGE - 1)
}
}
diff --git a/framework/aster-frame/src/arch/x86/mm/mod.rs b/framework/aster-frame/src/arch/x86/mm/mod.rs
--- a/framework/aster-frame/src/arch/x86/mm/mod.rs
+++ b/framework/aster-frame/src/arch/x86/mm/mod.rs
@@ -6,7 +6,6 @@ use pod::Pod;
use x86_64::{instructions::tlb, structures::paging::PhysFrame, VirtAddr};
use crate::{
- config::ENTRY_COUNT,
sync::Mutex,
vm::{
page_table::{table_of, PageTableEntryTrait, PageTableFlagsTrait},
diff --git a/framework/aster-frame/src/arch/x86/mm/mod.rs b/framework/aster-frame/src/arch/x86/mm/mod.rs
--- a/framework/aster-frame/src/arch/x86/mm/mod.rs
+++ b/framework/aster-frame/src/arch/x86/mm/mod.rs
@@ -6,7 +6,6 @@ use pod::Pod;
use x86_64::{instructions::tlb, structures::paging::PhysFrame, VirtAddr};
use crate::{
- config::ENTRY_COUNT,
sync::Mutex,
vm::{
page_table::{table_of, PageTableEntryTrait, PageTableFlagsTrait},
diff --git a/framework/aster-frame/src/arch/x86/mm/mod.rs b/framework/aster-frame/src/arch/x86/mm/mod.rs
--- a/framework/aster-frame/src/arch/x86/mm/mod.rs
+++ b/framework/aster-frame/src/arch/x86/mm/mod.rs
@@ -14,6 +13,8 @@ use crate::{
},
};
+pub(crate) const NR_ENTRIES_PER_PAGE: usize = 512;
+
bitflags::bitflags! {
#[derive(Pod)]
#[repr(C)]
diff --git a/framework/aster-frame/src/arch/x86/mm/mod.rs b/framework/aster-frame/src/arch/x86/mm/mod.rs
--- a/framework/aster-frame/src/arch/x86/mm/mod.rs
+++ b/framework/aster-frame/src/arch/x86/mm/mod.rs
@@ -14,6 +13,8 @@ use crate::{
},
};
+pub(crate) const NR_ENTRIES_PER_PAGE: usize = 512;
+
bitflags::bitflags! {
#[derive(Pod)]
#[repr(C)]
diff --git a/framework/aster-frame/src/arch/x86/mm/mod.rs b/framework/aster-frame/src/arch/x86/mm/mod.rs
--- a/framework/aster-frame/src/arch/x86/mm/mod.rs
+++ b/framework/aster-frame/src/arch/x86/mm/mod.rs
@@ -210,7 +211,7 @@ impl PageTableEntryTrait for PageTableEntry {
fn page_index(va: crate::vm::Vaddr, level: usize) -> usize {
debug_assert!((1..=5).contains(&level));
- va >> (12 + 9 * (level - 1)) & (ENTRY_COUNT - 1)
+ va >> (12 + 9 * (level - 1)) & (NR_ENTRIES_PER_PAGE - 1)
}
}
diff --git a/framework/aster-frame/src/arch/x86/mm/mod.rs b/framework/aster-frame/src/arch/x86/mm/mod.rs
--- a/framework/aster-frame/src/arch/x86/mm/mod.rs
+++ b/framework/aster-frame/src/arch/x86/mm/mod.rs
@@ -210,7 +211,7 @@ impl PageTableEntryTrait for PageTableEntry {
fn page_index(va: crate::vm::Vaddr, level: usize) -> usize {
debug_assert!((1..=5).contains(&level));
- va >> (12 + 9 * (level - 1)) & (ENTRY_COUNT - 1)
+ va >> (12 + 9 * (level - 1)) & (NR_ENTRIES_PER_PAGE - 1)
}
}
diff --git a/framework/aster-frame/src/arch/x86/tdx_guest.rs b/framework/aster-frame/src/arch/x86/tdx_guest.rs
--- a/framework/aster-frame/src/arch/x86/tdx_guest.rs
+++ b/framework/aster-frame/src/arch/x86/tdx_guest.rs
@@ -12,11 +12,11 @@ use tdx_guest::{
use crate::{
arch::mm::{is_kernel_vaddr, PageTableFlags},
- config::PAGE_SIZE,
vm::{
paddr_to_vaddr,
page_table::{PageTableError, KERNEL_PAGE_TABLE},
},
+ PAGE_SIZE,
};
const SHARED_BIT: u8 = 51;
diff --git a/framework/aster-frame/src/arch/x86/tdx_guest.rs b/framework/aster-frame/src/arch/x86/tdx_guest.rs
--- a/framework/aster-frame/src/arch/x86/tdx_guest.rs
+++ b/framework/aster-frame/src/arch/x86/tdx_guest.rs
@@ -12,11 +12,11 @@ use tdx_guest::{
use crate::{
arch::mm::{is_kernel_vaddr, PageTableFlags},
- config::PAGE_SIZE,
vm::{
paddr_to_vaddr,
page_table::{PageTableError, KERNEL_PAGE_TABLE},
},
+ PAGE_SIZE,
};
const SHARED_BIT: u8 = 51;
diff --git a/framework/aster-frame/src/config.rs /dev/null
--- a/framework/aster-frame/src/config.rs
+++ /dev/null
@@ -1,23 +0,0 @@
-// SPDX-License-Identifier: MPL-2.0
-
-#![allow(unused)]
-
-use log::Level;
-
-pub const USER_STACK_SIZE: usize = PAGE_SIZE * 4;
-pub const KERNEL_STACK_SIZE: usize = PAGE_SIZE * 64;
-pub const KERNEL_HEAP_SIZE: usize = PAGE_SIZE * 256;
-
-pub const KERNEL_OFFSET: usize = 0xffffffff80000000;
-
-pub const PHYS_OFFSET: usize = 0xFFFF800000000000;
-pub const ENTRY_COUNT: usize = 512;
-
-pub const PAGE_SIZE: usize = 0x1000;
-pub const PAGE_SIZE_BITS: usize = 0xc;
-
-pub const KVA_START: usize = (usize::MAX) << PAGE_SIZE_BITS;
-
-pub const DEFAULT_LOG_LEVEL: Level = Level::Error;
-
-pub const REAL_TIME_TASK_PRI: u16 = 100;
diff --git a/framework/aster-frame/src/config.rs /dev/null
--- a/framework/aster-frame/src/config.rs
+++ /dev/null
@@ -1,23 +0,0 @@
-// SPDX-License-Identifier: MPL-2.0
-
-#![allow(unused)]
-
-use log::Level;
-
-pub const USER_STACK_SIZE: usize = PAGE_SIZE * 4;
-pub const KERNEL_STACK_SIZE: usize = PAGE_SIZE * 64;
-pub const KERNEL_HEAP_SIZE: usize = PAGE_SIZE * 256;
-
-pub const KERNEL_OFFSET: usize = 0xffffffff80000000;
-
-pub const PHYS_OFFSET: usize = 0xFFFF800000000000;
-pub const ENTRY_COUNT: usize = 512;
-
-pub const PAGE_SIZE: usize = 0x1000;
-pub const PAGE_SIZE_BITS: usize = 0xc;
-
-pub const KVA_START: usize = (usize::MAX) << PAGE_SIZE_BITS;
-
-pub const DEFAULT_LOG_LEVEL: Level = Level::Error;
-
-pub const REAL_TIME_TASK_PRI: u16 = 100;
diff --git a/framework/aster-frame/src/lib.rs b/framework/aster-frame/src/lib.rs
--- a/framework/aster-frame/src/lib.rs
+++ b/framework/aster-frame/src/lib.rs
@@ -28,7 +28,6 @@ extern crate static_assertions;
pub mod arch;
pub mod boot;
pub mod bus;
-pub mod config;
pub mod console;
pub mod cpu;
mod error;
diff --git a/framework/aster-frame/src/lib.rs b/framework/aster-frame/src/lib.rs
--- a/framework/aster-frame/src/lib.rs
+++ b/framework/aster-frame/src/lib.rs
@@ -28,7 +28,6 @@ extern crate static_assertions;
pub mod arch;
pub mod boot;
pub mod bus;
-pub mod config;
pub mod console;
pub mod cpu;
mod error;
diff --git a/framework/aster-frame/src/logger.rs b/framework/aster-frame/src/logger.rs
--- a/framework/aster-frame/src/logger.rs
+++ b/framework/aster-frame/src/logger.rs
@@ -1,16 +1,20 @@
// SPDX-License-Identifier: MPL-2.0
-use log::{Metadata, Record};
+use log::{Level, Metadata, Record};
-use crate::{config::DEFAULT_LOG_LEVEL, early_println};
+use crate::early_println;
const LOGGER: Logger = Logger {};
+/// FIXME: The logs should be able to be read from files in the userspace,
+/// and the log level should be configurable.
+pub const INIT_LOG_LEVEL: Level = Level::Error;
+
struct Logger {}
impl log::Log for Logger {
fn enabled(&self, metadata: &Metadata) -> bool {
- metadata.level() <= DEFAULT_LOG_LEVEL
+ metadata.level() <= INIT_LOG_LEVEL
}
fn log(&self, record: &Record) {
diff --git a/framework/aster-frame/src/logger.rs b/framework/aster-frame/src/logger.rs
--- a/framework/aster-frame/src/logger.rs
+++ b/framework/aster-frame/src/logger.rs
@@ -1,16 +1,20 @@
// SPDX-License-Identifier: MPL-2.0
-use log::{Metadata, Record};
+use log::{Level, Metadata, Record};
-use crate::{config::DEFAULT_LOG_LEVEL, early_println};
+use crate::early_println;
const LOGGER: Logger = Logger {};
+/// FIXME: The logs should be able to be read from files in the userspace,
+/// and the log level should be configurable.
+pub const INIT_LOG_LEVEL: Level = Level::Error;
+
struct Logger {}
impl log::Log for Logger {
fn enabled(&self, metadata: &Metadata) -> bool {
- metadata.level() <= DEFAULT_LOG_LEVEL
+ metadata.level() <= INIT_LOG_LEVEL
}
fn log(&self, record: &Record) {
diff --git a/framework/aster-frame/src/logger.rs b/framework/aster-frame/src/logger.rs
--- a/framework/aster-frame/src/logger.rs
+++ b/framework/aster-frame/src/logger.rs
@@ -24,6 +28,6 @@ impl log::Log for Logger {
pub(crate) fn init() {
log::set_logger(&LOGGER)
- .map(|()| log::set_max_level(DEFAULT_LOG_LEVEL.to_level_filter()))
+ .map(|()| log::set_max_level(INIT_LOG_LEVEL.to_level_filter()))
.unwrap();
}
diff --git a/framework/aster-frame/src/logger.rs b/framework/aster-frame/src/logger.rs
--- a/framework/aster-frame/src/logger.rs
+++ b/framework/aster-frame/src/logger.rs
@@ -24,6 +28,6 @@ impl log::Log for Logger {
pub(crate) fn init() {
log::set_logger(&LOGGER)
- .map(|()| log::set_max_level(DEFAULT_LOG_LEVEL.to_level_filter()))
+ .map(|()| log::set_max_level(INIT_LOG_LEVEL.to_level_filter()))
.unwrap();
}
diff --git a/framework/aster-frame/src/task/priority.rs b/framework/aster-frame/src/task/priority.rs
--- a/framework/aster-frame/src/task/priority.rs
+++ b/framework/aster-frame/src/task/priority.rs
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: MPL-2.0
-use crate::config::REAL_TIME_TASK_PRI;
+pub const REAL_TIME_TASK_PRIORITY: u16 = 100;
/// The priority of a task.
/// Similar to Linux, a larger value represents a lower priority,
diff --git a/framework/aster-frame/src/task/priority.rs b/framework/aster-frame/src/task/priority.rs
--- a/framework/aster-frame/src/task/priority.rs
+++ b/framework/aster-frame/src/task/priority.rs
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: MPL-2.0
-use crate::config::REAL_TIME_TASK_PRI;
+pub const REAL_TIME_TASK_PRIORITY: u16 = 100;
/// The priority of a task.
/// Similar to Linux, a larger value represents a lower priority,
diff --git a/framework/aster-frame/src/task/priority.rs b/framework/aster-frame/src/task/priority.rs
--- a/framework/aster-frame/src/task/priority.rs
+++ b/framework/aster-frame/src/task/priority.rs
@@ -44,6 +44,6 @@ impl Priority {
}
pub const fn is_real_time(&self) -> bool {
- self.0 < REAL_TIME_TASK_PRI
+ self.0 < REAL_TIME_TASK_PRIORITY
}
}
diff --git a/framework/aster-frame/src/task/priority.rs b/framework/aster-frame/src/task/priority.rs
--- a/framework/aster-frame/src/task/priority.rs
+++ b/framework/aster-frame/src/task/priority.rs
@@ -44,6 +44,6 @@ impl Priority {
}
pub const fn is_real_time(&self) -> bool {
- self.0 < REAL_TIME_TASK_PRI
+ self.0 < REAL_TIME_TASK_PRIORITY
}
}
diff --git a/framework/aster-frame/src/task/task.rs b/framework/aster-frame/src/task/task.rs
--- a/framework/aster-frame/src/task/task.rs
+++ b/framework/aster-frame/src/task/task.rs
@@ -9,14 +9,15 @@ use super::{
};
use crate::{
arch::mm::PageTableFlags,
- config::{KERNEL_STACK_SIZE, PAGE_SIZE},
cpu::CpuSet,
prelude::*,
sync::{Mutex, MutexGuard},
user::UserSpace,
- vm::{page_table::KERNEL_PAGE_TABLE, VmAllocOptions, VmSegment},
+ vm::{page_table::KERNEL_PAGE_TABLE, VmAllocOptions, VmSegment, PAGE_SIZE},
};
+pub const KERNEL_STACK_SIZE: usize = PAGE_SIZE * 64;
+
core::arch::global_asm!(include_str!("switch.S"));
#[derive(Debug, Default, Clone, Copy)]
diff --git a/framework/aster-frame/src/task/task.rs b/framework/aster-frame/src/task/task.rs
--- a/framework/aster-frame/src/task/task.rs
+++ b/framework/aster-frame/src/task/task.rs
@@ -9,14 +9,15 @@ use super::{
};
use crate::{
arch::mm::PageTableFlags,
- config::{KERNEL_STACK_SIZE, PAGE_SIZE},
cpu::CpuSet,
prelude::*,
sync::{Mutex, MutexGuard},
user::UserSpace,
- vm::{page_table::KERNEL_PAGE_TABLE, VmAllocOptions, VmSegment},
+ vm::{page_table::KERNEL_PAGE_TABLE, VmAllocOptions, VmSegment, PAGE_SIZE},
};
+pub const KERNEL_STACK_SIZE: usize = PAGE_SIZE * 64;
+
core::arch::global_asm!(include_str!("switch.S"));
#[derive(Debug, Default, Clone, Copy)]
diff --git a/framework/aster-frame/src/vm/dma/mod.rs b/framework/aster-frame/src/vm/dma/mod.rs
--- a/framework/aster-frame/src/vm/dma/mod.rs
+++ b/framework/aster-frame/src/vm/dma/mod.rs
@@ -10,7 +10,7 @@ pub use dma_stream::{DmaDirection, DmaStream};
use spin::Once;
use super::Paddr;
-use crate::{arch::iommu::has_iommu, config::PAGE_SIZE, sync::SpinLock};
+use crate::{arch::iommu::has_iommu, sync::SpinLock, vm::PAGE_SIZE};
/// If a device performs DMA to read or write system
/// memory, the addresses used by the device are device addresses.
diff --git a/framework/aster-frame/src/vm/dma/mod.rs b/framework/aster-frame/src/vm/dma/mod.rs
--- a/framework/aster-frame/src/vm/dma/mod.rs
+++ b/framework/aster-frame/src/vm/dma/mod.rs
@@ -10,7 +10,7 @@ pub use dma_stream::{DmaDirection, DmaStream};
use spin::Once;
use super::Paddr;
-use crate::{arch::iommu::has_iommu, config::PAGE_SIZE, sync::SpinLock};
+use crate::{arch::iommu::has_iommu, sync::SpinLock, vm::PAGE_SIZE};
/// If a device performs DMA to read or write system
/// memory, the addresses used by the device are device addresses.
diff --git a/framework/aster-frame/src/vm/frame.rs b/framework/aster-frame/src/vm/frame.rs
--- a/framework/aster-frame/src/vm/frame.rs
+++ b/framework/aster-frame/src/vm/frame.rs
@@ -9,7 +9,7 @@ use core::{
use pod::Pod;
use super::{frame_allocator, HasPaddr, VmIo};
-use crate::{config::PAGE_SIZE, prelude::*, Error};
+use crate::{prelude::*, vm::PAGE_SIZE, Error};
/// A collection of page frames (physical memory pages).
///
diff --git a/framework/aster-frame/src/vm/frame.rs b/framework/aster-frame/src/vm/frame.rs
--- a/framework/aster-frame/src/vm/frame.rs
+++ b/framework/aster-frame/src/vm/frame.rs
@@ -9,7 +9,7 @@ use core::{
use pod::Pod;
use super::{frame_allocator, HasPaddr, VmIo};
-use crate::{config::PAGE_SIZE, prelude::*, Error};
+use crate::{prelude::*, vm::PAGE_SIZE, Error};
/// A collection of page frames (physical memory pages).
///
diff --git a/framework/aster-frame/src/vm/frame_allocator.rs b/framework/aster-frame/src/vm/frame_allocator.rs
--- a/framework/aster-frame/src/vm/frame_allocator.rs
+++ b/framework/aster-frame/src/vm/frame_allocator.rs
@@ -10,8 +10,8 @@ use spin::Once;
use super::{frame::VmFrameFlags, VmFrame, VmFrameVec, VmSegment};
use crate::{
boot::memory_region::{MemoryRegion, MemoryRegionType},
- config::PAGE_SIZE,
sync::SpinLock,
+ vm::PAGE_SIZE,
};
pub(super) static FRAME_ALLOCATOR: Once<SpinLock<FrameAllocator>> = Once::new();
diff --git a/framework/aster-frame/src/vm/frame_allocator.rs b/framework/aster-frame/src/vm/frame_allocator.rs
--- a/framework/aster-frame/src/vm/frame_allocator.rs
+++ b/framework/aster-frame/src/vm/frame_allocator.rs
@@ -10,8 +10,8 @@ use spin::Once;
use super::{frame::VmFrameFlags, VmFrame, VmFrameVec, VmSegment};
use crate::{
boot::memory_region::{MemoryRegion, MemoryRegionType},
- config::PAGE_SIZE,
sync::SpinLock,
+ vm::PAGE_SIZE,
};
pub(super) static FRAME_ALLOCATOR: Once<SpinLock<FrameAllocator>> = Once::new();
diff --git a/framework/aster-frame/src/vm/heap_allocator.rs b/framework/aster-frame/src/vm/heap_allocator.rs
--- a/framework/aster-frame/src/vm/heap_allocator.rs
+++ b/framework/aster-frame/src/vm/heap_allocator.rs
@@ -11,11 +11,10 @@ use log::debug;
use super::paddr_to_vaddr;
use crate::{
- config::{KERNEL_HEAP_SIZE, PAGE_SIZE},
prelude::*,
sync::SpinLock,
trap::disable_local,
- vm::frame_allocator::FRAME_ALLOCATOR,
+ vm::{frame_allocator::FRAME_ALLOCATOR, PAGE_SIZE},
Error,
};
diff --git a/framework/aster-frame/src/vm/heap_allocator.rs b/framework/aster-frame/src/vm/heap_allocator.rs
--- a/framework/aster-frame/src/vm/heap_allocator.rs
+++ b/framework/aster-frame/src/vm/heap_allocator.rs
@@ -11,11 +11,10 @@ use log::debug;
use super::paddr_to_vaddr;
use crate::{
- config::{KERNEL_HEAP_SIZE, PAGE_SIZE},
prelude::*,
sync::SpinLock,
trap::disable_local,
- vm::frame_allocator::FRAME_ALLOCATOR,
+ vm::{frame_allocator::FRAME_ALLOCATOR, PAGE_SIZE},
Error,
};
diff --git a/framework/aster-frame/src/vm/heap_allocator.rs b/framework/aster-frame/src/vm/heap_allocator.rs
--- a/framework/aster-frame/src/vm/heap_allocator.rs
+++ b/framework/aster-frame/src/vm/heap_allocator.rs
@@ -27,12 +26,14 @@ pub fn handle_alloc_error(layout: core::alloc::Layout) -> ! {
panic!("Heap allocation error, layout = {:?}", layout);
}
-static mut HEAP_SPACE: [u8; KERNEL_HEAP_SIZE] = [0; KERNEL_HEAP_SIZE];
+const INIT_KERNEL_HEAP_SIZE: usize = PAGE_SIZE * 256;
+
+static mut HEAP_SPACE: [u8; INIT_KERNEL_HEAP_SIZE] = [0; INIT_KERNEL_HEAP_SIZE];
pub fn init() {
// Safety: The HEAP_SPACE is a static memory range, so it's always valid.
unsafe {
- HEAP_ALLOCATOR.init(HEAP_SPACE.as_ptr(), KERNEL_HEAP_SIZE);
+ HEAP_ALLOCATOR.init(HEAP_SPACE.as_ptr(), INIT_KERNEL_HEAP_SIZE);
}
}
diff --git a/framework/aster-frame/src/vm/heap_allocator.rs b/framework/aster-frame/src/vm/heap_allocator.rs
--- a/framework/aster-frame/src/vm/heap_allocator.rs
+++ b/framework/aster-frame/src/vm/heap_allocator.rs
@@ -27,12 +26,14 @@ pub fn handle_alloc_error(layout: core::alloc::Layout) -> ! {
panic!("Heap allocation error, layout = {:?}", layout);
}
-static mut HEAP_SPACE: [u8; KERNEL_HEAP_SIZE] = [0; KERNEL_HEAP_SIZE];
+const INIT_KERNEL_HEAP_SIZE: usize = PAGE_SIZE * 256;
+
+static mut HEAP_SPACE: [u8; INIT_KERNEL_HEAP_SIZE] = [0; INIT_KERNEL_HEAP_SIZE];
pub fn init() {
// Safety: The HEAP_SPACE is a static memory range, so it's always valid.
unsafe {
- HEAP_ALLOCATOR.init(HEAP_SPACE.as_ptr(), KERNEL_HEAP_SIZE);
+ HEAP_ALLOCATOR.init(HEAP_SPACE.as_ptr(), INIT_KERNEL_HEAP_SIZE);
}
}
diff --git a/framework/aster-frame/src/vm/memory_set.rs b/framework/aster-frame/src/vm/memory_set.rs
--- a/framework/aster-frame/src/vm/memory_set.rs
+++ b/framework/aster-frame/src/vm/memory_set.rs
@@ -6,9 +6,11 @@ use core::fmt;
use super::page_table::{PageTable, PageTableConfig, UserMode};
use crate::{
arch::mm::{PageTableEntry, PageTableFlags},
- config::{PAGE_SIZE, PHYS_OFFSET},
prelude::*,
- vm::{is_page_aligned, VmAllocOptions, VmFrame, VmFrameVec, VmReader, VmWriter},
+ vm::{
+ is_page_aligned, VmAllocOptions, VmFrame, VmFrameVec, VmReader, VmWriter,
+ PHYS_MEM_BASE_VADDR, PAGE_SIZE,
+ },
Error,
};
diff --git a/framework/aster-frame/src/vm/memory_set.rs b/framework/aster-frame/src/vm/memory_set.rs
--- a/framework/aster-frame/src/vm/memory_set.rs
+++ b/framework/aster-frame/src/vm/memory_set.rs
@@ -6,9 +6,11 @@ use core::fmt;
use super::page_table::{PageTable, PageTableConfig, UserMode};
use crate::{
arch::mm::{PageTableEntry, PageTableFlags},
- config::{PAGE_SIZE, PHYS_OFFSET},
prelude::*,
- vm::{is_page_aligned, VmAllocOptions, VmFrame, VmFrameVec, VmReader, VmWriter},
+ vm::{
+ is_page_aligned, VmAllocOptions, VmFrame, VmFrameVec, VmReader, VmWriter,
+ PHYS_MEM_BASE_VADDR, PAGE_SIZE,
+ },
Error,
};
diff --git a/framework/aster-frame/src/vm/memory_set.rs b/framework/aster-frame/src/vm/memory_set.rs
--- a/framework/aster-frame/src/vm/memory_set.rs
+++ b/framework/aster-frame/src/vm/memory_set.rs
@@ -148,7 +150,7 @@ impl MemorySet {
if let Entry::Vacant(e) = self.areas.entry(area.start_va) {
let area = e.insert(area);
for (va, frame) in area.mapper.iter() {
- debug_assert!(frame.start_paddr() < PHYS_OFFSET);
+ debug_assert!(frame.start_paddr() < PHYS_MEM_BASE_VADDR);
self.pt.map(*va, frame, area.flags).unwrap();
}
} else {
diff --git a/framework/aster-frame/src/vm/memory_set.rs b/framework/aster-frame/src/vm/memory_set.rs
--- a/framework/aster-frame/src/vm/memory_set.rs
+++ b/framework/aster-frame/src/vm/memory_set.rs
@@ -148,7 +150,7 @@ impl MemorySet {
if let Entry::Vacant(e) = self.areas.entry(area.start_va) {
let area = e.insert(area);
for (va, frame) in area.mapper.iter() {
- debug_assert!(frame.start_paddr() < PHYS_OFFSET);
+ debug_assert!(frame.start_paddr() < PHYS_MEM_BASE_VADDR);
self.pt.map(*va, frame, area.flags).unwrap();
}
} else {
diff --git a/framework/aster-frame/src/vm/mod.rs b/framework/aster-frame/src/vm/mod.rs
--- a/framework/aster-frame/src/vm/mod.rs
+++ b/framework/aster-frame/src/vm/mod.rs
@@ -32,10 +32,38 @@ pub use self::{
page_table::PageTable,
space::{VmMapOptions, VmPerm, VmSpace},
};
-use crate::{
- boot::memory_region::{MemoryRegion, MemoryRegionType},
- config::{KERNEL_OFFSET, PAGE_SIZE, PHYS_OFFSET},
-};
+use crate::boot::memory_region::{MemoryRegion, MemoryRegionType};
+
+pub const PAGE_SIZE: usize = 0x1000;
+
+/// The maximum virtual address of user space (non inclusive).
+///
+/// Typicall 64-bit systems have at least 48-bit virtual address space.
+/// A typical way to reserve half of the address space for the kernel is
+/// to use the highest 48-bit virtual address space.
+///
+/// Also, the top page is not regarded as usable since it's a workaround
+/// for some x86_64 CPUs' bugs. See
+/// <https://github.com/torvalds/linux/blob/480e035fc4c714fb5536e64ab9db04fedc89e910/arch/x86/include/asm/page_64.h#L68-L78>
+/// for the rationale.
+pub const MAX_USERSPACE_VADDR: Vaddr = 0x0000_8000_0000_0000 - PAGE_SIZE;
+
+/// Start of the kernel address space.
+///
+/// This is the _lowest_ address of the x86-64's _high_ canonical addresses.
+///
+/// This is also the base address of the direct mapping of all physical
+/// memory in the kernel address space.
+pub(crate) const PHYS_MEM_BASE_VADDR: Vaddr = 0xffff_8000_0000_0000;
+
+/// The kernel code is linear mapped to this address.
+///
+/// FIXME: This offset should be randomly chosen by the loader or the
+/// boot compatibility layer. But we disabled it because the framework
+/// doesn't support relocatable kernel yet.
+pub fn kernel_loaded_offset() -> usize {
+ 0xffff_ffff_8000_0000
+}
/// Get physical address trait
pub trait HasPaddr {
diff --git a/framework/aster-frame/src/vm/mod.rs b/framework/aster-frame/src/vm/mod.rs
--- a/framework/aster-frame/src/vm/mod.rs
+++ b/framework/aster-frame/src/vm/mod.rs
@@ -32,10 +32,38 @@ pub use self::{
page_table::PageTable,
space::{VmMapOptions, VmPerm, VmSpace},
};
-use crate::{
- boot::memory_region::{MemoryRegion, MemoryRegionType},
- config::{KERNEL_OFFSET, PAGE_SIZE, PHYS_OFFSET},
-};
+use crate::boot::memory_region::{MemoryRegion, MemoryRegionType};
+
+pub const PAGE_SIZE: usize = 0x1000;
+
+/// The maximum virtual address of user space (non inclusive).
+///
+/// Typicall 64-bit systems have at least 48-bit virtual address space.
+/// A typical way to reserve half of the address space for the kernel is
+/// to use the highest 48-bit virtual address space.
+///
+/// Also, the top page is not regarded as usable since it's a workaround
+/// for some x86_64 CPUs' bugs. See
+/// <https://github.com/torvalds/linux/blob/480e035fc4c714fb5536e64ab9db04fedc89e910/arch/x86/include/asm/page_64.h#L68-L78>
+/// for the rationale.
+pub const MAX_USERSPACE_VADDR: Vaddr = 0x0000_8000_0000_0000 - PAGE_SIZE;
+
+/// Start of the kernel address space.
+///
+/// This is the _lowest_ address of the x86-64's _high_ canonical addresses.
+///
+/// This is also the base address of the direct mapping of all physical
+/// memory in the kernel address space.
+pub(crate) const PHYS_MEM_BASE_VADDR: Vaddr = 0xffff_8000_0000_0000;
+
+/// The kernel code is linear mapped to this address.
+///
+/// FIXME: This offset should be randomly chosen by the loader or the
+/// boot compatibility layer. But we disabled it because the framework
+/// doesn't support relocatable kernel yet.
+pub fn kernel_loaded_offset() -> usize {
+ 0xffff_ffff_8000_0000
+}
/// Get physical address trait
pub trait HasPaddr {
diff --git a/framework/aster-frame/src/vm/mod.rs b/framework/aster-frame/src/vm/mod.rs
--- a/framework/aster-frame/src/vm/mod.rs
+++ b/framework/aster-frame/src/vm/mod.rs
@@ -43,9 +71,9 @@ pub trait HasPaddr {
}
pub fn vaddr_to_paddr(va: Vaddr) -> Option<Paddr> {
- if (PHYS_OFFSET..=KERNEL_OFFSET).contains(&va) {
+ if (PHYS_MEM_BASE_VADDR..=kernel_loaded_offset()).contains(&va) {
// can use offset to get the physical address
- Some(va - PHYS_OFFSET)
+ Some(va - PHYS_MEM_BASE_VADDR)
} else {
page_table::vaddr_to_paddr(va)
}
diff --git a/framework/aster-frame/src/vm/mod.rs b/framework/aster-frame/src/vm/mod.rs
--- a/framework/aster-frame/src/vm/mod.rs
+++ b/framework/aster-frame/src/vm/mod.rs
@@ -43,9 +71,9 @@ pub trait HasPaddr {
}
pub fn vaddr_to_paddr(va: Vaddr) -> Option<Paddr> {
- if (PHYS_OFFSET..=KERNEL_OFFSET).contains(&va) {
+ if (PHYS_MEM_BASE_VADDR..=kernel_loaded_offset()).contains(&va) {
// can use offset to get the physical address
- Some(va - PHYS_OFFSET)
+ Some(va - PHYS_MEM_BASE_VADDR)
} else {
page_table::vaddr_to_paddr(va)
}
diff --git a/framework/aster-frame/src/vm/mod.rs b/framework/aster-frame/src/vm/mod.rs
--- a/framework/aster-frame/src/vm/mod.rs
+++ b/framework/aster-frame/src/vm/mod.rs
@@ -57,7 +85,7 @@ pub const fn is_page_aligned(p: usize) -> bool {
/// Convert physical address to virtual address using offset, only available inside aster-frame
pub(crate) fn paddr_to_vaddr(pa: usize) -> usize {
- pa + PHYS_OFFSET
+ pa + PHYS_MEM_BASE_VADDR
}
/// Only available inside aster-frame
diff --git a/framework/aster-frame/src/vm/mod.rs b/framework/aster-frame/src/vm/mod.rs
--- a/framework/aster-frame/src/vm/mod.rs
+++ b/framework/aster-frame/src/vm/mod.rs
@@ -57,7 +85,7 @@ pub const fn is_page_aligned(p: usize) -> bool {
/// Convert physical address to virtual address using offset, only available inside aster-frame
pub(crate) fn paddr_to_vaddr(pa: usize) -> usize {
- pa + PHYS_OFFSET
+ pa + PHYS_MEM_BASE_VADDR
}
/// Only available inside aster-frame
diff --git a/framework/aster-frame/src/vm/page_table.rs b/framework/aster-frame/src/vm/page_table.rs
--- a/framework/aster-frame/src/vm/page_table.rs
+++ b/framework/aster-frame/src/vm/page_table.rs
@@ -9,10 +9,9 @@ use spin::Once;
use super::{paddr_to_vaddr, Paddr, Vaddr, VmAllocOptions};
use crate::{
- arch::mm::{is_kernel_vaddr, is_user_vaddr, tlb_flush, PageTableEntry},
- config::{ENTRY_COUNT, PAGE_SIZE},
+ arch::mm::{is_kernel_vaddr, is_user_vaddr, tlb_flush, PageTableEntry, NR_ENTRIES_PER_PAGE},
sync::SpinLock,
- vm::VmFrame,
+ vm::{VmFrame, PAGE_SIZE},
};
pub trait PageTableFlagsTrait: Clone + Copy + Sized + Pod + Debug {
diff --git a/framework/aster-frame/src/vm/page_table.rs b/framework/aster-frame/src/vm/page_table.rs
--- a/framework/aster-frame/src/vm/page_table.rs
+++ b/framework/aster-frame/src/vm/page_table.rs
@@ -9,10 +9,9 @@ use spin::Once;
use super::{paddr_to_vaddr, Paddr, Vaddr, VmAllocOptions};
use crate::{
- arch::mm::{is_kernel_vaddr, is_user_vaddr, tlb_flush, PageTableEntry},
- config::{ENTRY_COUNT, PAGE_SIZE},
+ arch::mm::{is_kernel_vaddr, is_user_vaddr, tlb_flush, PageTableEntry, NR_ENTRIES_PER_PAGE},
sync::SpinLock,
- vm::VmFrame,
+ vm::{VmFrame, PAGE_SIZE},
};
pub trait PageTableFlagsTrait: Clone + Copy + Sized + Pod + Debug {
diff --git a/framework/aster-frame/src/vm/page_table.rs b/framework/aster-frame/src/vm/page_table.rs
--- a/framework/aster-frame/src/vm/page_table.rs
+++ b/framework/aster-frame/src/vm/page_table.rs
@@ -77,9 +76,9 @@ pub trait PageTableEntryTrait: Clone + Copy + Sized + Pod + Debug {
/// The index of the next PTE is determined based on the virtual address and the current level, and the level range is [1,5].
///
- /// For example, in x86 we use the following expression to get the index (ENTRY_COUNT is 512):
+ /// For example, in x86 we use the following expression to get the index (NR_ENTRIES_PER_PAGE is 512):
/// ```
- /// va >> (12 + 9 * (level - 1)) & (ENTRY_COUNT - 1)
+ /// va >> (12 + 9 * (level - 1)) & (NR_ENTRIES_PER_PAGE - 1)
/// ```
///
fn page_index(va: Vaddr, level: usize) -> usize;
diff --git a/framework/aster-frame/src/vm/page_table.rs b/framework/aster-frame/src/vm/page_table.rs
--- a/framework/aster-frame/src/vm/page_table.rs
+++ b/framework/aster-frame/src/vm/page_table.rs
@@ -77,9 +76,9 @@ pub trait PageTableEntryTrait: Clone + Copy + Sized + Pod + Debug {
/// The index of the next PTE is determined based on the virtual address and the current level, and the level range is [1,5].
///
- /// For example, in x86 we use the following expression to get the index (ENTRY_COUNT is 512):
+ /// For example, in x86 we use the following expression to get the index (NR_ENTRIES_PER_PAGE is 512):
/// ```
- /// va >> (12 + 9 * (level - 1)) & (ENTRY_COUNT - 1)
+ /// va >> (12 + 9 * (level - 1)) & (NR_ENTRIES_PER_PAGE - 1)
/// ```
///
fn page_index(va: Vaddr, level: usize) -> usize;
diff --git a/framework/aster-frame/src/vm/page_table.rs b/framework/aster-frame/src/vm/page_table.rs
--- a/framework/aster-frame/src/vm/page_table.rs
+++ b/framework/aster-frame/src/vm/page_table.rs
@@ -395,7 +394,7 @@ impl<T: PageTableEntryTrait, M> PageTable<T, M> {
}
}
-/// Read `ENTRY_COUNT` of PageTableEntry from an address
+/// Read `NR_ENTRIES_PER_PAGE` of PageTableEntry from an address
///
/// # Safety
///
diff --git a/framework/aster-frame/src/vm/page_table.rs b/framework/aster-frame/src/vm/page_table.rs
--- a/framework/aster-frame/src/vm/page_table.rs
+++ b/framework/aster-frame/src/vm/page_table.rs
@@ -395,7 +394,7 @@ impl<T: PageTableEntryTrait, M> PageTable<T, M> {
}
}
-/// Read `ENTRY_COUNT` of PageTableEntry from an address
+/// Read `NR_ENTRIES_PER_PAGE` of PageTableEntry from an address
///
/// # Safety
///
diff --git a/framework/aster-frame/src/vm/page_table.rs b/framework/aster-frame/src/vm/page_table.rs
--- a/framework/aster-frame/src/vm/page_table.rs
+++ b/framework/aster-frame/src/vm/page_table.rs
@@ -406,7 +405,7 @@ pub unsafe fn table_of<'a, T: PageTableEntryTrait>(pa: Paddr) -> Option<&'a mut
return None;
}
let ptr = super::paddr_to_vaddr(pa) as *mut _;
- Some(core::slice::from_raw_parts_mut(ptr, ENTRY_COUNT))
+ Some(core::slice::from_raw_parts_mut(ptr, NR_ENTRIES_PER_PAGE))
}
/// translate a virtual address to physical address which cannot use offset to get physical address
diff --git a/framework/aster-frame/src/vm/page_table.rs b/framework/aster-frame/src/vm/page_table.rs
--- a/framework/aster-frame/src/vm/page_table.rs
+++ b/framework/aster-frame/src/vm/page_table.rs
@@ -406,7 +405,7 @@ pub unsafe fn table_of<'a, T: PageTableEntryTrait>(pa: Paddr) -> Option<&'a mut
return None;
}
let ptr = super::paddr_to_vaddr(pa) as *mut _;
- Some(core::slice::from_raw_parts_mut(ptr, ENTRY_COUNT))
+ Some(core::slice::from_raw_parts_mut(ptr, NR_ENTRIES_PER_PAGE))
}
/// translate a virtual address to physical address which cannot use offset to get physical address
diff --git a/framework/aster-frame/src/vm/space.rs b/framework/aster-frame/src/vm/space.rs
--- a/framework/aster-frame/src/vm/space.rs
+++ b/framework/aster-frame/src/vm/space.rs
@@ -5,7 +5,7 @@ use core::ops::Range;
use bitflags::bitflags;
use super::{is_page_aligned, MapArea, MemorySet, VmFrameVec, VmIo};
-use crate::{arch::mm::PageTableFlags, config::PAGE_SIZE, prelude::*, sync::Mutex, Error};
+use crate::{arch::mm::PageTableFlags, prelude::*, sync::Mutex, vm::PAGE_SIZE, Error};
/// Virtual memory space.
///
diff --git a/framework/aster-frame/src/vm/space.rs b/framework/aster-frame/src/vm/space.rs
--- a/framework/aster-frame/src/vm/space.rs
+++ b/framework/aster-frame/src/vm/space.rs
@@ -5,7 +5,7 @@ use core::ops::Range;
use bitflags::bitflags;
use super::{is_page_aligned, MapArea, MemorySet, VmFrameVec, VmIo};
-use crate::{arch::mm::PageTableFlags, config::PAGE_SIZE, prelude::*, sync::Mutex, Error};
+use crate::{arch::mm::PageTableFlags, prelude::*, sync::Mutex, vm::PAGE_SIZE, Error};
/// Virtual memory space.
///
diff --git a/kernel/aster-nix/src/prelude.rs b/kernel/aster-nix/src/prelude.rs
--- a/kernel/aster-nix/src/prelude.rs
+++ b/kernel/aster-nix/src/prelude.rs
@@ -14,9 +14,8 @@ pub(crate) use alloc::{
pub(crate) use core::{any::Any, ffi::CStr, fmt::Debug};
pub(crate) use aster_frame::{
- config::PAGE_SIZE,
sync::{Mutex, MutexGuard, RwLock, RwMutex, SpinLock, SpinLockGuard},
- vm::Vaddr,
+ vm::{Vaddr, PAGE_SIZE},
};
pub(crate) use bitflags::bitflags;
pub(crate) use int_to_c_enum::TryFromInt;
diff --git a/kernel/aster-nix/src/prelude.rs b/kernel/aster-nix/src/prelude.rs
--- a/kernel/aster-nix/src/prelude.rs
+++ b/kernel/aster-nix/src/prelude.rs
@@ -14,9 +14,8 @@ pub(crate) use alloc::{
pub(crate) use core::{any::Any, ffi::CStr, fmt::Debug};
pub(crate) use aster_frame::{
- config::PAGE_SIZE,
sync::{Mutex, MutexGuard, RwLock, RwMutex, SpinLock, SpinLockGuard},
- vm::Vaddr,
+ vm::{Vaddr, PAGE_SIZE},
};
pub(crate) use bitflags::bitflags;
pub(crate) use int_to_c_enum::TryFromInt;
diff --git a/kernel/aster-nix/src/process/process_vm/mod.rs b/kernel/aster-nix/src/process/process_vm/mod.rs
--- a/kernel/aster-nix/src/process/process_vm/mod.rs
+++ b/kernel/aster-nix/src/process/process_vm/mod.rs
@@ -14,30 +14,40 @@ use user_heap::UserHeap;
use crate::vm::vmar::Vmar;
/*
-* The user vm space layout is look like below.
-* |-----------------------|-------The highest user vm address
-* | |
-* | Mmap Areas |
-* | |
-* | |
-* --------------------------------The init stack base
-* | |
-* | User Stack(Init Stack)|
-* | |
-* | || |
-* ----------||----------------------The user stack top, grows down
-* | \/ |
-* | |
-* | Unmapped Areas |
-* | |
-* | /\ |
-* ----------||---------------------The user heap top, grows up
-* | || |
-* | |
-* | User Heap |
-* | |
-* ----------------------------------The user heap base
-*/
+ * The user's virtual memory space layout looks like below.
+ * TODO: The layout of the userheap does not match the current implementation,
+ * And currently the initial program break is a fixed value.
+ *
+ * (high address)
+ * +---------------------+ <------+ The top of Vmar, which is the highest address usable
+ * | | Randomly padded pages
+ * +---------------------+ <------+ The base of the initial user stack
+ * | User stack |
+ * | |
+ * +---------||----------+ <------+ The user stack limit, can be extended lower
+ * | \/ |
+ * | ... |
+ * | |
+ * | MMAP Spaces |
+ * | |
+ * | ... |
+ * | /\ |
+ * +---------||----------+ <------+ The current program break
+ * | User heap |
+ * | |
+ * +---------------------+ <------+ The original program break
+ * | | Randomly padded pages
+ * +---------------------+ <------+ The end of the program's last segment
+ * | |
+ * | Loaded segments |
+ * | .text, .data, .bss |
+ * | , etc. |
+ * | |
+ * +---------------------+ <------+ The bottom of Vmar at 0x1_0000
+ * | | 64 KiB unusable space
+ * +---------------------+
+ * (low address)
+ */
/// The virtual space usage.
/// This struct is used to control brk and mmap now.
diff --git a/kernel/aster-nix/src/process/process_vm/mod.rs b/kernel/aster-nix/src/process/process_vm/mod.rs
--- a/kernel/aster-nix/src/process/process_vm/mod.rs
+++ b/kernel/aster-nix/src/process/process_vm/mod.rs
@@ -14,30 +14,40 @@ use user_heap::UserHeap;
use crate::vm::vmar::Vmar;
/*
-* The user vm space layout is look like below.
-* |-----------------------|-------The highest user vm address
-* | |
-* | Mmap Areas |
-* | |
-* | |
-* --------------------------------The init stack base
-* | |
-* | User Stack(Init Stack)|
-* | |
-* | || |
-* ----------||----------------------The user stack top, grows down
-* | \/ |
-* | |
-* | Unmapped Areas |
-* | |
-* | /\ |
-* ----------||---------------------The user heap top, grows up
-* | || |
-* | |
-* | User Heap |
-* | |
-* ----------------------------------The user heap base
-*/
+ * The user's virtual memory space layout looks like below.
+ * TODO: The layout of the userheap does not match the current implementation,
+ * And currently the initial program break is a fixed value.
+ *
+ * (high address)
+ * +---------------------+ <------+ The top of Vmar, which is the highest address usable
+ * | | Randomly padded pages
+ * +---------------------+ <------+ The base of the initial user stack
+ * | User stack |
+ * | |
+ * +---------||----------+ <------+ The user stack limit, can be extended lower
+ * | \/ |
+ * | ... |
+ * | |
+ * | MMAP Spaces |
+ * | |
+ * | ... |
+ * | /\ |
+ * +---------||----------+ <------+ The current program break
+ * | User heap |
+ * | |
+ * +---------------------+ <------+ The original program break
+ * | | Randomly padded pages
+ * +---------------------+ <------+ The end of the program's last segment
+ * | |
+ * | Loaded segments |
+ * | .text, .data, .bss |
+ * | , etc. |
+ * | |
+ * +---------------------+ <------+ The bottom of Vmar at 0x1_0000
+ * | | 64 KiB unusable space
+ * +---------------------+
+ * (low address)
+ */
/// The virtual space usage.
/// This struct is used to control brk and mmap now.
diff --git a/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs b/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
--- a/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
+++ b/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
@@ -7,7 +7,7 @@
use core::mem;
use align_ext::AlignExt;
-use aster_frame::vm::{VmIo, VmPerm};
+use aster_frame::vm::{VmIo, VmPerm, MAX_USERSPACE_VADDR};
use aster_rights::{Full, Rights};
use super::{
diff --git a/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs b/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
--- a/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
+++ b/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
@@ -7,7 +7,7 @@
use core::mem;
use align_ext::AlignExt;
-use aster_frame::vm::{VmIo, VmPerm};
+use aster_frame::vm::{VmIo, VmPerm, MAX_USERSPACE_VADDR};
use aster_rights::{Full, Rights};
use super::{
diff --git a/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs b/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
--- a/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
+++ b/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
@@ -20,15 +20,16 @@ use crate::{
vm::{perms::VmPerms, vmar::Vmar, vmo::VmoOptions},
};
-pub const INIT_STACK_BASE: Vaddr = 0x0000_0000_2000_0000;
-pub const INIT_STACK_SIZE: usize = 0x1000 * 16; // 64KB
+pub const INIT_STACK_SIZE: usize = 64 * 1024; // 64 KiB
/*
- * The initial stack of a process looks like below(This figure is from occlum):
+ * Illustration of the virtual memory space containing the processes' init stack:
*
- *
- * +---------------------+ <------+ Top of stack
- * | | (high address)
+ * (high address)
+ * +---------------------+ <------+ Highest address
+ * | | Random stack paddings
+ * +---------------------+ <------+ The base of stack (stack grows down)
+ * | |
* | Null-terminated |
* | strings referenced |
* | by variables below |
diff --git a/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs b/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
--- a/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
+++ b/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
@@ -20,15 +20,16 @@ use crate::{
vm::{perms::VmPerms, vmar::Vmar, vmo::VmoOptions},
};
-pub const INIT_STACK_BASE: Vaddr = 0x0000_0000_2000_0000;
-pub const INIT_STACK_SIZE: usize = 0x1000 * 16; // 64KB
+pub const INIT_STACK_SIZE: usize = 64 * 1024; // 64 KiB
/*
- * The initial stack of a process looks like below(This figure is from occlum):
+ * Illustration of the virtual memory space containing the processes' init stack:
*
- *
- * +---------------------+ <------+ Top of stack
- * | | (high address)
+ * (high address)
+ * +---------------------+ <------+ Highest address
+ * | | Random stack paddings
+ * +---------------------+ <------+ The base of stack (stack grows down)
+ * | |
* | Null-terminated |
* | strings referenced |
* | by variables below |
diff --git a/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs b/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
--- a/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
+++ b/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
@@ -62,8 +63,10 @@ pub const INIT_STACK_SIZE: usize = 0x1000 * 16; // 64KB
* +---------------------+
* | |
* | |
- * + +
- *
+ * +---------------------+
+ * | |
+ * +---------------------+ <------+ User stack default rlimit
+ * (low address)
*/
pub struct InitStack {
/// The high address of init stack
diff --git a/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs b/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
--- a/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
+++ b/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
@@ -62,8 +63,10 @@ pub const INIT_STACK_SIZE: usize = 0x1000 * 16; // 64KB
* +---------------------+
* | |
* | |
- * + +
- *
+ * +---------------------+
+ * | |
+ * +---------------------+ <------+ User stack default rlimit
+ * (low address)
*/
pub struct InitStack {
/// The high address of init stack
diff --git a/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs b/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
--- a/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
+++ b/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
@@ -93,9 +96,13 @@ impl InitStack {
}
}
- /// This function only work for first process
pub fn new_default_config(argv: Vec<CString>, envp: Vec<CString>) -> Self {
- let init_stack_top = INIT_STACK_BASE - PAGE_SIZE;
+ let nr_pages_padding = {
+ let mut random_nr_pages_padding: u8 = 0;
+ getrandom::getrandom(random_nr_pages_padding.as_bytes_mut()).unwrap();
+ random_nr_pages_padding as usize
+ };
+ let init_stack_top = MAX_USERSPACE_VADDR - PAGE_SIZE * nr_pages_padding;
let init_stack_size = INIT_STACK_SIZE;
InitStack::new(init_stack_top, init_stack_size, argv, envp)
}
diff --git a/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs b/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
--- a/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
+++ b/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
@@ -93,9 +96,13 @@ impl InitStack {
}
}
- /// This function only work for first process
pub fn new_default_config(argv: Vec<CString>, envp: Vec<CString>) -> Self {
- let init_stack_top = INIT_STACK_BASE - PAGE_SIZE;
+ let nr_pages_padding = {
+ let mut random_nr_pages_padding: u8 = 0;
+ getrandom::getrandom(random_nr_pages_padding.as_bytes_mut()).unwrap();
+ random_nr_pages_padding as usize
+ };
+ let init_stack_top = MAX_USERSPACE_VADDR - PAGE_SIZE * nr_pages_padding;
let init_stack_size = INIT_STACK_SIZE;
InitStack::new(init_stack_top, init_stack_size, argv, envp)
}
diff --git a/kernel/aster-nix/src/vdso.rs b/kernel/aster-nix/src/vdso.rs
--- a/kernel/aster-nix/src/vdso.rs
+++ b/kernel/aster-nix/src/vdso.rs
@@ -13,7 +13,10 @@
use alloc::{boxed::Box, sync::Arc};
-use aster_frame::{config::PAGE_SIZE, sync::Mutex, vm::VmIo};
+use aster_frame::{
+ sync::Mutex,
+ vm::{VmIo, PAGE_SIZE},
+};
use aster_rights::Rights;
use aster_time::Instant;
use aster_util::coeff::Coeff;
diff --git a/kernel/aster-nix/src/vdso.rs b/kernel/aster-nix/src/vdso.rs
--- a/kernel/aster-nix/src/vdso.rs
+++ b/kernel/aster-nix/src/vdso.rs
@@ -13,7 +13,10 @@
use alloc::{boxed::Box, sync::Arc};
-use aster_frame::{config::PAGE_SIZE, sync::Mutex, vm::VmIo};
+use aster_frame::{
+ sync::Mutex,
+ vm::{VmIo, PAGE_SIZE},
+};
use aster_rights::Rights;
use aster_time::Instant;
use aster_util::coeff::Coeff;
diff --git a/kernel/aster-nix/src/vm/vmar/mod.rs b/kernel/aster-nix/src/vm/vmar/mod.rs
--- a/kernel/aster-nix/src/vm/vmar/mod.rs
+++ b/kernel/aster-nix/src/vm/vmar/mod.rs
@@ -11,7 +11,7 @@ pub mod vm_mapping;
use core::ops::Range;
use align_ext::AlignExt;
-use aster_frame::vm::VmSpace;
+use aster_frame::vm::{VmSpace, MAX_USERSPACE_VADDR};
use aster_rights::Rights;
use self::{
diff --git a/kernel/aster-nix/src/vm/vmar/mod.rs b/kernel/aster-nix/src/vm/vmar/mod.rs
--- a/kernel/aster-nix/src/vm/vmar/mod.rs
+++ b/kernel/aster-nix/src/vm/vmar/mod.rs
@@ -11,7 +11,7 @@ pub mod vm_mapping;
use core::ops::Range;
use align_ext::AlignExt;
-use aster_frame::vm::VmSpace;
+use aster_frame::vm::{VmSpace, MAX_USERSPACE_VADDR};
use aster_rights::Rights;
use self::{
diff --git a/kernel/aster-nix/src/vm/vmar/mod.rs b/kernel/aster-nix/src/vm/vmar/mod.rs
--- a/kernel/aster-nix/src/vm/vmar/mod.rs
+++ b/kernel/aster-nix/src/vm/vmar/mod.rs
@@ -124,11 +124,8 @@ impl VmarInner {
}
}
-// FIXME: How to set the correct root vmar range?
-// We should not include addr 0 here(is this right?), since the 0 addr means the null pointer.
-// We should include addr 0x0040_0000, since non-pie executables typically are put on 0x0040_0000.
-const ROOT_VMAR_LOWEST_ADDR: Vaddr = 0x0010_0000;
-const ROOT_VMAR_HIGHEST_ADDR: Vaddr = 0x1000_0000_0000;
+const ROOT_VMAR_LOWEST_ADDR: Vaddr = 0x001_0000; // 64 KiB is the Linux configurable default
+const ROOT_VMAR_CAP_ADDR: Vaddr = MAX_USERSPACE_VADDR;
impl Interval<usize> for Arc<Vmar_> {
fn range(&self) -> Range<usize> {
diff --git a/kernel/aster-nix/src/vm/vmar/mod.rs b/kernel/aster-nix/src/vm/vmar/mod.rs
--- a/kernel/aster-nix/src/vm/vmar/mod.rs
+++ b/kernel/aster-nix/src/vm/vmar/mod.rs
@@ -124,11 +124,8 @@ impl VmarInner {
}
}
-// FIXME: How to set the correct root vmar range?
-// We should not include addr 0 here(is this right?), since the 0 addr means the null pointer.
-// We should include addr 0x0040_0000, since non-pie executables typically are put on 0x0040_0000.
-const ROOT_VMAR_LOWEST_ADDR: Vaddr = 0x0010_0000;
-const ROOT_VMAR_HIGHEST_ADDR: Vaddr = 0x1000_0000_0000;
+const ROOT_VMAR_LOWEST_ADDR: Vaddr = 0x001_0000; // 64 KiB is the Linux configurable default
+const ROOT_VMAR_CAP_ADDR: Vaddr = MAX_USERSPACE_VADDR;
impl Interval<usize> for Arc<Vmar_> {
fn range(&self) -> Range<usize> {
diff --git a/kernel/aster-nix/src/vm/vmar/mod.rs b/kernel/aster-nix/src/vm/vmar/mod.rs
--- a/kernel/aster-nix/src/vm/vmar/mod.rs
+++ b/kernel/aster-nix/src/vm/vmar/mod.rs
@@ -161,7 +158,7 @@ impl Vmar_ {
pub fn new_root() -> Arc<Self> {
let mut free_regions = BTreeMap::new();
- let root_region = FreeRegion::new(ROOT_VMAR_LOWEST_ADDR..ROOT_VMAR_HIGHEST_ADDR);
+ let root_region = FreeRegion::new(ROOT_VMAR_LOWEST_ADDR..ROOT_VMAR_CAP_ADDR);
free_regions.insert(root_region.start(), root_region);
let vmar_inner = VmarInner {
is_destroyed: false,
diff --git a/kernel/aster-nix/src/vm/vmar/mod.rs b/kernel/aster-nix/src/vm/vmar/mod.rs
--- a/kernel/aster-nix/src/vm/vmar/mod.rs
+++ b/kernel/aster-nix/src/vm/vmar/mod.rs
@@ -161,7 +158,7 @@ impl Vmar_ {
pub fn new_root() -> Arc<Self> {
let mut free_regions = BTreeMap::new();
- let root_region = FreeRegion::new(ROOT_VMAR_LOWEST_ADDR..ROOT_VMAR_HIGHEST_ADDR);
+ let root_region = FreeRegion::new(ROOT_VMAR_LOWEST_ADDR..ROOT_VMAR_CAP_ADDR);
free_regions.insert(root_region.start(), root_region);
let vmar_inner = VmarInner {
is_destroyed: false,
diff --git a/kernel/aster-nix/src/vm/vmar/mod.rs b/kernel/aster-nix/src/vm/vmar/mod.rs
--- a/kernel/aster-nix/src/vm/vmar/mod.rs
+++ b/kernel/aster-nix/src/vm/vmar/mod.rs
@@ -169,7 +166,7 @@ impl Vmar_ {
vm_mappings: BTreeMap::new(),
free_regions,
};
- Vmar_::new(vmar_inner, VmSpace::new(), 0, ROOT_VMAR_HIGHEST_ADDR, None)
+ Vmar_::new(vmar_inner, VmSpace::new(), 0, ROOT_VMAR_CAP_ADDR, None)
}
fn is_root_vmar(&self) -> bool {
diff --git a/kernel/aster-nix/src/vm/vmar/mod.rs b/kernel/aster-nix/src/vm/vmar/mod.rs
--- a/kernel/aster-nix/src/vm/vmar/mod.rs
+++ b/kernel/aster-nix/src/vm/vmar/mod.rs
@@ -169,7 +166,7 @@ impl Vmar_ {
vm_mappings: BTreeMap::new(),
free_regions,
};
- Vmar_::new(vmar_inner, VmSpace::new(), 0, ROOT_VMAR_HIGHEST_ADDR, None)
+ Vmar_::new(vmar_inner, VmSpace::new(), 0, ROOT_VMAR_CAP_ADDR, None)
}
fn is_root_vmar(&self) -> bool {
diff --git a/kernel/aster-nix/src/vm/vmar/mod.rs b/kernel/aster-nix/src/vm/vmar/mod.rs
--- a/kernel/aster-nix/src/vm/vmar/mod.rs
+++ b/kernel/aster-nix/src/vm/vmar/mod.rs
@@ -279,7 +276,7 @@ impl Vmar_ {
inner.child_vmar_s.clear();
inner.vm_mappings.clear();
inner.free_regions.clear();
- let root_region = FreeRegion::new(ROOT_VMAR_LOWEST_ADDR..ROOT_VMAR_HIGHEST_ADDR);
+ let root_region = FreeRegion::new(ROOT_VMAR_LOWEST_ADDR..ROOT_VMAR_CAP_ADDR);
inner.free_regions.insert(root_region.start(), root_region);
Ok(())
}
diff --git a/kernel/aster-nix/src/vm/vmar/mod.rs b/kernel/aster-nix/src/vm/vmar/mod.rs
--- a/kernel/aster-nix/src/vm/vmar/mod.rs
+++ b/kernel/aster-nix/src/vm/vmar/mod.rs
@@ -279,7 +276,7 @@ impl Vmar_ {
inner.child_vmar_s.clear();
inner.vm_mappings.clear();
inner.free_regions.clear();
- let root_region = FreeRegion::new(ROOT_VMAR_LOWEST_ADDR..ROOT_VMAR_HIGHEST_ADDR);
+ let root_region = FreeRegion::new(ROOT_VMAR_LOWEST_ADDR..ROOT_VMAR_CAP_ADDR);
inner.free_regions.insert(root_region.start(), root_region);
Ok(())
}
diff --git a/kernel/aster-nix/src/vm/vmar/options.rs b/kernel/aster-nix/src/vm/vmar/options.rs
--- a/kernel/aster-nix/src/vm/vmar/options.rs
+++ b/kernel/aster-nix/src/vm/vmar/options.rs
@@ -2,7 +2,7 @@
//! Options for allocating child VMARs.
-use aster_frame::{config::PAGE_SIZE, Error, Result};
+use aster_frame::{vm::PAGE_SIZE, Error, Result};
use super::Vmar;
diff --git a/kernel/aster-nix/src/vm/vmar/options.rs b/kernel/aster-nix/src/vm/vmar/options.rs
--- a/kernel/aster-nix/src/vm/vmar/options.rs
+++ b/kernel/aster-nix/src/vm/vmar/options.rs
@@ -2,7 +2,7 @@
//! Options for allocating child VMARs.
-use aster_frame::{config::PAGE_SIZE, Error, Result};
+use aster_frame::{vm::PAGE_SIZE, Error, Result};
use super::Vmar;
diff --git a/kernel/aster-nix/src/vm/vmar/options.rs b/kernel/aster-nix/src/vm/vmar/options.rs
--- a/kernel/aster-nix/src/vm/vmar/options.rs
+++ b/kernel/aster-nix/src/vm/vmar/options.rs
@@ -142,14 +142,14 @@ mod test {
use crate::vm::{
page_fault_handler::PageFaultHandler,
perms::VmPerms,
- vmar::ROOT_VMAR_HIGHEST_ADDR,
+ vmar::ROOT_VMAR_CAP_ADDR,
vmo::{VmoOptions, VmoRightsOp},
};
#[ktest]
fn root_vmar() {
let vmar = Vmar::<Full>::new_root();
- assert!(vmar.size() == ROOT_VMAR_HIGHEST_ADDR);
+ assert!(vmar.size() == ROOT_VMAR_CAP_ADDR);
}
#[ktest]
diff --git a/kernel/comps/block/src/lib.rs b/kernel/comps/block/src/lib.rs
--- a/kernel/comps/block/src/lib.rs
+++ b/kernel/comps/block/src/lib.rs
@@ -49,7 +49,7 @@ use self::{
prelude::*,
};
-pub const BLOCK_SIZE: usize = aster_frame::config::PAGE_SIZE;
+pub const BLOCK_SIZE: usize = aster_frame::vm::PAGE_SIZE;
pub const SECTOR_SIZE: usize = 512;
pub trait BlockDevice: Send + Sync + Any + Debug {
diff --git a/kernel/comps/block/src/lib.rs b/kernel/comps/block/src/lib.rs
--- a/kernel/comps/block/src/lib.rs
+++ b/kernel/comps/block/src/lib.rs
@@ -49,7 +49,7 @@ use self::{
prelude::*,
};
-pub const BLOCK_SIZE: usize = aster_frame::config::PAGE_SIZE;
+pub const BLOCK_SIZE: usize = aster_frame::vm::PAGE_SIZE;
pub const SECTOR_SIZE: usize = 512;
pub trait BlockDevice: Send + Sync + Any + Debug {
diff --git a/kernel/comps/framebuffer/src/lib.rs b/kernel/comps/framebuffer/src/lib.rs
--- a/kernel/comps/framebuffer/src/lib.rs
+++ b/kernel/comps/framebuffer/src/lib.rs
@@ -13,7 +13,12 @@ use core::{
ops::{Index, IndexMut},
};
-use aster_frame::{boot, config::PAGE_SIZE, io_mem::IoMem, sync::SpinLock, vm::VmIo};
+use aster_frame::{
+ boot,
+ io_mem::IoMem,
+ sync::SpinLock,
+ vm::{VmIo, PAGE_SIZE},
+};
use component::{init_component, ComponentInitError};
use font8x8::UnicodeFonts;
use spin::Once;
diff --git a/kernel/comps/framebuffer/src/lib.rs b/kernel/comps/framebuffer/src/lib.rs
--- a/kernel/comps/framebuffer/src/lib.rs
+++ b/kernel/comps/framebuffer/src/lib.rs
@@ -13,7 +13,12 @@ use core::{
ops::{Index, IndexMut},
};
-use aster_frame::{boot, config::PAGE_SIZE, io_mem::IoMem, sync::SpinLock, vm::VmIo};
+use aster_frame::{
+ boot,
+ io_mem::IoMem,
+ sync::SpinLock,
+ vm::{VmIo, PAGE_SIZE},
+};
use component::{init_component, ComponentInitError};
use font8x8::UnicodeFonts;
use spin::Once;
diff --git a/kernel/comps/virtio/src/device/console/device.rs b/kernel/comps/virtio/src/device/console/device.rs
--- a/kernel/comps/virtio/src/device/console/device.rs
+++ b/kernel/comps/virtio/src/device/console/device.rs
@@ -4,7 +4,7 @@ use alloc::{boxed::Box, fmt::Debug, string::ToString, sync::Arc, vec::Vec};
use core::hint::spin_loop;
use aster_console::{AnyConsoleDevice, ConsoleCallback};
-use aster_frame::{config::PAGE_SIZE, io_mem::IoMem, sync::SpinLock, trap::TrapFrame};
+use aster_frame::{io_mem::IoMem, sync::SpinLock, trap::TrapFrame, vm::PAGE_SIZE};
use aster_util::safe_ptr::SafePtr;
use log::debug;
diff --git a/kernel/comps/virtio/src/device/console/device.rs b/kernel/comps/virtio/src/device/console/device.rs
--- a/kernel/comps/virtio/src/device/console/device.rs
+++ b/kernel/comps/virtio/src/device/console/device.rs
@@ -4,7 +4,7 @@ use alloc::{boxed::Box, fmt::Debug, string::ToString, sync::Arc, vec::Vec};
use core::hint::spin_loop;
use aster_console::{AnyConsoleDevice, ConsoleCallback};
-use aster_frame::{config::PAGE_SIZE, io_mem::IoMem, sync::SpinLock, trap::TrapFrame};
+use aster_frame::{io_mem::IoMem, sync::SpinLock, trap::TrapFrame, vm::PAGE_SIZE};
use aster_util::safe_ptr::SafePtr;
use log::debug;
diff --git a/kernel/comps/virtio/src/transport/mmio/device.rs b/kernel/comps/virtio/src/transport/mmio/device.rs
--- a/kernel/comps/virtio/src/transport/mmio/device.rs
+++ b/kernel/comps/virtio/src/transport/mmio/device.rs
@@ -8,12 +8,11 @@ use aster_frame::{
bus::MmioDevice,
device::{MmioCommonDevice, VirtioMmioVersion},
},
- config::PAGE_SIZE,
io_mem::IoMem,
offset_of,
sync::RwLock,
trap::IrqCallbackFunction,
- vm::DmaCoherent,
+ vm::{DmaCoherent, PAGE_SIZE},
};
use aster_rights::{ReadOp, WriteOp};
use aster_util::{field_ptr, safe_ptr::SafePtr};
diff --git a/kernel/comps/virtio/src/transport/mmio/device.rs b/kernel/comps/virtio/src/transport/mmio/device.rs
--- a/kernel/comps/virtio/src/transport/mmio/device.rs
+++ b/kernel/comps/virtio/src/transport/mmio/device.rs
@@ -8,12 +8,11 @@ use aster_frame::{
bus::MmioDevice,
device::{MmioCommonDevice, VirtioMmioVersion},
},
- config::PAGE_SIZE,
io_mem::IoMem,
offset_of,
sync::RwLock,
trap::IrqCallbackFunction,
- vm::DmaCoherent,
+ vm::{DmaCoherent, PAGE_SIZE},
};
use aster_rights::{ReadOp, WriteOp};
use aster_util::{field_ptr, safe_ptr::SafePtr};
|
We currently have only the ability to manage <4G of memory. And the default QEMU boot option gives a 2G memory. Maybe an allocation of 629MiB caused an OOM.
Related to #318
```rust
if segment_vmo_size > tail_padding_offset {
let buffer = vec![0u8; segment_vmo_size - tail_padding_offset];
segment_vmo.write_bytes(tail_padding_offset, &buffer)?;
}
```
The troublemaker is found: the memsize of that segment is 629MiB. And we should do lazy zero out init rather than doing such a scary memset operation of vmo.
```
(gdb) bt
#0 alloc::alloc::handle_alloc_error (layout=...) at src/alloc.rs:389
#1 0xffffffff8904ba9e in alloc::raw_vec::RawVec<u8, alloc::alloc::Global>::allocate_in<u8, alloc::alloc::Global> (
capacity=659468632, init=alloc::raw_vec::AllocInit::Zeroed, alloc=...) at src/raw_vec.rs:204
#2 0xffffffff88ed31e8 in alloc::raw_vec::RawVec<u8, alloc::alloc::Global>::with_capacity_zeroed_in<u8, alloc::alloc::Global> (capacity=659468632, alloc=...)
at /root/.rustup/toolchains/nightly-2024-01-01-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/raw_vec.rs:153
#3 0xffffffff88ece3f4 in alloc::vec::spec_from_elem::{impl#3}::from_elem<alloc::alloc::Global> (elem=0, n=659468632,
alloc=...)
at /root/.rustup/toolchains/nightly-2024-01-01-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/vec/spec_from_elem.rs:52
#4 0xffffffff88ed190f in alloc::vec::from_elem<u8> (elem=0, n=659468632)
at /root/.rustup/toolchains/nightly-2024-01-01-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/vec/mod.rs:2627
#5 0xffffffff88b11985 in aster_nix::process::program_loader::elf::load_elf::init_segment_vmo (
program_header=0xffff80000c8d2d18, elf_file=0xffff80000c184810) at src/process/program_loader/elf/load_elf.rs:309
#6 0xffffffff88b103cd in aster_nix::process::program_loader::elf::load_elf::map_segment_vmos (elf=0xffff800003dbd6d8,
root_vmar=0xffff80000c8df010, elf_file=0xffff80000c184810) at src/process/program_loader/elf/load_elf.rs:201
#7 0xffffffff88b0faa0 in aster_nix::process::program_loader::elf::load_elf::init_and_map_vmos (
process_vm=0xffff80000c8df010, ldso=..., elf=0xffff800003dbd6d8, elf_file=0xffff80000c184810, argv=..., envp=...,
vdso_text_base=1064960) at src/process/program_loader/elf/load_elf.rs:123
#8 0xffffffff88b0eece in aster_nix::process::program_loader::elf::load_elf::load_elf_to_vm (
process_vm=0xffff80000c8df010, file_header=..., elf_file=..., fs_resolver=0xffff80000c8cf910, argv=..., envp=...,
vdso_text_base=1064960) at src/process/program_loader/elf/load_elf.rs:55
#9 0xffffffff88b0e212 in aster_nix::process::program_loader::load_program_to_vm (process_vm=0xffff80000c8df010,
elf_file=..., argv=..., envp=..., fs_resolver=0xffff80000c8cf910, recursion_limit=1)
at src/process/program_loader/mod.rs:89
#10 0xffffffff88d11dc3 in aster_nix::syscall::execve::do_execve (elf_file=..., argv_ptr_ptr=268442568,
envp_ptr_ptr=268442632, context=0xffff800003dc09c0) at src/syscall/execve.rs:119
#11 0xffffffff88d107b7 in aster_nix::syscall::execve::sys_execve (filename_ptr=268442504, argv_ptr_ptr=268442568,
envp_ptr_ptr=268442632, context=0xffff800003dc09c0) at src/syscall/execve.rs:36
#12 0xffffffff88d0cd6e in aster_nix::syscall::syscall_dispatch (syscall_number=59, args=..., context=0xffff800003dc09c0)
at src/syscall/mod.rs:462
#13 0xffffffff88d0c4dc in aster_nix::syscall::handle_syscall (context=0xffff800003dc09c0) at src/syscall/mod.rs:397
#14 0xffffffff88d09fee in aster_nix::thread::task::handle_user_event (user_event=aster_frame::user::UserEvent::Syscall,
context=0xffff800003dc09c0) at src/thread/task.rs:71
#15 0xffffffff88d09a6d in aster_nix::thread::task::create_new_user_task::user_task_entry () at src/thread/task.rs:37
#16 0xffffffff88d3f8ce in core::ops::function::Fn::call<fn(), ()> ()
at /root/.rustup/toolchains/nightly-2024-01-01-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:79
#17 0xffffffff88fc6ad6 in alloc::boxed::{impl#49}::call<(), (dyn core::ops::function::Fn<(), Output=()> + core::marker::Send + core::marker::Sync), alloc::alloc::Global> (self=0xffff80000c8cfe40, args=()) at /root/.rustup/toolchains/nightly-2024-01-01-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2029
#18 0xffffffff88fac554 in aster_frame::task::task::{impl#3}::build::kernel_task_entry () at src/task/task.rs:259
(gdb) f 6
#6 0xffffffff88b103cd in aster_nix::process::program_loader::elf::load_elf::map_segment_vmos (elf=0xffff800003dbd6d8,
root_vmar=0xffff80000c8df010, elf_file=0xffff80000c184810) at src/process/program_loader/elf/load_elf.rs:201
201 let vmo = init_segment_vmo(program_header, elf_file)?;
(gdb) p *program_header
$3 = xmas_elf::program::ProgramHeader64 {type_: xmas_elf::program::Type_ (1), flags: xmas_elf::program::Flags (6), offset: 8596504, virtual_addr: 8600600, physical_addr: 8600600, file_size: 66192, mem_size: 659531104, align: 4096}
```
|
2024-03-13T06:03:51Z
|
e210e68920481c911f62f03ade0a780f96e48e24
|
asterinas/asterinas
|
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -144,10 +144,14 @@ ktest: initramfs $(CARGO_OSDK)
(cd $$dir && cargo osdk test) || exit 1; \
done
-.PHONY: docs
-docs:
- @cargo doc # Build Rust docs
- @echo "" # Add a blank line
+docs: $(CARGO_OSDK)
+ @for dir in $(NON_OSDK_CRATES); do \
+ (cd $$dir && cargo doc --no-deps) || exit 1; \
+ done
+ @for dir in $(OSDK_CRATES); do \
+ (cd $$dir && cargo osdk doc --no-deps) || exit 1; \
+ done
+ @echo "" # Add a blank line
@cd docs && mdbook build # Build mdBook
.PHONY: format
diff --git a/osdk/src/cli.rs b/osdk/src/cli.rs
--- a/osdk/src/cli.rs
+++ b/osdk/src/cli.rs
@@ -6,8 +6,8 @@ use clap::{crate_version, Args, Parser};
use crate::{
commands::{
- execute_build_command, execute_check_command, execute_clippy_command, execute_new_command,
- execute_run_command, execute_test_command,
+ execute_build_command, execute_forwarded_command, execute_new_command, execute_run_command,
+ execute_test_command,
},
config_manager::{
boot::{BootLoader, BootProtocol},
diff --git a/osdk/src/cli.rs b/osdk/src/cli.rs
--- a/osdk/src/cli.rs
+++ b/osdk/src/cli.rs
@@ -37,8 +37,9 @@ pub fn main() {
let test_config = TestConfig::parse(test_args);
execute_test_command(&test_config);
}
- OsdkSubcommand::Check => execute_check_command(),
- OsdkSubcommand::Clippy => execute_clippy_command(),
+ OsdkSubcommand::Check(args) => execute_forwarded_command("check", &args.args),
+ OsdkSubcommand::Clippy(args) => execute_forwarded_command("clippy", &args.args),
+ OsdkSubcommand::Doc(args) => execute_forwarded_command("doc", &args.args),
}
}
diff --git a/osdk/src/cli.rs b/osdk/src/cli.rs
--- a/osdk/src/cli.rs
+++ b/osdk/src/cli.rs
@@ -68,10 +69,22 @@ pub enum OsdkSubcommand {
Run(RunArgs),
#[command(about = "Execute kernel mode unit test by starting a VMM")]
Test(TestArgs),
- #[command(about = "Analyze the current package and report errors")]
- Check,
- #[command(about = "Check the current package and catch common mistakes")]
- Clippy,
+ #[command(about = "Check a local package and all of its dependencies for errors")]
+ Check(ForwardedArguments),
+ #[command(about = "Checks a package to catch common mistakes and improve your Rust code")]
+ Clippy(ForwardedArguments),
+ #[command(about = "Build a package's documentation")]
+ Doc(ForwardedArguments),
+}
+
+#[derive(Debug, Parser)]
+pub struct ForwardedArguments {
+ #[arg(
+ help = "The full set of Cargo arguments",
+ trailing_var_arg = true,
+ allow_hyphen_values = true
+ )]
+ pub args: Vec<String>,
}
#[derive(Debug, Parser)]
diff --git a/osdk/src/commands/mod.rs b/osdk/src/commands/mod.rs
--- a/osdk/src/commands/mod.rs
+++ b/osdk/src/commands/mod.rs
@@ -3,14 +3,25 @@
//! This module contains subcommands of cargo-osdk.
mod build;
-mod check;
-mod clippy;
mod new;
mod run;
mod test;
mod util;
pub use self::{
- build::execute_build_command, check::execute_check_command, clippy::execute_clippy_command,
- new::execute_new_command, run::execute_run_command, test::execute_test_command,
+ build::execute_build_command, new::execute_new_command, run::execute_run_command,
+ test::execute_test_command,
};
+
+/// Execute the forwarded cargo command with args containing the subcommand and its arguments.
+pub fn execute_forwarded_command(subcommand: &str, args: &Vec<String>) -> ! {
+ let mut cargo = util::cargo();
+ cargo
+ .arg(subcommand)
+ .args(util::COMMON_CARGO_ARGS)
+ .arg("--target")
+ .arg("x86_64-unknown-none")
+ .args(args);
+ let status = cargo.status().expect("Failed to execute cargo");
+ std::process::exit(status.code().unwrap_or(1));
+}
|
[
"657"
] |
0.4
|
132d36bf2082acafa14edf665e98463f681d6363
|
[BUG] `cargo doc` reports error and fails
# Problem
`cargo doc` is used in `make docs` to generate API documentations. However, the command will fail currently. The problem seems to exist for a long time.
Before introducing OSDK, the `inventory` crate will report error. Since this crate is forked under Asterinas, we shoube be able to fix the error.

After indroducing OSDK, new problem occurs. The `linux-bzimage-setup` panics when running `cargo doc`.
<img width="1458" alt="截屏2024-02-29 15 30 54" src="https://github.com/asterinas/asterinas/assets/27764680/97c6f89c-419d-46d6-9045-ea515fe80b3c">
If running `cargo doc --target x86_64-unknown-none` to avoid panic in `linux-bzimage-setup` , more error occurs.
# Possible solution
1. Fix the error in `inventory`
2. Make `linux-bzimage-setup` can also build under other target, like `x86_64-unknown-linux-gnu`, but should we allow this behavior?
|
asterinas__asterinas-665
| 665
|
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -144,10 +144,14 @@ ktest: initramfs $(CARGO_OSDK)
(cd $$dir && cargo osdk test) || exit 1; \
done
-.PHONY: docs
-docs:
- @cargo doc # Build Rust docs
- @echo "" # Add a blank line
+docs: $(CARGO_OSDK)
+ @for dir in $(NON_OSDK_CRATES); do \
+ (cd $$dir && cargo doc --no-deps) || exit 1; \
+ done
+ @for dir in $(OSDK_CRATES); do \
+ (cd $$dir && cargo osdk doc --no-deps) || exit 1; \
+ done
+ @echo "" # Add a blank line
@cd docs && mdbook build # Build mdBook
.PHONY: format
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -169,7 +173,7 @@ check: $(CARGO_OSDK)
(cd $$dir && cargo clippy -- -D warnings) || exit 1; \
done
@for dir in $(OSDK_CRATES); do \
- (cd $$dir && cargo osdk clippy) || exit 1; \
+ (cd $$dir && cargo osdk clippy -- -- -D warnings) || exit 1; \
done
.PHONY: clean
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -169,7 +173,7 @@ check: $(CARGO_OSDK)
(cd $$dir && cargo clippy -- -D warnings) || exit 1; \
done
@for dir in $(OSDK_CRATES); do \
- (cd $$dir && cargo osdk clippy) || exit 1; \
+ (cd $$dir && cargo osdk clippy -- -- -D warnings) || exit 1; \
done
.PHONY: clean
diff --git a/framework/aster-frame/src/arch/x86/cpu.rs b/framework/aster-frame/src/arch/x86/cpu.rs
--- a/framework/aster-frame/src/arch/x86/cpu.rs
+++ b/framework/aster-frame/src/arch/x86/cpu.rs
@@ -309,7 +309,7 @@ impl UserContextApiInternal for UserContext {
}
}
-/// As Osdev Wiki defines(https://wiki.osdev.org/Exceptions):
+/// As Osdev Wiki defines(<https://wiki.osdev.org/Exceptions>):
/// CPU exceptions are classified as:
///
/// Faults: These can be corrected and the program may continue as if nothing happened.
diff --git a/framework/aster-frame/src/arch/x86/cpu.rs b/framework/aster-frame/src/arch/x86/cpu.rs
--- a/framework/aster-frame/src/arch/x86/cpu.rs
+++ b/framework/aster-frame/src/arch/x86/cpu.rs
@@ -309,7 +309,7 @@ impl UserContextApiInternal for UserContext {
}
}
-/// As Osdev Wiki defines(https://wiki.osdev.org/Exceptions):
+/// As Osdev Wiki defines(<https://wiki.osdev.org/Exceptions>):
/// CPU exceptions are classified as:
///
/// Faults: These can be corrected and the program may continue as if nothing happened.
diff --git a/framework/aster-frame/src/arch/x86/device/serial.rs b/framework/aster-frame/src/arch/x86/device/serial.rs
--- a/framework/aster-frame/src/arch/x86/device/serial.rs
+++ b/framework/aster-frame/src/arch/x86/device/serial.rs
@@ -7,7 +7,7 @@ use crate::arch::x86::device::io_port::{IoPort, ReadWriteAccess, WriteOnlyAccess
/// A serial port.
///
/// Serial ports are a legacy communications port common on IBM-PC compatible computers.
-/// Ref: https://wiki.osdev.org/Serial_Ports
+/// Ref: <https://wiki.osdev.org/Serial_Ports>
pub struct SerialPort {
pub data: IoPort<u8, ReadWriteAccess>,
pub int_en: IoPort<u8, WriteOnlyAccess>,
diff --git a/framework/aster-frame/src/arch/x86/device/serial.rs b/framework/aster-frame/src/arch/x86/device/serial.rs
--- a/framework/aster-frame/src/arch/x86/device/serial.rs
+++ b/framework/aster-frame/src/arch/x86/device/serial.rs
@@ -7,7 +7,7 @@ use crate::arch::x86::device::io_port::{IoPort, ReadWriteAccess, WriteOnlyAccess
/// A serial port.
///
/// Serial ports are a legacy communications port common on IBM-PC compatible computers.
-/// Ref: https://wiki.osdev.org/Serial_Ports
+/// Ref: <https://wiki.osdev.org/Serial_Ports>
pub struct SerialPort {
pub data: IoPort<u8, ReadWriteAccess>,
pub int_en: IoPort<u8, WriteOnlyAccess>,
diff --git a/framework/aster-frame/src/arch/x86/timer/pit.rs b/framework/aster-frame/src/arch/x86/timer/pit.rs
--- a/framework/aster-frame/src/arch/x86/timer/pit.rs
+++ b/framework/aster-frame/src/arch/x86/timer/pit.rs
@@ -4,7 +4,7 @@
//! a prescaler and 3 independent frequency dividers. Each frequency divider has an output, which is
//! used to allow the timer to control external circuitry (for example, IRQ 0).
//!
-//! Reference: https://wiki.osdev.org/Programmable_Interval_Timer
+//! Reference: <https://wiki.osdev.org/Programmable_Interval_Timer>
//!
use crate::{
diff --git a/framework/aster-frame/src/arch/x86/timer/pit.rs b/framework/aster-frame/src/arch/x86/timer/pit.rs
--- a/framework/aster-frame/src/arch/x86/timer/pit.rs
+++ b/framework/aster-frame/src/arch/x86/timer/pit.rs
@@ -4,7 +4,7 @@
//! a prescaler and 3 independent frequency dividers. Each frequency divider has an output, which is
//! used to allow the timer to control external circuitry (for example, IRQ 0).
//!
-//! Reference: https://wiki.osdev.org/Programmable_Interval_Timer
+//! Reference: <https://wiki.osdev.org/Programmable_Interval_Timer>
//!
use crate::{
diff --git a/framework/aster-frame/src/boot/kcmdline.rs b/framework/aster-frame/src/boot/kcmdline.rs
--- a/framework/aster-frame/src/boot/kcmdline.rs
+++ b/framework/aster-frame/src/boot/kcmdline.rs
@@ -5,7 +5,7 @@
//! The format of the Asterinas command line string conforms
//! to the Linux kernel command line rules:
//!
-//! https://www.kernel.org/doc/html/v6.4/admin-guide/kernel-parameters.html
+//! <https://www.kernel.org/doc/html/v6.4/admin-guide/kernel-parameters.html>
//!
use alloc::{
diff --git a/framework/aster-frame/src/boot/kcmdline.rs b/framework/aster-frame/src/boot/kcmdline.rs
--- a/framework/aster-frame/src/boot/kcmdline.rs
+++ b/framework/aster-frame/src/boot/kcmdline.rs
@@ -5,7 +5,7 @@
//! The format of the Asterinas command line string conforms
//! to the Linux kernel command line rules:
//!
-//! https://www.kernel.org/doc/html/v6.4/admin-guide/kernel-parameters.html
+//! <https://www.kernel.org/doc/html/v6.4/admin-guide/kernel-parameters.html>
//!
use alloc::{
diff --git a/framework/aster-frame/src/bus/pci/mod.rs b/framework/aster-frame/src/bus/pci/mod.rs
--- a/framework/aster-frame/src/bus/pci/mod.rs
+++ b/framework/aster-frame/src/bus/pci/mod.rs
@@ -9,7 +9,7 @@
//!
//! Use case:
//!
-//! ```rust norun
+//! ```rust no_run
//! #[derive(Debug)]
//! pub struct PciDeviceA {
//! common_device: PciCommonDevice,
diff --git a/framework/aster-frame/src/bus/pci/mod.rs b/framework/aster-frame/src/bus/pci/mod.rs
--- a/framework/aster-frame/src/bus/pci/mod.rs
+++ b/framework/aster-frame/src/bus/pci/mod.rs
@@ -9,7 +9,7 @@
//!
//! Use case:
//!
-//! ```rust norun
+//! ```rust no_run
//! #[derive(Debug)]
//! pub struct PciDeviceA {
//! common_device: PciCommonDevice,
diff --git a/framework/aster-frame/src/trap/irq.rs b/framework/aster-frame/src/trap/irq.rs
--- a/framework/aster-frame/src/trap/irq.rs
+++ b/framework/aster-frame/src/trap/irq.rs
@@ -103,7 +103,7 @@ impl Drop for IrqLine {
///
/// # Example
///
-/// ``rust
+/// ```rust
/// use aster_frame::irq;
///
/// {
diff --git a/framework/aster-frame/src/trap/irq.rs b/framework/aster-frame/src/trap/irq.rs
--- a/framework/aster-frame/src/trap/irq.rs
+++ b/framework/aster-frame/src/trap/irq.rs
@@ -103,7 +103,7 @@ impl Drop for IrqLine {
///
/// # Example
///
-/// ``rust
+/// ```rust
/// use aster_frame::irq;
///
/// {
diff --git a/framework/libs/linux-bzimage/builder/src/pe_header.rs b/framework/libs/linux-bzimage/builder/src/pe_header.rs
--- a/framework/libs/linux-bzimage/builder/src/pe_header.rs
+++ b/framework/libs/linux-bzimage/builder/src/pe_header.rs
@@ -3,10 +3,10 @@
//! Big zImage PE/COFF header generation.
//!
//! The definition of the PE/COFF header is in the Microsoft PE/COFF specification:
-//! https://learn.microsoft.com/en-us/windows/win32/debug/pe-format
+//! <https://learn.microsoft.com/en-us/windows/win32/debug/pe-format>
//!
//! The reference to the Linux PE header definition:
-//! https://github.com/torvalds/linux/blob/master/include/linux/pe.h
+//! <https://github.com/torvalds/linux/blob/master/include/linux/pe.h>
use std::{mem::size_of, ops::Range};
diff --git a/framework/libs/linux-bzimage/builder/src/pe_header.rs b/framework/libs/linux-bzimage/builder/src/pe_header.rs
--- a/framework/libs/linux-bzimage/builder/src/pe_header.rs
+++ b/framework/libs/linux-bzimage/builder/src/pe_header.rs
@@ -3,10 +3,10 @@
//! Big zImage PE/COFF header generation.
//!
//! The definition of the PE/COFF header is in the Microsoft PE/COFF specification:
-//! https://learn.microsoft.com/en-us/windows/win32/debug/pe-format
+//! <https://learn.microsoft.com/en-us/windows/win32/debug/pe-format>
//!
//! The reference to the Linux PE header definition:
-//! https://github.com/torvalds/linux/blob/master/include/linux/pe.h
+//! <https://github.com/torvalds/linux/blob/master/include/linux/pe.h>
use std::{mem::size_of, ops::Range};
diff --git a/kernel/aster-nix/src/console.rs b/kernel/aster-nix/src/console.rs
--- a/kernel/aster-nix/src/console.rs
+++ b/kernel/aster-nix/src/console.rs
@@ -22,7 +22,7 @@ pub fn _print(args: Arguments) {
VirtioConsolesPrinter.write_fmt(args).unwrap();
}
-/// Copy from Rust std: https://github.com/rust-lang/rust/blob/master/library/std/src/macros.rs
+/// Copied from Rust std: <https://github.com/rust-lang/rust/blob/master/library/std/src/macros.rs>
#[macro_export]
macro_rules! print {
($($arg:tt)*) => {{
diff --git a/kernel/aster-nix/src/console.rs b/kernel/aster-nix/src/console.rs
--- a/kernel/aster-nix/src/console.rs
+++ b/kernel/aster-nix/src/console.rs
@@ -22,7 +22,7 @@ pub fn _print(args: Arguments) {
VirtioConsolesPrinter.write_fmt(args).unwrap();
}
-/// Copy from Rust std: https://github.com/rust-lang/rust/blob/master/library/std/src/macros.rs
+/// Copied from Rust std: <https://github.com/rust-lang/rust/blob/master/library/std/src/macros.rs>
#[macro_export]
macro_rules! print {
($($arg:tt)*) => {{
diff --git a/kernel/aster-nix/src/console.rs b/kernel/aster-nix/src/console.rs
--- a/kernel/aster-nix/src/console.rs
+++ b/kernel/aster-nix/src/console.rs
@@ -30,7 +30,7 @@ macro_rules! print {
}};
}
-/// Copy from Rust std: https://github.com/rust-lang/rust/blob/master/library/std/src/macros.rs
+/// Copied from Rust std: <https://github.com/rust-lang/rust/blob/master/library/std/src/macros.rs>
#[macro_export]
macro_rules! println {
() => {
diff --git a/kernel/aster-nix/src/console.rs b/kernel/aster-nix/src/console.rs
--- a/kernel/aster-nix/src/console.rs
+++ b/kernel/aster-nix/src/console.rs
@@ -30,7 +30,7 @@ macro_rules! print {
}};
}
-/// Copy from Rust std: https://github.com/rust-lang/rust/blob/master/library/std/src/macros.rs
+/// Copied from Rust std: <https://github.com/rust-lang/rust/blob/master/library/std/src/macros.rs>
#[macro_export]
macro_rules! println {
() => {
diff --git a/kernel/aster-nix/src/net/iface/mod.rs b/kernel/aster-nix/src/net/iface/mod.rs
--- a/kernel/aster-nix/src/net/iface/mod.rs
+++ b/kernel/aster-nix/src/net/iface/mod.rs
@@ -39,7 +39,7 @@ pub trait Iface: internal::IfaceInternal + Send + Sync {
/// Bind a socket to the iface. So the packet for this socket will be dealt with by the interface.
/// If port is None, the iface will pick up an empheral port for the socket.
/// FIXME: The reason for binding socket and interface together is because there are limitations inside smoltcp.
- /// See discussion at https://github.com/smoltcp-rs/smoltcp/issues/779.
+ /// See discussion at <https://github.com/smoltcp-rs/smoltcp/issues/779>.
fn bind_socket(
&self,
socket: Box<AnyUnboundSocket>,
diff --git a/kernel/aster-nix/src/net/iface/mod.rs b/kernel/aster-nix/src/net/iface/mod.rs
--- a/kernel/aster-nix/src/net/iface/mod.rs
+++ b/kernel/aster-nix/src/net/iface/mod.rs
@@ -39,7 +39,7 @@ pub trait Iface: internal::IfaceInternal + Send + Sync {
/// Bind a socket to the iface. So the packet for this socket will be dealt with by the interface.
/// If port is None, the iface will pick up an empheral port for the socket.
/// FIXME: The reason for binding socket and interface together is because there are limitations inside smoltcp.
- /// See discussion at https://github.com/smoltcp-rs/smoltcp/issues/779.
+ /// See discussion at <https://github.com/smoltcp-rs/smoltcp/issues/779>.
fn bind_socket(
&self,
socket: Box<AnyUnboundSocket>,
diff --git a/kernel/aster-nix/src/net/socket/util/shutdown_cmd.rs b/kernel/aster-nix/src/net/socket/util/shutdown_cmd.rs
--- a/kernel/aster-nix/src/net/socket/util/shutdown_cmd.rs
+++ b/kernel/aster-nix/src/net/socket/util/shutdown_cmd.rs
@@ -3,7 +3,7 @@
use crate::prelude::*;
/// Shutdown types
-/// From https://elixir.bootlin.com/linux/v6.0.9/source/include/linux/net.h
+/// From <https://elixir.bootlin.com/linux/v6.0.9/source/include/linux/net.h>
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, TryFromInt)]
#[allow(non_camel_case_types)]
diff --git a/kernel/aster-nix/src/net/socket/util/shutdown_cmd.rs b/kernel/aster-nix/src/net/socket/util/shutdown_cmd.rs
--- a/kernel/aster-nix/src/net/socket/util/shutdown_cmd.rs
+++ b/kernel/aster-nix/src/net/socket/util/shutdown_cmd.rs
@@ -3,7 +3,7 @@
use crate::prelude::*;
/// Shutdown types
-/// From https://elixir.bootlin.com/linux/v6.0.9/source/include/linux/net.h
+/// From <https://elixir.bootlin.com/linux/v6.0.9/source/include/linux/net.h>
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, TryFromInt)]
#[allow(non_camel_case_types)]
diff --git a/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs b/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
--- a/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
+++ b/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
@@ -2,7 +2,7 @@
//! This module defines the process initial stack.
//! The process initial stack, contains arguments, environmental variables and auxiliary vectors
-//! The data layout of init stack can be seen in Figure 3.9 in https://uclibc.org/docs/psABI-x86_64.pdf
+//! The data layout of init stack can be seen in Figure 3.9 in <https://uclibc.org/docs/psABI-x86_64.pdf>
use core::mem;
diff --git a/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs b/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
--- a/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
+++ b/kernel/aster-nix/src/process/program_loader/elf/init_stack.rs
@@ -2,7 +2,7 @@
//! This module defines the process initial stack.
//! The process initial stack, contains arguments, environmental variables and auxiliary vectors
-//! The data layout of init stack can be seen in Figure 3.9 in https://uclibc.org/docs/psABI-x86_64.pdf
+//! The data layout of init stack can be seen in Figure 3.9 in <https://uclibc.org/docs/psABI-x86_64.pdf>
use core::mem;
diff --git a/kernel/aster-nix/src/util/net/options/mod.rs b/kernel/aster-nix/src/util/net/options/mod.rs
--- a/kernel/aster-nix/src/util/net/options/mod.rs
+++ b/kernel/aster-nix/src/util/net/options/mod.rs
@@ -24,7 +24,7 @@
//!
//! First, the option should be added in the net module for the TCP socket.
//!
-//! ```rust norun
+//! ```rust no_run
//! impl_socket_option!(TcpNodelay(bool));
//! ```
//!
diff --git a/kernel/aster-nix/src/util/net/options/mod.rs b/kernel/aster-nix/src/util/net/options/mod.rs
--- a/kernel/aster-nix/src/util/net/options/mod.rs
+++ b/kernel/aster-nix/src/util/net/options/mod.rs
@@ -24,7 +24,7 @@
//!
//! First, the option should be added in the net module for the TCP socket.
//!
-//! ```rust norun
+//! ```rust no_run
//! impl_socket_option!(TcpNodelay(bool));
//! ```
//!
diff --git a/kernel/aster-nix/src/util/net/options/mod.rs b/kernel/aster-nix/src/util/net/options/mod.rs
--- a/kernel/aster-nix/src/util/net/options/mod.rs
+++ b/kernel/aster-nix/src/util/net/options/mod.rs
@@ -32,15 +32,19 @@
//! in the utils module. These util functions can be shared if multiple options have the value
//! of same type.
//!
-//! ```rust norun
-//! impl ReadFromUser for bool { // content omitted here }
-//! impl WriteFromUser for bool { // content omitted here }
+//! ```rust compile_fail
+//! impl ReadFromUser for bool {
+//! // content omitted here
+//! }
+//! impl WriteFromUser for bool {
+//! // content omitted here
+//! }
//! ```
//!
//! At last, we can implement `RawSocketOption` for `TcpNodelay` so that it can be read/from
//! user space.
//!
-//! ```rust norun
+//! ```rust no_run
//! impl_raw_socket_option!(TcpNodeley);
//! ```
//!
diff --git a/kernel/aster-nix/src/util/net/options/mod.rs b/kernel/aster-nix/src/util/net/options/mod.rs
--- a/kernel/aster-nix/src/util/net/options/mod.rs
+++ b/kernel/aster-nix/src/util/net/options/mod.rs
@@ -32,15 +32,19 @@
//! in the utils module. These util functions can be shared if multiple options have the value
//! of same type.
//!
-//! ```rust norun
-//! impl ReadFromUser for bool { // content omitted here }
-//! impl WriteFromUser for bool { // content omitted here }
+//! ```rust compile_fail
+//! impl ReadFromUser for bool {
+//! // content omitted here
+//! }
+//! impl WriteFromUser for bool {
+//! // content omitted here
+//! }
//! ```
//!
//! At last, we can implement `RawSocketOption` for `TcpNodelay` so that it can be read/from
//! user space.
//!
-//! ```rust norun
+//! ```rust no_run
//! impl_raw_socket_option!(TcpNodeley);
//! ```
//!
diff --git a/kernel/comps/virtio/src/device/input/mod.rs b/kernel/comps/virtio/src/device/input/mod.rs
--- a/kernel/comps/virtio/src/device/input/mod.rs
+++ b/kernel/comps/virtio/src/device/input/mod.rs
@@ -35,7 +35,7 @@ use crate::transport::VirtioTransport;
pub static DEVICE_NAME: &str = "Virtio-Input";
-/// Select value used for [`VirtIOInput::query_config_select()`].
+/// Select value used for [`device::InputDevice::query_config_select()`].
#[repr(u8)]
#[derive(Debug, Clone, Copy)]
pub enum InputConfigSelect {
diff --git a/kernel/comps/virtio/src/device/input/mod.rs b/kernel/comps/virtio/src/device/input/mod.rs
--- a/kernel/comps/virtio/src/device/input/mod.rs
+++ b/kernel/comps/virtio/src/device/input/mod.rs
@@ -35,7 +35,7 @@ use crate::transport::VirtioTransport;
pub static DEVICE_NAME: &str = "Virtio-Input";
-/// Select value used for [`VirtIOInput::query_config_select()`].
+/// Select value used for [`device::InputDevice::query_config_select()`].
#[repr(u8)]
#[derive(Debug, Clone, Copy)]
pub enum InputConfigSelect {
diff --git a/kernel/libs/aster-rights-proc/src/lib.rs b/kernel/libs/aster-rights-proc/src/lib.rs
--- a/kernel/libs/aster-rights-proc/src/lib.rs
+++ b/kernel/libs/aster-rights-proc/src/lib.rs
@@ -4,11 +4,11 @@
//! When use this crate, typeflags and typeflags-util should also be added as dependency.
//!
//! The require macro are used to ensure that an object has the enough capability to call the function.
-//! The **require** macro can accept constraint [SomeRightSet] > [SomeRight],
-//! which means the SomeRightSet should **contain** the SomeRight.
-//! The **require** macro can also accept constraint [SomeRightSet] > [AnotherRightSet],
-//! which means the SomeRightSet should **include** the AnotherRightSet. In this case, AnotherRightSet should be a **generic parameter**.
-//! i.e., AnotherRightSet should occur the the generic param list of the function.
+//! The **require** macro can accept constraint `SomeRightSet` > `SomeRight`,
+//! which means the `SomeRightSet` should **contain** the `SomeRight`.
+//! The **require** macro can also accept constraint `SomeRightSet` > `AnotherRightSet`,
+//! which means the `SomeRightSet` should **include** the `AnotherRightSet`. In this case, `AnotherRightSet` should be a **generic parameter**.
+//! i.e., `AnotherRightSet` should occur the the generic param list of the function.
//!
//! If there are multiple constraits, they can be seperated with `|`, which means all constraits should be satisfied.
//!
diff --git a/kernel/libs/aster-rights-proc/src/lib.rs b/kernel/libs/aster-rights-proc/src/lib.rs
--- a/kernel/libs/aster-rights-proc/src/lib.rs
+++ b/kernel/libs/aster-rights-proc/src/lib.rs
@@ -4,11 +4,11 @@
//! When use this crate, typeflags and typeflags-util should also be added as dependency.
//!
//! The require macro are used to ensure that an object has the enough capability to call the function.
-//! The **require** macro can accept constraint [SomeRightSet] > [SomeRight],
-//! which means the SomeRightSet should **contain** the SomeRight.
-//! The **require** macro can also accept constraint [SomeRightSet] > [AnotherRightSet],
-//! which means the SomeRightSet should **include** the AnotherRightSet. In this case, AnotherRightSet should be a **generic parameter**.
-//! i.e., AnotherRightSet should occur the the generic param list of the function.
+//! The **require** macro can accept constraint `SomeRightSet` > `SomeRight`,
+//! which means the `SomeRightSet` should **contain** the `SomeRight`.
+//! The **require** macro can also accept constraint `SomeRightSet` > `AnotherRightSet`,
+//! which means the `SomeRightSet` should **include** the `AnotherRightSet`. In this case, `AnotherRightSet` should be a **generic parameter**.
+//! i.e., `AnotherRightSet` should occur the the generic param list of the function.
//!
//! If there are multiple constraits, they can be seperated with `|`, which means all constraits should be satisfied.
//!
diff --git a/kernel/libs/aster-rights/src/lib.rs b/kernel/libs/aster-rights/src/lib.rs
--- a/kernel/libs/aster-rights/src/lib.rs
+++ b/kernel/libs/aster-rights/src/lib.rs
@@ -55,7 +55,7 @@ pub type WriteOp = TRights![Write];
pub type FullOp = TRights![Read, Write, Dup];
/// Wrapper for TRights, used to bypass an error message from the Rust compiler,
-/// the relevant issue is: https://github.com/rust-lang/rfcs/issues/2758
+/// the relevant issue is: <https://github.com/rust-lang/rfcs/issues/2758>
///
/// Example:
///
diff --git a/kernel/libs/aster-rights/src/lib.rs b/kernel/libs/aster-rights/src/lib.rs
--- a/kernel/libs/aster-rights/src/lib.rs
+++ b/kernel/libs/aster-rights/src/lib.rs
@@ -55,7 +55,7 @@ pub type WriteOp = TRights![Write];
pub type FullOp = TRights![Read, Write, Dup];
/// Wrapper for TRights, used to bypass an error message from the Rust compiler,
-/// the relevant issue is: https://github.com/rust-lang/rfcs/issues/2758
+/// the relevant issue is: <https://github.com/rust-lang/rfcs/issues/2758>
///
/// Example:
///
diff --git a/osdk/src/cli.rs b/osdk/src/cli.rs
--- a/osdk/src/cli.rs
+++ b/osdk/src/cli.rs
@@ -6,8 +6,8 @@ use clap::{crate_version, Args, Parser};
use crate::{
commands::{
- execute_build_command, execute_check_command, execute_clippy_command, execute_new_command,
- execute_run_command, execute_test_command,
+ execute_build_command, execute_forwarded_command, execute_new_command, execute_run_command,
+ execute_test_command,
},
config_manager::{
boot::{BootLoader, BootProtocol},
diff --git a/osdk/src/cli.rs b/osdk/src/cli.rs
--- a/osdk/src/cli.rs
+++ b/osdk/src/cli.rs
@@ -37,8 +37,9 @@ pub fn main() {
let test_config = TestConfig::parse(test_args);
execute_test_command(&test_config);
}
- OsdkSubcommand::Check => execute_check_command(),
- OsdkSubcommand::Clippy => execute_clippy_command(),
+ OsdkSubcommand::Check(args) => execute_forwarded_command("check", &args.args),
+ OsdkSubcommand::Clippy(args) => execute_forwarded_command("clippy", &args.args),
+ OsdkSubcommand::Doc(args) => execute_forwarded_command("doc", &args.args),
}
}
diff --git a/osdk/src/cli.rs b/osdk/src/cli.rs
--- a/osdk/src/cli.rs
+++ b/osdk/src/cli.rs
@@ -68,10 +69,22 @@ pub enum OsdkSubcommand {
Run(RunArgs),
#[command(about = "Execute kernel mode unit test by starting a VMM")]
Test(TestArgs),
- #[command(about = "Analyze the current package and report errors")]
- Check,
- #[command(about = "Check the current package and catch common mistakes")]
- Clippy,
+ #[command(about = "Check a local package and all of its dependencies for errors")]
+ Check(ForwardedArguments),
+ #[command(about = "Checks a package to catch common mistakes and improve your Rust code")]
+ Clippy(ForwardedArguments),
+ #[command(about = "Build a package's documentation")]
+ Doc(ForwardedArguments),
+}
+
+#[derive(Debug, Parser)]
+pub struct ForwardedArguments {
+ #[arg(
+ help = "The full set of Cargo arguments",
+ trailing_var_arg = true,
+ allow_hyphen_values = true
+ )]
+ pub args: Vec<String>,
}
#[derive(Debug, Parser)]
diff --git a/osdk/src/commands/check.rs /dev/null
--- a/osdk/src/commands/check.rs
+++ /dev/null
@@ -1,20 +0,0 @@
-// SPDX-License-Identifier: MPL-2.0
-
-use std::process;
-
-use super::util::{cargo, COMMON_CARGO_ARGS};
-use crate::{error::Errno, error_msg};
-
-pub fn execute_check_command() {
- let mut command = cargo();
- command
- .arg("check")
- .arg("--target")
- .arg("x86_64-unknown-none");
- command.args(COMMON_CARGO_ARGS);
- let status = command.status().unwrap();
- if !status.success() {
- error_msg!("Check failed");
- process::exit(Errno::ExecuteCommand as _);
- }
-}
diff --git a/osdk/src/commands/check.rs /dev/null
--- a/osdk/src/commands/check.rs
+++ /dev/null
@@ -1,20 +0,0 @@
-// SPDX-License-Identifier: MPL-2.0
-
-use std::process;
-
-use super::util::{cargo, COMMON_CARGO_ARGS};
-use crate::{error::Errno, error_msg};
-
-pub fn execute_check_command() {
- let mut command = cargo();
- command
- .arg("check")
- .arg("--target")
- .arg("x86_64-unknown-none");
- command.args(COMMON_CARGO_ARGS);
- let status = command.status().unwrap();
- if !status.success() {
- error_msg!("Check failed");
- process::exit(Errno::ExecuteCommand as _);
- }
-}
diff --git a/osdk/src/commands/clippy.rs /dev/null
--- a/osdk/src/commands/clippy.rs
+++ /dev/null
@@ -1,38 +0,0 @@
-// SPDX-License-Identifier: MPL-2.0
-
-use std::process;
-
-use super::util::{cargo, COMMON_CARGO_ARGS};
-use crate::{error::Errno, error_msg};
-
-pub fn execute_clippy_command() {
- let mut command = cargo();
- command
- .arg("clippy")
- .arg("-h")
- .arg("--target")
- .arg("x86_64-unknown-none")
- .args(COMMON_CARGO_ARGS);
- info!("Running `cargo clippy -h`");
- let output = command.output().unwrap();
- if !output.status.success() {
- let stderr = String::from_utf8_lossy(&output.stderr);
- eprintln!("{}", &stderr);
- error_msg!("Cargo clippy failed");
- process::exit(Errno::ExecuteCommand as _);
- }
-
- let mut command = cargo();
- command
- .arg("clippy")
- .arg("--target")
- .arg("x86_64-unknown-none")
- .args(COMMON_CARGO_ARGS);
- // TODO: Add support for custom clippy args using OSDK commandline rather than hardcode it.
- command.args(["--", "-D", "warnings"]);
- let status = command.status().unwrap();
- if !status.success() {
- error_msg!("Cargo clippy failed");
- process::exit(Errno::ExecuteCommand as _);
- }
-}
diff --git a/osdk/src/commands/clippy.rs /dev/null
--- a/osdk/src/commands/clippy.rs
+++ /dev/null
@@ -1,38 +0,0 @@
-// SPDX-License-Identifier: MPL-2.0
-
-use std::process;
-
-use super::util::{cargo, COMMON_CARGO_ARGS};
-use crate::{error::Errno, error_msg};
-
-pub fn execute_clippy_command() {
- let mut command = cargo();
- command
- .arg("clippy")
- .arg("-h")
- .arg("--target")
- .arg("x86_64-unknown-none")
- .args(COMMON_CARGO_ARGS);
- info!("Running `cargo clippy -h`");
- let output = command.output().unwrap();
- if !output.status.success() {
- let stderr = String::from_utf8_lossy(&output.stderr);
- eprintln!("{}", &stderr);
- error_msg!("Cargo clippy failed");
- process::exit(Errno::ExecuteCommand as _);
- }
-
- let mut command = cargo();
- command
- .arg("clippy")
- .arg("--target")
- .arg("x86_64-unknown-none")
- .args(COMMON_CARGO_ARGS);
- // TODO: Add support for custom clippy args using OSDK commandline rather than hardcode it.
- command.args(["--", "-D", "warnings"]);
- let status = command.status().unwrap();
- if !status.success() {
- error_msg!("Cargo clippy failed");
- process::exit(Errno::ExecuteCommand as _);
- }
-}
diff --git a/osdk/src/commands/mod.rs b/osdk/src/commands/mod.rs
--- a/osdk/src/commands/mod.rs
+++ b/osdk/src/commands/mod.rs
@@ -3,14 +3,25 @@
//! This module contains subcommands of cargo-osdk.
mod build;
-mod check;
-mod clippy;
mod new;
mod run;
mod test;
mod util;
pub use self::{
- build::execute_build_command, check::execute_check_command, clippy::execute_clippy_command,
- new::execute_new_command, run::execute_run_command, test::execute_test_command,
+ build::execute_build_command, new::execute_new_command, run::execute_run_command,
+ test::execute_test_command,
};
+
+/// Execute the forwarded cargo command with args containing the subcommand and its arguments.
+pub fn execute_forwarded_command(subcommand: &str, args: &Vec<String>) -> ! {
+ let mut cargo = util::cargo();
+ cargo
+ .arg(subcommand)
+ .args(util::COMMON_CARGO_ARGS)
+ .arg("--target")
+ .arg("x86_64-unknown-none")
+ .args(args);
+ let status = cargo.status().expect("Failed to execute cargo");
+ std::process::exit(status.code().unwrap_or(1));
+}
|
This will work.
```bash
cargo doc --target x86_64-unknown-none -Zbuild-std=core,alloc,compiler_builtins -Zbuild-std-features=compiler-builtins-mem
```
|
2024-03-06T09:10:55Z
|
e210e68920481c911f62f03ade0a780f96e48e24
|
asterinas/asterinas
|
diff --git a/regression/apps/network/send_buf_full.c b/regression/apps/network/send_buf_full.c
--- a/regression/apps/network/send_buf_full.c
+++ b/regression/apps/network/send_buf_full.c
@@ -197,6 +192,9 @@ int test_full_send_buffer(struct sockaddr_in *addr)
if (pid == 0) {
ssize_t recv_len;
+ close(sendfd);
+ sendfd = -1;
+
// Ensure that the parent executes send() first, then the child
// executes recv().
sleep(1);
diff --git a/regression/apps/network/send_buf_full.c b/regression/apps/network/send_buf_full.c
--- a/regression/apps/network/send_buf_full.c
+++ b/regression/apps/network/send_buf_full.c
@@ -230,6 +228,9 @@ int test_full_send_buffer(struct sockaddr_in *addr)
sent_len += 1;
fprintf(stderr, "Sent bytes: %lu\n", sent_len);
+ close(sendfd);
+ sendfd = -1;
+
ret = 0;
wait:
diff --git a/regression/apps/network/send_buf_full.c b/regression/apps/network/send_buf_full.c
--- a/regression/apps/network/send_buf_full.c
+++ b/regression/apps/network/send_buf_full.c
@@ -250,7 +251,8 @@ int test_full_send_buffer(struct sockaddr_in *addr)
close(recvfd);
out_send:
- close(sendfd);
+ if (sendfd >= 0)
+ close(sendfd);
out_listen:
close(listenfd);
diff --git a/regression/apps/scripts/network.sh b/regression/apps/scripts/network.sh
--- a/regression/apps/scripts/network.sh
+++ b/regression/apps/scripts/network.sh
@@ -18,7 +18,7 @@ echo "Start network test......"
./socketpair
./sockoption
./listen_backlog
-# ./send_buf_full
+./send_buf_full
./http_server &
./http_client
./tcp_err
|
[
"646"
] |
0.4
|
07fbbcfd8c22459719c9af7eeeb3dee5ad24ba92
|
The send_buf_full test fails on host linux
The test is run within Asterinas dev container.
To replay the results, commands are
```bash
make build
cd regression/build/initramfs/regression/network
./send_buf_full
```
I run `./send_buf_full` for four times, the results are
```
root@kx-2288H-V6:~/asterinas/regression/build/initramfs/regression/network# ./send_buf_full
Start receiving...
Sent bytes: 2586567
Received bytes: 2553825
Test failed: Mismatched sent bytes and received bytes
Test failed: Error occurs in child process
root@kx-2288H-V6:~/asterinas/regression/build/initramfs/regression/network# ./send_buf_full
Start receiving...
Sent bytes: 2586567
Received bytes: 2553825
Test failed: Mismatched sent bytes and received bytes
Test failed: Error occurs in child process
root@kx-2288H-V6:~/asterinas/regression/build/initramfs/regression/network# ./send_buf_full
Start receiving...
Sent bytes: 2586567
Received bytes: 2586567
Test passed: Equal sent bytes and received bytes
root@kx-2288H-V6:~/asterinas/regression/build/initramfs/regression/network# ./send_buf_full
new_bound_socket: bind: Address already in use
Test failed: Error occurs in new_bound_socket
```
I have repeated the test several time and find the same results: the test fails at the first run and succeeds in some following run. And once the test succeeds, the following run will report `Address already in use` error.
|
asterinas__asterinas-650
| 650
|
diff --git a/regression/apps/network/send_buf_full.c b/regression/apps/network/send_buf_full.c
--- a/regression/apps/network/send_buf_full.c
+++ b/regression/apps/network/send_buf_full.c
@@ -105,14 +105,9 @@ static ssize_t receive_all(int sockfd)
size_t recv_len = 0;
ssize_t ret;
- if (mark_filde_nonblock(sockfd) < 0) {
- perror("receive_all: mark_filde_nonblock");
- return -1;
- }
-
for (;;) {
ret = recv(sockfd, buffer, sizeof(buffer), 0);
- if (ret < 0 && errno == EAGAIN)
+ if (ret == 0)
break;
if (ret < 0) {
diff --git a/regression/apps/network/send_buf_full.c b/regression/apps/network/send_buf_full.c
--- a/regression/apps/network/send_buf_full.c
+++ b/regression/apps/network/send_buf_full.c
@@ -105,14 +105,9 @@ static ssize_t receive_all(int sockfd)
size_t recv_len = 0;
ssize_t ret;
- if (mark_filde_nonblock(sockfd) < 0) {
- perror("receive_all: mark_filde_nonblock");
- return -1;
- }
-
for (;;) {
ret = recv(sockfd, buffer, sizeof(buffer), 0);
- if (ret < 0 && errno == EAGAIN)
+ if (ret == 0)
break;
if (ret < 0) {
diff --git a/regression/apps/network/send_buf_full.c b/regression/apps/network/send_buf_full.c
--- a/regression/apps/network/send_buf_full.c
+++ b/regression/apps/network/send_buf_full.c
@@ -197,6 +192,9 @@ int test_full_send_buffer(struct sockaddr_in *addr)
if (pid == 0) {
ssize_t recv_len;
+ close(sendfd);
+ sendfd = -1;
+
// Ensure that the parent executes send() first, then the child
// executes recv().
sleep(1);
diff --git a/regression/apps/network/send_buf_full.c b/regression/apps/network/send_buf_full.c
--- a/regression/apps/network/send_buf_full.c
+++ b/regression/apps/network/send_buf_full.c
@@ -230,6 +228,9 @@ int test_full_send_buffer(struct sockaddr_in *addr)
sent_len += 1;
fprintf(stderr, "Sent bytes: %lu\n", sent_len);
+ close(sendfd);
+ sendfd = -1;
+
ret = 0;
wait:
diff --git a/regression/apps/network/send_buf_full.c b/regression/apps/network/send_buf_full.c
--- a/regression/apps/network/send_buf_full.c
+++ b/regression/apps/network/send_buf_full.c
@@ -250,7 +251,8 @@ int test_full_send_buffer(struct sockaddr_in *addr)
close(recvfd);
out_send:
- close(sendfd);
+ if (sendfd >= 0)
+ close(sendfd);
out_listen:
close(listenfd);
diff --git a/regression/apps/scripts/network.sh b/regression/apps/scripts/network.sh
--- a/regression/apps/scripts/network.sh
+++ b/regression/apps/scripts/network.sh
@@ -18,7 +18,7 @@ echo "Start network test......"
./socketpair
./sockoption
./listen_backlog
-# ./send_buf_full
+./send_buf_full
./http_server &
./http_client
./tcp_err
|
2024-02-23T12:37:06Z
|
e210e68920481c911f62f03ade0a780f96e48e24
|
|
asterinas/asterinas
|
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -40,6 +40,7 @@ members = [
"framework/libs/linux-bzimage/setup",
"framework/libs/ktest",
"framework/libs/tdx-guest",
+ "services/aster-nix",
"services/comps/block",
"services/comps/console",
"services/comps/framebuffer",
diff --git a/services/libs/aster-std/Cargo.toml b/services/aster-nix/Cargo.toml
--- a/services/libs/aster-std/Cargo.toml
+++ b/services/aster-nix/Cargo.toml
@@ -40,8 +40,8 @@ smoltcp = { version = "0.9.1", default-features = false, features = [
"socket-raw",
"socket-dhcpv4",
] }
-ktest = { path = "../../../framework/libs/ktest" }
-tdx-guest = { path = "../../../framework/libs/tdx-guest", optional = true }
+ktest = { path = "../../framework/libs/ktest" }
+tdx-guest = { path = "../../framework/libs/tdx-guest", optional = true }
# parse elf file
xmas-elf = "0.8.0"
|
[
"592"
] |
0.3
|
8d456ebe8fc200fc11c75654fdca2f0dd896e656
|
Rename `aster-std` to `aster-nix`
# Background
In the current codebase, the Linux/UNIX layer is implemented in the `aster-std` crate under `services/libs`. The crate does the heavy-lifting job of implementing high-level OS concepts like processes, signals, file systems, sockets, etc. Ideally, we would like to have the system call layer to be more modular, breaking up the large crate into smaller ones. But this is going to take time and is probably done in an incremental fashion. So in the near future, we will still have to make peace with the sheer size of the `aster-std` crate.
# Goal
Given the role and size of the `aster-std` crate, I propose to change the name and location of the crate.
Its current name is only for historic reason: the crate is originally positioned as the std library for Asterinas, but it ends up with all system calls implemented in it. So calling it std is no longer appropriate. **I propose renaming it `aster-nix`**, as it implements the Linux and UNIX concepts and system calls.
The crate is currently buried in the third level of the project hierarchy, under `services/libs`. This crate is probably the second most important crate (after `aster-frame`) and the most frequently-updated one. Given its importance, I think it makes sense to given the crate a more _visible_ location. So **I propose to move the crate to `services/`**.
|
asterinas__asterinas-637
| 637
|
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -221,37 +221,7 @@ dependencies = [
]
[[package]]
-name = "aster-rights"
-version = "0.1.0"
-dependencies = [
- "aster-rights-proc",
- "bitflags 1.3.2",
- "typeflags",
- "typeflags-util",
-]
-
-[[package]]
-name = "aster-rights-proc"
-version = "0.1.0"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 1.0.109",
-]
-
-[[package]]
-name = "aster-runner"
-version = "0.1.0"
-dependencies = [
- "anyhow",
- "clap",
- "linux-bzimage-builder",
- "rand",
- "xmas-elf 0.8.0",
-]
-
-[[package]]
-name = "aster-std"
+name = "aster-nix"
version = "0.1.0"
dependencies = [
"align_ext",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -221,37 +221,7 @@ dependencies = [
]
[[package]]
-name = "aster-rights"
-version = "0.1.0"
-dependencies = [
- "aster-rights-proc",
- "bitflags 1.3.2",
- "typeflags",
- "typeflags-util",
-]
-
-[[package]]
-name = "aster-rights-proc"
-version = "0.1.0"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 1.0.109",
-]
-
-[[package]]
-name = "aster-runner"
-version = "0.1.0"
-dependencies = [
- "anyhow",
- "clap",
- "linux-bzimage-builder",
- "rand",
- "xmas-elf 0.8.0",
-]
-
-[[package]]
-name = "aster-std"
+name = "aster-nix"
version = "0.1.0"
dependencies = [
"align_ext",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -296,6 +266,36 @@ dependencies = [
"xmas-elf 0.8.0",
]
+[[package]]
+name = "aster-rights"
+version = "0.1.0"
+dependencies = [
+ "aster-rights-proc",
+ "bitflags 1.3.2",
+ "typeflags",
+ "typeflags-util",
+]
+
+[[package]]
+name = "aster-rights-proc"
+version = "0.1.0"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "aster-runner"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "clap",
+ "linux-bzimage-builder",
+ "rand",
+ "xmas-elf 0.8.0",
+]
+
[[package]]
name = "aster-time"
version = "0.1.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -296,6 +266,36 @@ dependencies = [
"xmas-elf 0.8.0",
]
+[[package]]
+name = "aster-rights"
+version = "0.1.0"
+dependencies = [
+ "aster-rights-proc",
+ "bitflags 1.3.2",
+ "typeflags",
+ "typeflags-util",
+]
+
+[[package]]
+name = "aster-rights-proc"
+version = "0.1.0"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "aster-runner"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "clap",
+ "linux-bzimage-builder",
+ "rand",
+ "xmas-elf 0.8.0",
+]
+
[[package]]
name = "aster-time"
version = "0.1.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -350,7 +350,7 @@ version = "0.3.0"
dependencies = [
"aster-frame",
"aster-framebuffer",
- "aster-std",
+ "aster-nix",
"aster-time",
"component",
"x86_64",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -350,7 +350,7 @@ version = "0.3.0"
dependencies = [
"aster-frame",
"aster-framebuffer",
- "aster-std",
+ "aster-nix",
"aster-time",
"component",
"x86_64",
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -9,7 +9,7 @@ path = "kernel/main.rs"
[dependencies]
aster-frame = { path = "framework/aster-frame" }
-aster-std = { path = "services/libs/aster-std" }
+aster-nix = { path = "services/aster-nix" }
component = { path = "services/libs/comp-sys/component" }
[dev-dependencies]
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -9,7 +9,7 @@ path = "kernel/main.rs"
[dependencies]
aster-frame = { path = "framework/aster-frame" }
-aster-std = { path = "services/libs/aster-std" }
+aster-nix = { path = "services/aster-nix" }
component = { path = "services/libs/comp-sys/component" }
[dev-dependencies]
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -40,6 +40,7 @@ members = [
"framework/libs/linux-bzimage/setup",
"framework/libs/ktest",
"framework/libs/tdx-guest",
+ "services/aster-nix",
"services/comps/block",
"services/comps/console",
"services/comps/framebuffer",
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -52,7 +53,6 @@ members = [
"services/libs/int-to-c-enum/derive",
"services/libs/aster-rights",
"services/libs/aster-rights-proc",
- "services/libs/aster-std",
"services/libs/aster-util",
"services/libs/keyable-arc",
"services/libs/typeflags",
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -52,7 +53,6 @@ members = [
"services/libs/int-to-c-enum/derive",
"services/libs/aster-rights",
"services/libs/aster-rights-proc",
- "services/libs/aster-std",
"services/libs/aster-util",
"services/libs/keyable-arc",
"services/libs/typeflags",
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -67,4 +67,4 @@ exclude = [
]
[features]
-intel_tdx = ["aster-frame/intel_tdx", "aster-std/intel_tdx"]
+intel_tdx = ["aster-frame/intel_tdx", "aster-nix/intel_tdx"]
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -67,4 +67,4 @@ exclude = [
]
[features]
-intel_tdx = ["aster-frame/intel_tdx", "aster-std/intel_tdx"]
+intel_tdx = ["aster-frame/intel_tdx", "aster-nix/intel_tdx"]
diff --git a/Components.toml b/Components.toml
--- a/Components.toml
+++ b/Components.toml
@@ -1,6 +1,6 @@
# template
[components]
-std = { name = "aster-std" }
+nix = { name = "aster-nix" }
virtio = { name = "aster-virtio" }
input = { name = "aster-input" }
block = { name = "aster-block" }
diff --git a/Components.toml b/Components.toml
--- a/Components.toml
+++ b/Components.toml
@@ -1,6 +1,6 @@
# template
[components]
-std = { name = "aster-std" }
+nix = { name = "aster-nix" }
virtio = { name = "aster-virtio" }
input = { name = "aster-input" }
block = { name = "aster-block" }
diff --git a/Components.toml b/Components.toml
--- a/Components.toml
+++ b/Components.toml
@@ -11,5 +11,5 @@ network = { name = "aster-network" }
main = { name = "asterinas" }
[whitelist]
-[whitelist.std.run_first_process]
+[whitelist.nix.run_first_process]
main = true
diff --git a/Components.toml b/Components.toml
--- a/Components.toml
+++ b/Components.toml
@@ -11,5 +11,5 @@ network = { name = "aster-network" }
main = { name = "asterinas" }
[whitelist]
-[whitelist.std.run_first_process]
+[whitelist.nix.run_first_process]
main = true
diff --git a/kernel/main.rs b/kernel/main.rs
--- a/kernel/main.rs
+++ b/kernel/main.rs
@@ -14,6 +14,6 @@ pub fn main() -> ! {
aster_frame::init();
early_println!("[kernel] finish init aster_frame");
component::init_all(component::parse_metadata!()).unwrap();
- aster_std::init();
- aster_std::run_first_process();
+ aster_nix::init();
+ aster_nix::run_first_process();
}
diff --git a/kernel/main.rs b/kernel/main.rs
--- a/kernel/main.rs
+++ b/kernel/main.rs
@@ -14,6 +14,6 @@ pub fn main() -> ! {
aster_frame::init();
early_println!("[kernel] finish init aster_frame");
component::init_all(component::parse_metadata!()).unwrap();
- aster_std::init();
- aster_std::run_first_process();
+ aster_nix::init();
+ aster_nix::run_first_process();
}
diff --git a/services/libs/aster-std/Cargo.toml b/services/aster-nix/Cargo.toml
--- a/services/libs/aster-std/Cargo.toml
+++ b/services/aster-nix/Cargo.toml
@@ -1,28 +1,28 @@
[package]
-name = "aster-std"
+name = "aster-nix"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
-aster-frame = { path = "../../../framework/aster-frame" }
-align_ext = { path = "../../../framework/libs/align_ext" }
+aster-frame = { path = "../../framework/aster-frame" }
+align_ext = { path = "../../framework/libs/align_ext" }
pod = { git = "https://github.com/asterinas/pod", rev = "d7dba56" }
-aster-input = { path = "../../comps/input" }
-aster-block = { path = "../../comps/block" }
-aster-network = { path = "../../comps/network" }
-aster-console = { path = "../../comps/console" }
-aster-time = { path = "../../comps/time" }
-aster-virtio = { path = "../../comps/virtio" }
-aster-rights = { path = "../aster-rights" }
-controlled = { path = "../../libs/comp-sys/controlled" }
-typeflags = { path = "../typeflags" }
-typeflags-util = { path = "../typeflags-util" }
-aster-rights-proc = { path = "../aster-rights-proc" }
-aster-util = { path = "../aster-util" }
-int-to-c-enum = { path = "../../libs/int-to-c-enum" }
-cpio-decoder = { path = "../cpio-decoder" }
+aster-input = { path = "../comps/input" }
+aster-block = { path = "../comps/block" }
+aster-network = { path = "../comps/network" }
+aster-console = { path = "../comps/console" }
+aster-time = { path = "../comps/time" }
+aster-virtio = { path = "../comps/virtio" }
+aster-rights = { path = "../libs/aster-rights" }
+controlled = { path = "../libs/comp-sys/controlled" }
+typeflags = { path = "../libs/typeflags" }
+typeflags-util = { path = "../libs/typeflags-util" }
+aster-rights-proc = { path = "../libs/aster-rights-proc" }
+aster-util = { path = "../libs/aster-util" }
+int-to-c-enum = { path = "../libs/int-to-c-enum" }
+cpio-decoder = { path = "../libs/cpio-decoder" }
ascii = { version = "1.1", default-features = false, features = ["alloc"] }
intrusive-collections = "0.9.5"
time = { version = "0.3", default-features = false, features = ["alloc"] }
diff --git a/services/libs/aster-std/Cargo.toml b/services/aster-nix/Cargo.toml
--- a/services/libs/aster-std/Cargo.toml
+++ b/services/aster-nix/Cargo.toml
@@ -1,28 +1,28 @@
[package]
-name = "aster-std"
+name = "aster-nix"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
-aster-frame = { path = "../../../framework/aster-frame" }
-align_ext = { path = "../../../framework/libs/align_ext" }
+aster-frame = { path = "../../framework/aster-frame" }
+align_ext = { path = "../../framework/libs/align_ext" }
pod = { git = "https://github.com/asterinas/pod", rev = "d7dba56" }
-aster-input = { path = "../../comps/input" }
-aster-block = { path = "../../comps/block" }
-aster-network = { path = "../../comps/network" }
-aster-console = { path = "../../comps/console" }
-aster-time = { path = "../../comps/time" }
-aster-virtio = { path = "../../comps/virtio" }
-aster-rights = { path = "../aster-rights" }
-controlled = { path = "../../libs/comp-sys/controlled" }
-typeflags = { path = "../typeflags" }
-typeflags-util = { path = "../typeflags-util" }
-aster-rights-proc = { path = "../aster-rights-proc" }
-aster-util = { path = "../aster-util" }
-int-to-c-enum = { path = "../../libs/int-to-c-enum" }
-cpio-decoder = { path = "../cpio-decoder" }
+aster-input = { path = "../comps/input" }
+aster-block = { path = "../comps/block" }
+aster-network = { path = "../comps/network" }
+aster-console = { path = "../comps/console" }
+aster-time = { path = "../comps/time" }
+aster-virtio = { path = "../comps/virtio" }
+aster-rights = { path = "../libs/aster-rights" }
+controlled = { path = "../libs/comp-sys/controlled" }
+typeflags = { path = "../libs/typeflags" }
+typeflags-util = { path = "../libs/typeflags-util" }
+aster-rights-proc = { path = "../libs/aster-rights-proc" }
+aster-util = { path = "../libs/aster-util" }
+int-to-c-enum = { path = "../libs/int-to-c-enum" }
+cpio-decoder = { path = "../libs/cpio-decoder" }
ascii = { version = "1.1", default-features = false, features = ["alloc"] }
intrusive-collections = "0.9.5"
time = { version = "0.3", default-features = false, features = ["alloc"] }
diff --git a/services/libs/aster-std/Cargo.toml b/services/aster-nix/Cargo.toml
--- a/services/libs/aster-std/Cargo.toml
+++ b/services/aster-nix/Cargo.toml
@@ -40,8 +40,8 @@ smoltcp = { version = "0.9.1", default-features = false, features = [
"socket-raw",
"socket-dhcpv4",
] }
-ktest = { path = "../../../framework/libs/ktest" }
-tdx-guest = { path = "../../../framework/libs/tdx-guest", optional = true }
+ktest = { path = "../../framework/libs/ktest" }
+tdx-guest = { path = "../../framework/libs/tdx-guest", optional = true }
# parse elf file
xmas-elf = "0.8.0"
diff --git a/services/libs/aster-std/Cargo.toml b/services/aster-nix/Cargo.toml
--- a/services/libs/aster-std/Cargo.toml
+++ b/services/aster-nix/Cargo.toml
@@ -49,7 +49,7 @@ xmas-elf = "0.8.0"
# data-structures
bitflags = "1.3"
ringbuf = { version = "0.3.2", default-features = false, features = ["alloc"] }
-keyable-arc = { path = "../keyable-arc" }
+keyable-arc = { path = "../libs/keyable-arc" }
# unzip initramfs
libflate = { git = "https://github.com/asterinas/libflate", rev = "b781da6", features = [
"no_std",
diff --git a/services/libs/aster-std/Cargo.toml b/services/aster-nix/Cargo.toml
--- a/services/libs/aster-std/Cargo.toml
+++ b/services/aster-nix/Cargo.toml
@@ -49,7 +49,7 @@ xmas-elf = "0.8.0"
# data-structures
bitflags = "1.3"
ringbuf = { version = "0.3.2", default-features = false, features = ["alloc"] }
-keyable-arc = { path = "../keyable-arc" }
+keyable-arc = { path = "../libs/keyable-arc" }
# unzip initramfs
libflate = { git = "https://github.com/asterinas/libflate", rev = "b781da6", features = [
"no_std",
diff --git a/services/libs/aster-std/src/lib.rs b/services/aster-nix/src/lib.rs
--- a/services/libs/aster-std/src/lib.rs
+++ b/services/aster-nix/src/lib.rs
@@ -89,7 +89,7 @@ fn init_thread() {
}));
thread.join();
info!(
- "[aster-std/lib.rs] spawn kernel thread, tid = {}",
+ "[aster-nix/lib.rs] spawn kernel thread, tid = {}",
thread.tid()
);
thread::work_queue::init();
diff --git a/services/libs/aster-std/src/lib.rs b/services/aster-nix/src/lib.rs
--- a/services/libs/aster-std/src/lib.rs
+++ b/services/aster-nix/src/lib.rs
@@ -89,7 +89,7 @@ fn init_thread() {
}));
thread.join();
info!(
- "[aster-std/lib.rs] spawn kernel thread, tid = {}",
+ "[aster-nix/lib.rs] spawn kernel thread, tid = {}",
thread.tid()
);
thread::work_queue::init();
|
2024-02-05T08:00:55Z
|
8d456ebe8fc200fc11c75654fdca2f0dd896e656
|
|
asterinas/asterinas
|
diff --git a/regression/apps/scripts/network.sh b/regression/apps/scripts/network.sh
--- a/regression/apps/scripts/network.sh
+++ b/regression/apps/scripts/network.sh
@@ -18,7 +18,7 @@ echo "Start network test......"
./socketpair
./sockoption
./listen_backlog
-./send_buf_full
+# ./send_buf_full
echo "All network test passed"
|
[
"625"
] |
0.4
|
b450eef1660c0362ba65de07a3bd03c8199c3265
|
Support for in-kernel sleep
Currently sleep function we provide seems to be the only `pauser.pause_until_or_timeout()` for the POSIX threads from users, as in the `clock_nanosleep` syscall. However, some functionalities within kernel also need sleep like
https://github.com/asterinas/asterinas/blob/bd6f65667df494f6fb88fc60eb4ed18a106bed71/services/libs/aster-std/src/net/iface/util.rs#L49-L76
Without the support for kernel-level sleep, the polling would consume all the CPU cycles just to busy polling, while there is already hint for how long it should wait.
|
asterinas__asterinas-630
| 630
|
diff --git a/kernel/aster-nix/src/net/iface/common.rs b/kernel/aster-nix/src/net/iface/common.rs
--- a/kernel/aster-nix/src/net/iface/common.rs
+++ b/kernel/aster-nix/src/net/iface/common.rs
@@ -3,6 +3,7 @@
use alloc::collections::btree_map::Entry;
use core::sync::atomic::{AtomicU64, Ordering};
+use aster_frame::sync::WaitQueue;
use keyable_arc::KeyableWeak;
use smoltcp::{
iface::{SocketHandle, SocketSet},
diff --git a/kernel/aster-nix/src/net/iface/common.rs b/kernel/aster-nix/src/net/iface/common.rs
--- a/kernel/aster-nix/src/net/iface/common.rs
+++ b/kernel/aster-nix/src/net/iface/common.rs
@@ -3,6 +3,7 @@
use alloc::collections::btree_map::Entry;
use core::sync::atomic::{AtomicU64, Ordering};
+use aster_frame::sync::WaitQueue;
use keyable_arc::KeyableWeak;
use smoltcp::{
iface::{SocketHandle, SocketSet},
diff --git a/kernel/aster-nix/src/net/iface/common.rs b/kernel/aster-nix/src/net/iface/common.rs
--- a/kernel/aster-nix/src/net/iface/common.rs
+++ b/kernel/aster-nix/src/net/iface/common.rs
@@ -22,9 +23,11 @@ pub struct IfaceCommon {
interface: SpinLock<smoltcp::iface::Interface>,
sockets: SpinLock<SocketSet<'static>>,
used_ports: RwLock<BTreeMap<u16, usize>>,
- /// The time should do next poll. We stores the total microseconds since system boots up.
+ /// The time should do next poll. We stores the total milliseconds since system boots up.
next_poll_at_ms: AtomicU64,
bound_sockets: RwLock<BTreeSet<KeyableWeak<AnyBoundSocket>>>,
+ /// The wait queue that background polling thread will sleep on
+ polling_wait_queue: WaitQueue,
}
impl IfaceCommon {
diff --git a/kernel/aster-nix/src/net/iface/common.rs b/kernel/aster-nix/src/net/iface/common.rs
--- a/kernel/aster-nix/src/net/iface/common.rs
+++ b/kernel/aster-nix/src/net/iface/common.rs
@@ -22,9 +23,11 @@ pub struct IfaceCommon {
interface: SpinLock<smoltcp::iface::Interface>,
sockets: SpinLock<SocketSet<'static>>,
used_ports: RwLock<BTreeMap<u16, usize>>,
- /// The time should do next poll. We stores the total microseconds since system boots up.
+ /// The time should do next poll. We stores the total milliseconds since system boots up.
next_poll_at_ms: AtomicU64,
bound_sockets: RwLock<BTreeSet<KeyableWeak<AnyBoundSocket>>>,
+ /// The wait queue that background polling thread will sleep on
+ polling_wait_queue: WaitQueue,
}
impl IfaceCommon {
diff --git a/kernel/aster-nix/src/net/iface/common.rs b/kernel/aster-nix/src/net/iface/common.rs
--- a/kernel/aster-nix/src/net/iface/common.rs
+++ b/kernel/aster-nix/src/net/iface/common.rs
@@ -37,6 +40,7 @@ impl IfaceCommon {
used_ports: RwLock::new(used_ports),
next_poll_at_ms: AtomicU64::new(0),
bound_sockets: RwLock::new(BTreeSet::new()),
+ polling_wait_queue: WaitQueue::new(),
}
}
diff --git a/kernel/aster-nix/src/net/iface/common.rs b/kernel/aster-nix/src/net/iface/common.rs
--- a/kernel/aster-nix/src/net/iface/common.rs
+++ b/kernel/aster-nix/src/net/iface/common.rs
@@ -37,6 +40,7 @@ impl IfaceCommon {
used_ports: RwLock::new(used_ports),
next_poll_at_ms: AtomicU64::new(0),
bound_sockets: RwLock::new(BTreeSet::new()),
+ polling_wait_queue: WaitQueue::new(),
}
}
diff --git a/kernel/aster-nix/src/net/iface/common.rs b/kernel/aster-nix/src/net/iface/common.rs
--- a/kernel/aster-nix/src/net/iface/common.rs
+++ b/kernel/aster-nix/src/net/iface/common.rs
@@ -60,6 +64,10 @@ impl IfaceCommon {
})
}
+ pub(super) fn polling_wait_queue(&self) -> &WaitQueue {
+ &self.polling_wait_queue
+ }
+
/// Alloc an unused port range from 49152 ~ 65535 (According to smoltcp docs)
fn alloc_ephemeral_port(&self) -> Result<u16> {
let mut used_ports = self.used_ports.write();
diff --git a/kernel/aster-nix/src/net/iface/common.rs b/kernel/aster-nix/src/net/iface/common.rs
--- a/kernel/aster-nix/src/net/iface/common.rs
+++ b/kernel/aster-nix/src/net/iface/common.rs
@@ -60,6 +64,10 @@ impl IfaceCommon {
})
}
+ pub(super) fn polling_wait_queue(&self) -> &WaitQueue {
+ &self.polling_wait_queue
+ }
+
/// Alloc an unused port range from 49152 ~ 65535 (According to smoltcp docs)
fn alloc_ephemeral_port(&self) -> Result<u16> {
let mut used_ports = self.used_ports.write();
diff --git a/kernel/aster-nix/src/net/iface/common.rs b/kernel/aster-nix/src/net/iface/common.rs
--- a/kernel/aster-nix/src/net/iface/common.rs
+++ b/kernel/aster-nix/src/net/iface/common.rs
@@ -155,10 +163,16 @@ impl IfaceCommon {
let sockets = self.sockets.lock_irq_disabled();
if let Some(instant) = interface.poll_at(timestamp, &sockets) {
+ let old_instant = self.next_poll_at_ms.load(Ordering::Acquire);
+ let new_instant = instant.total_millis() as u64;
self.next_poll_at_ms
- .store(instant.total_millis() as u64, Ordering::SeqCst);
+ .store(instant.total_millis() as u64, Ordering::Relaxed);
+
+ if new_instant < old_instant {
+ self.polling_wait_queue.wake_all();
+ }
} else {
- self.next_poll_at_ms.store(0, Ordering::SeqCst);
+ self.next_poll_at_ms.store(0, Ordering::Relaxed);
}
}
diff --git a/kernel/aster-nix/src/net/iface/common.rs b/kernel/aster-nix/src/net/iface/common.rs
--- a/kernel/aster-nix/src/net/iface/common.rs
+++ b/kernel/aster-nix/src/net/iface/common.rs
@@ -155,10 +163,16 @@ impl IfaceCommon {
let sockets = self.sockets.lock_irq_disabled();
if let Some(instant) = interface.poll_at(timestamp, &sockets) {
+ let old_instant = self.next_poll_at_ms.load(Ordering::Acquire);
+ let new_instant = instant.total_millis() as u64;
self.next_poll_at_ms
- .store(instant.total_millis() as u64, Ordering::SeqCst);
+ .store(instant.total_millis() as u64, Ordering::Relaxed);
+
+ if new_instant < old_instant {
+ self.polling_wait_queue.wake_all();
+ }
} else {
- self.next_poll_at_ms.store(0, Ordering::SeqCst);
+ self.next_poll_at_ms.store(0, Ordering::Relaxed);
}
}
diff --git a/kernel/aster-nix/src/net/iface/mod.rs b/kernel/aster-nix/src/net/iface/mod.rs
--- a/kernel/aster-nix/src/net/iface/mod.rs
+++ b/kernel/aster-nix/src/net/iface/mod.rs
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: MPL-2.0
+use aster_frame::sync::WaitQueue;
use smoltcp::iface::SocketSet;
use self::common::IfaceCommon;
diff --git a/kernel/aster-nix/src/net/iface/mod.rs b/kernel/aster-nix/src/net/iface/mod.rs
--- a/kernel/aster-nix/src/net/iface/mod.rs
+++ b/kernel/aster-nix/src/net/iface/mod.rs
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: MPL-2.0
+use aster_frame::sync::WaitQueue;
use smoltcp::iface::SocketSet;
use self::common::IfaceCommon;
diff --git a/kernel/aster-nix/src/net/iface/mod.rs b/kernel/aster-nix/src/net/iface/mod.rs
--- a/kernel/aster-nix/src/net/iface/mod.rs
+++ b/kernel/aster-nix/src/net/iface/mod.rs
@@ -60,6 +61,11 @@ pub trait Iface: internal::IfaceInternal + Send + Sync {
fn netmask(&self) -> Option<Ipv4Address> {
self.common().netmask()
}
+
+ /// The waitqueue used to background polling thread
+ fn polling_wait_queue(&self) -> &WaitQueue {
+ self.common().polling_wait_queue()
+ }
}
mod internal {
diff --git a/kernel/aster-nix/src/net/iface/mod.rs b/kernel/aster-nix/src/net/iface/mod.rs
--- a/kernel/aster-nix/src/net/iface/mod.rs
+++ b/kernel/aster-nix/src/net/iface/mod.rs
@@ -60,6 +61,11 @@ pub trait Iface: internal::IfaceInternal + Send + Sync {
fn netmask(&self) -> Option<Ipv4Address> {
self.common().netmask()
}
+
+ /// The waitqueue used to background polling thread
+ fn polling_wait_queue(&self) -> &WaitQueue {
+ self.common().polling_wait_queue()
+ }
}
mod internal {
diff --git a/kernel/aster-nix/src/net/iface/util.rs b/kernel/aster-nix/src/net/iface/util.rs
--- a/kernel/aster-nix/src/net/iface/util.rs
+++ b/kernel/aster-nix/src/net/iface/util.rs
@@ -1,6 +1,8 @@
// SPDX-License-Identifier: MPL-2.0
-use aster_frame::timer::read_monotonic_milli_seconds;
+use core::time::Duration;
+
+use aster_frame::{task::Priority, timer::read_monotonic_milli_seconds};
use super::Iface;
use crate::{
diff --git a/kernel/aster-nix/src/net/iface/util.rs b/kernel/aster-nix/src/net/iface/util.rs
--- a/kernel/aster-nix/src/net/iface/util.rs
+++ b/kernel/aster-nix/src/net/iface/util.rs
@@ -1,6 +1,8 @@
// SPDX-License-Identifier: MPL-2.0
-use aster_frame::timer::read_monotonic_milli_seconds;
+use core::time::Duration;
+
+use aster_frame::{task::Priority, timer::read_monotonic_milli_seconds};
use super::Iface;
use crate::{
diff --git a/kernel/aster-nix/src/net/iface/util.rs b/kernel/aster-nix/src/net/iface/util.rs
--- a/kernel/aster-nix/src/net/iface/util.rs
+++ b/kernel/aster-nix/src/net/iface/util.rs
@@ -46,30 +48,40 @@ impl BindPortConfig {
}
pub fn spawn_background_poll_thread(iface: Arc<dyn Iface>) {
- // FIXME: use timer or wait_timeout when timer is enable.
let task_fn = move || {
- debug!("spawn background poll thread");
+ trace!("spawn background poll thread for {}", iface.name());
+ let wait_queue = iface.polling_wait_queue();
loop {
- let next_poll_time = if let Some(next_poll_time) = iface.next_poll_at_ms() {
- next_poll_time
+ let next_poll_at_ms = if let Some(next_poll_at_ms) = iface.next_poll_at_ms() {
+ next_poll_at_ms
} else {
- Thread::yield_now();
- continue;
+ wait_queue.wait_until(|| iface.next_poll_at_ms())
};
- let now = read_monotonic_milli_seconds();
- if now > next_poll_time {
- // FIXME: now is later than next poll time. This may cause problem.
+
+ let now_as_ms = read_monotonic_milli_seconds();
+
+ // FIXME: Ideally, we should perform the `poll` just before `next_poll_at_ms`.
+ // However, this approach may result in a spinning busy loop
+ // if the `poll` operation yields no results.
+ // To mitigate this issue,
+ // we have opted to assign a high priority to the polling thread,
+ // ensuring that the `poll` runs as soon as possible.
+ // For a more in-depth discussion, please refer to the following link:
+ // <https://github.com/asterinas/asterinas/pull/630#discussion_r1496817030>.
+ if now_as_ms >= next_poll_at_ms {
iface.poll();
continue;
}
- let duration = next_poll_time - now;
- // FIXME: choose a suitable time interval
- if duration < 10 {
- iface.poll();
- } else {
- Thread::yield_now();
- }
+
+ let duration = Duration::from_millis(next_poll_at_ms - now_as_ms);
+ wait_queue.wait_until_or_timeout(
+ // If `iface.next_poll_at_ms()` changes to an earlier time, we will end the waiting.
+ || (iface.next_poll_at_ms()? < next_poll_at_ms).then_some(()),
+ &duration,
+ );
}
};
- Thread::spawn_kernel_thread(ThreadOptions::new(task_fn));
+
+ let options = ThreadOptions::new(task_fn).priority(Priority::high());
+ Thread::spawn_kernel_thread(options);
}
diff --git a/kernel/aster-nix/src/net/iface/util.rs b/kernel/aster-nix/src/net/iface/util.rs
--- a/kernel/aster-nix/src/net/iface/util.rs
+++ b/kernel/aster-nix/src/net/iface/util.rs
@@ -46,30 +48,40 @@ impl BindPortConfig {
}
pub fn spawn_background_poll_thread(iface: Arc<dyn Iface>) {
- // FIXME: use timer or wait_timeout when timer is enable.
let task_fn = move || {
- debug!("spawn background poll thread");
+ trace!("spawn background poll thread for {}", iface.name());
+ let wait_queue = iface.polling_wait_queue();
loop {
- let next_poll_time = if let Some(next_poll_time) = iface.next_poll_at_ms() {
- next_poll_time
+ let next_poll_at_ms = if let Some(next_poll_at_ms) = iface.next_poll_at_ms() {
+ next_poll_at_ms
} else {
- Thread::yield_now();
- continue;
+ wait_queue.wait_until(|| iface.next_poll_at_ms())
};
- let now = read_monotonic_milli_seconds();
- if now > next_poll_time {
- // FIXME: now is later than next poll time. This may cause problem.
+
+ let now_as_ms = read_monotonic_milli_seconds();
+
+ // FIXME: Ideally, we should perform the `poll` just before `next_poll_at_ms`.
+ // However, this approach may result in a spinning busy loop
+ // if the `poll` operation yields no results.
+ // To mitigate this issue,
+ // we have opted to assign a high priority to the polling thread,
+ // ensuring that the `poll` runs as soon as possible.
+ // For a more in-depth discussion, please refer to the following link:
+ // <https://github.com/asterinas/asterinas/pull/630#discussion_r1496817030>.
+ if now_as_ms >= next_poll_at_ms {
iface.poll();
continue;
}
- let duration = next_poll_time - now;
- // FIXME: choose a suitable time interval
- if duration < 10 {
- iface.poll();
- } else {
- Thread::yield_now();
- }
+
+ let duration = Duration::from_millis(next_poll_at_ms - now_as_ms);
+ wait_queue.wait_until_or_timeout(
+ // If `iface.next_poll_at_ms()` changes to an earlier time, we will end the waiting.
+ || (iface.next_poll_at_ms()? < next_poll_at_ms).then_some(()),
+ &duration,
+ );
}
};
- Thread::spawn_kernel_thread(ThreadOptions::new(task_fn));
+
+ let options = ThreadOptions::new(task_fn).priority(Priority::high());
+ Thread::spawn_kernel_thread(options);
}
diff --git a/regression/apps/scripts/network.sh b/regression/apps/scripts/network.sh
--- a/regression/apps/scripts/network.sh
+++ b/regression/apps/scripts/network.sh
@@ -18,7 +18,7 @@ echo "Start network test......"
./socketpair
./sockoption
./listen_backlog
-./send_buf_full
+# ./send_buf_full
echo "All network test passed"
|
In-kernel sleep is supported. A kernel thread can sleep using the `WaitQueue` API provided by the Framework. `Pauser` is in fact based on `WaitQueue`.
In theory, the specific code snippet you show can and should be refactored using `WaitQueue` to avoid busy looping. But it is written that way. Why? My guess is that at the time when this busy loop is written, the timer API of the Framework is not ready.
```rust
// FIXME: use timer or wait_timeout when timer is enable.
```
@StevenJiang1110 is the original author so his answer is the most wanted.
Yes, the origin code is added when `WaitQueue` cannot accept a `timeout` parameter. Since timeout is supported now, we can avoid using busy loop here. #630 provides a fix for this problem.
|
2024-01-29T03:53:41Z
|
e210e68920481c911f62f03ade0a780f96e48e24
|
asterinas/asterinas
|
diff --git /dev/null b/.github/workflows/license_check.yml
new file mode 100644
--- /dev/null
+++ b/.github/workflows/license_check.yml
@@ -0,0 +1,14 @@
+name: Check License
+on:
+ pull_request:
+ push:
+ branches:
+ - main
+jobs:
+ check-license-lines:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@master
+ - name: Check License
+ # Check license lines of each file in this repository.
+ uses: apache/skywalking-eyes@v0.5.0
diff --git /dev/null b/.licenserc.yaml
new file mode 100644
--- /dev/null
+++ b/.licenserc.yaml
@@ -0,0 +1,61 @@
+# This is the configuration file for github action License Eye Header. The action is used
+# to check that each source file contains the license header lines. For the configuration
+# details, see https://github.com/marketplace/actions/license-eye-header#configurations.
+
+header:
+ # Files are licensed under MPL-2.0, by default.
+ - paths:
+ - '**/*.rs'
+ - '**/*.S'
+ - '**/*.s'
+ - '**/*.c'
+ - '**/*.sh'
+ - '**/Makefile'
+ - '**/Dockerfile.*'
+ paths-ignore:
+ # These directories are licensed under licenses other than MPL-2.0.
+ - 'services/libs/comp-sys/cargo-component'
+ - 'framework/libs/tdx-guest'
+ license:
+ content: |
+ SPDX-License-Identifier: MPL-2.0
+ language:
+ # License Eye Header cannot recognize files with extension .S, so we add
+ # the definition here.
+ Assembly:
+ extensions:
+ - ".S"
+ comment_style_id: SlashAsterisk
+
+ # Files under tdx-guest are licensed under BSD-3-Clause license.
+ - paths:
+ - 'framework/libs/tdx-guest/**'
+ paths-ignore:
+ - 'Cargo.toml'
+ - '.gitignore'
+ license:
+ content: |
+ SPDX-License-Identifier: BSD-3-Clause
+ Copyright(c) 2023-2024 Intel Corporation.
+
+ # Files under cargo-component are licensed under Apache-2.0 or MIT license.
+ - paths:
+ - 'services/libs/comp-sys/cargo-component/**'
+ paths-ignore:
+ - '**/*.md'
+ - '**/*.toml'
+ - 'Cargo.lock'
+ - '.gitignore'
+ # These directories do not contain test source code and are just for test input.
+ - '**/tests/duplicate_lib_name_test/**'
+ - '**/tests/missing_toml_test/**'
+ - '**/tests/reexport_test/**'
+ - '**/tests/regression_test/**'
+ - '**/tests/trait_method_test/**'
+ - '**/tests/violate_policy_test/**'
+
+ license:
+ content: |
+ Licensed under the Apache License, Version 2.0 or the MIT License.
+ Copyright (C) 2023-2024 Ant Group.
+
\ No newline at end of file
diff --git a/framework/libs/align_ext/src/lib.rs b/framework/libs/align_ext/src/lib.rs
--- a/framework/libs/align_ext/src/lib.rs
+++ b/framework/libs/align_ext/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#![cfg_attr(not(test), no_std)]
/// An extension trait for Rust integer types, including `u8`, `u16`, `u32`,
diff --git a/framework/libs/ktest-proc-macro/src/lib.rs b/framework/libs/ktest-proc-macro/src/lib.rs
--- a/framework/libs/ktest-proc-macro/src/lib.rs
+++ b/framework/libs/ktest-proc-macro/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#![feature(proc_macro_span)]
extern crate proc_macro2;
diff --git a/framework/libs/ktest/src/lib.rs b/framework/libs/ktest/src/lib.rs
--- a/framework/libs/ktest/src/lib.rs
+++ b/framework/libs/ktest/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! # The kernel mode testing framework of Asterinas.
//!
//! `ktest` stands for kernel-mode testing framework. Its goal is to provide a
diff --git a/framework/libs/ktest/src/path.rs b/framework/libs/ktest/src/path.rs
--- a/framework/libs/ktest/src/path.rs
+++ b/framework/libs/ktest/src/path.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::{
collections::{vec_deque, BTreeMap, VecDeque},
string::{String, ToString},
diff --git a/framework/libs/ktest/src/runner.rs b/framework/libs/ktest/src/runner.rs
--- a/framework/libs/ktest/src/runner.rs
+++ b/framework/libs/ktest/src/runner.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Test runner enabling control over the tests.
//!
diff --git a/framework/libs/ktest/src/tree.rs b/framework/libs/ktest/src/tree.rs
--- a/framework/libs/ktest/src/tree.rs
+++ b/framework/libs/ktest/src/tree.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The source module tree of ktests.
//!
//! In the `KtestTree`, the root is abstract, and the children of the root are the
diff --git a/regression/apps/execve/Makefile b/regression/apps/execve/Makefile
--- a/regression/apps/execve/Makefile
+++ b/regression/apps/execve/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
include ../test_common.mk
EXTRA_C_FLAGS :=-static
diff --git a/regression/apps/fork/Makefile b/regression/apps/fork/Makefile
--- a/regression/apps/fork/Makefile
+++ b/regression/apps/fork/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
include ../test_common.mk
EXTRA_C_FLAGS :=-static -nostdlib
diff --git a/regression/apps/fork_c/Makefile b/regression/apps/fork_c/Makefile
--- a/regression/apps/fork_c/Makefile
+++ b/regression/apps/fork_c/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
include ../test_common.mk
EXTRA_C_FLAGS :=-static
diff --git a/regression/apps/hello_c/Makefile b/regression/apps/hello_c/Makefile
--- a/regression/apps/hello_c/Makefile
+++ b/regression/apps/hello_c/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
include ../test_common.mk
EXTRA_C_FLAGS :=-static -mno-sse
diff --git a/regression/apps/hello_pie/Makefile b/regression/apps/hello_pie/Makefile
--- a/regression/apps/hello_pie/Makefile
+++ b/regression/apps/hello_pie/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
include ../test_common.mk
EXTRA_C_FLAGS :=
diff --git a/regression/apps/hello_world/Makefile b/regression/apps/hello_world/Makefile
--- a/regression/apps/hello_world/Makefile
+++ b/regression/apps/hello_world/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
include ../test_common.mk
EXTRA_C_FLAGS :=-static -nostdlib
diff --git a/regression/apps/network/Makefile b/regression/apps/network/Makefile
--- a/regression/apps/network/Makefile
+++ b/regression/apps/network/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
include ../test_common.mk
EXTRA_C_FLAGS :=
diff --git a/regression/apps/pthread/Makefile b/regression/apps/pthread/Makefile
--- a/regression/apps/pthread/Makefile
+++ b/regression/apps/pthread/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
include ../test_common.mk
EXTRA_C_FLAGS :=-static -lpthread
diff --git a/regression/apps/pthread/pthread_test.c b/regression/apps/pthread/pthread_test.c
--- a/regression/apps/pthread/pthread_test.c
+++ b/regression/apps/pthread/pthread_test.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
// This test file is from occlum pthread test.
#include <sys/types.h>
diff --git a/regression/apps/pty/Makefile b/regression/apps/pty/Makefile
--- a/regression/apps/pty/Makefile
+++ b/regression/apps/pty/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
include ../test_common.mk
EXTRA_C_FLAGS :=
diff --git a/regression/apps/scripts/run_regression_test.sh b/regression/apps/scripts/run_regression_test.sh
--- a/regression/apps/scripts/run_regression_test.sh
+++ b/regression/apps/scripts/run_regression_test.sh
@@ -1,5 +1,7 @@
#!/bin/sh
+# SPDX-License-Identifier: MPL-2.0
+
set -e
SCRIPT_DIR=/regression
diff --git a/regression/apps/signal_c/Makefile b/regression/apps/signal_c/Makefile
--- a/regression/apps/signal_c/Makefile
+++ b/regression/apps/signal_c/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
include ../test_common.mk
EXTRA_C_FLAGS :=-static
diff --git a/regression/apps/signal_c/signal_test.c b/regression/apps/signal_c/signal_test.c
--- a/regression/apps/signal_c/signal_test.c
+++ b/regression/apps/signal_c/signal_test.c
@@ -1,4 +1,6 @@
-// This test file is from occlum, to test whether we implement signal correctly.
+// SPDX-License-Identifier: MPL-2.0
+
+// This test file is from occlum signal test.
#define _GNU_SOURCE
#include <sys/types.h>
diff --git a/regression/apps/test_common.mk b/regression/apps/test_common.mk
--- a/regression/apps/test_common.mk
+++ b/regression/apps/test_common.mk
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
MAIN_MAKEFILE := $(firstword $(MAKEFILE_LIST))
INCLUDE_MAKEFILE := $(lastword $(MAKEFILE_LIST))
CUR_DIR := $(shell dirname $(realpath $(MAIN_MAKEFILE)))
diff --git a/regression/syscall_test/Makefile b/regression/syscall_test/Makefile
--- a/regression/syscall_test/Makefile
+++ b/regression/syscall_test/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
TESTS ?= chmod_test fsync_test getdents_test link_test lseek_test mkdir_test \
open_create_test open_test pty_test read_test rename_test stat_test \
statfs_test symlink_test sync_test uidgid_test unlink_test \
diff --git a/regression/syscall_test/run_syscall_test.sh b/regression/syscall_test/run_syscall_test.sh
--- a/regression/syscall_test/run_syscall_test.sh
+++ b/regression/syscall_test/run_syscall_test.sh
@@ -1,5 +1,7 @@
#!/bin/sh
+# SPDX-License-Identifier: MPL-2.0
+
SCRIPT_DIR=$(dirname "$0")
TEST_TMP_DIR=${SYSCALL_TEST_DIR:-/tmp}
TEST_BIN_DIR=$SCRIPT_DIR/tests
diff --git a/runner/src/main.rs b/runner/src/main.rs
--- a/runner/src/main.rs
+++ b/runner/src/main.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! aster-runner is the Asterinas runner script to ease the pain of running
//! and testing Asterinas inside a QEMU VM. It should be built and run as the
//! cargo runner: https://doc.rust-lang.org/cargo/reference/config.html
diff --git a/services/libs/comp-sys/cargo-component/tests/duplicate_lib_name.rs b/services/libs/comp-sys/cargo-component/tests/duplicate_lib_name.rs
--- a/services/libs/comp-sys/cargo-component/tests/duplicate_lib_name.rs
+++ b/services/libs/comp-sys/cargo-component/tests/duplicate_lib_name.rs
@@ -1,3 +1,6 @@
+// Licensed under the Apache License, Version 2.0 or the MIT License.
+// Copyright (C) 2023-2024 Ant Group.
+
//! This test checks that if two components have same name, the compiler will panic.
#![feature(once_cell)]
diff --git a/services/libs/comp-sys/cargo-component/tests/missing_toml.rs b/services/libs/comp-sys/cargo-component/tests/missing_toml.rs
--- a/services/libs/comp-sys/cargo-component/tests/missing_toml.rs
+++ b/services/libs/comp-sys/cargo-component/tests/missing_toml.rs
@@ -1,3 +1,6 @@
+// Licensed under the Apache License, Version 2.0 or the MIT License.
+// Copyright (C) 2023-2024 Ant Group.
+
//! This test checks that if Components.toml is missed, the compiler will panic.
#![feature(once_cell)]
diff --git a/services/libs/comp-sys/cargo-component/tests/reexport.rs b/services/libs/comp-sys/cargo-component/tests/reexport.rs
--- a/services/libs/comp-sys/cargo-component/tests/reexport.rs
+++ b/services/libs/comp-sys/cargo-component/tests/reexport.rs
@@ -1,3 +1,6 @@
+// Licensed under the Apache License, Version 2.0 or the MIT License.
+// Copyright (C) 2023-2024 Ant Group.
+
//! This test checks that if cargo-component can control reexported entry points.
#![feature(once_cell)]
diff --git a/services/libs/comp-sys/cargo-component/tests/regression.rs b/services/libs/comp-sys/cargo-component/tests/regression.rs
--- a/services/libs/comp-sys/cargo-component/tests/regression.rs
+++ b/services/libs/comp-sys/cargo-component/tests/regression.rs
@@ -1,3 +1,6 @@
+// Licensed under the Apache License, Version 2.0 or the MIT License.
+// Copyright (C) 2023-2024 Ant Group.
+
//! This test checks that visiting controlled resources in whitelist is allowed.
#![feature(once_cell)]
diff --git a/services/libs/comp-sys/cargo-component/tests/test_utils/mod.rs b/services/libs/comp-sys/cargo-component/tests/test_utils/mod.rs
--- a/services/libs/comp-sys/cargo-component/tests/test_utils/mod.rs
+++ b/services/libs/comp-sys/cargo-component/tests/test_utils/mod.rs
@@ -1,3 +1,6 @@
+// Licensed under the Apache License, Version 2.0 or the MIT License.
+// Copyright (C) 2023-2024 Ant Group.
+
#![allow(unused)]
use std::path::PathBuf;
diff --git a/services/libs/comp-sys/cargo-component/tests/trait_method.rs b/services/libs/comp-sys/cargo-component/tests/trait_method.rs
--- a/services/libs/comp-sys/cargo-component/tests/trait_method.rs
+++ b/services/libs/comp-sys/cargo-component/tests/trait_method.rs
@@ -1,3 +1,6 @@
+// Licensed under the Apache License, Version 2.0 or the MIT License.
+// Copyright (C) 2023-2024 Ant Group.
+
//! This test checks that if cargo-component can control method and trait method
#![feature(once_cell)]
diff --git a/services/libs/comp-sys/cargo-component/tests/violate_policy.rs b/services/libs/comp-sys/cargo-component/tests/violate_policy.rs
--- a/services/libs/comp-sys/cargo-component/tests/violate_policy.rs
+++ b/services/libs/comp-sys/cargo-component/tests/violate_policy.rs
@@ -1,4 +1,8 @@
-//! This test checks that if controlled resource not in whitelist is visited, cargo-component will report warning message.
+// Licensed under the Apache License, Version 2.0 or the MIT License.
+// Copyright (C) 2023-2024 Ant Group.
+
+//! This test checks that if controlled resource not in whitelist is visited, cargo-component will
+//! report warning message.
#![feature(once_cell)]
diff --git a/services/libs/comp-sys/component/tests/init-order/first-init/src/lib.rs b/services/libs/comp-sys/component/tests/init-order/first-init/src/lib.rs
--- a/services/libs/comp-sys/component/tests/init-order/first-init/src/lib.rs
+++ b/services/libs/comp-sys/component/tests/init-order/first-init/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::Relaxed;
diff --git a/services/libs/comp-sys/component/tests/init-order/second-init/src/lib.rs b/services/libs/comp-sys/component/tests/init-order/second-init/src/lib.rs
--- a/services/libs/comp-sys/component/tests/init-order/second-init/src/lib.rs
+++ b/services/libs/comp-sys/component/tests/init-order/second-init/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use std::sync::atomic::{Ordering::Relaxed, AtomicBool};
use component::init_component;
diff --git a/services/libs/comp-sys/component/tests/init-order/second-init/tests/test.rs b/services/libs/comp-sys/component/tests/init-order/second-init/tests/test.rs
--- a/services/libs/comp-sys/component/tests/init-order/second-init/tests/test.rs
+++ b/services/libs/comp-sys/component/tests/init-order/second-init/tests/test.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use second_init::HAS_INIT;
use std::sync::atomic::Ordering::Relaxed;
diff --git a/services/libs/comp-sys/component/tests/init-order/src/main.rs b/services/libs/comp-sys/component/tests/init-order/src/main.rs
--- a/services/libs/comp-sys/component/tests/init-order/src/main.rs
+++ b/services/libs/comp-sys/component/tests/init-order/src/main.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use std::sync::atomic::{Ordering::Relaxed, AtomicBool};
use component::init_component;
diff --git a/services/libs/comp-sys/component/tests/init-order/tests/test.rs b/services/libs/comp-sys/component/tests/init-order/tests/test.rs
--- a/services/libs/comp-sys/component/tests/init-order/tests/test.rs
+++ b/services/libs/comp-sys/component/tests/init-order/tests/test.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use first_init::HAS_INIT;
use component::init_component;
use std::sync::atomic::Ordering::Relaxed;
diff --git a/services/libs/cpio-decoder/src/test.rs b/services/libs/cpio-decoder/src/test.rs
--- a/services/libs/cpio-decoder/src/test.rs
+++ b/services/libs/cpio-decoder/src/test.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::error::*;
use super::{CpioDecoder, FileType};
use lending_iterator::LendingIterator;
diff --git a/services/libs/int-to-c-enum/tests/regression.rs b/services/libs/int-to-c-enum/tests/regression.rs
--- a/services/libs/int-to-c-enum/tests/regression.rs
+++ b/services/libs/int-to-c-enum/tests/regression.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use int_to_c_enum::TryFromInt;
#[derive(TryFromInt, Debug, PartialEq, Eq)]
|
[
"555"
] |
0.3
|
5fb8a9f7e558977a8027eec32565a2de6b87636b
|
Add copyright and license info to the header of every file
Need to insert the copyright header to every source code file.
Here is the header for each Rust file.
```rust
// SPDX-License-Identifier: MPL-2.0
```
|
asterinas__asterinas-567
| 567
|
diff --git /dev/null b/.github/workflows/license_check.yml
new file mode 100644
--- /dev/null
+++ b/.github/workflows/license_check.yml
@@ -0,0 +1,14 @@
+name: Check License
+on:
+ pull_request:
+ push:
+ branches:
+ - main
+jobs:
+ check-license-lines:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@master
+ - name: Check License
+ # Check license lines of each file in this repository.
+ uses: apache/skywalking-eyes@v0.5.0
diff --git /dev/null b/.licenserc.yaml
new file mode 100644
--- /dev/null
+++ b/.licenserc.yaml
@@ -0,0 +1,61 @@
+# This is the configuration file for github action License Eye Header. The action is used
+# to check that each source file contains the license header lines. For the configuration
+# details, see https://github.com/marketplace/actions/license-eye-header#configurations.
+
+header:
+ # Files are licensed under MPL-2.0, by default.
+ - paths:
+ - '**/*.rs'
+ - '**/*.S'
+ - '**/*.s'
+ - '**/*.c'
+ - '**/*.sh'
+ - '**/Makefile'
+ - '**/Dockerfile.*'
+ paths-ignore:
+ # These directories are licensed under licenses other than MPL-2.0.
+ - 'services/libs/comp-sys/cargo-component'
+ - 'framework/libs/tdx-guest'
+ license:
+ content: |
+ SPDX-License-Identifier: MPL-2.0
+ language:
+ # License Eye Header cannot recognize files with extension .S, so we add
+ # the definition here.
+ Assembly:
+ extensions:
+ - ".S"
+ comment_style_id: SlashAsterisk
+
+ # Files under tdx-guest are licensed under BSD-3-Clause license.
+ - paths:
+ - 'framework/libs/tdx-guest/**'
+ paths-ignore:
+ - 'Cargo.toml'
+ - '.gitignore'
+ license:
+ content: |
+ SPDX-License-Identifier: BSD-3-Clause
+ Copyright(c) 2023-2024 Intel Corporation.
+
+ # Files under cargo-component are licensed under Apache-2.0 or MIT license.
+ - paths:
+ - 'services/libs/comp-sys/cargo-component/**'
+ paths-ignore:
+ - '**/*.md'
+ - '**/*.toml'
+ - 'Cargo.lock'
+ - '.gitignore'
+ # These directories do not contain test source code and are just for test input.
+ - '**/tests/duplicate_lib_name_test/**'
+ - '**/tests/missing_toml_test/**'
+ - '**/tests/reexport_test/**'
+ - '**/tests/regression_test/**'
+ - '**/tests/trait_method_test/**'
+ - '**/tests/violate_policy_test/**'
+
+ license:
+ content: |
+ Licensed under the Apache License, Version 2.0 or the MIT License.
+ Copyright (C) 2023-2024 Ant Group.
+
\ No newline at end of file
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
# Make varaiables and defaults, you should refer to aster-runner for more details
AUTO_TEST ?= none
BOOT_METHOD ?= qemu-grub
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
# Make varaiables and defaults, you should refer to aster-runner for more details
AUTO_TEST ?= none
BOOT_METHOD ?= qemu-grub
diff --git a/build.rs b/build.rs
--- a/build.rs
+++ b/build.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use std::{error::Error, path::PathBuf};
fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
diff --git a/build.rs b/build.rs
--- a/build.rs
+++ b/build.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use std::{error::Error, path::PathBuf};
fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
diff --git a/framework/aster-frame/src/arch/mod.rs b/framework/aster-frame/src/arch/mod.rs
--- a/framework/aster-frame/src/arch/mod.rs
+++ b/framework/aster-frame/src/arch/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#[cfg(target_arch = "x86_64")]
pub mod x86;
diff --git a/framework/aster-frame/src/arch/mod.rs b/framework/aster-frame/src/arch/mod.rs
--- a/framework/aster-frame/src/arch/mod.rs
+++ b/framework/aster-frame/src/arch/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#[cfg(target_arch = "x86_64")]
pub mod x86;
diff --git a/framework/aster-frame/src/arch/x86/boot/boot.S b/framework/aster-frame/src/arch/x86/boot/boot.S
--- a/framework/aster-frame/src/arch/x86/boot/boot.S
+++ b/framework/aster-frame/src/arch/x86/boot/boot.S
@@ -1,3 +1,5 @@
+/* SPDX-License-Identifier: MPL-2.0 */
+
// The boot header, initial boot setup code, temporary GDT and page tables are
// in the boot section. The boot section is mapped writable since kernel may
// modify the initial page table.
diff --git a/framework/aster-frame/src/arch/x86/boot/boot.S b/framework/aster-frame/src/arch/x86/boot/boot.S
--- a/framework/aster-frame/src/arch/x86/boot/boot.S
+++ b/framework/aster-frame/src/arch/x86/boot/boot.S
@@ -1,3 +1,5 @@
+/* SPDX-License-Identifier: MPL-2.0 */
+
// The boot header, initial boot setup code, temporary GDT and page tables are
// in the boot section. The boot section is mapped writable since kernel may
// modify the initial page table.
diff --git a/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs b/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs
--- a/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The Linux 64-bit Boot Protocol supporting module.
//!
diff --git a/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs b/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs
--- a/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The Linux 64-bit Boot Protocol supporting module.
//!
diff --git a/framework/aster-frame/src/arch/x86/boot/mod.rs b/framework/aster-frame/src/arch/x86/boot/mod.rs
--- a/framework/aster-frame/src/arch/x86/boot/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The x86 boot module defines the entrypoints of Asterinas and
//! the corresponding headers for different x86 boot protocols.
//!
diff --git a/framework/aster-frame/src/arch/x86/boot/mod.rs b/framework/aster-frame/src/arch/x86/boot/mod.rs
--- a/framework/aster-frame/src/arch/x86/boot/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The x86 boot module defines the entrypoints of Asterinas and
//! the corresponding headers for different x86 boot protocols.
//!
diff --git a/framework/aster-frame/src/arch/x86/boot/multiboot/header.S b/framework/aster-frame/src/arch/x86/boot/multiboot/header.S
--- a/framework/aster-frame/src/arch/x86/boot/multiboot/header.S
+++ b/framework/aster-frame/src/arch/x86/boot/multiboot/header.S
@@ -1,3 +1,5 @@
+/* SPDX-License-Identifier: MPL-2.0 */
+
// This is the GNU Multiboot header.
// Reference: https://www.gnu.org/software/grub/manual/multiboot/multiboot.html
.section ".multiboot_header", "a"
diff --git a/framework/aster-frame/src/arch/x86/boot/multiboot/header.S b/framework/aster-frame/src/arch/x86/boot/multiboot/header.S
--- a/framework/aster-frame/src/arch/x86/boot/multiboot/header.S
+++ b/framework/aster-frame/src/arch/x86/boot/multiboot/header.S
@@ -1,3 +1,5 @@
+/* SPDX-License-Identifier: MPL-2.0 */
+
// This is the GNU Multiboot header.
// Reference: https://www.gnu.org/software/grub/manual/multiboot/multiboot.html
.section ".multiboot_header", "a"
diff --git a/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs b/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs
--- a/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::{string::String, vec::Vec};
use multiboot2::MemoryAreaType;
use spin::Once;
diff --git a/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs b/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs
--- a/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::{string::String, vec::Vec};
use multiboot2::MemoryAreaType;
use spin::Once;
diff --git a/framework/aster-frame/src/arch/x86/boot/multiboot2/header.S b/framework/aster-frame/src/arch/x86/boot/multiboot2/header.S
--- a/framework/aster-frame/src/arch/x86/boot/multiboot2/header.S
+++ b/framework/aster-frame/src/arch/x86/boot/multiboot2/header.S
@@ -1,3 +1,5 @@
+/* SPDX-License-Identifier: MPL-2.0 */
+
// This is the GNU Multiboot 2 header.
// Reference: https://www.gnu.org/software/grub/manual/multiboot2/html_node/Index.html//Index
.section ".multiboot2_header", "a"
diff --git a/framework/aster-frame/src/arch/x86/boot/multiboot2/header.S b/framework/aster-frame/src/arch/x86/boot/multiboot2/header.S
--- a/framework/aster-frame/src/arch/x86/boot/multiboot2/header.S
+++ b/framework/aster-frame/src/arch/x86/boot/multiboot2/header.S
@@ -1,3 +1,5 @@
+/* SPDX-License-Identifier: MPL-2.0 */
+
// This is the GNU Multiboot 2 header.
// Reference: https://www.gnu.org/software/grub/manual/multiboot2/html_node/Index.html//Index
.section ".multiboot2_header", "a"
diff --git a/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs b/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs
--- a/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::{
string::{String, ToString},
vec::Vec,
diff --git a/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs b/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs
--- a/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::{
string::{String, ToString},
vec::Vec,
diff --git a/framework/aster-frame/src/arch/x86/console.rs b/framework/aster-frame/src/arch/x86/console.rs
--- a/framework/aster-frame/src/arch/x86/console.rs
+++ b/framework/aster-frame/src/arch/x86/console.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::fmt::Write;
use crate::sync::SpinLock;
diff --git a/framework/aster-frame/src/arch/x86/console.rs b/framework/aster-frame/src/arch/x86/console.rs
--- a/framework/aster-frame/src/arch/x86/console.rs
+++ b/framework/aster-frame/src/arch/x86/console.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::fmt::Write;
use crate::sync::SpinLock;
diff --git a/framework/aster-frame/src/arch/x86/cpu.rs b/framework/aster-frame/src/arch/x86/cpu.rs
--- a/framework/aster-frame/src/arch/x86/cpu.rs
+++ b/framework/aster-frame/src/arch/x86/cpu.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! CPU.
use core::arch::x86_64::{_fxrstor, _fxsave};
diff --git a/framework/aster-frame/src/arch/x86/cpu.rs b/framework/aster-frame/src/arch/x86/cpu.rs
--- a/framework/aster-frame/src/arch/x86/cpu.rs
+++ b/framework/aster-frame/src/arch/x86/cpu.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! CPU.
use core::arch::x86_64::{_fxrstor, _fxsave};
diff --git a/framework/aster-frame/src/arch/x86/device/cmos.rs b/framework/aster-frame/src/arch/x86/device/cmos.rs
--- a/framework/aster-frame/src/arch/x86/device/cmos.rs
+++ b/framework/aster-frame/src/arch/x86/device/cmos.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use acpi::{fadt::Fadt, sdt::Signature};
use x86_64::instructions::port::{ReadOnlyAccess, WriteOnlyAccess};
diff --git a/framework/aster-frame/src/arch/x86/device/cmos.rs b/framework/aster-frame/src/arch/x86/device/cmos.rs
--- a/framework/aster-frame/src/arch/x86/device/cmos.rs
+++ b/framework/aster-frame/src/arch/x86/device/cmos.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use acpi::{fadt::Fadt, sdt::Signature};
use x86_64::instructions::port::{ReadOnlyAccess, WriteOnlyAccess};
diff --git a/framework/aster-frame/src/arch/x86/device/io_port.rs b/framework/aster-frame/src/arch/x86/device/io_port.rs
--- a/framework/aster-frame/src/arch/x86/device/io_port.rs
+++ b/framework/aster-frame/src/arch/x86/device/io_port.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::marker::PhantomData;
pub use x86_64::instructions::port::{
diff --git a/framework/aster-frame/src/arch/x86/device/io_port.rs b/framework/aster-frame/src/arch/x86/device/io_port.rs
--- a/framework/aster-frame/src/arch/x86/device/io_port.rs
+++ b/framework/aster-frame/src/arch/x86/device/io_port.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::marker::PhantomData;
pub use x86_64::instructions::port::{
diff --git a/framework/aster-frame/src/arch/x86/device/mod.rs b/framework/aster-frame/src/arch/x86/device/mod.rs
--- a/framework/aster-frame/src/arch/x86/device/mod.rs
+++ b/framework/aster-frame/src/arch/x86/device/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Device-related APIs.
//! This module mainly contains the APIs that should exposed to the device driver like PCI, RTC
diff --git a/framework/aster-frame/src/arch/x86/device/mod.rs b/framework/aster-frame/src/arch/x86/device/mod.rs
--- a/framework/aster-frame/src/arch/x86/device/mod.rs
+++ b/framework/aster-frame/src/arch/x86/device/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Device-related APIs.
//! This module mainly contains the APIs that should exposed to the device driver like PCI, RTC
diff --git a/framework/aster-frame/src/arch/x86/device/serial.rs b/framework/aster-frame/src/arch/x86/device/serial.rs
--- a/framework/aster-frame/src/arch/x86/device/serial.rs
+++ b/framework/aster-frame/src/arch/x86/device/serial.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! A port-mapped UART. Copied from uart_16550.
use crate::arch::x86::device::io_port::{IoPort, ReadWriteAccess, WriteOnlyAccess};
diff --git a/framework/aster-frame/src/arch/x86/device/serial.rs b/framework/aster-frame/src/arch/x86/device/serial.rs
--- a/framework/aster-frame/src/arch/x86/device/serial.rs
+++ b/framework/aster-frame/src/arch/x86/device/serial.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! A port-mapped UART. Copied from uart_16550.
use crate::arch::x86::device::io_port::{IoPort, ReadWriteAccess, WriteOnlyAccess};
diff --git a/framework/aster-frame/src/arch/x86/iommu/context_table.rs b/framework/aster-frame/src/arch/x86/iommu/context_table.rs
--- a/framework/aster-frame/src/arch/x86/iommu/context_table.rs
+++ b/framework/aster-frame/src/arch/x86/iommu/context_table.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::mem::size_of;
use alloc::collections::BTreeMap;
diff --git a/framework/aster-frame/src/arch/x86/iommu/context_table.rs b/framework/aster-frame/src/arch/x86/iommu/context_table.rs
--- a/framework/aster-frame/src/arch/x86/iommu/context_table.rs
+++ b/framework/aster-frame/src/arch/x86/iommu/context_table.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::mem::size_of;
use alloc::collections::BTreeMap;
diff --git a/framework/aster-frame/src/arch/x86/iommu/fault.rs b/framework/aster-frame/src/arch/x86/iommu/fault.rs
--- a/framework/aster-frame/src/arch/x86/iommu/fault.rs
+++ b/framework/aster-frame/src/arch/x86/iommu/fault.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::fmt::Debug;
use alloc::vec::Vec;
diff --git a/framework/aster-frame/src/arch/x86/iommu/fault.rs b/framework/aster-frame/src/arch/x86/iommu/fault.rs
--- a/framework/aster-frame/src/arch/x86/iommu/fault.rs
+++ b/framework/aster-frame/src/arch/x86/iommu/fault.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::fmt::Debug;
use alloc::vec::Vec;
diff --git a/framework/aster-frame/src/arch/x86/iommu/mod.rs b/framework/aster-frame/src/arch/x86/iommu/mod.rs
--- a/framework/aster-frame/src/arch/x86/iommu/mod.rs
+++ b/framework/aster-frame/src/arch/x86/iommu/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod context_table;
mod fault;
mod remapping;
diff --git a/framework/aster-frame/src/arch/x86/iommu/mod.rs b/framework/aster-frame/src/arch/x86/iommu/mod.rs
--- a/framework/aster-frame/src/arch/x86/iommu/mod.rs
+++ b/framework/aster-frame/src/arch/x86/iommu/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod context_table;
mod fault;
mod remapping;
diff --git a/framework/aster-frame/src/arch/x86/iommu/remapping.rs b/framework/aster-frame/src/arch/x86/iommu/remapping.rs
--- a/framework/aster-frame/src/arch/x86/iommu/remapping.rs
+++ b/framework/aster-frame/src/arch/x86/iommu/remapping.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use bitflags::bitflags;
use log::debug;
use spin::Once;
diff --git a/framework/aster-frame/src/arch/x86/iommu/remapping.rs b/framework/aster-frame/src/arch/x86/iommu/remapping.rs
--- a/framework/aster-frame/src/arch/x86/iommu/remapping.rs
+++ b/framework/aster-frame/src/arch/x86/iommu/remapping.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use bitflags::bitflags;
use log::debug;
use spin::Once;
diff --git a/framework/aster-frame/src/arch/x86/iommu/second_stage.rs b/framework/aster-frame/src/arch/x86/iommu/second_stage.rs
--- a/framework/aster-frame/src/arch/x86/iommu/second_stage.rs
+++ b/framework/aster-frame/src/arch/x86/iommu/second_stage.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use pod::Pod;
use crate::{
diff --git a/framework/aster-frame/src/arch/x86/iommu/second_stage.rs b/framework/aster-frame/src/arch/x86/iommu/second_stage.rs
--- a/framework/aster-frame/src/arch/x86/iommu/second_stage.rs
+++ b/framework/aster-frame/src/arch/x86/iommu/second_stage.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use pod::Pod;
use crate::{
diff --git a/framework/aster-frame/src/arch/x86/irq.rs b/framework/aster-frame/src/arch/x86/irq.rs
--- a/framework/aster-frame/src/arch/x86/irq.rs
+++ b/framework/aster-frame/src/arch/x86/irq.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::sync::Mutex;
use alloc::{boxed::Box, fmt::Debug, sync::Arc, vec::Vec};
use spin::Once;
diff --git a/framework/aster-frame/src/arch/x86/irq.rs b/framework/aster-frame/src/arch/x86/irq.rs
--- a/framework/aster-frame/src/arch/x86/irq.rs
+++ b/framework/aster-frame/src/arch/x86/irq.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::sync::Mutex;
use alloc::{boxed::Box, fmt::Debug, sync::Arc, vec::Vec};
use spin::Once;
diff --git a/framework/aster-frame/src/arch/x86/kernel/acpi/dmar.rs b/framework/aster-frame/src/arch/x86/kernel/acpi/dmar.rs
--- a/framework/aster-frame/src/arch/x86/kernel/acpi/dmar.rs
+++ b/framework/aster-frame/src/arch/x86/kernel/acpi/dmar.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::{fmt::Debug, mem::size_of, slice::Iter};
use acpi::{sdt::Signature, AcpiTable};
diff --git a/framework/aster-frame/src/arch/x86/kernel/acpi/dmar.rs b/framework/aster-frame/src/arch/x86/kernel/acpi/dmar.rs
--- a/framework/aster-frame/src/arch/x86/kernel/acpi/dmar.rs
+++ b/framework/aster-frame/src/arch/x86/kernel/acpi/dmar.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::{fmt::Debug, mem::size_of, slice::Iter};
use acpi::{sdt::Signature, AcpiTable};
diff --git a/framework/aster-frame/src/arch/x86/kernel/acpi/mod.rs b/framework/aster-frame/src/arch/x86/kernel/acpi/mod.rs
--- a/framework/aster-frame/src/arch/x86/kernel/acpi/mod.rs
+++ b/framework/aster-frame/src/arch/x86/kernel/acpi/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod dmar;
pub mod remapping;
diff --git a/framework/aster-frame/src/arch/x86/kernel/acpi/mod.rs b/framework/aster-frame/src/arch/x86/kernel/acpi/mod.rs
--- a/framework/aster-frame/src/arch/x86/kernel/acpi/mod.rs
+++ b/framework/aster-frame/src/arch/x86/kernel/acpi/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod dmar;
pub mod remapping;
diff --git a/framework/aster-frame/src/arch/x86/kernel/acpi/remapping.rs b/framework/aster-frame/src/arch/x86/kernel/acpi/remapping.rs
--- a/framework/aster-frame/src/arch/x86/kernel/acpi/remapping.rs
+++ b/framework/aster-frame/src/arch/x86/kernel/acpi/remapping.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Remapping structures of DMAR table.
//! This file defines these structures and provides a "Debug" implementation to see the value inside these structures.
//! Most of the introduction are copied from Intel vt-directed-io-specification.
diff --git a/framework/aster-frame/src/arch/x86/kernel/acpi/remapping.rs b/framework/aster-frame/src/arch/x86/kernel/acpi/remapping.rs
--- a/framework/aster-frame/src/arch/x86/kernel/acpi/remapping.rs
+++ b/framework/aster-frame/src/arch/x86/kernel/acpi/remapping.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Remapping structures of DMAR table.
//! This file defines these structures and provides a "Debug" implementation to see the value inside these structures.
//! Most of the introduction are copied from Intel vt-directed-io-specification.
diff --git a/framework/aster-frame/src/arch/x86/kernel/apic/ioapic.rs b/framework/aster-frame/src/arch/x86/kernel/apic/ioapic.rs
--- a/framework/aster-frame/src/arch/x86/kernel/apic/ioapic.rs
+++ b/framework/aster-frame/src/arch/x86/kernel/apic/ioapic.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use acpi::PlatformInfo;
use alloc::vec;
use alloc::vec::Vec;
diff --git a/framework/aster-frame/src/arch/x86/kernel/apic/ioapic.rs b/framework/aster-frame/src/arch/x86/kernel/apic/ioapic.rs
--- a/framework/aster-frame/src/arch/x86/kernel/apic/ioapic.rs
+++ b/framework/aster-frame/src/arch/x86/kernel/apic/ioapic.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use acpi::PlatformInfo;
use alloc::vec;
use alloc::vec::Vec;
diff --git a/framework/aster-frame/src/arch/x86/kernel/apic/mod.rs b/framework/aster-frame/src/arch/x86/kernel/apic/mod.rs
--- a/framework/aster-frame/src/arch/x86/kernel/apic/mod.rs
+++ b/framework/aster-frame/src/arch/x86/kernel/apic/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::sync::Mutex;
use alloc::boxed::Box;
use alloc::sync::Arc;
diff --git a/framework/aster-frame/src/arch/x86/kernel/apic/mod.rs b/framework/aster-frame/src/arch/x86/kernel/apic/mod.rs
--- a/framework/aster-frame/src/arch/x86/kernel/apic/mod.rs
+++ b/framework/aster-frame/src/arch/x86/kernel/apic/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::sync::Mutex;
use alloc::boxed::Box;
use alloc::sync::Arc;
diff --git a/framework/aster-frame/src/arch/x86/kernel/apic/x2apic.rs b/framework/aster-frame/src/arch/x86/kernel/apic/x2apic.rs
--- a/framework/aster-frame/src/arch/x86/kernel/apic/x2apic.rs
+++ b/framework/aster-frame/src/arch/x86/kernel/apic/x2apic.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use x86::msr::{
rdmsr, wrmsr, IA32_APIC_BASE, IA32_X2APIC_APICID, IA32_X2APIC_CUR_COUNT, IA32_X2APIC_DIV_CONF,
IA32_X2APIC_EOI, IA32_X2APIC_INIT_COUNT, IA32_X2APIC_LVT_TIMER, IA32_X2APIC_SIVR,
diff --git a/framework/aster-frame/src/arch/x86/kernel/apic/x2apic.rs b/framework/aster-frame/src/arch/x86/kernel/apic/x2apic.rs
--- a/framework/aster-frame/src/arch/x86/kernel/apic/x2apic.rs
+++ b/framework/aster-frame/src/arch/x86/kernel/apic/x2apic.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use x86::msr::{
rdmsr, wrmsr, IA32_APIC_BASE, IA32_X2APIC_APICID, IA32_X2APIC_CUR_COUNT, IA32_X2APIC_DIV_CONF,
IA32_X2APIC_EOI, IA32_X2APIC_INIT_COUNT, IA32_X2APIC_LVT_TIMER, IA32_X2APIC_SIVR,
diff --git a/framework/aster-frame/src/arch/x86/kernel/apic/xapic.rs b/framework/aster-frame/src/arch/x86/kernel/apic/xapic.rs
--- a/framework/aster-frame/src/arch/x86/kernel/apic/xapic.rs
+++ b/framework/aster-frame/src/arch/x86/kernel/apic/xapic.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::sync::Mutex;
use crate::vm;
use spin::Once;
diff --git a/framework/aster-frame/src/arch/x86/kernel/apic/xapic.rs b/framework/aster-frame/src/arch/x86/kernel/apic/xapic.rs
--- a/framework/aster-frame/src/arch/x86/kernel/apic/xapic.rs
+++ b/framework/aster-frame/src/arch/x86/kernel/apic/xapic.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::sync::Mutex;
use crate::vm;
use spin::Once;
diff --git a/framework/aster-frame/src/arch/x86/kernel/mod.rs b/framework/aster-frame/src/arch/x86/kernel/mod.rs
--- a/framework/aster-frame/src/arch/x86/kernel/mod.rs
+++ b/framework/aster-frame/src/arch/x86/kernel/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub(super) mod acpi;
pub(super) mod apic;
pub(super) mod pic;
diff --git a/framework/aster-frame/src/arch/x86/kernel/mod.rs b/framework/aster-frame/src/arch/x86/kernel/mod.rs
--- a/framework/aster-frame/src/arch/x86/kernel/mod.rs
+++ b/framework/aster-frame/src/arch/x86/kernel/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub(super) mod acpi;
pub(super) mod apic;
pub(super) mod pic;
diff --git a/framework/aster-frame/src/arch/x86/kernel/pic.rs b/framework/aster-frame/src/arch/x86/kernel/pic.rs
--- a/framework/aster-frame/src/arch/x86/kernel/pic.rs
+++ b/framework/aster-frame/src/arch/x86/kernel/pic.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::arch::x86::device::io_port::{IoPort, WriteOnlyAccess};
use crate::trap::IrqLine;
use core::sync::atomic::Ordering::Relaxed;
diff --git a/framework/aster-frame/src/arch/x86/kernel/pic.rs b/framework/aster-frame/src/arch/x86/kernel/pic.rs
--- a/framework/aster-frame/src/arch/x86/kernel/pic.rs
+++ b/framework/aster-frame/src/arch/x86/kernel/pic.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::arch::x86::device::io_port::{IoPort, WriteOnlyAccess};
use crate::trap::IrqLine;
use core::sync::atomic::Ordering::Relaxed;
diff --git a/framework/aster-frame/src/arch/x86/kernel/tsc.rs b/framework/aster-frame/src/arch/x86/kernel/tsc.rs
--- a/framework/aster-frame/src/arch/x86/kernel/tsc.rs
+++ b/framework/aster-frame/src/arch/x86/kernel/tsc.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::AtomicU64;
use x86::cpuid::cpuid;
diff --git a/framework/aster-frame/src/arch/x86/kernel/tsc.rs b/framework/aster-frame/src/arch/x86/kernel/tsc.rs
--- a/framework/aster-frame/src/arch/x86/kernel/tsc.rs
+++ b/framework/aster-frame/src/arch/x86/kernel/tsc.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::AtomicU64;
use x86::cpuid::cpuid;
diff --git a/framework/aster-frame/src/arch/x86/mm/mod.rs b/framework/aster-frame/src/arch/x86/mm/mod.rs
--- a/framework/aster-frame/src/arch/x86/mm/mod.rs
+++ b/framework/aster-frame/src/arch/x86/mm/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::sync::Mutex;
use alloc::{collections::BTreeMap, fmt};
use pod::Pod;
diff --git a/framework/aster-frame/src/arch/x86/mm/mod.rs b/framework/aster-frame/src/arch/x86/mm/mod.rs
--- a/framework/aster-frame/src/arch/x86/mm/mod.rs
+++ b/framework/aster-frame/src/arch/x86/mm/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::sync::Mutex;
use alloc::{collections::BTreeMap, fmt};
use pod::Pod;
diff --git a/framework/aster-frame/src/arch/x86/mod.rs b/framework/aster-frame/src/arch/x86/mod.rs
--- a/framework/aster-frame/src/arch/x86/mod.rs
+++ b/framework/aster-frame/src/arch/x86/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod boot;
pub mod console;
pub(crate) mod cpu;
diff --git a/framework/aster-frame/src/arch/x86/mod.rs b/framework/aster-frame/src/arch/x86/mod.rs
--- a/framework/aster-frame/src/arch/x86/mod.rs
+++ b/framework/aster-frame/src/arch/x86/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod boot;
pub mod console;
pub(crate) mod cpu;
diff --git a/framework/aster-frame/src/arch/x86/pci.rs b/framework/aster-frame/src/arch/x86/pci.rs
--- a/framework/aster-frame/src/arch/x86/pci.rs
+++ b/framework/aster-frame/src/arch/x86/pci.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! PCI bus io port
use super::device::io_port::{IoPort, ReadWriteAccess, WriteOnlyAccess};
diff --git a/framework/aster-frame/src/arch/x86/pci.rs b/framework/aster-frame/src/arch/x86/pci.rs
--- a/framework/aster-frame/src/arch/x86/pci.rs
+++ b/framework/aster-frame/src/arch/x86/pci.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! PCI bus io port
use super::device::io_port::{IoPort, ReadWriteAccess, WriteOnlyAccess};
diff --git a/framework/aster-frame/src/arch/x86/qemu.rs b/framework/aster-frame/src/arch/x86/qemu.rs
--- a/framework/aster-frame/src/arch/x86/qemu.rs
+++ b/framework/aster-frame/src/arch/x86/qemu.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Providing the ability to exit QEMU and return a value as debug result.
/// The exit code of x86 QEMU isa debug device. In `qemu-system-x86_64` the
diff --git a/framework/aster-frame/src/arch/x86/qemu.rs b/framework/aster-frame/src/arch/x86/qemu.rs
--- a/framework/aster-frame/src/arch/x86/qemu.rs
+++ b/framework/aster-frame/src/arch/x86/qemu.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Providing the ability to exit QEMU and return a value as debug result.
/// The exit code of x86 QEMU isa debug device. In `qemu-system-x86_64` the
diff --git a/framework/aster-frame/src/arch/x86/tdx_guest.rs b/framework/aster-frame/src/arch/x86/tdx_guest.rs
--- a/framework/aster-frame/src/arch/x86/tdx_guest.rs
+++ b/framework/aster-frame/src/arch/x86/tdx_guest.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use tdx_guest::{
tdcall::TdgVeInfo,
tdvmcall::{cpuid, hlt, rdmsr, wrmsr, IoSize},
diff --git a/framework/aster-frame/src/arch/x86/tdx_guest.rs b/framework/aster-frame/src/arch/x86/tdx_guest.rs
--- a/framework/aster-frame/src/arch/x86/tdx_guest.rs
+++ b/framework/aster-frame/src/arch/x86/tdx_guest.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use tdx_guest::{
tdcall::TdgVeInfo,
tdvmcall::{cpuid, hlt, rdmsr, wrmsr, IoSize},
diff --git a/framework/aster-frame/src/arch/x86/timer/apic.rs b/framework/aster-frame/src/arch/x86/timer/apic.rs
--- a/framework/aster-frame/src/arch/x86/timer/apic.rs
+++ b/framework/aster-frame/src/arch/x86/timer/apic.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::sync::Arc;
use core::arch::x86_64::_rdtsc;
use core::sync::atomic::{AtomicBool, AtomicU64, Ordering};
diff --git a/framework/aster-frame/src/arch/x86/timer/apic.rs b/framework/aster-frame/src/arch/x86/timer/apic.rs
--- a/framework/aster-frame/src/arch/x86/timer/apic.rs
+++ b/framework/aster-frame/src/arch/x86/timer/apic.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::sync::Arc;
use core::arch::x86_64::_rdtsc;
use core::sync::atomic::{AtomicBool, AtomicU64, Ordering};
diff --git a/framework/aster-frame/src/arch/x86/timer/hpet.rs b/framework/aster-frame/src/arch/x86/timer/hpet.rs
--- a/framework/aster-frame/src/arch/x86/timer/hpet.rs
+++ b/framework/aster-frame/src/arch/x86/timer/hpet.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{trap::IrqLine, vm::paddr_to_vaddr};
use acpi::{AcpiError, HpetInfo};
use alloc::vec::Vec;
diff --git a/framework/aster-frame/src/arch/x86/timer/hpet.rs b/framework/aster-frame/src/arch/x86/timer/hpet.rs
--- a/framework/aster-frame/src/arch/x86/timer/hpet.rs
+++ b/framework/aster-frame/src/arch/x86/timer/hpet.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{trap::IrqLine, vm::paddr_to_vaddr};
use acpi::{AcpiError, HpetInfo};
use alloc::vec::Vec;
diff --git a/framework/aster-frame/src/arch/x86/timer/mod.rs b/framework/aster-frame/src/arch/x86/timer/mod.rs
--- a/framework/aster-frame/src/arch/x86/timer/mod.rs
+++ b/framework/aster-frame/src/arch/x86/timer/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod apic;
pub mod hpet;
pub mod pit;
diff --git a/framework/aster-frame/src/arch/x86/timer/mod.rs b/framework/aster-frame/src/arch/x86/timer/mod.rs
--- a/framework/aster-frame/src/arch/x86/timer/mod.rs
+++ b/framework/aster-frame/src/arch/x86/timer/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod apic;
pub mod hpet;
pub mod pit;
diff --git a/framework/aster-frame/src/arch/x86/timer/pit.rs b/framework/aster-frame/src/arch/x86/timer/pit.rs
--- a/framework/aster-frame/src/arch/x86/timer/pit.rs
+++ b/framework/aster-frame/src/arch/x86/timer/pit.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! used for PIT Timer
use crate::config::TIMER_FREQ;
diff --git a/framework/aster-frame/src/arch/x86/timer/pit.rs b/framework/aster-frame/src/arch/x86/timer/pit.rs
--- a/framework/aster-frame/src/arch/x86/timer/pit.rs
+++ b/framework/aster-frame/src/arch/x86/timer/pit.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! used for PIT Timer
use crate::config::TIMER_FREQ;
diff --git a/framework/aster-frame/src/boot/kcmdline.rs b/framework/aster-frame/src/boot/kcmdline.rs
--- a/framework/aster-frame/src/boot/kcmdline.rs
+++ b/framework/aster-frame/src/boot/kcmdline.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The module to parse kernel command-line arguments.
//!
//! The format of the Asterinas command line string conforms
diff --git a/framework/aster-frame/src/boot/kcmdline.rs b/framework/aster-frame/src/boot/kcmdline.rs
--- a/framework/aster-frame/src/boot/kcmdline.rs
+++ b/framework/aster-frame/src/boot/kcmdline.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The module to parse kernel command-line arguments.
//!
//! The format of the Asterinas command line string conforms
diff --git a/framework/aster-frame/src/boot/memory_region.rs b/framework/aster-frame/src/boot/memory_region.rs
--- a/framework/aster-frame/src/boot/memory_region.rs
+++ b/framework/aster-frame/src/boot/memory_region.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Information of memory regions in the boot phase.
//!
diff --git a/framework/aster-frame/src/boot/memory_region.rs b/framework/aster-frame/src/boot/memory_region.rs
--- a/framework/aster-frame/src/boot/memory_region.rs
+++ b/framework/aster-frame/src/boot/memory_region.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Information of memory regions in the boot phase.
//!
diff --git a/framework/aster-frame/src/boot/mod.rs b/framework/aster-frame/src/boot/mod.rs
--- a/framework/aster-frame/src/boot/mod.rs
+++ b/framework/aster-frame/src/boot/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The architecture-independent boot module, which provides a universal interface
//! from the bootloader to the rest of the framework.
//!
diff --git a/framework/aster-frame/src/boot/mod.rs b/framework/aster-frame/src/boot/mod.rs
--- a/framework/aster-frame/src/boot/mod.rs
+++ b/framework/aster-frame/src/boot/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The architecture-independent boot module, which provides a universal interface
//! from the bootloader to the rest of the framework.
//!
diff --git a/framework/aster-frame/src/bus/mmio/bus.rs b/framework/aster-frame/src/bus/mmio/bus.rs
--- a/framework/aster-frame/src/bus/mmio/bus.rs
+++ b/framework/aster-frame/src/bus/mmio/bus.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::{collections::VecDeque, fmt::Debug, sync::Arc, vec::Vec};
use log::{debug, error};
diff --git a/framework/aster-frame/src/bus/mmio/bus.rs b/framework/aster-frame/src/bus/mmio/bus.rs
--- a/framework/aster-frame/src/bus/mmio/bus.rs
+++ b/framework/aster-frame/src/bus/mmio/bus.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::{collections::VecDeque, fmt::Debug, sync::Arc, vec::Vec};
use log::{debug, error};
diff --git a/framework/aster-frame/src/bus/mmio/device.rs b/framework/aster-frame/src/bus/mmio/device.rs
--- a/framework/aster-frame/src/bus/mmio/device.rs
+++ b/framework/aster-frame/src/bus/mmio/device.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use int_to_c_enum::TryFromInt;
use log::info;
diff --git a/framework/aster-frame/src/bus/mmio/device.rs b/framework/aster-frame/src/bus/mmio/device.rs
--- a/framework/aster-frame/src/bus/mmio/device.rs
+++ b/framework/aster-frame/src/bus/mmio/device.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use int_to_c_enum::TryFromInt;
use log::info;
diff --git a/framework/aster-frame/src/bus/mmio/mod.rs b/framework/aster-frame/src/bus/mmio/mod.rs
--- a/framework/aster-frame/src/bus/mmio/mod.rs
+++ b/framework/aster-frame/src/bus/mmio/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Virtio over MMIO
pub mod bus;
diff --git a/framework/aster-frame/src/bus/mmio/mod.rs b/framework/aster-frame/src/bus/mmio/mod.rs
--- a/framework/aster-frame/src/bus/mmio/mod.rs
+++ b/framework/aster-frame/src/bus/mmio/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Virtio over MMIO
pub mod bus;
diff --git a/framework/aster-frame/src/bus/mod.rs b/framework/aster-frame/src/bus/mod.rs
--- a/framework/aster-frame/src/bus/mod.rs
+++ b/framework/aster-frame/src/bus/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod mmio;
pub mod pci;
diff --git a/framework/aster-frame/src/bus/mod.rs b/framework/aster-frame/src/bus/mod.rs
--- a/framework/aster-frame/src/bus/mod.rs
+++ b/framework/aster-frame/src/bus/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod mmio;
pub mod pci;
diff --git a/framework/aster-frame/src/bus/pci/bus.rs b/framework/aster-frame/src/bus/pci/bus.rs
--- a/framework/aster-frame/src/bus/pci/bus.rs
+++ b/framework/aster-frame/src/bus/pci/bus.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::fmt::Debug;
use alloc::{collections::VecDeque, sync::Arc, vec::Vec};
diff --git a/framework/aster-frame/src/bus/pci/bus.rs b/framework/aster-frame/src/bus/pci/bus.rs
--- a/framework/aster-frame/src/bus/pci/bus.rs
+++ b/framework/aster-frame/src/bus/pci/bus.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::fmt::Debug;
use alloc::{collections::VecDeque, sync::Arc, vec::Vec};
diff --git a/framework/aster-frame/src/bus/pci/capability/mod.rs b/framework/aster-frame/src/bus/pci/capability/mod.rs
--- a/framework/aster-frame/src/bus/pci/capability/mod.rs
+++ b/framework/aster-frame/src/bus/pci/capability/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::vec::Vec;
use self::{msix::CapabilityMsixData, vendor::CapabilityVndrData};
diff --git a/framework/aster-frame/src/bus/pci/capability/mod.rs b/framework/aster-frame/src/bus/pci/capability/mod.rs
--- a/framework/aster-frame/src/bus/pci/capability/mod.rs
+++ b/framework/aster-frame/src/bus/pci/capability/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::vec::Vec;
use self::{msix::CapabilityMsixData, vendor::CapabilityVndrData};
diff --git a/framework/aster-frame/src/bus/pci/capability/msix.rs b/framework/aster-frame/src/bus/pci/capability/msix.rs
--- a/framework/aster-frame/src/bus/pci/capability/msix.rs
+++ b/framework/aster-frame/src/bus/pci/capability/msix.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::{sync::Arc, vec::Vec};
use crate::{
diff --git a/framework/aster-frame/src/bus/pci/capability/msix.rs b/framework/aster-frame/src/bus/pci/capability/msix.rs
--- a/framework/aster-frame/src/bus/pci/capability/msix.rs
+++ b/framework/aster-frame/src/bus/pci/capability/msix.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::{sync::Arc, vec::Vec};
use crate::{
diff --git a/framework/aster-frame/src/bus/pci/capability/vendor.rs b/framework/aster-frame/src/bus/pci/capability/vendor.rs
--- a/framework/aster-frame/src/bus/pci/capability/vendor.rs
+++ b/framework/aster-frame/src/bus/pci/capability/vendor.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::bus::pci::{common_device::PciCommonDevice, device_info::PciDeviceLocation};
use crate::{Error, Result};
diff --git a/framework/aster-frame/src/bus/pci/capability/vendor.rs b/framework/aster-frame/src/bus/pci/capability/vendor.rs
--- a/framework/aster-frame/src/bus/pci/capability/vendor.rs
+++ b/framework/aster-frame/src/bus/pci/capability/vendor.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::bus::pci::{common_device::PciCommonDevice, device_info::PciDeviceLocation};
use crate::{Error, Result};
diff --git a/framework/aster-frame/src/bus/pci/cfg_space.rs b/framework/aster-frame/src/bus/pci/cfg_space.rs
--- a/framework/aster-frame/src/bus/pci/cfg_space.rs
+++ b/framework/aster-frame/src/bus/pci/cfg_space.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::sync::Arc;
use bitflags::bitflags;
diff --git a/framework/aster-frame/src/bus/pci/cfg_space.rs b/framework/aster-frame/src/bus/pci/cfg_space.rs
--- a/framework/aster-frame/src/bus/pci/cfg_space.rs
+++ b/framework/aster-frame/src/bus/pci/cfg_space.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::sync::Arc;
use bitflags::bitflags;
diff --git a/framework/aster-frame/src/bus/pci/common_device.rs b/framework/aster-frame/src/bus/pci/common_device.rs
--- a/framework/aster-frame/src/bus/pci/common_device.rs
+++ b/framework/aster-frame/src/bus/pci/common_device.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::vec::Vec;
use super::{
diff --git a/framework/aster-frame/src/bus/pci/common_device.rs b/framework/aster-frame/src/bus/pci/common_device.rs
--- a/framework/aster-frame/src/bus/pci/common_device.rs
+++ b/framework/aster-frame/src/bus/pci/common_device.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::vec::Vec;
use super::{
diff --git a/framework/aster-frame/src/bus/pci/device_info.rs b/framework/aster-frame/src/bus/pci/device_info.rs
--- a/framework/aster-frame/src/bus/pci/device_info.rs
+++ b/framework/aster-frame/src/bus/pci/device_info.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::iter;
use crate::arch::pci::{PCI_ADDRESS_PORT, PCI_DATA_PORT};
diff --git a/framework/aster-frame/src/bus/pci/device_info.rs b/framework/aster-frame/src/bus/pci/device_info.rs
--- a/framework/aster-frame/src/bus/pci/device_info.rs
+++ b/framework/aster-frame/src/bus/pci/device_info.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::iter;
use crate::arch::pci::{PCI_ADDRESS_PORT, PCI_DATA_PORT};
diff --git a/framework/aster-frame/src/bus/pci/mod.rs b/framework/aster-frame/src/bus/pci/mod.rs
--- a/framework/aster-frame/src/bus/pci/mod.rs
+++ b/framework/aster-frame/src/bus/pci/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! PCI bus
//!
//! Users can implement the bus under the `PciDriver` to the PCI bus to register devices,
diff --git a/framework/aster-frame/src/bus/pci/mod.rs b/framework/aster-frame/src/bus/pci/mod.rs
--- a/framework/aster-frame/src/bus/pci/mod.rs
+++ b/framework/aster-frame/src/bus/pci/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! PCI bus
//!
//! Users can implement the bus under the `PciDriver` to the PCI bus to register devices,
diff --git a/framework/aster-frame/src/config.rs b/framework/aster-frame/src/config.rs
--- a/framework/aster-frame/src/config.rs
+++ b/framework/aster-frame/src/config.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#![allow(unused)]
use log::Level;
diff --git a/framework/aster-frame/src/config.rs b/framework/aster-frame/src/config.rs
--- a/framework/aster-frame/src/config.rs
+++ b/framework/aster-frame/src/config.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#![allow(unused)]
use log::Level;
diff --git a/framework/aster-frame/src/console.rs b/framework/aster-frame/src/console.rs
--- a/framework/aster-frame/src/console.rs
+++ b/framework/aster-frame/src/console.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::fmt::Arguments;
pub fn print(args: Arguments) {
diff --git a/framework/aster-frame/src/console.rs b/framework/aster-frame/src/console.rs
--- a/framework/aster-frame/src/console.rs
+++ b/framework/aster-frame/src/console.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::fmt::Arguments;
pub fn print(args: Arguments) {
diff --git a/framework/aster-frame/src/cpu.rs b/framework/aster-frame/src/cpu.rs
--- a/framework/aster-frame/src/cpu.rs
+++ b/framework/aster-frame/src/cpu.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! CPU.
use crate::trap::disable_local;
diff --git a/framework/aster-frame/src/cpu.rs b/framework/aster-frame/src/cpu.rs
--- a/framework/aster-frame/src/cpu.rs
+++ b/framework/aster-frame/src/cpu.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! CPU.
use crate::trap::disable_local;
diff --git a/framework/aster-frame/src/error.rs b/framework/aster-frame/src/error.rs
--- a/framework/aster-frame/src/error.rs
+++ b/framework/aster-frame/src/error.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
/// The error type which is returned from the APIs of this crate.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Error {
diff --git a/framework/aster-frame/src/error.rs b/framework/aster-frame/src/error.rs
--- a/framework/aster-frame/src/error.rs
+++ b/framework/aster-frame/src/error.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
/// The error type which is returned from the APIs of this crate.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Error {
diff --git a/framework/aster-frame/src/io_mem.rs b/framework/aster-frame/src/io_mem.rs
--- a/framework/aster-frame/src/io_mem.rs
+++ b/framework/aster-frame/src/io_mem.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::{mem::size_of, ops::Range};
use pod::Pod;
diff --git a/framework/aster-frame/src/io_mem.rs b/framework/aster-frame/src/io_mem.rs
--- a/framework/aster-frame/src/io_mem.rs
+++ b/framework/aster-frame/src/io_mem.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::{mem::size_of, ops::Range};
use pod::Pod;
diff --git a/framework/aster-frame/src/lib.rs b/framework/aster-frame/src/lib.rs
--- a/framework/aster-frame/src/lib.rs
+++ b/framework/aster-frame/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The framework part of Asterinas.
#![feature(alloc_error_handler)]
#![feature(const_mut_refs)]
diff --git a/framework/aster-frame/src/lib.rs b/framework/aster-frame/src/lib.rs
--- a/framework/aster-frame/src/lib.rs
+++ b/framework/aster-frame/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The framework part of Asterinas.
#![feature(alloc_error_handler)]
#![feature(const_mut_refs)]
diff --git a/framework/aster-frame/src/logger.rs b/framework/aster-frame/src/logger.rs
--- a/framework/aster-frame/src/logger.rs
+++ b/framework/aster-frame/src/logger.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{config::DEFAULT_LOG_LEVEL, early_println};
use log::{Metadata, Record};
diff --git a/framework/aster-frame/src/logger.rs b/framework/aster-frame/src/logger.rs
--- a/framework/aster-frame/src/logger.rs
+++ b/framework/aster-frame/src/logger.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{config::DEFAULT_LOG_LEVEL, early_println};
use log::{Metadata, Record};
diff --git a/framework/aster-frame/src/panicking.rs b/framework/aster-frame/src/panicking.rs
--- a/framework/aster-frame/src/panicking.rs
+++ b/framework/aster-frame/src/panicking.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Panic support.
use alloc::{boxed::Box, string::ToString};
diff --git a/framework/aster-frame/src/panicking.rs b/framework/aster-frame/src/panicking.rs
--- a/framework/aster-frame/src/panicking.rs
+++ b/framework/aster-frame/src/panicking.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Panic support.
use alloc::{boxed::Box, string::ToString};
diff --git a/framework/aster-frame/src/prelude.rs b/framework/aster-frame/src/prelude.rs
--- a/framework/aster-frame/src/prelude.rs
+++ b/framework/aster-frame/src/prelude.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The prelude.
pub type Result<T> = core::result::Result<T, crate::error::Error>;
diff --git a/framework/aster-frame/src/prelude.rs b/framework/aster-frame/src/prelude.rs
--- a/framework/aster-frame/src/prelude.rs
+++ b/framework/aster-frame/src/prelude.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The prelude.
pub type Result<T> = core::result::Result<T, crate::error::Error>;
diff --git a/framework/aster-frame/src/sync/atomic_bits.rs b/framework/aster-frame/src/sync/atomic_bits.rs
--- a/framework/aster-frame/src/sync/atomic_bits.rs
+++ b/framework/aster-frame/src/sync/atomic_bits.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::fmt::{self};
use core::sync::atomic::{AtomicU64, Ordering::Relaxed};
diff --git a/framework/aster-frame/src/sync/atomic_bits.rs b/framework/aster-frame/src/sync/atomic_bits.rs
--- a/framework/aster-frame/src/sync/atomic_bits.rs
+++ b/framework/aster-frame/src/sync/atomic_bits.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::fmt::{self};
use core::sync::atomic::{AtomicU64, Ordering::Relaxed};
diff --git a/framework/aster-frame/src/sync/mod.rs b/framework/aster-frame/src/sync/mod.rs
--- a/framework/aster-frame/src/sync/mod.rs
+++ b/framework/aster-frame/src/sync/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod atomic_bits;
mod mutex;
// TODO: refactor this rcu implementation
diff --git a/framework/aster-frame/src/sync/mod.rs b/framework/aster-frame/src/sync/mod.rs
--- a/framework/aster-frame/src/sync/mod.rs
+++ b/framework/aster-frame/src/sync/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod atomic_bits;
mod mutex;
// TODO: refactor this rcu implementation
diff --git a/framework/aster-frame/src/sync/mutex.rs b/framework/aster-frame/src/sync/mutex.rs
--- a/framework/aster-frame/src/sync/mutex.rs
+++ b/framework/aster-frame/src/sync/mutex.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::WaitQueue;
use core::cell::UnsafeCell;
use core::ops::{Deref, DerefMut};
diff --git a/framework/aster-frame/src/sync/mutex.rs b/framework/aster-frame/src/sync/mutex.rs
--- a/framework/aster-frame/src/sync/mutex.rs
+++ b/framework/aster-frame/src/sync/mutex.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::WaitQueue;
use core::cell::UnsafeCell;
use core::ops::{Deref, DerefMut};
diff --git a/framework/aster-frame/src/sync/rcu/mod.rs b/framework/aster-frame/src/sync/rcu/mod.rs
--- a/framework/aster-frame/src/sync/rcu/mod.rs
+++ b/framework/aster-frame/src/sync/rcu/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Read-copy update (RCU).
use core::marker::PhantomData;
diff --git a/framework/aster-frame/src/sync/rcu/mod.rs b/framework/aster-frame/src/sync/rcu/mod.rs
--- a/framework/aster-frame/src/sync/rcu/mod.rs
+++ b/framework/aster-frame/src/sync/rcu/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Read-copy update (RCU).
use core::marker::PhantomData;
diff --git a/framework/aster-frame/src/sync/rcu/monitor.rs b/framework/aster-frame/src/sync/rcu/monitor.rs
--- a/framework/aster-frame/src/sync/rcu/monitor.rs
+++ b/framework/aster-frame/src/sync/rcu/monitor.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::collections::VecDeque;
use core::sync::atomic::{
AtomicBool,
diff --git a/framework/aster-frame/src/sync/rcu/monitor.rs b/framework/aster-frame/src/sync/rcu/monitor.rs
--- a/framework/aster-frame/src/sync/rcu/monitor.rs
+++ b/framework/aster-frame/src/sync/rcu/monitor.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::collections::VecDeque;
use core::sync::atomic::{
AtomicBool,
diff --git a/framework/aster-frame/src/sync/rcu/owner_ptr.rs b/framework/aster-frame/src/sync/rcu/owner_ptr.rs
--- a/framework/aster-frame/src/sync/rcu/owner_ptr.rs
+++ b/framework/aster-frame/src/sync/rcu/owner_ptr.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::ptr::NonNull;
use crate::prelude::*;
diff --git a/framework/aster-frame/src/sync/rcu/owner_ptr.rs b/framework/aster-frame/src/sync/rcu/owner_ptr.rs
--- a/framework/aster-frame/src/sync/rcu/owner_ptr.rs
+++ b/framework/aster-frame/src/sync/rcu/owner_ptr.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::ptr::NonNull;
use crate::prelude::*;
diff --git a/framework/aster-frame/src/sync/rwlock.rs b/framework/aster-frame/src/sync/rwlock.rs
--- a/framework/aster-frame/src/sync/rwlock.rs
+++ b/framework/aster-frame/src/sync/rwlock.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::cell::UnsafeCell;
use core::fmt;
use core::ops::{Deref, DerefMut};
diff --git a/framework/aster-frame/src/sync/rwlock.rs b/framework/aster-frame/src/sync/rwlock.rs
--- a/framework/aster-frame/src/sync/rwlock.rs
+++ b/framework/aster-frame/src/sync/rwlock.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::cell::UnsafeCell;
use core::fmt;
use core::ops::{Deref, DerefMut};
diff --git a/framework/aster-frame/src/sync/rwmutex.rs b/framework/aster-frame/src/sync/rwmutex.rs
--- a/framework/aster-frame/src/sync/rwmutex.rs
+++ b/framework/aster-frame/src/sync/rwmutex.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::cell::UnsafeCell;
use core::fmt;
use core::ops::{Deref, DerefMut};
diff --git a/framework/aster-frame/src/sync/rwmutex.rs b/framework/aster-frame/src/sync/rwmutex.rs
--- a/framework/aster-frame/src/sync/rwmutex.rs
+++ b/framework/aster-frame/src/sync/rwmutex.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::cell::UnsafeCell;
use core::fmt;
use core::ops::{Deref, DerefMut};
diff --git a/framework/aster-frame/src/sync/spin.rs b/framework/aster-frame/src/sync/spin.rs
--- a/framework/aster-frame/src/sync/spin.rs
+++ b/framework/aster-frame/src/sync/spin.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::cell::UnsafeCell;
use core::fmt;
use core::ops::{Deref, DerefMut};
diff --git a/framework/aster-frame/src/sync/spin.rs b/framework/aster-frame/src/sync/spin.rs
--- a/framework/aster-frame/src/sync/spin.rs
+++ b/framework/aster-frame/src/sync/spin.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::cell::UnsafeCell;
use core::fmt;
use core::ops::{Deref, DerefMut};
diff --git a/framework/aster-frame/src/sync/wait.rs b/framework/aster-frame/src/sync/wait.rs
--- a/framework/aster-frame/src/sync/wait.rs
+++ b/framework/aster-frame/src/sync/wait.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::SpinLock;
use crate::arch::timer::add_timeout_list;
use crate::config::TIMER_FREQ;
diff --git a/framework/aster-frame/src/sync/wait.rs b/framework/aster-frame/src/sync/wait.rs
--- a/framework/aster-frame/src/sync/wait.rs
+++ b/framework/aster-frame/src/sync/wait.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::SpinLock;
use crate::arch::timer::add_timeout_list;
use crate::config::TIMER_FREQ;
diff --git a/framework/aster-frame/src/task/mod.rs b/framework/aster-frame/src/task/mod.rs
--- a/framework/aster-frame/src/task/mod.rs
+++ b/framework/aster-frame/src/task/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Tasks are the unit of code execution.
mod priority;
diff --git a/framework/aster-frame/src/task/mod.rs b/framework/aster-frame/src/task/mod.rs
--- a/framework/aster-frame/src/task/mod.rs
+++ b/framework/aster-frame/src/task/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Tasks are the unit of code execution.
mod priority;
diff --git a/framework/aster-frame/src/task/priority.rs b/framework/aster-frame/src/task/priority.rs
--- a/framework/aster-frame/src/task/priority.rs
+++ b/framework/aster-frame/src/task/priority.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::config::REAL_TIME_TASK_PRI;
/// The priority of a task.
diff --git a/framework/aster-frame/src/task/priority.rs b/framework/aster-frame/src/task/priority.rs
--- a/framework/aster-frame/src/task/priority.rs
+++ b/framework/aster-frame/src/task/priority.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::config::REAL_TIME_TASK_PRI;
/// The priority of a task.
diff --git a/framework/aster-frame/src/task/processor.rs b/framework/aster-frame/src/task/processor.rs
--- a/framework/aster-frame/src/task/processor.rs
+++ b/framework/aster-frame/src/task/processor.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::AtomicUsize;
use crate::cpu_local;
diff --git a/framework/aster-frame/src/task/processor.rs b/framework/aster-frame/src/task/processor.rs
--- a/framework/aster-frame/src/task/processor.rs
+++ b/framework/aster-frame/src/task/processor.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::AtomicUsize;
use crate::cpu_local;
diff --git a/framework/aster-frame/src/task/scheduler.rs b/framework/aster-frame/src/task/scheduler.rs
--- a/framework/aster-frame/src/task/scheduler.rs
+++ b/framework/aster-frame/src/task/scheduler.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use crate::sync::SpinLock;
use crate::task::Task;
diff --git a/framework/aster-frame/src/task/scheduler.rs b/framework/aster-frame/src/task/scheduler.rs
--- a/framework/aster-frame/src/task/scheduler.rs
+++ b/framework/aster-frame/src/task/scheduler.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use crate::sync::SpinLock;
use crate::task::Task;
diff --git a/framework/aster-frame/src/task/switch.S b/framework/aster-frame/src/task/switch.S
--- a/framework/aster-frame/src/task/switch.S
+++ b/framework/aster-frame/src/task/switch.S
@@ -1,3 +1,5 @@
+/* SPDX-License-Identifier: MPL-2.0 */
+
.text
.global context_switch
.code64
diff --git a/framework/aster-frame/src/task/switch.S b/framework/aster-frame/src/task/switch.S
--- a/framework/aster-frame/src/task/switch.S
+++ b/framework/aster-frame/src/task/switch.S
@@ -1,3 +1,5 @@
+/* SPDX-License-Identifier: MPL-2.0 */
+
.text
.global context_switch
.code64
diff --git a/framework/aster-frame/src/task/task.rs b/framework/aster-frame/src/task/task.rs
--- a/framework/aster-frame/src/task/task.rs
+++ b/framework/aster-frame/src/task/task.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::arch::mm::PageTableFlags;
use crate::config::{KERNEL_STACK_SIZE, PAGE_SIZE};
use crate::cpu::CpuSet;
diff --git a/framework/aster-frame/src/task/task.rs b/framework/aster-frame/src/task/task.rs
--- a/framework/aster-frame/src/task/task.rs
+++ b/framework/aster-frame/src/task/task.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::arch::mm::PageTableFlags;
use crate::config::{KERNEL_STACK_SIZE, PAGE_SIZE};
use crate::cpu::CpuSet;
diff --git a/framework/aster-frame/src/timer.rs b/framework/aster-frame/src/timer.rs
--- a/framework/aster-frame/src/timer.rs
+++ b/framework/aster-frame/src/timer.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Timer.
#[cfg(target_arch = "x86_64")]
diff --git a/framework/aster-frame/src/timer.rs b/framework/aster-frame/src/timer.rs
--- a/framework/aster-frame/src/timer.rs
+++ b/framework/aster-frame/src/timer.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Timer.
#[cfg(target_arch = "x86_64")]
diff --git a/framework/aster-frame/src/trap/handler.rs b/framework/aster-frame/src/trap/handler.rs
--- a/framework/aster-frame/src/trap/handler.rs
+++ b/framework/aster-frame/src/trap/handler.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{arch::irq::IRQ_LIST, cpu::CpuException};
#[cfg(feature = "intel_tdx")]
diff --git a/framework/aster-frame/src/trap/handler.rs b/framework/aster-frame/src/trap/handler.rs
--- a/framework/aster-frame/src/trap/handler.rs
+++ b/framework/aster-frame/src/trap/handler.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{arch::irq::IRQ_LIST, cpu::CpuException};
#[cfg(feature = "intel_tdx")]
diff --git a/framework/aster-frame/src/trap/irq.rs b/framework/aster-frame/src/trap/irq.rs
--- a/framework/aster-frame/src/trap/irq.rs
+++ b/framework/aster-frame/src/trap/irq.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::arch::irq::{self, IrqCallbackHandle, NOT_USING_IRQ};
use crate::task::{disable_preempt, DisablePreemptGuard};
use crate::{prelude::*, Error};
diff --git a/framework/aster-frame/src/trap/irq.rs b/framework/aster-frame/src/trap/irq.rs
--- a/framework/aster-frame/src/trap/irq.rs
+++ b/framework/aster-frame/src/trap/irq.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::arch::irq::{self, IrqCallbackHandle, NOT_USING_IRQ};
use crate::task::{disable_preempt, DisablePreemptGuard};
use crate::{prelude::*, Error};
diff --git a/framework/aster-frame/src/trap/mod.rs b/framework/aster-frame/src/trap/mod.rs
--- a/framework/aster-frame/src/trap/mod.rs
+++ b/framework/aster-frame/src/trap/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod handler;
mod irq;
diff --git a/framework/aster-frame/src/trap/mod.rs b/framework/aster-frame/src/trap/mod.rs
--- a/framework/aster-frame/src/trap/mod.rs
+++ b/framework/aster-frame/src/trap/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod handler;
mod irq;
diff --git a/framework/aster-frame/src/user.rs b/framework/aster-frame/src/user.rs
--- a/framework/aster-frame/src/user.rs
+++ b/framework/aster-frame/src/user.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! User space.
use crate::cpu::UserContext;
diff --git a/framework/aster-frame/src/user.rs b/framework/aster-frame/src/user.rs
--- a/framework/aster-frame/src/user.rs
+++ b/framework/aster-frame/src/user.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! User space.
use crate::cpu::UserContext;
diff --git a/framework/aster-frame/src/util/mod.rs b/framework/aster-frame/src/util/mod.rs
--- a/framework/aster-frame/src/util/mod.rs
+++ b/framework/aster-frame/src/util/mod.rs
@@ -1,1 +1,3 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod recycle_allocator;
diff --git a/framework/aster-frame/src/util/mod.rs b/framework/aster-frame/src/util/mod.rs
--- a/framework/aster-frame/src/util/mod.rs
+++ b/framework/aster-frame/src/util/mod.rs
@@ -1,1 +1,3 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod recycle_allocator;
diff --git a/framework/aster-frame/src/util/recycle_allocator.rs b/framework/aster-frame/src/util/recycle_allocator.rs
--- a/framework/aster-frame/src/util/recycle_allocator.rs
+++ b/framework/aster-frame/src/util/recycle_allocator.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::vec::Vec;
#[derive(Debug)]
diff --git a/framework/aster-frame/src/util/recycle_allocator.rs b/framework/aster-frame/src/util/recycle_allocator.rs
--- a/framework/aster-frame/src/util/recycle_allocator.rs
+++ b/framework/aster-frame/src/util/recycle_allocator.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::vec::Vec;
#[derive(Debug)]
diff --git a/framework/aster-frame/src/vm/dma/dma_coherent.rs b/framework/aster-frame/src/vm/dma/dma_coherent.rs
--- a/framework/aster-frame/src/vm/dma/dma_coherent.rs
+++ b/framework/aster-frame/src/vm/dma/dma_coherent.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::sync::Arc;
use core::ops::Deref;
diff --git a/framework/aster-frame/src/vm/dma/dma_coherent.rs b/framework/aster-frame/src/vm/dma/dma_coherent.rs
--- a/framework/aster-frame/src/vm/dma/dma_coherent.rs
+++ b/framework/aster-frame/src/vm/dma/dma_coherent.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::sync::Arc;
use core::ops::Deref;
diff --git a/framework/aster-frame/src/vm/dma/dma_stream.rs b/framework/aster-frame/src/vm/dma/dma_stream.rs
--- a/framework/aster-frame/src/vm/dma/dma_stream.rs
+++ b/framework/aster-frame/src/vm/dma/dma_stream.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::sync::Arc;
use core::arch::x86_64::_mm_clflush;
use core::ops::Range;
diff --git a/framework/aster-frame/src/vm/dma/dma_stream.rs b/framework/aster-frame/src/vm/dma/dma_stream.rs
--- a/framework/aster-frame/src/vm/dma/dma_stream.rs
+++ b/framework/aster-frame/src/vm/dma/dma_stream.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::sync::Arc;
use core::arch::x86_64::_mm_clflush;
use core::ops::Range;
diff --git a/framework/aster-frame/src/vm/dma/mod.rs b/framework/aster-frame/src/vm/dma/mod.rs
--- a/framework/aster-frame/src/vm/dma/mod.rs
+++ b/framework/aster-frame/src/vm/dma/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod dma_coherent;
mod dma_stream;
diff --git a/framework/aster-frame/src/vm/dma/mod.rs b/framework/aster-frame/src/vm/dma/mod.rs
--- a/framework/aster-frame/src/vm/dma/mod.rs
+++ b/framework/aster-frame/src/vm/dma/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod dma_coherent;
mod dma_stream;
diff --git a/framework/aster-frame/src/vm/frame.rs b/framework/aster-frame/src/vm/frame.rs
--- a/framework/aster-frame/src/vm/frame.rs
+++ b/framework/aster-frame/src/vm/frame.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::vec;
use core::{
iter::Iterator,
diff --git a/framework/aster-frame/src/vm/frame.rs b/framework/aster-frame/src/vm/frame.rs
--- a/framework/aster-frame/src/vm/frame.rs
+++ b/framework/aster-frame/src/vm/frame.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::vec;
use core::{
iter::Iterator,
diff --git a/framework/aster-frame/src/vm/frame_allocator.rs b/framework/aster-frame/src/vm/frame_allocator.rs
--- a/framework/aster-frame/src/vm/frame_allocator.rs
+++ b/framework/aster-frame/src/vm/frame_allocator.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use align_ext::AlignExt;
use alloc::vec::Vec;
use buddy_system_allocator::FrameAllocator;
diff --git a/framework/aster-frame/src/vm/frame_allocator.rs b/framework/aster-frame/src/vm/frame_allocator.rs
--- a/framework/aster-frame/src/vm/frame_allocator.rs
+++ b/framework/aster-frame/src/vm/frame_allocator.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use align_ext::AlignExt;
use alloc::vec::Vec;
use buddy_system_allocator::FrameAllocator;
diff --git a/framework/aster-frame/src/vm/heap_allocator.rs b/framework/aster-frame/src/vm/heap_allocator.rs
--- a/framework/aster-frame/src/vm/heap_allocator.rs
+++ b/framework/aster-frame/src/vm/heap_allocator.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::config::{KERNEL_HEAP_SIZE, PAGE_SIZE};
use crate::prelude::*;
use crate::sync::SpinLock;
diff --git a/framework/aster-frame/src/vm/heap_allocator.rs b/framework/aster-frame/src/vm/heap_allocator.rs
--- a/framework/aster-frame/src/vm/heap_allocator.rs
+++ b/framework/aster-frame/src/vm/heap_allocator.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::config::{KERNEL_HEAP_SIZE, PAGE_SIZE};
use crate::prelude::*;
use crate::sync::SpinLock;
diff --git a/framework/aster-frame/src/vm/io.rs b/framework/aster-frame/src/vm/io.rs
--- a/framework/aster-frame/src/vm/io.rs
+++ b/framework/aster-frame/src/vm/io.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use pod::Pod;
diff --git a/framework/aster-frame/src/vm/io.rs b/framework/aster-frame/src/vm/io.rs
--- a/framework/aster-frame/src/vm/io.rs
+++ b/framework/aster-frame/src/vm/io.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use pod::Pod;
diff --git a/framework/aster-frame/src/vm/memory_set.rs b/framework/aster-frame/src/vm/memory_set.rs
--- a/framework/aster-frame/src/vm/memory_set.rs
+++ b/framework/aster-frame/src/vm/memory_set.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::page_table::{PageTable, PageTableConfig, UserMode};
use crate::{
arch::mm::{PageTableEntry, PageTableFlags},
diff --git a/framework/aster-frame/src/vm/memory_set.rs b/framework/aster-frame/src/vm/memory_set.rs
--- a/framework/aster-frame/src/vm/memory_set.rs
+++ b/framework/aster-frame/src/vm/memory_set.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::page_table::{PageTable, PageTableConfig, UserMode};
use crate::{
arch::mm::{PageTableEntry, PageTableFlags},
diff --git a/framework/aster-frame/src/vm/mod.rs b/framework/aster-frame/src/vm/mod.rs
--- a/framework/aster-frame/src/vm/mod.rs
+++ b/framework/aster-frame/src/vm/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Virtual memory (VM).
/// Virtual addresses.
diff --git a/framework/aster-frame/src/vm/mod.rs b/framework/aster-frame/src/vm/mod.rs
--- a/framework/aster-frame/src/vm/mod.rs
+++ b/framework/aster-frame/src/vm/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Virtual memory (VM).
/// Virtual addresses.
diff --git a/framework/aster-frame/src/vm/offset.rs b/framework/aster-frame/src/vm/offset.rs
--- a/framework/aster-frame/src/vm/offset.rs
+++ b/framework/aster-frame/src/vm/offset.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
/// Get the offset of a field within a type as a pointer.
///
/// ```rust
diff --git a/framework/aster-frame/src/vm/offset.rs b/framework/aster-frame/src/vm/offset.rs
--- a/framework/aster-frame/src/vm/offset.rs
+++ b/framework/aster-frame/src/vm/offset.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
/// Get the offset of a field within a type as a pointer.
///
/// ```rust
diff --git a/framework/aster-frame/src/vm/options.rs b/framework/aster-frame/src/vm/options.rs
--- a/framework/aster-frame/src/vm/options.rs
+++ b/framework/aster-frame/src/vm/options.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{prelude::*, Error};
use super::{frame::VmFrameFlags, frame_allocator, VmFrame, VmFrameVec, VmSegment};
diff --git a/framework/aster-frame/src/vm/options.rs b/framework/aster-frame/src/vm/options.rs
--- a/framework/aster-frame/src/vm/options.rs
+++ b/framework/aster-frame/src/vm/options.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{prelude::*, Error};
use super::{frame::VmFrameFlags, frame_allocator, VmFrame, VmFrameVec, VmSegment};
diff --git a/framework/aster-frame/src/vm/page_table.rs b/framework/aster-frame/src/vm/page_table.rs
--- a/framework/aster-frame/src/vm/page_table.rs
+++ b/framework/aster-frame/src/vm/page_table.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{paddr_to_vaddr, Paddr, Vaddr, VmAllocOptions};
use crate::{
arch::mm::{is_kernel_vaddr, is_user_vaddr, tlb_flush, PageTableEntry},
diff --git a/framework/aster-frame/src/vm/page_table.rs b/framework/aster-frame/src/vm/page_table.rs
--- a/framework/aster-frame/src/vm/page_table.rs
+++ b/framework/aster-frame/src/vm/page_table.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{paddr_to_vaddr, Paddr, Vaddr, VmAllocOptions};
use crate::{
arch::mm::{is_kernel_vaddr, is_user_vaddr, tlb_flush, PageTableEntry},
diff --git a/framework/aster-frame/src/vm/space.rs b/framework/aster-frame/src/vm/space.rs
--- a/framework/aster-frame/src/vm/space.rs
+++ b/framework/aster-frame/src/vm/space.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::arch::mm::PageTableFlags;
use crate::config::PAGE_SIZE;
use crate::sync::Mutex;
diff --git a/framework/aster-frame/src/vm/space.rs b/framework/aster-frame/src/vm/space.rs
--- a/framework/aster-frame/src/vm/space.rs
+++ b/framework/aster-frame/src/vm/space.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::arch::mm::PageTableFlags;
use crate::config::PAGE_SIZE;
use crate::sync::Mutex;
diff --git a/framework/libs/align_ext/src/lib.rs b/framework/libs/align_ext/src/lib.rs
--- a/framework/libs/align_ext/src/lib.rs
+++ b/framework/libs/align_ext/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#![cfg_attr(not(test), no_std)]
/// An extension trait for Rust integer types, including `u8`, `u16`, `u32`,
diff --git a/framework/libs/ktest-proc-macro/src/lib.rs b/framework/libs/ktest-proc-macro/src/lib.rs
--- a/framework/libs/ktest-proc-macro/src/lib.rs
+++ b/framework/libs/ktest-proc-macro/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#![feature(proc_macro_span)]
extern crate proc_macro2;
diff --git a/framework/libs/ktest/src/lib.rs b/framework/libs/ktest/src/lib.rs
--- a/framework/libs/ktest/src/lib.rs
+++ b/framework/libs/ktest/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! # The kernel mode testing framework of Asterinas.
//!
//! `ktest` stands for kernel-mode testing framework. Its goal is to provide a
diff --git a/framework/libs/ktest/src/path.rs b/framework/libs/ktest/src/path.rs
--- a/framework/libs/ktest/src/path.rs
+++ b/framework/libs/ktest/src/path.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::{
collections::{vec_deque, BTreeMap, VecDeque},
string::{String, ToString},
diff --git a/framework/libs/ktest/src/runner.rs b/framework/libs/ktest/src/runner.rs
--- a/framework/libs/ktest/src/runner.rs
+++ b/framework/libs/ktest/src/runner.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Test runner enabling control over the tests.
//!
diff --git a/framework/libs/ktest/src/tree.rs b/framework/libs/ktest/src/tree.rs
--- a/framework/libs/ktest/src/tree.rs
+++ b/framework/libs/ktest/src/tree.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The source module tree of ktests.
//!
//! In the `KtestTree`, the root is abstract, and the children of the root are the
diff --git a/framework/libs/linux-bzimage/boot-params/src/lib.rs b/framework/libs/linux-bzimage/boot-params/src/lib.rs
--- a/framework/libs/linux-bzimage/boot-params/src/lib.rs
+++ b/framework/libs/linux-bzimage/boot-params/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The definition of Linux Boot Protocol boot_params struct.
//!
//! The bootloader will deliver the address of the `BootParams` struct
diff --git a/framework/libs/linux-bzimage/boot-params/src/lib.rs b/framework/libs/linux-bzimage/boot-params/src/lib.rs
--- a/framework/libs/linux-bzimage/boot-params/src/lib.rs
+++ b/framework/libs/linux-bzimage/boot-params/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The definition of Linux Boot Protocol boot_params struct.
//!
//! The bootloader will deliver the address of the `BootParams` struct
diff --git a/framework/libs/linux-bzimage/builder/src/lib.rs b/framework/libs/linux-bzimage/builder/src/lib.rs
--- a/framework/libs/linux-bzimage/builder/src/lib.rs
+++ b/framework/libs/linux-bzimage/builder/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The linux bzImage builder.
//!
//! This crate is responsible for building the bzImage. It contains methods to build
diff --git a/framework/libs/linux-bzimage/builder/src/lib.rs b/framework/libs/linux-bzimage/builder/src/lib.rs
--- a/framework/libs/linux-bzimage/builder/src/lib.rs
+++ b/framework/libs/linux-bzimage/builder/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The linux bzImage builder.
//!
//! This crate is responsible for building the bzImage. It contains methods to build
diff --git a/framework/libs/linux-bzimage/builder/src/mapping.rs b/framework/libs/linux-bzimage/builder/src/mapping.rs
--- a/framework/libs/linux-bzimage/builder/src/mapping.rs
+++ b/framework/libs/linux-bzimage/builder/src/mapping.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! In the setup, VA - SETUP32_LMA == FileOffset - LEGACY_SETUP_SEC_SIZE.
//! And the addresses are specified in the ELF file.
//!
diff --git a/framework/libs/linux-bzimage/builder/src/mapping.rs b/framework/libs/linux-bzimage/builder/src/mapping.rs
--- a/framework/libs/linux-bzimage/builder/src/mapping.rs
+++ b/framework/libs/linux-bzimage/builder/src/mapping.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! In the setup, VA - SETUP32_LMA == FileOffset - LEGACY_SETUP_SEC_SIZE.
//! And the addresses are specified in the ELF file.
//!
diff --git a/framework/libs/linux-bzimage/builder/src/pe_header.rs b/framework/libs/linux-bzimage/builder/src/pe_header.rs
--- a/framework/libs/linux-bzimage/builder/src/pe_header.rs
+++ b/framework/libs/linux-bzimage/builder/src/pe_header.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Big zImage PE/COFF header generation.
//!
//! The definition of the PE/COFF header is in the Microsoft PE/COFF specification:
diff --git a/framework/libs/linux-bzimage/builder/src/pe_header.rs b/framework/libs/linux-bzimage/builder/src/pe_header.rs
--- a/framework/libs/linux-bzimage/builder/src/pe_header.rs
+++ b/framework/libs/linux-bzimage/builder/src/pe_header.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Big zImage PE/COFF header generation.
//!
//! The definition of the PE/COFF header is in the Microsoft PE/COFF specification:
diff --git a/framework/libs/linux-bzimage/setup/build.rs b/framework/libs/linux-bzimage/setup/build.rs
--- a/framework/libs/linux-bzimage/setup/build.rs
+++ b/framework/libs/linux-bzimage/setup/build.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use std::path::PathBuf;
fn main() {
diff --git a/framework/libs/linux-bzimage/setup/build.rs b/framework/libs/linux-bzimage/setup/build.rs
--- a/framework/libs/linux-bzimage/setup/build.rs
+++ b/framework/libs/linux-bzimage/setup/build.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use std::path::PathBuf;
fn main() {
diff --git a/framework/libs/linux-bzimage/setup/src/console.rs b/framework/libs/linux-bzimage/setup/src/console.rs
--- a/framework/libs/linux-bzimage/setup/src/console.rs
+++ b/framework/libs/linux-bzimage/setup/src/console.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::fmt::{self, Write};
use uart_16550::SerialPort;
diff --git a/framework/libs/linux-bzimage/setup/src/console.rs b/framework/libs/linux-bzimage/setup/src/console.rs
--- a/framework/libs/linux-bzimage/setup/src/console.rs
+++ b/framework/libs/linux-bzimage/setup/src/console.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::fmt::{self, Write};
use uart_16550::SerialPort;
diff --git a/framework/libs/linux-bzimage/setup/src/loader.rs b/framework/libs/linux-bzimage/setup/src/loader.rs
--- a/framework/libs/linux-bzimage/setup/src/loader.rs
+++ b/framework/libs/linux-bzimage/setup/src/loader.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use xmas_elf::program::{ProgramHeader, SegmentData};
/// Load the kernel ELF payload to memory.
diff --git a/framework/libs/linux-bzimage/setup/src/loader.rs b/framework/libs/linux-bzimage/setup/src/loader.rs
--- a/framework/libs/linux-bzimage/setup/src/loader.rs
+++ b/framework/libs/linux-bzimage/setup/src/loader.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use xmas_elf::program::{ProgramHeader, SegmentData};
/// Load the kernel ELF payload to memory.
diff --git a/framework/libs/linux-bzimage/setup/src/main.rs b/framework/libs/linux-bzimage/setup/src/main.rs
--- a/framework/libs/linux-bzimage/setup/src/main.rs
+++ b/framework/libs/linux-bzimage/setup/src/main.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The linux bzImage setup binary.
//!
//! With respect to the format of the bzImage, we design our bzImage setup in the similar
diff --git a/framework/libs/linux-bzimage/setup/src/main.rs b/framework/libs/linux-bzimage/setup/src/main.rs
--- a/framework/libs/linux-bzimage/setup/src/main.rs
+++ b/framework/libs/linux-bzimage/setup/src/main.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The linux bzImage setup binary.
//!
//! With respect to the format of the bzImage, we design our bzImage setup in the similar
diff --git a/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs b/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs
--- a/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs
+++ b/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use uefi::{
data_types::Handle,
proto::loaded_image::LoadedImage,
diff --git a/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs b/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs
--- a/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs
+++ b/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/efi.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use uefi::{
data_types::Handle,
proto::loaded_image::LoadedImage,
diff --git a/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/header.S b/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/header.S
--- a/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/header.S
+++ b/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/header.S
@@ -1,3 +1,5 @@
+/* SPDX-License-Identifier: MPL-2.0 */
+
// The compatibility file for the Linux x86 Boot Protocol.
// See https://www.kernel.org/doc/html/v5.6/x86/boot.html for
// more information on the Linux x86 Boot Protocol.
diff --git a/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/header.S b/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/header.S
--- a/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/header.S
+++ b/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/header.S
@@ -1,3 +1,5 @@
+/* SPDX-License-Identifier: MPL-2.0 */
+
// The compatibility file for the Linux x86 Boot Protocol.
// See https://www.kernel.org/doc/html/v5.6/x86/boot.html for
// more information on the Linux x86 Boot Protocol.
diff --git a/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/mod.rs b/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/mod.rs
--- a/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/mod.rs
+++ b/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod efi;
mod paging;
mod relocation;
diff --git a/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/mod.rs b/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/mod.rs
--- a/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/mod.rs
+++ b/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod efi;
mod paging;
mod relocation;
diff --git a/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs b/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs
--- a/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs
+++ b/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! This module provides abstraction over the Intel IA32E paging mechanism. And
//! offers method to create linear page tables.
//!
diff --git a/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs b/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs
--- a/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs
+++ b/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/paging.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! This module provides abstraction over the Intel IA32E paging mechanism. And
//! offers method to create linear page tables.
//!
diff --git a/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs b/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs
--- a/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs
+++ b/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::x86::get_image_loaded_offset;
struct Elf64Rela {
diff --git a/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs b/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs
--- a/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs
+++ b/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/relocation.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::x86::get_image_loaded_offset;
struct Elf64Rela {
diff --git a/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/setup.S b/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/setup.S
--- a/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/setup.S
+++ b/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/setup.S
@@ -1,3 +1,5 @@
+/* SPDX-License-Identifier: MPL-2.0 */
+
.section ".setup", "ax"
.code64
// start_of_setup32 should be loaded at CODE32_START, which is our base.
diff --git a/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/setup.S b/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/setup.S
--- a/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/setup.S
+++ b/framework/libs/linux-bzimage/setup/src/x86/amd64_efi/setup.S
@@ -1,3 +1,5 @@
+/* SPDX-License-Identifier: MPL-2.0 */
+
.section ".setup", "ax"
.code64
// start_of_setup32 should be loaded at CODE32_START, which is our base.
diff --git a/framework/libs/linux-bzimage/setup/src/x86/legacy_i386/header.S b/framework/libs/linux-bzimage/setup/src/x86/legacy_i386/header.S
--- a/framework/libs/linux-bzimage/setup/src/x86/legacy_i386/header.S
+++ b/framework/libs/linux-bzimage/setup/src/x86/legacy_i386/header.S
@@ -1,3 +1,5 @@
+/* SPDX-License-Identifier: MPL-2.0 */
+
// The compatibility file for the Linux x86 Boot Protocol.
// See https://www.kernel.org/doc/html/v5.6/x86/boot.html for
// more information on the Linux x86 Boot Protocol.
diff --git a/framework/libs/linux-bzimage/setup/src/x86/legacy_i386/header.S b/framework/libs/linux-bzimage/setup/src/x86/legacy_i386/header.S
--- a/framework/libs/linux-bzimage/setup/src/x86/legacy_i386/header.S
+++ b/framework/libs/linux-bzimage/setup/src/x86/legacy_i386/header.S
@@ -1,3 +1,5 @@
+/* SPDX-License-Identifier: MPL-2.0 */
+
// The compatibility file for the Linux x86 Boot Protocol.
// See https://www.kernel.org/doc/html/v5.6/x86/boot.html for
// more information on the Linux x86 Boot Protocol.
diff --git a/framework/libs/linux-bzimage/setup/src/x86/legacy_i386/mod.rs b/framework/libs/linux-bzimage/setup/src/x86/legacy_i386/mod.rs
--- a/framework/libs/linux-bzimage/setup/src/x86/legacy_i386/mod.rs
+++ b/framework/libs/linux-bzimage/setup/src/x86/legacy_i386/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use linux_boot_params::BootParams;
use core::arch::{asm, global_asm};
diff --git a/framework/libs/linux-bzimage/setup/src/x86/legacy_i386/mod.rs b/framework/libs/linux-bzimage/setup/src/x86/legacy_i386/mod.rs
--- a/framework/libs/linux-bzimage/setup/src/x86/legacy_i386/mod.rs
+++ b/framework/libs/linux-bzimage/setup/src/x86/legacy_i386/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use linux_boot_params::BootParams;
use core::arch::{asm, global_asm};
diff --git a/framework/libs/linux-bzimage/setup/src/x86/legacy_i386/setup.S b/framework/libs/linux-bzimage/setup/src/x86/legacy_i386/setup.S
--- a/framework/libs/linux-bzimage/setup/src/x86/legacy_i386/setup.S
+++ b/framework/libs/linux-bzimage/setup/src/x86/legacy_i386/setup.S
@@ -1,3 +1,5 @@
+/* SPDX-License-Identifier: MPL-2.0 */
+
// 32-bit setup code starts here, and will be loaded at CODE32_START.
.section ".setup", "ax"
.code32
diff --git a/framework/libs/linux-bzimage/setup/src/x86/legacy_i386/setup.S b/framework/libs/linux-bzimage/setup/src/x86/legacy_i386/setup.S
--- a/framework/libs/linux-bzimage/setup/src/x86/legacy_i386/setup.S
+++ b/framework/libs/linux-bzimage/setup/src/x86/legacy_i386/setup.S
@@ -1,3 +1,5 @@
+/* SPDX-License-Identifier: MPL-2.0 */
+
// 32-bit setup code starts here, and will be loaded at CODE32_START.
.section ".setup", "ax"
.code32
diff --git a/framework/libs/linux-bzimage/setup/src/x86/mod.rs b/framework/libs/linux-bzimage/setup/src/x86/mod.rs
--- a/framework/libs/linux-bzimage/setup/src/x86/mod.rs
+++ b/framework/libs/linux-bzimage/setup/src/x86/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
cfg_if::cfg_if! {
if #[cfg(target_arch = "x86_64")] {
mod amd64_efi;
diff --git a/framework/libs/linux-bzimage/setup/src/x86/mod.rs b/framework/libs/linux-bzimage/setup/src/x86/mod.rs
--- a/framework/libs/linux-bzimage/setup/src/x86/mod.rs
+++ b/framework/libs/linux-bzimage/setup/src/x86/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
cfg_if::cfg_if! {
if #[cfg(target_arch = "x86_64")] {
mod amd64_efi;
diff --git a/framework/libs/tdx-guest/src/asm/mod.rs b/framework/libs/tdx-guest/src/asm/mod.rs
--- a/framework/libs/tdx-guest/src/asm/mod.rs
+++ b/framework/libs/tdx-guest/src/asm/mod.rs
@@ -1,3 +1,6 @@
+// SPDX-License-Identifier: BSD-3-Clause
+// Copyright(c) 2023-2024 Intel Corporation.
+
use crate::{tdcall::TdcallArgs, tdvmcall::TdVmcallArgs};
use core::arch::global_asm;
diff --git a/framework/libs/tdx-guest/src/asm/mod.rs b/framework/libs/tdx-guest/src/asm/mod.rs
--- a/framework/libs/tdx-guest/src/asm/mod.rs
+++ b/framework/libs/tdx-guest/src/asm/mod.rs
@@ -1,3 +1,6 @@
+// SPDX-License-Identifier: BSD-3-Clause
+// Copyright(c) 2023-2024 Intel Corporation.
+
use crate::{tdcall::TdcallArgs, tdvmcall::TdVmcallArgs};
use core::arch::global_asm;
diff --git a/framework/libs/tdx-guest/src/asm/tdcall.asm b/framework/libs/tdx-guest/src/asm/tdcall.asm
--- a/framework/libs/tdx-guest/src/asm/tdcall.asm
+++ b/framework/libs/tdx-guest/src/asm/tdcall.asm
@@ -1,3 +1,6 @@
+# SPDX-License-Identifier: BSD-3-Clause
+# Copyright(c) 2023-2024 Intel Corporation.
+
.section .text
# Arguments offsets in TdVmcallArgs struct
diff --git a/framework/libs/tdx-guest/src/asm/tdcall.asm b/framework/libs/tdx-guest/src/asm/tdcall.asm
--- a/framework/libs/tdx-guest/src/asm/tdcall.asm
+++ b/framework/libs/tdx-guest/src/asm/tdcall.asm
@@ -1,3 +1,6 @@
+# SPDX-License-Identifier: BSD-3-Clause
+# Copyright(c) 2023-2024 Intel Corporation.
+
.section .text
# Arguments offsets in TdVmcallArgs struct
diff --git a/framework/libs/tdx-guest/src/asm/tdvmcall.asm b/framework/libs/tdx-guest/src/asm/tdvmcall.asm
--- a/framework/libs/tdx-guest/src/asm/tdvmcall.asm
+++ b/framework/libs/tdx-guest/src/asm/tdvmcall.asm
@@ -1,3 +1,6 @@
+# SPDX-License-Identifier: BSD-3-Clause
+# Copyright(c) 2023-2024 Intel Corporation.
+
.section .text
# Mask used to control which part of the guest TD GPR and XMM
diff --git a/framework/libs/tdx-guest/src/asm/tdvmcall.asm b/framework/libs/tdx-guest/src/asm/tdvmcall.asm
--- a/framework/libs/tdx-guest/src/asm/tdvmcall.asm
+++ b/framework/libs/tdx-guest/src/asm/tdvmcall.asm
@@ -1,3 +1,6 @@
+# SPDX-License-Identifier: BSD-3-Clause
+# Copyright(c) 2023-2024 Intel Corporation.
+
.section .text
# Mask used to control which part of the guest TD GPR and XMM
diff --git a/framework/libs/tdx-guest/src/lib.rs b/framework/libs/tdx-guest/src/lib.rs
--- a/framework/libs/tdx-guest/src/lib.rs
+++ b/framework/libs/tdx-guest/src/lib.rs
@@ -1,3 +1,6 @@
+// SPDX-License-Identifier: BSD-3-Clause
+// Copyright(c) 2023-2024 Intel Corporation.
+
#![no_std]
#![allow(dead_code)]
#![allow(unused_variables)]
diff --git a/framework/libs/tdx-guest/src/lib.rs b/framework/libs/tdx-guest/src/lib.rs
--- a/framework/libs/tdx-guest/src/lib.rs
+++ b/framework/libs/tdx-guest/src/lib.rs
@@ -1,3 +1,6 @@
+// SPDX-License-Identifier: BSD-3-Clause
+// Copyright(c) 2023-2024 Intel Corporation.
+
#![no_std]
#![allow(dead_code)]
#![allow(unused_variables)]
diff --git a/framework/libs/tdx-guest/src/tdcall.rs b/framework/libs/tdx-guest/src/tdcall.rs
--- a/framework/libs/tdx-guest/src/tdcall.rs
+++ b/framework/libs/tdx-guest/src/tdcall.rs
@@ -1,3 +1,6 @@
+// SPDX-License-Identifier: BSD-3-Clause
+// Copyright(c) 2023-2024 Intel Corporation.
+
//! The TDCALL instruction causes a VM exit to the Intel TDX module.
//! It is used to call guest-side Intel TDX functions. For more information about
//! TDCALL, please refer to the [Intel® TDX Module v1.5 ABI Specification](https://cdrdv2.intel.com/v1/dl/getContent/733579)
diff --git a/framework/libs/tdx-guest/src/tdcall.rs b/framework/libs/tdx-guest/src/tdcall.rs
--- a/framework/libs/tdx-guest/src/tdcall.rs
+++ b/framework/libs/tdx-guest/src/tdcall.rs
@@ -1,3 +1,6 @@
+// SPDX-License-Identifier: BSD-3-Clause
+// Copyright(c) 2023-2024 Intel Corporation.
+
//! The TDCALL instruction causes a VM exit to the Intel TDX module.
//! It is used to call guest-side Intel TDX functions. For more information about
//! TDCALL, please refer to the [Intel® TDX Module v1.5 ABI Specification](https://cdrdv2.intel.com/v1/dl/getContent/733579)
diff --git a/framework/libs/tdx-guest/src/tdvmcall.rs b/framework/libs/tdx-guest/src/tdvmcall.rs
--- a/framework/libs/tdx-guest/src/tdvmcall.rs
+++ b/framework/libs/tdx-guest/src/tdvmcall.rs
@@ -1,3 +1,6 @@
+// SPDX-License-Identifier: BSD-3-Clause
+// Copyright(c) 2023-2024 Intel Corporation.
+
//! The TDVMCALL helps invoke services from the host VMM. From the perspective of the host VMM, the TDVMCALL is a trap-like, VM exit into
//! the host VMM, reported via the SEAMRET instruction flow.
//! By design, after the SEAMRET, the host VMM services the request specified in the parameters
diff --git a/framework/libs/tdx-guest/src/tdvmcall.rs b/framework/libs/tdx-guest/src/tdvmcall.rs
--- a/framework/libs/tdx-guest/src/tdvmcall.rs
+++ b/framework/libs/tdx-guest/src/tdvmcall.rs
@@ -1,3 +1,6 @@
+// SPDX-License-Identifier: BSD-3-Clause
+// Copyright(c) 2023-2024 Intel Corporation.
+
//! The TDVMCALL helps invoke services from the host VMM. From the perspective of the host VMM, the TDVMCALL is a trap-like, VM exit into
//! the host VMM, reported via the SEAMRET instruction flow.
//! By design, after the SEAMRET, the host VMM services the request specified in the parameters
diff --git a/kernel/main.rs b/kernel/main.rs
--- a/kernel/main.rs
+++ b/kernel/main.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#![no_std]
#![no_main]
// The `export_name` attribute for the `aster_main` entrypoint requires the removal of safety check.
diff --git a/kernel/main.rs b/kernel/main.rs
--- a/kernel/main.rs
+++ b/kernel/main.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#![no_std]
#![no_main]
// The `export_name` attribute for the `aster_main` entrypoint requires the removal of safety check.
diff --git a/regression/Makefile b/regression/Makefile
--- a/regression/Makefile
+++ b/regression/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
MKFILE_PATH := $(abspath $(lastword $(MAKEFILE_LIST)))
CUR_DIR := $(patsubst %/,%,$(dir $(MKFILE_PATH)))
BUILD_DIR := $(CUR_DIR)/build
diff --git a/regression/Makefile b/regression/Makefile
--- a/regression/Makefile
+++ b/regression/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
MKFILE_PATH := $(abspath $(lastword $(MAKEFILE_LIST)))
CUR_DIR := $(patsubst %/,%,$(dir $(MKFILE_PATH)))
BUILD_DIR := $(CUR_DIR)/build
diff --git a/regression/apps/Makefile b/regression/apps/Makefile
--- a/regression/apps/Makefile
+++ b/regression/apps/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
MAKEFLAGS += --no-builtin-rules # Prevent the implicit rules from compiling ".c" or ".s" files automatically.
MKFILE_PATH := $(abspath $(lastword $(MAKEFILE_LIST)))
CUR_DIR := $(patsubst %/,%,$(dir $(MKFILE_PATH)))
diff --git a/regression/apps/Makefile b/regression/apps/Makefile
--- a/regression/apps/Makefile
+++ b/regression/apps/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
MAKEFLAGS += --no-builtin-rules # Prevent the implicit rules from compiling ".c" or ".s" files automatically.
MKFILE_PATH := $(abspath $(lastword $(MAKEFILE_LIST)))
CUR_DIR := $(patsubst %/,%,$(dir $(MKFILE_PATH)))
diff --git a/regression/apps/execve/Makefile b/regression/apps/execve/Makefile
--- a/regression/apps/execve/Makefile
+++ b/regression/apps/execve/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
include ../test_common.mk
EXTRA_C_FLAGS :=-static
diff --git a/regression/apps/execve/execve.c b/regression/apps/execve/execve.c
--- a/regression/apps/execve/execve.c
+++ b/regression/apps/execve/execve.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <stdio.h>
#include <unistd.h>
diff --git a/regression/apps/execve/execve.c b/regression/apps/execve/execve.c
--- a/regression/apps/execve/execve.c
+++ b/regression/apps/execve/execve.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <stdio.h>
#include <unistd.h>
diff --git a/regression/apps/execve/hello.c b/regression/apps/execve/hello.c
--- a/regression/apps/execve/hello.c
+++ b/regression/apps/execve/hello.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <stdio.h>
int main(int argc, char *argv[], char *envp[]) {
diff --git a/regression/apps/execve/hello.c b/regression/apps/execve/hello.c
--- a/regression/apps/execve/hello.c
+++ b/regression/apps/execve/hello.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <stdio.h>
int main(int argc, char *argv[], char *envp[]) {
diff --git a/regression/apps/fork/Makefile b/regression/apps/fork/Makefile
--- a/regression/apps/fork/Makefile
+++ b/regression/apps/fork/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
include ../test_common.mk
EXTRA_C_FLAGS :=-static -nostdlib
diff --git a/regression/apps/fork/fork.s b/regression/apps/fork/fork.s
--- a/regression/apps/fork/fork.s
+++ b/regression/apps/fork/fork.s
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
.global _start
.section .text
diff --git a/regression/apps/fork/fork.s b/regression/apps/fork/fork.s
--- a/regression/apps/fork/fork.s
+++ b/regression/apps/fork/fork.s
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
.global _start
.section .text
diff --git a/regression/apps/fork_c/Makefile b/regression/apps/fork_c/Makefile
--- a/regression/apps/fork_c/Makefile
+++ b/regression/apps/fork_c/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
include ../test_common.mk
EXTRA_C_FLAGS :=-static
diff --git a/regression/apps/fork_c/fork.c b/regression/apps/fork_c/fork.c
--- a/regression/apps/fork_c/fork.c
+++ b/regression/apps/fork_c/fork.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <stdio.h>
#include <unistd.h>
diff --git a/regression/apps/fork_c/fork.c b/regression/apps/fork_c/fork.c
--- a/regression/apps/fork_c/fork.c
+++ b/regression/apps/fork_c/fork.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <stdio.h>
#include <unistd.h>
diff --git a/regression/apps/hello_c/Makefile b/regression/apps/hello_c/Makefile
--- a/regression/apps/hello_c/Makefile
+++ b/regression/apps/hello_c/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
include ../test_common.mk
EXTRA_C_FLAGS :=-static -mno-sse
diff --git a/regression/apps/hello_c/hello.c b/regression/apps/hello_c/hello.c
--- a/regression/apps/hello_c/hello.c
+++ b/regression/apps/hello_c/hello.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <stdio.h>
int main() {
diff --git a/regression/apps/hello_c/hello.c b/regression/apps/hello_c/hello.c
--- a/regression/apps/hello_c/hello.c
+++ b/regression/apps/hello_c/hello.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <stdio.h>
int main() {
diff --git a/regression/apps/hello_pie/Makefile b/regression/apps/hello_pie/Makefile
--- a/regression/apps/hello_pie/Makefile
+++ b/regression/apps/hello_pie/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
include ../test_common.mk
EXTRA_C_FLAGS :=
diff --git a/regression/apps/hello_pie/hello.c b/regression/apps/hello_pie/hello.c
--- a/regression/apps/hello_pie/hello.c
+++ b/regression/apps/hello_pie/hello.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <stdio.h>
int main() {
diff --git a/regression/apps/hello_pie/hello.c b/regression/apps/hello_pie/hello.c
--- a/regression/apps/hello_pie/hello.c
+++ b/regression/apps/hello_pie/hello.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <stdio.h>
int main() {
diff --git a/regression/apps/hello_world/Makefile b/regression/apps/hello_world/Makefile
--- a/regression/apps/hello_world/Makefile
+++ b/regression/apps/hello_world/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
include ../test_common.mk
EXTRA_C_FLAGS :=-static -nostdlib
diff --git a/regression/apps/hello_world/hello_world.s b/regression/apps/hello_world/hello_world.s
--- a/regression/apps/hello_world/hello_world.s
+++ b/regression/apps/hello_world/hello_world.s
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
.global _start
.section .text
diff --git a/regression/apps/hello_world/hello_world.s b/regression/apps/hello_world/hello_world.s
--- a/regression/apps/hello_world/hello_world.s
+++ b/regression/apps/hello_world/hello_world.s
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
.global _start
.section .text
diff --git a/regression/apps/network/Makefile b/regression/apps/network/Makefile
--- a/regression/apps/network/Makefile
+++ b/regression/apps/network/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
include ../test_common.mk
EXTRA_C_FLAGS :=
diff --git a/regression/apps/network/listen_backlog.c b/regression/apps/network/listen_backlog.c
--- a/regression/apps/network/listen_backlog.c
+++ b/regression/apps/network/listen_backlog.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
diff --git a/regression/apps/network/listen_backlog.c b/regression/apps/network/listen_backlog.c
--- a/regression/apps/network/listen_backlog.c
+++ b/regression/apps/network/listen_backlog.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
diff --git a/regression/apps/network/send_buf_full.c b/regression/apps/network/send_buf_full.c
--- a/regression/apps/network/send_buf_full.c
+++ b/regression/apps/network/send_buf_full.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
diff --git a/regression/apps/network/send_buf_full.c b/regression/apps/network/send_buf_full.c
--- a/regression/apps/network/send_buf_full.c
+++ b/regression/apps/network/send_buf_full.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
diff --git a/regression/apps/network/socketpair.c b/regression/apps/network/socketpair.c
--- a/regression/apps/network/socketpair.c
+++ b/regression/apps/network/socketpair.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
diff --git a/regression/apps/network/socketpair.c b/regression/apps/network/socketpair.c
--- a/regression/apps/network/socketpair.c
+++ b/regression/apps/network/socketpair.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
diff --git a/regression/apps/network/sockoption.c b/regression/apps/network/sockoption.c
--- a/regression/apps/network/sockoption.c
+++ b/regression/apps/network/sockoption.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
diff --git a/regression/apps/network/sockoption.c b/regression/apps/network/sockoption.c
--- a/regression/apps/network/sockoption.c
+++ b/regression/apps/network/sockoption.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
diff --git a/regression/apps/network/tcp_client.c b/regression/apps/network/tcp_client.c
--- a/regression/apps/network/tcp_client.c
+++ b/regression/apps/network/tcp_client.c
@@ -1,51 +1,44 @@
-// From: https://www.geeksforgeeks.org/socket-programming-cc/.
-// Some minor modifications are made to the original code base.
-// Lisenced under CCBY-SA.
+// SPDX-License-Identifier: MPL-2.0
-// Client side C/C++ program to demonstrate socket programming
-#include <arpa/inet.h>
#include <stdio.h>
+#include <stdlib.h>
#include <string.h>
-#include <sys/socket.h>
#include <unistd.h>
+#include <arpa/inet.h>
+
#define PORT 8080
-
-int main(int argc, char const* argv[])
-{
- int status, valread, client_fd;
+
+int main() {
+ int sock = 0, valread;
struct sockaddr_in serv_addr;
- char* hello = "Hello from client";
- char buffer[1024] = { 0 };
- if ((client_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
+ char *hello = "Hello from client";
+ char buffer[1024] = {0};
+
+ // Create socket
+ if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("\n Socket creation error \n");
return -1;
}
-
+
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
-
- // Convert IPv4 and IPv6 addresses from text to binary
- // form
- if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)
- <= 0) {
- printf(
- "\nInvalid address/ Address not supported \n");
+
+ // Convert IPv4 address from text to binary form
+ if (inet_pton(AF_INET, "127.0.0.1", &(serv_addr.sin_addr)) <= 0) {
+ printf("\n Invalid address/ Address not supported \n");
return -1;
}
-
- if ((status
- = connect(client_fd, (struct sockaddr*)&serv_addr,
- sizeof(serv_addr)))
- < 0) {
- printf("\nConnection Failed \n");
+
+ // Connect to the server
+ if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
+ printf("\n Connection Failed \n");
return -1;
}
- send(client_fd, hello, strlen(hello), 0);
+
+ // Send message to the server and receive the reply
+ send(sock, hello, strlen(hello), 0);
printf("Hello message sent\n");
- valread = read(client_fd, buffer, 1024);
- printf("%s\n", buffer);
-
- // closing the connected socket
- close(client_fd);
+ valread = read(sock, buffer, 1024);
+ printf("Server: %s\n", buffer);
return 0;
-}
\ No newline at end of file
+}
diff --git a/regression/apps/network/tcp_client.c b/regression/apps/network/tcp_client.c
--- a/regression/apps/network/tcp_client.c
+++ b/regression/apps/network/tcp_client.c
@@ -1,51 +1,44 @@
-// From: https://www.geeksforgeeks.org/socket-programming-cc/.
-// Some minor modifications are made to the original code base.
-// Lisenced under CCBY-SA.
+// SPDX-License-Identifier: MPL-2.0
-// Client side C/C++ program to demonstrate socket programming
-#include <arpa/inet.h>
#include <stdio.h>
+#include <stdlib.h>
#include <string.h>
-#include <sys/socket.h>
#include <unistd.h>
+#include <arpa/inet.h>
+
#define PORT 8080
-
-int main(int argc, char const* argv[])
-{
- int status, valread, client_fd;
+
+int main() {
+ int sock = 0, valread;
struct sockaddr_in serv_addr;
- char* hello = "Hello from client";
- char buffer[1024] = { 0 };
- if ((client_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
+ char *hello = "Hello from client";
+ char buffer[1024] = {0};
+
+ // Create socket
+ if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("\n Socket creation error \n");
return -1;
}
-
+
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
-
- // Convert IPv4 and IPv6 addresses from text to binary
- // form
- if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)
- <= 0) {
- printf(
- "\nInvalid address/ Address not supported \n");
+
+ // Convert IPv4 address from text to binary form
+ if (inet_pton(AF_INET, "127.0.0.1", &(serv_addr.sin_addr)) <= 0) {
+ printf("\n Invalid address/ Address not supported \n");
return -1;
}
-
- if ((status
- = connect(client_fd, (struct sockaddr*)&serv_addr,
- sizeof(serv_addr)))
- < 0) {
- printf("\nConnection Failed \n");
+
+ // Connect to the server
+ if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
+ printf("\n Connection Failed \n");
return -1;
}
- send(client_fd, hello, strlen(hello), 0);
+
+ // Send message to the server and receive the reply
+ send(sock, hello, strlen(hello), 0);
printf("Hello message sent\n");
- valread = read(client_fd, buffer, 1024);
- printf("%s\n", buffer);
-
- // closing the connected socket
- close(client_fd);
+ valread = read(sock, buffer, 1024);
+ printf("Server: %s\n", buffer);
return 0;
-}
\ No newline at end of file
+}
diff --git a/regression/apps/network/tcp_server.c b/regression/apps/network/tcp_server.c
--- a/regression/apps/network/tcp_server.c
+++ b/regression/apps/network/tcp_server.c
@@ -1,75 +1,65 @@
-// From: https://www.geeksforgeeks.org/socket-programming-cc/.
-// Some minor modifications are made to the original code base.
-// Lisenced under CCBY-SA.
+// SPDX-License-Identifier: MPL-2.0
-// Server side C/C++ program to demonstrate socket programming
-#include <arpa/inet.h>
-#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#include <sys/socket.h>
#include <unistd.h>
+#include <arpa/inet.h>
+
#define PORT 8080
-int main(int argc, char const* argv[])
-{
+
+int main() {
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
- char buffer[1024] = { 0 };
- char* hello = "Hello from server";
-
- // Creating socket file descriptor
- if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
+ char buffer[1024] = {0};
+ char *hello = "Hello from server";
+
+ // Create socket
+ if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
-
- // Forcefully attaching socket to the port 8080
- if (setsockopt(server_fd, SOL_SOCKET,
- SO_REUSEADDR | SO_REUSEPORT, &opt,
- sizeof(opt))) {
- perror("setsockopt");
+
+ // Set socket options
+ if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
+ perror("setsockopt failed");
exit(EXIT_FAILURE);
}
+
address.sin_family = AF_INET;
+ address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
- // Convert IPv4 and IPv6 addresses from text to binary
- // form
- if (inet_pton(AF_INET, "127.0.0.1", &address.sin_addr)
- <= 0) {
- printf(
- "\nInvalid address/ Address not supported \n");
+
+ // Convert IPv4 address from text to binary form
+ if (inet_pton(AF_INET, "127.0.0.1", &(address.sin_addr)) <= 0) {
+ printf("\n Invalid address/ Address not supported \n");
return -1;
}
-
- // Forcefully attaching socket to the port 8080
- if (bind(server_fd, (struct sockaddr*)&address,
- sizeof(address))
- < 0) {
+
+ // Bind the socket to specified IP and port
+ if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
+
+ // Listen for connections
if (listen(server_fd, 3) < 0) {
- perror("listen");
+ perror("listen failed");
exit(EXIT_FAILURE);
}
- if ((new_socket
- = accept(server_fd, (struct sockaddr*)&address,
- (socklen_t*)&addrlen))
- < 0) {
- perror("accept");
+
+ // Accept the connection
+ if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&addrlen)) < 0) {
+ perror("accept failed");
exit(EXIT_FAILURE);
}
+
+ // Read the message from the client and reply
valread = read(new_socket, buffer, 1024);
- printf("%s\n", buffer);
+ printf("Client: %s\n", buffer);
send(new_socket, hello, strlen(hello), 0);
printf("Hello message sent\n");
-
- // closing the connected socket
- close(new_socket);
- // closing the listening socket
- shutdown(server_fd, SHUT_RDWR);
return 0;
-}
\ No newline at end of file
+}
diff --git a/regression/apps/network/tcp_server.c b/regression/apps/network/tcp_server.c
--- a/regression/apps/network/tcp_server.c
+++ b/regression/apps/network/tcp_server.c
@@ -1,75 +1,65 @@
-// From: https://www.geeksforgeeks.org/socket-programming-cc/.
-// Some minor modifications are made to the original code base.
-// Lisenced under CCBY-SA.
+// SPDX-License-Identifier: MPL-2.0
-// Server side C/C++ program to demonstrate socket programming
-#include <arpa/inet.h>
-#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#include <sys/socket.h>
#include <unistd.h>
+#include <arpa/inet.h>
+
#define PORT 8080
-int main(int argc, char const* argv[])
-{
+
+int main() {
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
- char buffer[1024] = { 0 };
- char* hello = "Hello from server";
-
- // Creating socket file descriptor
- if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
+ char buffer[1024] = {0};
+ char *hello = "Hello from server";
+
+ // Create socket
+ if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
-
- // Forcefully attaching socket to the port 8080
- if (setsockopt(server_fd, SOL_SOCKET,
- SO_REUSEADDR | SO_REUSEPORT, &opt,
- sizeof(opt))) {
- perror("setsockopt");
+
+ // Set socket options
+ if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
+ perror("setsockopt failed");
exit(EXIT_FAILURE);
}
+
address.sin_family = AF_INET;
+ address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
- // Convert IPv4 and IPv6 addresses from text to binary
- // form
- if (inet_pton(AF_INET, "127.0.0.1", &address.sin_addr)
- <= 0) {
- printf(
- "\nInvalid address/ Address not supported \n");
+
+ // Convert IPv4 address from text to binary form
+ if (inet_pton(AF_INET, "127.0.0.1", &(address.sin_addr)) <= 0) {
+ printf("\n Invalid address/ Address not supported \n");
return -1;
}
-
- // Forcefully attaching socket to the port 8080
- if (bind(server_fd, (struct sockaddr*)&address,
- sizeof(address))
- < 0) {
+
+ // Bind the socket to specified IP and port
+ if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
+
+ // Listen for connections
if (listen(server_fd, 3) < 0) {
- perror("listen");
+ perror("listen failed");
exit(EXIT_FAILURE);
}
- if ((new_socket
- = accept(server_fd, (struct sockaddr*)&address,
- (socklen_t*)&addrlen))
- < 0) {
- perror("accept");
+
+ // Accept the connection
+ if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&addrlen)) < 0) {
+ perror("accept failed");
exit(EXIT_FAILURE);
}
+
+ // Read the message from the client and reply
valread = read(new_socket, buffer, 1024);
- printf("%s\n", buffer);
+ printf("Client: %s\n", buffer);
send(new_socket, hello, strlen(hello), 0);
printf("Hello message sent\n");
-
- // closing the connected socket
- close(new_socket);
- // closing the listening socket
- shutdown(server_fd, SHUT_RDWR);
return 0;
-}
\ No newline at end of file
+}
diff --git a/regression/apps/network/udp_client.c b/regression/apps/network/udp_client.c
--- a/regression/apps/network/udp_client.c
+++ b/regression/apps/network/udp_client.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
diff --git a/regression/apps/network/udp_client.c b/regression/apps/network/udp_client.c
--- a/regression/apps/network/udp_client.c
+++ b/regression/apps/network/udp_client.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
diff --git a/regression/apps/network/udp_server.c b/regression/apps/network/udp_server.c
--- a/regression/apps/network/udp_server.c
+++ b/regression/apps/network/udp_server.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
diff --git a/regression/apps/network/udp_server.c b/regression/apps/network/udp_server.c
--- a/regression/apps/network/udp_server.c
+++ b/regression/apps/network/udp_server.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
diff --git a/regression/apps/network/unix_client.c b/regression/apps/network/unix_client.c
--- a/regression/apps/network/unix_client.c
+++ b/regression/apps/network/unix_client.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
diff --git a/regression/apps/network/unix_client.c b/regression/apps/network/unix_client.c
--- a/regression/apps/network/unix_client.c
+++ b/regression/apps/network/unix_client.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
diff --git a/regression/apps/network/unix_server.c b/regression/apps/network/unix_server.c
--- a/regression/apps/network/unix_server.c
+++ b/regression/apps/network/unix_server.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
diff --git a/regression/apps/network/unix_server.c b/regression/apps/network/unix_server.c
--- a/regression/apps/network/unix_server.c
+++ b/regression/apps/network/unix_server.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
diff --git a/regression/apps/pthread/Makefile b/regression/apps/pthread/Makefile
--- a/regression/apps/pthread/Makefile
+++ b/regression/apps/pthread/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
include ../test_common.mk
EXTRA_C_FLAGS :=-static -lpthread
diff --git a/regression/apps/pthread/pthread_test.c b/regression/apps/pthread/pthread_test.c
--- a/regression/apps/pthread/pthread_test.c
+++ b/regression/apps/pthread/pthread_test.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
// This test file is from occlum pthread test.
#include <sys/types.h>
diff --git a/regression/apps/pty/Makefile b/regression/apps/pty/Makefile
--- a/regression/apps/pty/Makefile
+++ b/regression/apps/pty/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
include ../test_common.mk
EXTRA_C_FLAGS :=
diff --git a/regression/apps/pty/open_pty.c b/regression/apps/pty/open_pty.c
--- a/regression/apps/pty/open_pty.c
+++ b/regression/apps/pty/open_pty.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
diff --git a/regression/apps/pty/open_pty.c b/regression/apps/pty/open_pty.c
--- a/regression/apps/pty/open_pty.c
+++ b/regression/apps/pty/open_pty.c
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
diff --git a/regression/apps/scripts/Makefile b/regression/apps/scripts/Makefile
--- a/regression/apps/scripts/Makefile
+++ b/regression/apps/scripts/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
.PHONY: all
all: ./*.sh
diff --git a/regression/apps/scripts/Makefile b/regression/apps/scripts/Makefile
--- a/regression/apps/scripts/Makefile
+++ b/regression/apps/scripts/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
.PHONY: all
all: ./*.sh
diff --git a/regression/apps/scripts/network.sh b/regression/apps/scripts/network.sh
--- a/regression/apps/scripts/network.sh
+++ b/regression/apps/scripts/network.sh
@@ -1,5 +1,7 @@
#!/bin/sh
+# SPDX-License-Identifier: MPL-2.0
+
set -e
NETTEST_DIR=/regression/network
diff --git a/regression/apps/scripts/network.sh b/regression/apps/scripts/network.sh
--- a/regression/apps/scripts/network.sh
+++ b/regression/apps/scripts/network.sh
@@ -1,5 +1,7 @@
#!/bin/sh
+# SPDX-License-Identifier: MPL-2.0
+
set -e
NETTEST_DIR=/regression/network
diff --git a/regression/apps/scripts/process.sh b/regression/apps/scripts/process.sh
--- a/regression/apps/scripts/process.sh
+++ b/regression/apps/scripts/process.sh
@@ -1,5 +1,7 @@
#!/bin/sh
+# SPDX-License-Identifier: MPL-2.0
+
set -e
SCRIPT_DIR=/regression
diff --git a/regression/apps/scripts/process.sh b/regression/apps/scripts/process.sh
--- a/regression/apps/scripts/process.sh
+++ b/regression/apps/scripts/process.sh
@@ -1,5 +1,7 @@
#!/bin/sh
+# SPDX-License-Identifier: MPL-2.0
+
set -e
SCRIPT_DIR=/regression
diff --git a/regression/apps/scripts/run_regression_test.sh b/regression/apps/scripts/run_regression_test.sh
--- a/regression/apps/scripts/run_regression_test.sh
+++ b/regression/apps/scripts/run_regression_test.sh
@@ -1,5 +1,7 @@
#!/bin/sh
+# SPDX-License-Identifier: MPL-2.0
+
set -e
SCRIPT_DIR=/regression
diff --git a/regression/apps/scripts/shell_cmd.sh b/regression/apps/scripts/shell_cmd.sh
--- a/regression/apps/scripts/shell_cmd.sh
+++ b/regression/apps/scripts/shell_cmd.sh
@@ -1,5 +1,7 @@
#!/bin/sh
+# SPDX-License-Identifier: MPL-2.0
+
set -e
set -x
diff --git a/regression/apps/scripts/shell_cmd.sh b/regression/apps/scripts/shell_cmd.sh
--- a/regression/apps/scripts/shell_cmd.sh
+++ b/regression/apps/scripts/shell_cmd.sh
@@ -1,5 +1,7 @@
#!/bin/sh
+# SPDX-License-Identifier: MPL-2.0
+
set -e
set -x
diff --git a/regression/apps/signal_c/Makefile b/regression/apps/signal_c/Makefile
--- a/regression/apps/signal_c/Makefile
+++ b/regression/apps/signal_c/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
include ../test_common.mk
EXTRA_C_FLAGS :=-static
diff --git a/regression/apps/signal_c/signal_test.c b/regression/apps/signal_c/signal_test.c
--- a/regression/apps/signal_c/signal_test.c
+++ b/regression/apps/signal_c/signal_test.c
@@ -1,4 +1,6 @@
-// This test file is from occlum, to test whether we implement signal correctly.
+// SPDX-License-Identifier: MPL-2.0
+
+// This test file is from occlum signal test.
#define _GNU_SOURCE
#include <sys/types.h>
diff --git a/regression/apps/test_common.mk b/regression/apps/test_common.mk
--- a/regression/apps/test_common.mk
+++ b/regression/apps/test_common.mk
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
MAIN_MAKEFILE := $(firstword $(MAKEFILE_LIST))
INCLUDE_MAKEFILE := $(lastword $(MAKEFILE_LIST))
CUR_DIR := $(shell dirname $(realpath $(MAIN_MAKEFILE)))
diff --git a/regression/syscall_test/Makefile b/regression/syscall_test/Makefile
--- a/regression/syscall_test/Makefile
+++ b/regression/syscall_test/Makefile
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
TESTS ?= chmod_test fsync_test getdents_test link_test lseek_test mkdir_test \
open_create_test open_test pty_test read_test rename_test stat_test \
statfs_test symlink_test sync_test uidgid_test unlink_test \
diff --git a/regression/syscall_test/run_syscall_test.sh b/regression/syscall_test/run_syscall_test.sh
--- a/regression/syscall_test/run_syscall_test.sh
+++ b/regression/syscall_test/run_syscall_test.sh
@@ -1,5 +1,7 @@
#!/bin/sh
+# SPDX-License-Identifier: MPL-2.0
+
SCRIPT_DIR=$(dirname "$0")
TEST_TMP_DIR=${SYSCALL_TEST_DIR:-/tmp}
TEST_BIN_DIR=$SCRIPT_DIR/tests
diff --git a/runner/src/gdb.rs b/runner/src/gdb.rs
--- a/runner/src/gdb.rs
+++ b/runner/src/gdb.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Providing the utility to run the GDB scripts for the runner.
use crate::qemu_grub_efi;
diff --git a/runner/src/gdb.rs b/runner/src/gdb.rs
--- a/runner/src/gdb.rs
+++ b/runner/src/gdb.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Providing the utility to run the GDB scripts for the runner.
use crate::qemu_grub_efi;
diff --git a/runner/src/machine/microvm.rs b/runner/src/machine/microvm.rs
--- a/runner/src/machine/microvm.rs
+++ b/runner/src/machine/microvm.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use std::{
fs::OpenOptions,
io::{Seek, SeekFrom, Write},
diff --git a/runner/src/machine/microvm.rs b/runner/src/machine/microvm.rs
--- a/runner/src/machine/microvm.rs
+++ b/runner/src/machine/microvm.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use std::{
fs::OpenOptions,
io::{Seek, SeekFrom, Write},
diff --git a/runner/src/machine/mod.rs b/runner/src/machine/mod.rs
--- a/runner/src/machine/mod.rs
+++ b/runner/src/machine/mod.rs
@@ -1,2 +1,4 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod microvm;
pub mod qemu_grub_efi;
diff --git a/runner/src/machine/mod.rs b/runner/src/machine/mod.rs
--- a/runner/src/machine/mod.rs
+++ b/runner/src/machine/mod.rs
@@ -1,2 +1,4 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod microvm;
pub mod qemu_grub_efi;
diff --git a/runner/src/machine/qemu_grub_efi.rs b/runner/src/machine/qemu_grub_efi.rs
--- a/runner/src/machine/qemu_grub_efi.rs
+++ b/runner/src/machine/qemu_grub_efi.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use linux_bzimage_builder::{make_bzimage, BzImageType};
use std::{
diff --git a/runner/src/machine/qemu_grub_efi.rs b/runner/src/machine/qemu_grub_efi.rs
--- a/runner/src/machine/qemu_grub_efi.rs
+++ b/runner/src/machine/qemu_grub_efi.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use linux_bzimage_builder::{make_bzimage, BzImageType};
use std::{
diff --git a/runner/src/main.rs b/runner/src/main.rs
--- a/runner/src/main.rs
+++ b/runner/src/main.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! aster-runner is the Asterinas runner script to ease the pain of running
//! and testing Asterinas inside a QEMU VM. It should be built and run as the
//! cargo runner: https://doc.rust-lang.org/cargo/reference/config.html
diff --git a/services/comps/block/src/bio.rs b/services/comps/block/src/bio.rs
--- a/services/comps/block/src/bio.rs
+++ b/services/comps/block/src/bio.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use super::{id::Sid, BlockDevice};
diff --git a/services/comps/block/src/bio.rs b/services/comps/block/src/bio.rs
--- a/services/comps/block/src/bio.rs
+++ b/services/comps/block/src/bio.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use super::{id::Sid, BlockDevice};
diff --git a/services/comps/block/src/id.rs b/services/comps/block/src/id.rs
--- a/services/comps/block/src/id.rs
+++ b/services/comps/block/src/id.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::{
iter::Step,
ops::{Add, Sub},
diff --git a/services/comps/block/src/id.rs b/services/comps/block/src/id.rs
--- a/services/comps/block/src/id.rs
+++ b/services/comps/block/src/id.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::{
iter::Step,
ops::{Add, Sub},
diff --git a/services/comps/block/src/impl_block_device.rs b/services/comps/block/src/impl_block_device.rs
--- a/services/comps/block/src/impl_block_device.rs
+++ b/services/comps/block/src/impl_block_device.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use super::{
diff --git a/services/comps/block/src/impl_block_device.rs b/services/comps/block/src/impl_block_device.rs
--- a/services/comps/block/src/impl_block_device.rs
+++ b/services/comps/block/src/impl_block_device.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use super::{
diff --git a/services/comps/block/src/lib.rs b/services/comps/block/src/lib.rs
--- a/services/comps/block/src/lib.rs
+++ b/services/comps/block/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The block devices of Asterinas.
//!
//!This crate provides a number of base components for block devices, including
diff --git a/services/comps/block/src/lib.rs b/services/comps/block/src/lib.rs
--- a/services/comps/block/src/lib.rs
+++ b/services/comps/block/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The block devices of Asterinas.
//!
//!This crate provides a number of base components for block devices, including
diff --git a/services/comps/block/src/prelude.rs b/services/comps/block/src/prelude.rs
--- a/services/comps/block/src/prelude.rs
+++ b/services/comps/block/src/prelude.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub(crate) use alloc::collections::{BTreeMap, VecDeque};
pub(crate) use alloc::string::String;
pub(crate) use alloc::sync::Arc;
diff --git a/services/comps/block/src/prelude.rs b/services/comps/block/src/prelude.rs
--- a/services/comps/block/src/prelude.rs
+++ b/services/comps/block/src/prelude.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub(crate) use alloc::collections::{BTreeMap, VecDeque};
pub(crate) use alloc::string::String;
pub(crate) use alloc::sync::Arc;
diff --git a/services/comps/block/src/request_queue.rs b/services/comps/block/src/request_queue.rs
--- a/services/comps/block/src/request_queue.rs
+++ b/services/comps/block/src/request_queue.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use super::{
diff --git a/services/comps/block/src/request_queue.rs b/services/comps/block/src/request_queue.rs
--- a/services/comps/block/src/request_queue.rs
+++ b/services/comps/block/src/request_queue.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use super::{
diff --git a/services/comps/console/src/lib.rs b/services/comps/console/src/lib.rs
--- a/services/comps/console/src/lib.rs
+++ b/services/comps/console/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The console device of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
diff --git a/services/comps/console/src/lib.rs b/services/comps/console/src/lib.rs
--- a/services/comps/console/src/lib.rs
+++ b/services/comps/console/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The console device of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
diff --git a/services/comps/framebuffer/src/lib.rs b/services/comps/framebuffer/src/lib.rs
--- a/services/comps/framebuffer/src/lib.rs
+++ b/services/comps/framebuffer/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The framebuffer of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
diff --git a/services/comps/framebuffer/src/lib.rs b/services/comps/framebuffer/src/lib.rs
--- a/services/comps/framebuffer/src/lib.rs
+++ b/services/comps/framebuffer/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The framebuffer of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
diff --git a/services/comps/input/src/lib.rs b/services/comps/input/src/lib.rs
--- a/services/comps/input/src/lib.rs
+++ b/services/comps/input/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The input devices of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
diff --git a/services/comps/input/src/lib.rs b/services/comps/input/src/lib.rs
--- a/services/comps/input/src/lib.rs
+++ b/services/comps/input/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The input devices of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
diff --git a/services/comps/network/src/buffer.rs b/services/comps/network/src/buffer.rs
--- a/services/comps/network/src/buffer.rs
+++ b/services/comps/network/src/buffer.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::mem::size_of;
use align_ext::AlignExt;
diff --git a/services/comps/network/src/buffer.rs b/services/comps/network/src/buffer.rs
--- a/services/comps/network/src/buffer.rs
+++ b/services/comps/network/src/buffer.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::mem::size_of;
use align_ext::AlignExt;
diff --git a/services/comps/network/src/driver.rs b/services/comps/network/src/driver.rs
--- a/services/comps/network/src/driver.rs
+++ b/services/comps/network/src/driver.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::vec;
use smoltcp::{phy, time::Instant};
diff --git a/services/comps/network/src/driver.rs b/services/comps/network/src/driver.rs
--- a/services/comps/network/src/driver.rs
+++ b/services/comps/network/src/driver.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::vec;
use smoltcp::{phy, time::Instant};
diff --git a/services/comps/network/src/lib.rs b/services/comps/network/src/lib.rs
--- a/services/comps/network/src/lib.rs
+++ b/services/comps/network/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#![no_std]
#![forbid(unsafe_code)]
#![feature(trait_alias)]
diff --git a/services/comps/network/src/lib.rs b/services/comps/network/src/lib.rs
--- a/services/comps/network/src/lib.rs
+++ b/services/comps/network/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#![no_std]
#![forbid(unsafe_code)]
#![feature(trait_alias)]
diff --git a/services/comps/time/src/clocksource.rs b/services/comps/time/src/clocksource.rs
--- a/services/comps/time/src/clocksource.rs
+++ b/services/comps/time/src/clocksource.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! This module provides abstractions for hardware-assisted timing mechanisms, encapsulated by the `ClockSource` struct.
//! A `ClockSource` can be constructed from any counter with a stable frequency, enabling precise time measurements to be taken
//! by retrieving instances of `Instant`.
diff --git a/services/comps/time/src/clocksource.rs b/services/comps/time/src/clocksource.rs
--- a/services/comps/time/src/clocksource.rs
+++ b/services/comps/time/src/clocksource.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! This module provides abstractions for hardware-assisted timing mechanisms, encapsulated by the `ClockSource` struct.
//! A `ClockSource` can be constructed from any counter with a stable frequency, enabling precise time measurements to be taken
//! by retrieving instances of `Instant`.
diff --git a/services/comps/time/src/lib.rs b/services/comps/time/src/lib.rs
--- a/services/comps/time/src/lib.rs
+++ b/services/comps/time/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The system time of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
diff --git a/services/comps/time/src/lib.rs b/services/comps/time/src/lib.rs
--- a/services/comps/time/src/lib.rs
+++ b/services/comps/time/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The system time of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
diff --git a/services/comps/time/src/rtc.rs b/services/comps/time/src/rtc.rs
--- a/services/comps/time/src/rtc.rs
+++ b/services/comps/time/src/rtc.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::arch::x86::device::cmos::{get_century_register, CMOS_ADDRESS, CMOS_DATA};
use core::sync::atomic::AtomicU8;
use core::sync::atomic::Ordering::Relaxed;
diff --git a/services/comps/time/src/rtc.rs b/services/comps/time/src/rtc.rs
--- a/services/comps/time/src/rtc.rs
+++ b/services/comps/time/src/rtc.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::arch::x86::device::cmos::{get_century_register, CMOS_ADDRESS, CMOS_DATA};
use core::sync::atomic::AtomicU8;
use core::sync::atomic::Ordering::Relaxed;
diff --git a/services/comps/time/src/tsc.rs b/services/comps/time/src/tsc.rs
--- a/services/comps/time/src/tsc.rs
+++ b/services/comps/time/src/tsc.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! This module provide a instance of `ClockSource` based on TSC.
//!
//! Use `init` to initialize this module.
diff --git a/services/comps/time/src/tsc.rs b/services/comps/time/src/tsc.rs
--- a/services/comps/time/src/tsc.rs
+++ b/services/comps/time/src/tsc.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! This module provide a instance of `ClockSource` based on TSC.
//!
//! Use `init` to initialize this module.
diff --git a/services/comps/virtio/src/device/block/device.rs b/services/comps/virtio/src/device/block/device.rs
--- a/services/comps/virtio/src/device/block/device.rs
+++ b/services/comps/virtio/src/device/block/device.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::{
fmt::Debug,
hint::spin_loop,
diff --git a/services/comps/virtio/src/device/block/device.rs b/services/comps/virtio/src/device/block/device.rs
--- a/services/comps/virtio/src/device/block/device.rs
+++ b/services/comps/virtio/src/device/block/device.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::{
fmt::Debug,
hint::spin_loop,
diff --git a/services/comps/virtio/src/device/block/mod.rs b/services/comps/virtio/src/device/block/mod.rs
--- a/services/comps/virtio/src/device/block/mod.rs
+++ b/services/comps/virtio/src/device/block/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod device;
use aster_frame::io_mem::IoMem;
diff --git a/services/comps/virtio/src/device/block/mod.rs b/services/comps/virtio/src/device/block/mod.rs
--- a/services/comps/virtio/src/device/block/mod.rs
+++ b/services/comps/virtio/src/device/block/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod device;
use aster_frame::io_mem::IoMem;
diff --git a/services/comps/virtio/src/device/console/config.rs b/services/comps/virtio/src/device/console/config.rs
--- a/services/comps/virtio/src/device/console/config.rs
+++ b/services/comps/virtio/src/device/console/config.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::io_mem::IoMem;
use aster_util::safe_ptr::SafePtr;
use pod::Pod;
diff --git a/services/comps/virtio/src/device/console/config.rs b/services/comps/virtio/src/device/console/config.rs
--- a/services/comps/virtio/src/device/console/config.rs
+++ b/services/comps/virtio/src/device/console/config.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::io_mem::IoMem;
use aster_util::safe_ptr::SafePtr;
use pod::Pod;
diff --git a/services/comps/virtio/src/device/console/device.rs b/services/comps/virtio/src/device/console/device.rs
--- a/services/comps/virtio/src/device/console/device.rs
+++ b/services/comps/virtio/src/device/console/device.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::hint::spin_loop;
use alloc::{boxed::Box, fmt::Debug, string::ToString, sync::Arc, vec::Vec};
diff --git a/services/comps/virtio/src/device/console/device.rs b/services/comps/virtio/src/device/console/device.rs
--- a/services/comps/virtio/src/device/console/device.rs
+++ b/services/comps/virtio/src/device/console/device.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::hint::spin_loop;
use alloc::{boxed::Box, fmt::Debug, string::ToString, sync::Arc, vec::Vec};
diff --git a/services/comps/virtio/src/device/console/mod.rs b/services/comps/virtio/src/device/console/mod.rs
--- a/services/comps/virtio/src/device/console/mod.rs
+++ b/services/comps/virtio/src/device/console/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod config;
pub mod device;
diff --git a/services/comps/virtio/src/device/console/mod.rs b/services/comps/virtio/src/device/console/mod.rs
--- a/services/comps/virtio/src/device/console/mod.rs
+++ b/services/comps/virtio/src/device/console/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod config;
pub mod device;
diff --git a/services/comps/virtio/src/device/input/device.rs b/services/comps/virtio/src/device/input/device.rs
--- a/services/comps/virtio/src/device/input/device.rs
+++ b/services/comps/virtio/src/device/input/device.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::fmt::Debug;
use crate::{device::VirtioDeviceError, queue::VirtQueue, transport::VirtioTransport};
diff --git a/services/comps/virtio/src/device/input/device.rs b/services/comps/virtio/src/device/input/device.rs
--- a/services/comps/virtio/src/device/input/device.rs
+++ b/services/comps/virtio/src/device/input/device.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::fmt::Debug;
use crate::{device::VirtioDeviceError, queue::VirtQueue, transport::VirtioTransport};
diff --git a/services/comps/virtio/src/device/input/mod.rs b/services/comps/virtio/src/device/input/mod.rs
--- a/services/comps/virtio/src/device/input/mod.rs
+++ b/services/comps/virtio/src/device/input/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
// Modified from input.rs in virtio-drivers project
//
// MIT License
diff --git a/services/comps/virtio/src/device/input/mod.rs b/services/comps/virtio/src/device/input/mod.rs
--- a/services/comps/virtio/src/device/input/mod.rs
+++ b/services/comps/virtio/src/device/input/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
// Modified from input.rs in virtio-drivers project
//
// MIT License
diff --git a/services/comps/virtio/src/device/mod.rs b/services/comps/virtio/src/device/mod.rs
--- a/services/comps/virtio/src/device/mod.rs
+++ b/services/comps/virtio/src/device/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::queue::QueueError;
use int_to_c_enum::TryFromInt;
diff --git a/services/comps/virtio/src/device/mod.rs b/services/comps/virtio/src/device/mod.rs
--- a/services/comps/virtio/src/device/mod.rs
+++ b/services/comps/virtio/src/device/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::queue::QueueError;
use int_to_c_enum::TryFromInt;
diff --git a/services/comps/virtio/src/device/network/config.rs b/services/comps/virtio/src/device/network/config.rs
--- a/services/comps/virtio/src/device/network/config.rs
+++ b/services/comps/virtio/src/device/network/config.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::io_mem::IoMem;
use aster_network::EthernetAddr;
use aster_util::safe_ptr::SafePtr;
diff --git a/services/comps/virtio/src/device/network/config.rs b/services/comps/virtio/src/device/network/config.rs
--- a/services/comps/virtio/src/device/network/config.rs
+++ b/services/comps/virtio/src/device/network/config.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::io_mem::IoMem;
use aster_network::EthernetAddr;
use aster_util::safe_ptr::SafePtr;
diff --git a/services/comps/virtio/src/device/network/device.rs b/services/comps/virtio/src/device/network/device.rs
--- a/services/comps/virtio/src/device/network/device.rs
+++ b/services/comps/virtio/src/device/network/device.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::{fmt::Debug, hint::spin_loop, mem::size_of};
use alloc::{boxed::Box, string::ToString, sync::Arc, vec::Vec};
diff --git a/services/comps/virtio/src/device/network/device.rs b/services/comps/virtio/src/device/network/device.rs
--- a/services/comps/virtio/src/device/network/device.rs
+++ b/services/comps/virtio/src/device/network/device.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::{fmt::Debug, hint::spin_loop, mem::size_of};
use alloc::{boxed::Box, string::ToString, sync::Arc, vec::Vec};
diff --git a/services/comps/virtio/src/device/network/header.rs b/services/comps/virtio/src/device/network/header.rs
--- a/services/comps/virtio/src/device/network/header.rs
+++ b/services/comps/virtio/src/device/network/header.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use bitflags::bitflags;
use int_to_c_enum::TryFromInt;
use pod::Pod;
diff --git a/services/comps/virtio/src/device/network/header.rs b/services/comps/virtio/src/device/network/header.rs
--- a/services/comps/virtio/src/device/network/header.rs
+++ b/services/comps/virtio/src/device/network/header.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use bitflags::bitflags;
use int_to_c_enum::TryFromInt;
use pod::Pod;
diff --git a/services/comps/virtio/src/device/network/mod.rs b/services/comps/virtio/src/device/network/mod.rs
--- a/services/comps/virtio/src/device/network/mod.rs
+++ b/services/comps/virtio/src/device/network/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod config;
pub mod device;
pub mod header;
diff --git a/services/comps/virtio/src/device/network/mod.rs b/services/comps/virtio/src/device/network/mod.rs
--- a/services/comps/virtio/src/device/network/mod.rs
+++ b/services/comps/virtio/src/device/network/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod config;
pub mod device;
pub mod header;
diff --git a/services/comps/virtio/src/lib.rs b/services/comps/virtio/src/lib.rs
--- a/services/comps/virtio/src/lib.rs
+++ b/services/comps/virtio/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The virtio of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
diff --git a/services/comps/virtio/src/lib.rs b/services/comps/virtio/src/lib.rs
--- a/services/comps/virtio/src/lib.rs
+++ b/services/comps/virtio/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The virtio of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
diff --git a/services/comps/virtio/src/queue.rs b/services/comps/virtio/src/queue.rs
--- a/services/comps/virtio/src/queue.rs
+++ b/services/comps/virtio/src/queue.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Virtqueue
use crate::transport::VirtioTransport;
diff --git a/services/comps/virtio/src/queue.rs b/services/comps/virtio/src/queue.rs
--- a/services/comps/virtio/src/queue.rs
+++ b/services/comps/virtio/src/queue.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Virtqueue
use crate::transport::VirtioTransport;
diff --git a/services/comps/virtio/src/transport/mmio/device.rs b/services/comps/virtio/src/transport/mmio/device.rs
--- a/services/comps/virtio/src/transport/mmio/device.rs
+++ b/services/comps/virtio/src/transport/mmio/device.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::{boxed::Box, sync::Arc};
use aster_frame::{
bus::mmio::{
diff --git a/services/comps/virtio/src/transport/mmio/device.rs b/services/comps/virtio/src/transport/mmio/device.rs
--- a/services/comps/virtio/src/transport/mmio/device.rs
+++ b/services/comps/virtio/src/transport/mmio/device.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::{boxed::Box, sync::Arc};
use aster_frame::{
bus::mmio::{
diff --git a/services/comps/virtio/src/transport/mmio/driver.rs b/services/comps/virtio/src/transport/mmio/driver.rs
--- a/services/comps/virtio/src/transport/mmio/driver.rs
+++ b/services/comps/virtio/src/transport/mmio/driver.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::{sync::Arc, vec::Vec};
use aster_frame::{
bus::{
diff --git a/services/comps/virtio/src/transport/mmio/driver.rs b/services/comps/virtio/src/transport/mmio/driver.rs
--- a/services/comps/virtio/src/transport/mmio/driver.rs
+++ b/services/comps/virtio/src/transport/mmio/driver.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::{sync::Arc, vec::Vec};
use aster_frame::{
bus::{
diff --git a/services/comps/virtio/src/transport/mmio/layout.rs b/services/comps/virtio/src/transport/mmio/layout.rs
--- a/services/comps/virtio/src/transport/mmio/layout.rs
+++ b/services/comps/virtio/src/transport/mmio/layout.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::fmt::Debug;
use pod::Pod;
diff --git a/services/comps/virtio/src/transport/mmio/layout.rs b/services/comps/virtio/src/transport/mmio/layout.rs
--- a/services/comps/virtio/src/transport/mmio/layout.rs
+++ b/services/comps/virtio/src/transport/mmio/layout.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::fmt::Debug;
use pod::Pod;
diff --git a/services/comps/virtio/src/transport/mmio/mod.rs b/services/comps/virtio/src/transport/mmio/mod.rs
--- a/services/comps/virtio/src/transport/mmio/mod.rs
+++ b/services/comps/virtio/src/transport/mmio/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::sync::Arc;
use aster_frame::bus::mmio::MMIO_BUS;
use spin::Once;
diff --git a/services/comps/virtio/src/transport/mmio/mod.rs b/services/comps/virtio/src/transport/mmio/mod.rs
--- a/services/comps/virtio/src/transport/mmio/mod.rs
+++ b/services/comps/virtio/src/transport/mmio/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::sync::Arc;
use aster_frame::bus::mmio::MMIO_BUS;
use spin::Once;
diff --git a/services/comps/virtio/src/transport/mmio/multiplex.rs b/services/comps/virtio/src/transport/mmio/multiplex.rs
--- a/services/comps/virtio/src/transport/mmio/multiplex.rs
+++ b/services/comps/virtio/src/transport/mmio/multiplex.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::fmt::Debug;
use alloc::{boxed::Box, sync::Arc, vec::Vec};
diff --git a/services/comps/virtio/src/transport/mmio/multiplex.rs b/services/comps/virtio/src/transport/mmio/multiplex.rs
--- a/services/comps/virtio/src/transport/mmio/multiplex.rs
+++ b/services/comps/virtio/src/transport/mmio/multiplex.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::fmt::Debug;
use alloc::{boxed::Box, sync::Arc, vec::Vec};
diff --git a/services/comps/virtio/src/transport/mod.rs b/services/comps/virtio/src/transport/mod.rs
--- a/services/comps/virtio/src/transport/mod.rs
+++ b/services/comps/virtio/src/transport/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::fmt::Debug;
use alloc::boxed::Box;
diff --git a/services/comps/virtio/src/transport/mod.rs b/services/comps/virtio/src/transport/mod.rs
--- a/services/comps/virtio/src/transport/mod.rs
+++ b/services/comps/virtio/src/transport/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::fmt::Debug;
use alloc::boxed::Box;
diff --git a/services/comps/virtio/src/transport/pci/capability.rs b/services/comps/virtio/src/transport/pci/capability.rs
--- a/services/comps/virtio/src/transport/pci/capability.rs
+++ b/services/comps/virtio/src/transport/pci/capability.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::sync::Arc;
use aster_frame::bus::pci::{
capability::vendor::CapabilityVndrData,
diff --git a/services/comps/virtio/src/transport/pci/capability.rs b/services/comps/virtio/src/transport/pci/capability.rs
--- a/services/comps/virtio/src/transport/pci/capability.rs
+++ b/services/comps/virtio/src/transport/pci/capability.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::sync::Arc;
use aster_frame::bus::pci::{
capability::vendor::CapabilityVndrData,
diff --git a/services/comps/virtio/src/transport/pci/common_cfg.rs b/services/comps/virtio/src/transport/pci/common_cfg.rs
--- a/services/comps/virtio/src/transport/pci/common_cfg.rs
+++ b/services/comps/virtio/src/transport/pci/common_cfg.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::io_mem::IoMem;
use aster_util::safe_ptr::SafePtr;
use pod::Pod;
diff --git a/services/comps/virtio/src/transport/pci/common_cfg.rs b/services/comps/virtio/src/transport/pci/common_cfg.rs
--- a/services/comps/virtio/src/transport/pci/common_cfg.rs
+++ b/services/comps/virtio/src/transport/pci/common_cfg.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::io_mem::IoMem;
use aster_util::safe_ptr::SafePtr;
use pod::Pod;
diff --git a/services/comps/virtio/src/transport/pci/device.rs b/services/comps/virtio/src/transport/pci/device.rs
--- a/services/comps/virtio/src/transport/pci/device.rs
+++ b/services/comps/virtio/src/transport/pci/device.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::{
bus::{
pci::{
diff --git a/services/comps/virtio/src/transport/pci/device.rs b/services/comps/virtio/src/transport/pci/device.rs
--- a/services/comps/virtio/src/transport/pci/device.rs
+++ b/services/comps/virtio/src/transport/pci/device.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::{
bus::{
pci::{
diff --git a/services/comps/virtio/src/transport/pci/driver.rs b/services/comps/virtio/src/transport/pci/driver.rs
--- a/services/comps/virtio/src/transport/pci/driver.rs
+++ b/services/comps/virtio/src/transport/pci/driver.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::{sync::Arc, vec::Vec};
use aster_frame::{
bus::{
diff --git a/services/comps/virtio/src/transport/pci/driver.rs b/services/comps/virtio/src/transport/pci/driver.rs
--- a/services/comps/virtio/src/transport/pci/driver.rs
+++ b/services/comps/virtio/src/transport/pci/driver.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::{sync::Arc, vec::Vec};
use aster_frame::{
bus::{
diff --git a/services/comps/virtio/src/transport/pci/mod.rs b/services/comps/virtio/src/transport/pci/mod.rs
--- a/services/comps/virtio/src/transport/pci/mod.rs
+++ b/services/comps/virtio/src/transport/pci/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod capability;
pub mod common_cfg;
pub mod device;
diff --git a/services/comps/virtio/src/transport/pci/mod.rs b/services/comps/virtio/src/transport/pci/mod.rs
--- a/services/comps/virtio/src/transport/pci/mod.rs
+++ b/services/comps/virtio/src/transport/pci/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod capability;
pub mod common_cfg;
pub mod device;
diff --git a/services/comps/virtio/src/transport/pci/msix.rs b/services/comps/virtio/src/transport/pci/msix.rs
--- a/services/comps/virtio/src/transport/pci/msix.rs
+++ b/services/comps/virtio/src/transport/pci/msix.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::vec::Vec;
use aster_frame::{bus::pci::capability::msix::CapabilityMsixData, trap::IrqLine};
diff --git a/services/comps/virtio/src/transport/pci/msix.rs b/services/comps/virtio/src/transport/pci/msix.rs
--- a/services/comps/virtio/src/transport/pci/msix.rs
+++ b/services/comps/virtio/src/transport/pci/msix.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::vec::Vec;
use aster_frame::{bus::pci::capability::msix::CapabilityMsixData, trap::IrqLine};
diff --git a/services/libs/aster-rights-proc/src/lib.rs b/services/libs/aster-rights-proc/src/lib.rs
--- a/services/libs/aster-rights-proc/src/lib.rs
+++ b/services/libs/aster-rights-proc/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//!This crate defines the require procedural macros to implement capability for Asterinas.
//! When use this crate, typeflags and typeflags-util should also be added as dependency.
//!
diff --git a/services/libs/aster-rights-proc/src/lib.rs b/services/libs/aster-rights-proc/src/lib.rs
--- a/services/libs/aster-rights-proc/src/lib.rs
+++ b/services/libs/aster-rights-proc/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//!This crate defines the require procedural macros to implement capability for Asterinas.
//! When use this crate, typeflags and typeflags-util should also be added as dependency.
//!
diff --git a/services/libs/aster-rights-proc/src/require_attr.rs b/services/libs/aster-rights-proc/src/require_attr.rs
--- a/services/libs/aster-rights-proc/src/require_attr.rs
+++ b/services/libs/aster-rights-proc/src/require_attr.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! expand the require macro
use proc_macro2::{Ident, TokenStream};
diff --git a/services/libs/aster-rights-proc/src/require_attr.rs b/services/libs/aster-rights-proc/src/require_attr.rs
--- a/services/libs/aster-rights-proc/src/require_attr.rs
+++ b/services/libs/aster-rights-proc/src/require_attr.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! expand the require macro
use proc_macro2::{Ident, TokenStream};
diff --git a/services/libs/aster-rights-proc/src/require_item.rs b/services/libs/aster-rights-proc/src/require_item.rs
--- a/services/libs/aster-rights-proc/src/require_item.rs
+++ b/services/libs/aster-rights-proc/src/require_item.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use syn::{parse::Parse, ItemFn, ItemImpl, Token};
pub enum RequireItem {
diff --git a/services/libs/aster-rights-proc/src/require_item.rs b/services/libs/aster-rights-proc/src/require_item.rs
--- a/services/libs/aster-rights-proc/src/require_item.rs
+++ b/services/libs/aster-rights-proc/src/require_item.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use syn::{parse::Parse, ItemFn, ItemImpl, Token};
pub enum RequireItem {
diff --git a/services/libs/aster-rights/src/lib.rs b/services/libs/aster-rights/src/lib.rs
--- a/services/libs/aster-rights/src/lib.rs
+++ b/services/libs/aster-rights/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#![no_std]
use core::ops::{Deref, DerefMut};
diff --git a/services/libs/aster-rights/src/lib.rs b/services/libs/aster-rights/src/lib.rs
--- a/services/libs/aster-rights/src/lib.rs
+++ b/services/libs/aster-rights/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#![no_std]
use core::ops::{Deref, DerefMut};
diff --git a/services/libs/aster-std/src/console.rs b/services/libs/aster-std/src/console.rs
--- a/services/libs/aster-std/src/console.rs
+++ b/services/libs/aster-std/src/console.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! `print` and `println` macros
//!
//! FIXME: It will print to all `virtio-console` devices, which is not a good choice.
diff --git a/services/libs/aster-std/src/console.rs b/services/libs/aster-std/src/console.rs
--- a/services/libs/aster-std/src/console.rs
+++ b/services/libs/aster-std/src/console.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! `print` and `println` macros
//!
//! FIXME: It will print to all `virtio-console` devices, which is not a good choice.
diff --git a/services/libs/aster-std/src/device/mod.rs b/services/libs/aster-std/src/device/mod.rs
--- a/services/libs/aster-std/src/device/mod.rs
+++ b/services/libs/aster-std/src/device/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod null;
mod pty;
mod random;
diff --git a/services/libs/aster-std/src/device/mod.rs b/services/libs/aster-std/src/device/mod.rs
--- a/services/libs/aster-std/src/device/mod.rs
+++ b/services/libs/aster-std/src/device/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod null;
mod pty;
mod random;
diff --git a/services/libs/aster-std/src/device/null.rs b/services/libs/aster-std/src/device/null.rs
--- a/services/libs/aster-std/src/device/null.rs
+++ b/services/libs/aster-std/src/device/null.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::*;
use crate::events::IoEvents;
use crate::fs::inode_handle::FileIo;
diff --git a/services/libs/aster-std/src/device/null.rs b/services/libs/aster-std/src/device/null.rs
--- a/services/libs/aster-std/src/device/null.rs
+++ b/services/libs/aster-std/src/device/null.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::*;
use crate::events::IoEvents;
use crate::fs::inode_handle::FileIo;
diff --git a/services/libs/aster-std/src/device/pty/mod.rs b/services/libs/aster-std/src/device/pty/mod.rs
--- a/services/libs/aster-std/src/device/pty/mod.rs
+++ b/services/libs/aster-std/src/device/pty/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::devpts::DevPts;
use crate::fs::fs_resolver::{FsPath, FsResolver};
use crate::fs::utils::{Dentry, Inode, InodeMode, InodeType};
diff --git a/services/libs/aster-std/src/device/pty/mod.rs b/services/libs/aster-std/src/device/pty/mod.rs
--- a/services/libs/aster-std/src/device/pty/mod.rs
+++ b/services/libs/aster-std/src/device/pty/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::devpts::DevPts;
use crate::fs::fs_resolver::{FsPath, FsResolver};
use crate::fs::utils::{Dentry, Inode, InodeMode, InodeType};
diff --git a/services/libs/aster-std/src/device/pty/pty.rs b/services/libs/aster-std/src/device/pty/pty.rs
--- a/services/libs/aster-std/src/device/pty/pty.rs
+++ b/services/libs/aster-std/src/device/pty/pty.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::format;
use ringbuf::{ring_buffer::RbBase, HeapRb, Rb};
diff --git a/services/libs/aster-std/src/device/pty/pty.rs b/services/libs/aster-std/src/device/pty/pty.rs
--- a/services/libs/aster-std/src/device/pty/pty.rs
+++ b/services/libs/aster-std/src/device/pty/pty.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::format;
use ringbuf::{ring_buffer::RbBase, HeapRb, Rb};
diff --git a/services/libs/aster-std/src/device/random.rs b/services/libs/aster-std/src/device/random.rs
--- a/services/libs/aster-std/src/device/random.rs
+++ b/services/libs/aster-std/src/device/random.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::IoEvents;
use crate::fs::device::{Device, DeviceId, DeviceType};
use crate::fs::inode_handle::FileIo;
diff --git a/services/libs/aster-std/src/device/random.rs b/services/libs/aster-std/src/device/random.rs
--- a/services/libs/aster-std/src/device/random.rs
+++ b/services/libs/aster-std/src/device/random.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::IoEvents;
use crate::fs::device::{Device, DeviceId, DeviceType};
use crate::fs::inode_handle::FileIo;
diff --git a/services/libs/aster-std/src/device/tdxguest/mod.rs b/services/libs/aster-std/src/device/tdxguest/mod.rs
--- a/services/libs/aster-std/src/device/tdxguest/mod.rs
+++ b/services/libs/aster-std/src/device/tdxguest/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::*;
use crate::error::Error;
use crate::events::IoEvents;
diff --git a/services/libs/aster-std/src/device/tdxguest/mod.rs b/services/libs/aster-std/src/device/tdxguest/mod.rs
--- a/services/libs/aster-std/src/device/tdxguest/mod.rs
+++ b/services/libs/aster-std/src/device/tdxguest/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::*;
use crate::error::Error;
use crate::events::IoEvents;
diff --git a/services/libs/aster-std/src/device/tty/device.rs b/services/libs/aster-std/src/device/tty/device.rs
--- a/services/libs/aster-std/src/device/tty/device.rs
+++ b/services/libs/aster-std/src/device/tty/device.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::IoEvents;
use crate::fs::device::{Device, DeviceId, DeviceType};
use crate::fs::inode_handle::FileIo;
diff --git a/services/libs/aster-std/src/device/tty/device.rs b/services/libs/aster-std/src/device/tty/device.rs
--- a/services/libs/aster-std/src/device/tty/device.rs
+++ b/services/libs/aster-std/src/device/tty/device.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::IoEvents;
use crate::fs::device::{Device, DeviceId, DeviceType};
use crate::fs::inode_handle::FileIo;
diff --git a/services/libs/aster-std/src/device/tty/driver.rs b/services/libs/aster-std/src/device/tty/driver.rs
--- a/services/libs/aster-std/src/device/tty/driver.rs
+++ b/services/libs/aster-std/src/device/tty/driver.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub use aster_frame::arch::console::register_console_input_callback;
use spin::Once;
diff --git a/services/libs/aster-std/src/device/tty/driver.rs b/services/libs/aster-std/src/device/tty/driver.rs
--- a/services/libs/aster-std/src/device/tty/driver.rs
+++ b/services/libs/aster-std/src/device/tty/driver.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub use aster_frame::arch::console::register_console_input_callback;
use spin::Once;
diff --git a/services/libs/aster-std/src/device/tty/line_discipline.rs b/services/libs/aster-std/src/device/tty/line_discipline.rs
--- a/services/libs/aster-std/src/device/tty/line_discipline.rs
+++ b/services/libs/aster-std/src/device/tty/line_discipline.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::IoEvents;
use crate::prelude::*;
use crate::process::signal::constants::{SIGINT, SIGQUIT};
diff --git a/services/libs/aster-std/src/device/tty/line_discipline.rs b/services/libs/aster-std/src/device/tty/line_discipline.rs
--- a/services/libs/aster-std/src/device/tty/line_discipline.rs
+++ b/services/libs/aster-std/src/device/tty/line_discipline.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::IoEvents;
use crate::prelude::*;
use crate::process::signal::constants::{SIGINT, SIGQUIT};
diff --git a/services/libs/aster-std/src/device/tty/mod.rs b/services/libs/aster-std/src/device/tty/mod.rs
--- a/services/libs/aster-std/src/device/tty/mod.rs
+++ b/services/libs/aster-std/src/device/tty/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use spin::Once;
use self::driver::TtyDriver;
diff --git a/services/libs/aster-std/src/device/tty/mod.rs b/services/libs/aster-std/src/device/tty/mod.rs
--- a/services/libs/aster-std/src/device/tty/mod.rs
+++ b/services/libs/aster-std/src/device/tty/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use spin::Once;
use self::driver::TtyDriver;
diff --git a/services/libs/aster-std/src/device/tty/termio.rs b/services/libs/aster-std/src/device/tty/termio.rs
--- a/services/libs/aster-std/src/device/tty/termio.rs
+++ b/services/libs/aster-std/src/device/tty/termio.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#![allow(non_camel_case_types)]
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/device/tty/termio.rs b/services/libs/aster-std/src/device/tty/termio.rs
--- a/services/libs/aster-std/src/device/tty/termio.rs
+++ b/services/libs/aster-std/src/device/tty/termio.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#![allow(non_camel_case_types)]
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/device/urandom.rs b/services/libs/aster-std/src/device/urandom.rs
--- a/services/libs/aster-std/src/device/urandom.rs
+++ b/services/libs/aster-std/src/device/urandom.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::IoEvents;
use crate::fs::device::{Device, DeviceId, DeviceType};
use crate::fs::inode_handle::FileIo;
diff --git a/services/libs/aster-std/src/device/urandom.rs b/services/libs/aster-std/src/device/urandom.rs
--- a/services/libs/aster-std/src/device/urandom.rs
+++ b/services/libs/aster-std/src/device/urandom.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::IoEvents;
use crate::fs::device::{Device, DeviceId, DeviceType};
use crate::fs::inode_handle::FileIo;
diff --git a/services/libs/aster-std/src/device/zero.rs b/services/libs/aster-std/src/device/zero.rs
--- a/services/libs/aster-std/src/device/zero.rs
+++ b/services/libs/aster-std/src/device/zero.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::*;
use crate::events::IoEvents;
use crate::fs::inode_handle::FileIo;
diff --git a/services/libs/aster-std/src/device/zero.rs b/services/libs/aster-std/src/device/zero.rs
--- a/services/libs/aster-std/src/device/zero.rs
+++ b/services/libs/aster-std/src/device/zero.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::*;
use crate::events::IoEvents;
use crate::fs::inode_handle::FileIo;
diff --git a/services/libs/aster-std/src/driver/mod.rs b/services/libs/aster-std/src/driver/mod.rs
--- a/services/libs/aster-std/src/driver/mod.rs
+++ b/services/libs/aster-std/src/driver/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use log::info;
pub fn init() {
diff --git a/services/libs/aster-std/src/driver/mod.rs b/services/libs/aster-std/src/driver/mod.rs
--- a/services/libs/aster-std/src/driver/mod.rs
+++ b/services/libs/aster-std/src/driver/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use log::info;
pub fn init() {
diff --git a/services/libs/aster-std/src/error.rs b/services/libs/aster-std/src/error.rs
--- a/services/libs/aster-std/src/error.rs
+++ b/services/libs/aster-std/src/error.rs
@@ -1,4 +1,6 @@
-/// Errno. Copied from Occlum
+// SPDX-License-Identifier: MPL-2.0
+
+/// Error number.
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Errno {
diff --git a/services/libs/aster-std/src/error.rs b/services/libs/aster-std/src/error.rs
--- a/services/libs/aster-std/src/error.rs
+++ b/services/libs/aster-std/src/error.rs
@@ -1,4 +1,6 @@
-/// Errno. Copied from Occlum
+// SPDX-License-Identifier: MPL-2.0
+
+/// Error number.
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Errno {
diff --git a/services/libs/aster-std/src/events/events.rs b/services/libs/aster-std/src/events/events.rs
--- a/services/libs/aster-std/src/events/events.rs
+++ b/services/libs/aster-std/src/events/events.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
/// A trait to represent any events.
///
/// # The unit event
diff --git a/services/libs/aster-std/src/events/events.rs b/services/libs/aster-std/src/events/events.rs
--- a/services/libs/aster-std/src/events/events.rs
+++ b/services/libs/aster-std/src/events/events.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
/// A trait to represent any events.
///
/// # The unit event
diff --git a/services/libs/aster-std/src/events/io_events.rs b/services/libs/aster-std/src/events/io_events.rs
--- a/services/libs/aster-std/src/events/io_events.rs
+++ b/services/libs/aster-std/src/events/io_events.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{Events, EventsFilter};
crate::bitflags! {
diff --git a/services/libs/aster-std/src/events/io_events.rs b/services/libs/aster-std/src/events/io_events.rs
--- a/services/libs/aster-std/src/events/io_events.rs
+++ b/services/libs/aster-std/src/events/io_events.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{Events, EventsFilter};
crate::bitflags! {
diff --git a/services/libs/aster-std/src/events/mod.rs b/services/libs/aster-std/src/events/mod.rs
--- a/services/libs/aster-std/src/events/mod.rs
+++ b/services/libs/aster-std/src/events/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#[allow(clippy::module_inception)]
mod events;
mod io_events;
diff --git a/services/libs/aster-std/src/events/mod.rs b/services/libs/aster-std/src/events/mod.rs
--- a/services/libs/aster-std/src/events/mod.rs
+++ b/services/libs/aster-std/src/events/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#[allow(clippy::module_inception)]
mod events;
mod io_events;
diff --git a/services/libs/aster-std/src/events/observer.rs b/services/libs/aster-std/src/events/observer.rs
--- a/services/libs/aster-std/src/events/observer.rs
+++ b/services/libs/aster-std/src/events/observer.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::Events;
/// An observer for events.
diff --git a/services/libs/aster-std/src/events/observer.rs b/services/libs/aster-std/src/events/observer.rs
--- a/services/libs/aster-std/src/events/observer.rs
+++ b/services/libs/aster-std/src/events/observer.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::Events;
/// An observer for events.
diff --git a/services/libs/aster-std/src/events/subject.rs b/services/libs/aster-std/src/events/subject.rs
--- a/services/libs/aster-std/src/events/subject.rs
+++ b/services/libs/aster-std/src/events/subject.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use core::sync::atomic::{AtomicUsize, Ordering};
diff --git a/services/libs/aster-std/src/events/subject.rs b/services/libs/aster-std/src/events/subject.rs
--- a/services/libs/aster-std/src/events/subject.rs
+++ b/services/libs/aster-std/src/events/subject.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use core::sync::atomic::{AtomicUsize, Ordering};
diff --git a/services/libs/aster-std/src/fs/device.rs b/services/libs/aster-std/src/fs/device.rs
--- a/services/libs/aster-std/src/fs/device.rs
+++ b/services/libs/aster-std/src/fs/device.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::fs_resolver::{FsPath, FsResolver};
use crate::fs::utils::Dentry;
use crate::fs::utils::{InodeMode, InodeType};
diff --git a/services/libs/aster-std/src/fs/device.rs b/services/libs/aster-std/src/fs/device.rs
--- a/services/libs/aster-std/src/fs/device.rs
+++ b/services/libs/aster-std/src/fs/device.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::fs_resolver::{FsPath, FsResolver};
use crate::fs::utils::Dentry;
use crate::fs::utils::{InodeMode, InodeType};
diff --git a/services/libs/aster-std/src/fs/devpts/mod.rs b/services/libs/aster-std/src/fs/devpts/mod.rs
--- a/services/libs/aster-std/src/fs/devpts/mod.rs
+++ b/services/libs/aster-std/src/fs/devpts/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::device::PtyMaster;
use crate::fs::device::{Device, DeviceId, DeviceType};
use crate::fs::utils::{
diff --git a/services/libs/aster-std/src/fs/devpts/mod.rs b/services/libs/aster-std/src/fs/devpts/mod.rs
--- a/services/libs/aster-std/src/fs/devpts/mod.rs
+++ b/services/libs/aster-std/src/fs/devpts/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::device::PtyMaster;
use crate::fs::device::{Device, DeviceId, DeviceType};
use crate::fs::utils::{
diff --git a/services/libs/aster-std/src/fs/devpts/ptmx.rs b/services/libs/aster-std/src/fs/devpts/ptmx.rs
--- a/services/libs/aster-std/src/fs/devpts/ptmx.rs
+++ b/services/libs/aster-std/src/fs/devpts/ptmx.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::device::PtyMaster;
use crate::events::IoEvents;
use crate::fs::inode_handle::FileIo;
diff --git a/services/libs/aster-std/src/fs/devpts/ptmx.rs b/services/libs/aster-std/src/fs/devpts/ptmx.rs
--- a/services/libs/aster-std/src/fs/devpts/ptmx.rs
+++ b/services/libs/aster-std/src/fs/devpts/ptmx.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::device::PtyMaster;
use crate::events::IoEvents;
use crate::fs::inode_handle::FileIo;
diff --git a/services/libs/aster-std/src/fs/devpts/slave.rs b/services/libs/aster-std/src/fs/devpts/slave.rs
--- a/services/libs/aster-std/src/fs/devpts/slave.rs
+++ b/services/libs/aster-std/src/fs/devpts/slave.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::IoEvents;
use crate::fs::inode_handle::FileIo;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/fs/devpts/slave.rs b/services/libs/aster-std/src/fs/devpts/slave.rs
--- a/services/libs/aster-std/src/fs/devpts/slave.rs
+++ b/services/libs/aster-std/src/fs/devpts/slave.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::IoEvents;
use crate::fs::inode_handle::FileIo;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/fs/epoll/epoll_file.rs b/services/libs/aster-std/src/fs/epoll/epoll_file.rs
--- a/services/libs/aster-std/src/fs/epoll/epoll_file.rs
+++ b/services/libs/aster-std/src/fs/epoll/epoll_file.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::{IoEvents, Observer};
use crate::fs::file_handle::FileLike;
use crate::fs::file_table::{FdEvents, FileDescripter};
diff --git a/services/libs/aster-std/src/fs/epoll/epoll_file.rs b/services/libs/aster-std/src/fs/epoll/epoll_file.rs
--- a/services/libs/aster-std/src/fs/epoll/epoll_file.rs
+++ b/services/libs/aster-std/src/fs/epoll/epoll_file.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::{IoEvents, Observer};
use crate::fs::file_handle::FileLike;
use crate::fs::file_table::{FdEvents, FileDescripter};
diff --git a/services/libs/aster-std/src/fs/epoll/mod.rs b/services/libs/aster-std/src/fs/epoll/mod.rs
--- a/services/libs/aster-std/src/fs/epoll/mod.rs
+++ b/services/libs/aster-std/src/fs/epoll/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::file_table::FileDescripter;
use crate::events::IoEvents;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/fs/epoll/mod.rs b/services/libs/aster-std/src/fs/epoll/mod.rs
--- a/services/libs/aster-std/src/fs/epoll/mod.rs
+++ b/services/libs/aster-std/src/fs/epoll/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::file_table::FileDescripter;
use crate::events::IoEvents;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/fs/ext2/block_group.rs b/services/libs/aster-std/src/fs/ext2/block_group.rs
--- a/services/libs/aster-std/src/fs/ext2/block_group.rs
+++ b/services/libs/aster-std/src/fs/ext2/block_group.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::fs::Ext2;
use super::inode::{Inode, InodeDesc, RawInode};
use super::prelude::*;
diff --git a/services/libs/aster-std/src/fs/ext2/block_group.rs b/services/libs/aster-std/src/fs/ext2/block_group.rs
--- a/services/libs/aster-std/src/fs/ext2/block_group.rs
+++ b/services/libs/aster-std/src/fs/ext2/block_group.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::fs::Ext2;
use super::inode::{Inode, InodeDesc, RawInode};
use super::prelude::*;
diff --git a/services/libs/aster-std/src/fs/ext2/blocks_hole.rs b/services/libs/aster-std/src/fs/ext2/blocks_hole.rs
--- a/services/libs/aster-std/src/fs/ext2/blocks_hole.rs
+++ b/services/libs/aster-std/src/fs/ext2/blocks_hole.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use bitvec::prelude::BitVec;
/// A blocks hole descriptor implemented by the `BitVec`.
diff --git a/services/libs/aster-std/src/fs/ext2/blocks_hole.rs b/services/libs/aster-std/src/fs/ext2/blocks_hole.rs
--- a/services/libs/aster-std/src/fs/ext2/blocks_hole.rs
+++ b/services/libs/aster-std/src/fs/ext2/blocks_hole.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use bitvec::prelude::BitVec;
/// A blocks hole descriptor implemented by the `BitVec`.
diff --git a/services/libs/aster-std/src/fs/ext2/dir.rs b/services/libs/aster-std/src/fs/ext2/dir.rs
--- a/services/libs/aster-std/src/fs/ext2/dir.rs
+++ b/services/libs/aster-std/src/fs/ext2/dir.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::inode::{FileType, MAX_FNAME_LEN};
use super::prelude::*;
diff --git a/services/libs/aster-std/src/fs/ext2/dir.rs b/services/libs/aster-std/src/fs/ext2/dir.rs
--- a/services/libs/aster-std/src/fs/ext2/dir.rs
+++ b/services/libs/aster-std/src/fs/ext2/dir.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::inode::{FileType, MAX_FNAME_LEN};
use super::prelude::*;
diff --git a/services/libs/aster-std/src/fs/ext2/fs.rs b/services/libs/aster-std/src/fs/ext2/fs.rs
--- a/services/libs/aster-std/src/fs/ext2/fs.rs
+++ b/services/libs/aster-std/src/fs/ext2/fs.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::block_group::{BlockGroup, RawGroupDescriptor};
use super::inode::{FilePerm, FileType, Inode, InodeDesc, RawInode};
use super::prelude::*;
diff --git a/services/libs/aster-std/src/fs/ext2/fs.rs b/services/libs/aster-std/src/fs/ext2/fs.rs
--- a/services/libs/aster-std/src/fs/ext2/fs.rs
+++ b/services/libs/aster-std/src/fs/ext2/fs.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::block_group::{BlockGroup, RawGroupDescriptor};
use super::inode::{FilePerm, FileType, Inode, InodeDesc, RawInode};
use super::prelude::*;
diff --git a/services/libs/aster-std/src/fs/ext2/impl_for_vfs/fs.rs b/services/libs/aster-std/src/fs/ext2/impl_for_vfs/fs.rs
--- a/services/libs/aster-std/src/fs/ext2/impl_for_vfs/fs.rs
+++ b/services/libs/aster-std/src/fs/ext2/impl_for_vfs/fs.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::ext2::{utils::Dirty, Ext2, SuperBlock as Ext2SuperBlock, MAGIC_NUM as EXT2_MAGIC};
use crate::fs::utils::{FileSystem, FsFlags, Inode, SuperBlock, NAME_MAX};
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/fs/ext2/impl_for_vfs/fs.rs b/services/libs/aster-std/src/fs/ext2/impl_for_vfs/fs.rs
--- a/services/libs/aster-std/src/fs/ext2/impl_for_vfs/fs.rs
+++ b/services/libs/aster-std/src/fs/ext2/impl_for_vfs/fs.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::ext2::{utils::Dirty, Ext2, SuperBlock as Ext2SuperBlock, MAGIC_NUM as EXT2_MAGIC};
use crate::fs::utils::{FileSystem, FsFlags, Inode, SuperBlock, NAME_MAX};
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/fs/ext2/impl_for_vfs/inode.rs b/services/libs/aster-std/src/fs/ext2/impl_for_vfs/inode.rs
--- a/services/libs/aster-std/src/fs/ext2/impl_for_vfs/inode.rs
+++ b/services/libs/aster-std/src/fs/ext2/impl_for_vfs/inode.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::device::Device;
use crate::fs::ext2::{FilePerm, FileType, Inode as Ext2Inode};
use crate::fs::utils::{
diff --git a/services/libs/aster-std/src/fs/ext2/impl_for_vfs/inode.rs b/services/libs/aster-std/src/fs/ext2/impl_for_vfs/inode.rs
--- a/services/libs/aster-std/src/fs/ext2/impl_for_vfs/inode.rs
+++ b/services/libs/aster-std/src/fs/ext2/impl_for_vfs/inode.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::device::Device;
use crate::fs::ext2::{FilePerm, FileType, Inode as Ext2Inode};
use crate::fs::utils::{
diff --git a/services/libs/aster-std/src/fs/ext2/impl_for_vfs/mod.rs b/services/libs/aster-std/src/fs/ext2/impl_for_vfs/mod.rs
--- a/services/libs/aster-std/src/fs/ext2/impl_for_vfs/mod.rs
+++ b/services/libs/aster-std/src/fs/ext2/impl_for_vfs/mod.rs
@@ -1,2 +1,4 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod fs;
mod inode;
diff --git a/services/libs/aster-std/src/fs/ext2/impl_for_vfs/mod.rs b/services/libs/aster-std/src/fs/ext2/impl_for_vfs/mod.rs
--- a/services/libs/aster-std/src/fs/ext2/impl_for_vfs/mod.rs
+++ b/services/libs/aster-std/src/fs/ext2/impl_for_vfs/mod.rs
@@ -1,2 +1,4 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod fs;
mod inode;
diff --git a/services/libs/aster-std/src/fs/ext2/inode.rs b/services/libs/aster-std/src/fs/ext2/inode.rs
--- a/services/libs/aster-std/src/fs/ext2/inode.rs
+++ b/services/libs/aster-std/src/fs/ext2/inode.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::blocks_hole::BlocksHoleDesc;
use super::dir::{DirEntry, DirEntryReader, DirEntryWriter};
use super::fs::Ext2;
diff --git a/services/libs/aster-std/src/fs/ext2/inode.rs b/services/libs/aster-std/src/fs/ext2/inode.rs
--- a/services/libs/aster-std/src/fs/ext2/inode.rs
+++ b/services/libs/aster-std/src/fs/ext2/inode.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::blocks_hole::BlocksHoleDesc;
use super::dir::{DirEntry, DirEntryReader, DirEntryWriter};
use super::fs::Ext2;
diff --git a/services/libs/aster-std/src/fs/ext2/mod.rs b/services/libs/aster-std/src/fs/ext2/mod.rs
--- a/services/libs/aster-std/src/fs/ext2/mod.rs
+++ b/services/libs/aster-std/src/fs/ext2/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! A safe Rust Ext2 filesystem.
//!
//! The Second Extended File System(Ext2) is a major rewrite of the Ext filesystem.
diff --git a/services/libs/aster-std/src/fs/ext2/mod.rs b/services/libs/aster-std/src/fs/ext2/mod.rs
--- a/services/libs/aster-std/src/fs/ext2/mod.rs
+++ b/services/libs/aster-std/src/fs/ext2/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! A safe Rust Ext2 filesystem.
//!
//! The Second Extended File System(Ext2) is a major rewrite of the Ext filesystem.
diff --git a/services/libs/aster-std/src/fs/ext2/prelude.rs b/services/libs/aster-std/src/fs/ext2/prelude.rs
--- a/services/libs/aster-std/src/fs/ext2/prelude.rs
+++ b/services/libs/aster-std/src/fs/ext2/prelude.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub(super) use super::utils::{Dirty, IsPowerOf};
pub(super) use crate::fs::utils::{
diff --git a/services/libs/aster-std/src/fs/ext2/prelude.rs b/services/libs/aster-std/src/fs/ext2/prelude.rs
--- a/services/libs/aster-std/src/fs/ext2/prelude.rs
+++ b/services/libs/aster-std/src/fs/ext2/prelude.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub(super) use super::utils::{Dirty, IsPowerOf};
pub(super) use crate::fs::utils::{
diff --git a/services/libs/aster-std/src/fs/ext2/super_block.rs b/services/libs/aster-std/src/fs/ext2/super_block.rs
--- a/services/libs/aster-std/src/fs/ext2/super_block.rs
+++ b/services/libs/aster-std/src/fs/ext2/super_block.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::inode::RawInode;
use super::prelude::*;
diff --git a/services/libs/aster-std/src/fs/ext2/super_block.rs b/services/libs/aster-std/src/fs/ext2/super_block.rs
--- a/services/libs/aster-std/src/fs/ext2/super_block.rs
+++ b/services/libs/aster-std/src/fs/ext2/super_block.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::inode::RawInode;
use super::prelude::*;
diff --git a/services/libs/aster-std/src/fs/ext2/utils.rs b/services/libs/aster-std/src/fs/ext2/utils.rs
--- a/services/libs/aster-std/src/fs/ext2/utils.rs
+++ b/services/libs/aster-std/src/fs/ext2/utils.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::prelude::*;
use core::ops::MulAssign;
diff --git a/services/libs/aster-std/src/fs/ext2/utils.rs b/services/libs/aster-std/src/fs/ext2/utils.rs
--- a/services/libs/aster-std/src/fs/ext2/utils.rs
+++ b/services/libs/aster-std/src/fs/ext2/utils.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::prelude::*;
use core::ops::MulAssign;
diff --git a/services/libs/aster-std/src/fs/file_handle.rs b/services/libs/aster-std/src/fs/file_handle.rs
--- a/services/libs/aster-std/src/fs/file_handle.rs
+++ b/services/libs/aster-std/src/fs/file_handle.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Opend File Handle
use crate::events::{IoEvents, Observer};
diff --git a/services/libs/aster-std/src/fs/file_handle.rs b/services/libs/aster-std/src/fs/file_handle.rs
--- a/services/libs/aster-std/src/fs/file_handle.rs
+++ b/services/libs/aster-std/src/fs/file_handle.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Opend File Handle
use crate::events::{IoEvents, Observer};
diff --git a/services/libs/aster-std/src/fs/file_table.rs b/services/libs/aster-std/src/fs/file_table.rs
--- a/services/libs/aster-std/src/fs/file_table.rs
+++ b/services/libs/aster-std/src/fs/file_table.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::{Events, Observer, Subject};
use crate::net::socket::Socket;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/fs/file_table.rs b/services/libs/aster-std/src/fs/file_table.rs
--- a/services/libs/aster-std/src/fs/file_table.rs
+++ b/services/libs/aster-std/src/fs/file_table.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::{Events, Observer, Subject};
use crate::net::socket::Socket;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/fs/fs_resolver.rs b/services/libs/aster-std/src/fs/fs_resolver.rs
--- a/services/libs/aster-std/src/fs/fs_resolver.rs
+++ b/services/libs/aster-std/src/fs/fs_resolver.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use alloc::str;
diff --git a/services/libs/aster-std/src/fs/fs_resolver.rs b/services/libs/aster-std/src/fs/fs_resolver.rs
--- a/services/libs/aster-std/src/fs/fs_resolver.rs
+++ b/services/libs/aster-std/src/fs/fs_resolver.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use alloc::str;
diff --git a/services/libs/aster-std/src/fs/inode_handle/dyn_cap.rs b/services/libs/aster-std/src/fs/inode_handle/dyn_cap.rs
--- a/services/libs/aster-std/src/fs/inode_handle/dyn_cap.rs
+++ b/services/libs/aster-std/src/fs/inode_handle/dyn_cap.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::IoEvents;
use crate::prelude::*;
use crate::process::signal::Poller;
diff --git a/services/libs/aster-std/src/fs/inode_handle/dyn_cap.rs b/services/libs/aster-std/src/fs/inode_handle/dyn_cap.rs
--- a/services/libs/aster-std/src/fs/inode_handle/dyn_cap.rs
+++ b/services/libs/aster-std/src/fs/inode_handle/dyn_cap.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::IoEvents;
use crate::prelude::*;
use crate::process::signal::Poller;
diff --git a/services/libs/aster-std/src/fs/inode_handle/mod.rs b/services/libs/aster-std/src/fs/inode_handle/mod.rs
--- a/services/libs/aster-std/src/fs/inode_handle/mod.rs
+++ b/services/libs/aster-std/src/fs/inode_handle/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Opend Inode-backed File Handle
mod dyn_cap;
diff --git a/services/libs/aster-std/src/fs/inode_handle/mod.rs b/services/libs/aster-std/src/fs/inode_handle/mod.rs
--- a/services/libs/aster-std/src/fs/inode_handle/mod.rs
+++ b/services/libs/aster-std/src/fs/inode_handle/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Opend Inode-backed File Handle
mod dyn_cap;
diff --git a/services/libs/aster-std/src/fs/inode_handle/static_cap.rs b/services/libs/aster-std/src/fs/inode_handle/static_cap.rs
--- a/services/libs/aster-std/src/fs/inode_handle/static_cap.rs
+++ b/services/libs/aster-std/src/fs/inode_handle/static_cap.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use aster_rights::{Read, TRightSet, TRights, Write};
use aster_rights_proc::require;
diff --git a/services/libs/aster-std/src/fs/inode_handle/static_cap.rs b/services/libs/aster-std/src/fs/inode_handle/static_cap.rs
--- a/services/libs/aster-std/src/fs/inode_handle/static_cap.rs
+++ b/services/libs/aster-std/src/fs/inode_handle/static_cap.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use aster_rights::{Read, TRightSet, TRights, Write};
use aster_rights_proc::require;
diff --git a/services/libs/aster-std/src/fs/mod.rs b/services/libs/aster-std/src/fs/mod.rs
--- a/services/libs/aster-std/src/fs/mod.rs
+++ b/services/libs/aster-std/src/fs/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod device;
pub mod devpts;
pub mod epoll;
diff --git a/services/libs/aster-std/src/fs/mod.rs b/services/libs/aster-std/src/fs/mod.rs
--- a/services/libs/aster-std/src/fs/mod.rs
+++ b/services/libs/aster-std/src/fs/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod device;
pub mod devpts;
pub mod epoll;
diff --git a/services/libs/aster-std/src/fs/pipe.rs b/services/libs/aster-std/src/fs/pipe.rs
--- a/services/libs/aster-std/src/fs/pipe.rs
+++ b/services/libs/aster-std/src/fs/pipe.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::{IoEvents, Observer};
use crate::prelude::*;
use crate::process::signal::Poller;
diff --git a/services/libs/aster-std/src/fs/pipe.rs b/services/libs/aster-std/src/fs/pipe.rs
--- a/services/libs/aster-std/src/fs/pipe.rs
+++ b/services/libs/aster-std/src/fs/pipe.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::{IoEvents, Observer};
use crate::prelude::*;
use crate::process::signal::Poller;
diff --git a/services/libs/aster-std/src/fs/procfs/mod.rs b/services/libs/aster-std/src/fs/procfs/mod.rs
--- a/services/libs/aster-std/src/fs/procfs/mod.rs
+++ b/services/libs/aster-std/src/fs/procfs/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicUsize, Ordering};
use crate::events::Observer;
diff --git a/services/libs/aster-std/src/fs/procfs/mod.rs b/services/libs/aster-std/src/fs/procfs/mod.rs
--- a/services/libs/aster-std/src/fs/procfs/mod.rs
+++ b/services/libs/aster-std/src/fs/procfs/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicUsize, Ordering};
use crate::events::Observer;
diff --git a/services/libs/aster-std/src/fs/procfs/pid/comm.rs b/services/libs/aster-std/src/fs/procfs/pid/comm.rs
--- a/services/libs/aster-std/src/fs/procfs/pid/comm.rs
+++ b/services/libs/aster-std/src/fs/procfs/pid/comm.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::*;
/// Represents the inode at `/proc/[pid]/comm`.
diff --git a/services/libs/aster-std/src/fs/procfs/pid/comm.rs b/services/libs/aster-std/src/fs/procfs/pid/comm.rs
--- a/services/libs/aster-std/src/fs/procfs/pid/comm.rs
+++ b/services/libs/aster-std/src/fs/procfs/pid/comm.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::*;
/// Represents the inode at `/proc/[pid]/comm`.
diff --git a/services/libs/aster-std/src/fs/procfs/pid/exe.rs b/services/libs/aster-std/src/fs/procfs/pid/exe.rs
--- a/services/libs/aster-std/src/fs/procfs/pid/exe.rs
+++ b/services/libs/aster-std/src/fs/procfs/pid/exe.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::*;
/// Represents the inode at `/proc/[pid]/exe`.
diff --git a/services/libs/aster-std/src/fs/procfs/pid/exe.rs b/services/libs/aster-std/src/fs/procfs/pid/exe.rs
--- a/services/libs/aster-std/src/fs/procfs/pid/exe.rs
+++ b/services/libs/aster-std/src/fs/procfs/pid/exe.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::*;
/// Represents the inode at `/proc/[pid]/exe`.
diff --git a/services/libs/aster-std/src/fs/procfs/pid/fd.rs b/services/libs/aster-std/src/fs/procfs/pid/fd.rs
--- a/services/libs/aster-std/src/fs/procfs/pid/fd.rs
+++ b/services/libs/aster-std/src/fs/procfs/pid/fd.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::*;
use crate::fs::file_handle::FileLike;
use crate::fs::file_table::FileDescripter;
diff --git a/services/libs/aster-std/src/fs/procfs/pid/fd.rs b/services/libs/aster-std/src/fs/procfs/pid/fd.rs
--- a/services/libs/aster-std/src/fs/procfs/pid/fd.rs
+++ b/services/libs/aster-std/src/fs/procfs/pid/fd.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::*;
use crate::fs::file_handle::FileLike;
use crate::fs::file_table::FileDescripter;
diff --git a/services/libs/aster-std/src/fs/procfs/pid/mod.rs b/services/libs/aster-std/src/fs/procfs/pid/mod.rs
--- a/services/libs/aster-std/src/fs/procfs/pid/mod.rs
+++ b/services/libs/aster-std/src/fs/procfs/pid/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::Observer;
use crate::fs::file_table::FdEvents;
use crate::fs::utils::{DirEntryVecExt, Inode};
diff --git a/services/libs/aster-std/src/fs/procfs/pid/mod.rs b/services/libs/aster-std/src/fs/procfs/pid/mod.rs
--- a/services/libs/aster-std/src/fs/procfs/pid/mod.rs
+++ b/services/libs/aster-std/src/fs/procfs/pid/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::Observer;
use crate::fs::file_table::FdEvents;
use crate::fs::utils::{DirEntryVecExt, Inode};
diff --git a/services/libs/aster-std/src/fs/procfs/self_.rs b/services/libs/aster-std/src/fs/procfs/self_.rs
--- a/services/libs/aster-std/src/fs/procfs/self_.rs
+++ b/services/libs/aster-std/src/fs/procfs/self_.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::*;
/// Represents the inode at `/proc/self`.
diff --git a/services/libs/aster-std/src/fs/procfs/self_.rs b/services/libs/aster-std/src/fs/procfs/self_.rs
--- a/services/libs/aster-std/src/fs/procfs/self_.rs
+++ b/services/libs/aster-std/src/fs/procfs/self_.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::*;
/// Represents the inode at `/proc/self`.
diff --git a/services/libs/aster-std/src/fs/procfs/template/builder.rs b/services/libs/aster-std/src/fs/procfs/template/builder.rs
--- a/services/libs/aster-std/src/fs/procfs/template/builder.rs
+++ b/services/libs/aster-std/src/fs/procfs/template/builder.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::utils::{FileSystem, Inode};
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/fs/procfs/template/builder.rs b/services/libs/aster-std/src/fs/procfs/template/builder.rs
--- a/services/libs/aster-std/src/fs/procfs/template/builder.rs
+++ b/services/libs/aster-std/src/fs/procfs/template/builder.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::utils::{FileSystem, Inode};
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/fs/procfs/template/dir.rs b/services/libs/aster-std/src/fs/procfs/template/dir.rs
--- a/services/libs/aster-std/src/fs/procfs/template/dir.rs
+++ b/services/libs/aster-std/src/fs/procfs/template/dir.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_util::slot_vec::SlotVec;
use core::time::Duration;
diff --git a/services/libs/aster-std/src/fs/procfs/template/dir.rs b/services/libs/aster-std/src/fs/procfs/template/dir.rs
--- a/services/libs/aster-std/src/fs/procfs/template/dir.rs
+++ b/services/libs/aster-std/src/fs/procfs/template/dir.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_util::slot_vec::SlotVec;
use core::time::Duration;
diff --git a/services/libs/aster-std/src/fs/procfs/template/file.rs b/services/libs/aster-std/src/fs/procfs/template/file.rs
--- a/services/libs/aster-std/src/fs/procfs/template/file.rs
+++ b/services/libs/aster-std/src/fs/procfs/template/file.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::time::Duration;
use crate::fs::utils::{FileSystem, Inode, InodeMode, InodeType, IoctlCmd, Metadata};
diff --git a/services/libs/aster-std/src/fs/procfs/template/file.rs b/services/libs/aster-std/src/fs/procfs/template/file.rs
--- a/services/libs/aster-std/src/fs/procfs/template/file.rs
+++ b/services/libs/aster-std/src/fs/procfs/template/file.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::time::Duration;
use crate::fs::utils::{FileSystem, Inode, InodeMode, InodeType, IoctlCmd, Metadata};
diff --git a/services/libs/aster-std/src/fs/procfs/template/mod.rs b/services/libs/aster-std/src/fs/procfs/template/mod.rs
--- a/services/libs/aster-std/src/fs/procfs/template/mod.rs
+++ b/services/libs/aster-std/src/fs/procfs/template/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::time::Duration;
use crate::fs::utils::{FileSystem, InodeMode, Metadata};
diff --git a/services/libs/aster-std/src/fs/procfs/template/mod.rs b/services/libs/aster-std/src/fs/procfs/template/mod.rs
--- a/services/libs/aster-std/src/fs/procfs/template/mod.rs
+++ b/services/libs/aster-std/src/fs/procfs/template/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::time::Duration;
use crate::fs::utils::{FileSystem, InodeMode, Metadata};
diff --git a/services/libs/aster-std/src/fs/procfs/template/sym.rs b/services/libs/aster-std/src/fs/procfs/template/sym.rs
--- a/services/libs/aster-std/src/fs/procfs/template/sym.rs
+++ b/services/libs/aster-std/src/fs/procfs/template/sym.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::time::Duration;
use crate::fs::utils::{FileSystem, Inode, InodeMode, InodeType, IoctlCmd, Metadata};
diff --git a/services/libs/aster-std/src/fs/procfs/template/sym.rs b/services/libs/aster-std/src/fs/procfs/template/sym.rs
--- a/services/libs/aster-std/src/fs/procfs/template/sym.rs
+++ b/services/libs/aster-std/src/fs/procfs/template/sym.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::time::Duration;
use crate::fs::utils::{FileSystem, Inode, InodeMode, InodeType, IoctlCmd, Metadata};
diff --git a/services/libs/aster-std/src/fs/ramfs/fs.rs b/services/libs/aster-std/src/fs/ramfs/fs.rs
--- a/services/libs/aster-std/src/fs/ramfs/fs.rs
+++ b/services/libs/aster-std/src/fs/ramfs/fs.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::sync::RwLockWriteGuard;
use aster_frame::vm::VmFrame;
use aster_frame::vm::VmIo;
diff --git a/services/libs/aster-std/src/fs/ramfs/fs.rs b/services/libs/aster-std/src/fs/ramfs/fs.rs
--- a/services/libs/aster-std/src/fs/ramfs/fs.rs
+++ b/services/libs/aster-std/src/fs/ramfs/fs.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::sync::RwLockWriteGuard;
use aster_frame::vm::VmFrame;
use aster_frame::vm::VmIo;
diff --git a/services/libs/aster-std/src/fs/ramfs/mod.rs b/services/libs/aster-std/src/fs/ramfs/mod.rs
--- a/services/libs/aster-std/src/fs/ramfs/mod.rs
+++ b/services/libs/aster-std/src/fs/ramfs/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Ramfs based on PageCache
pub use fs::RamFS;
diff --git a/services/libs/aster-std/src/fs/ramfs/mod.rs b/services/libs/aster-std/src/fs/ramfs/mod.rs
--- a/services/libs/aster-std/src/fs/ramfs/mod.rs
+++ b/services/libs/aster-std/src/fs/ramfs/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Ramfs based on PageCache
pub use fs::RamFS;
diff --git a/services/libs/aster-std/src/fs/rootfs.rs b/services/libs/aster-std/src/fs/rootfs.rs
--- a/services/libs/aster-std/src/fs/rootfs.rs
+++ b/services/libs/aster-std/src/fs/rootfs.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use super::fs_resolver::{FsPath, FsResolver};
diff --git a/services/libs/aster-std/src/fs/rootfs.rs b/services/libs/aster-std/src/fs/rootfs.rs
--- a/services/libs/aster-std/src/fs/rootfs.rs
+++ b/services/libs/aster-std/src/fs/rootfs.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use super::fs_resolver::{FsPath, FsResolver};
diff --git a/services/libs/aster-std/src/fs/utils/access_mode.rs b/services/libs/aster-std/src/fs/utils/access_mode.rs
--- a/services/libs/aster-std/src/fs/utils/access_mode.rs
+++ b/services/libs/aster-std/src/fs/utils/access_mode.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use aster_rights::Rights;
diff --git a/services/libs/aster-std/src/fs/utils/access_mode.rs b/services/libs/aster-std/src/fs/utils/access_mode.rs
--- a/services/libs/aster-std/src/fs/utils/access_mode.rs
+++ b/services/libs/aster-std/src/fs/utils/access_mode.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use aster_rights::Rights;
diff --git a/services/libs/aster-std/src/fs/utils/channel.rs b/services/libs/aster-std/src/fs/utils/channel.rs
--- a/services/libs/aster-std/src/fs/utils/channel.rs
+++ b/services/libs/aster-std/src/fs/utils/channel.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_rights_proc::require;
use core::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use ringbuf::{HeapConsumer as HeapRbConsumer, HeapProducer as HeapRbProducer, HeapRb};
diff --git a/services/libs/aster-std/src/fs/utils/channel.rs b/services/libs/aster-std/src/fs/utils/channel.rs
--- a/services/libs/aster-std/src/fs/utils/channel.rs
+++ b/services/libs/aster-std/src/fs/utils/channel.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_rights_proc::require;
use core::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use ringbuf::{HeapConsumer as HeapRbConsumer, HeapProducer as HeapRbProducer, HeapRb};
diff --git a/services/libs/aster-std/src/fs/utils/creation_flags.rs b/services/libs/aster-std/src/fs/utils/creation_flags.rs
--- a/services/libs/aster-std/src/fs/utils/creation_flags.rs
+++ b/services/libs/aster-std/src/fs/utils/creation_flags.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use bitflags::bitflags;
bitflags! {
diff --git a/services/libs/aster-std/src/fs/utils/creation_flags.rs b/services/libs/aster-std/src/fs/utils/creation_flags.rs
--- a/services/libs/aster-std/src/fs/utils/creation_flags.rs
+++ b/services/libs/aster-std/src/fs/utils/creation_flags.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use bitflags::bitflags;
bitflags! {
diff --git a/services/libs/aster-std/src/fs/utils/dentry.rs b/services/libs/aster-std/src/fs/utils/dentry.rs
--- a/services/libs/aster-std/src/fs/utils/dentry.rs
+++ b/services/libs/aster-std/src/fs/utils/dentry.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::device::Device;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/fs/utils/dentry.rs b/services/libs/aster-std/src/fs/utils/dentry.rs
--- a/services/libs/aster-std/src/fs/utils/dentry.rs
+++ b/services/libs/aster-std/src/fs/utils/dentry.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::device::Device;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/fs/utils/dirent_visitor.rs b/services/libs/aster-std/src/fs/utils/dirent_visitor.rs
--- a/services/libs/aster-std/src/fs/utils/dirent_visitor.rs
+++ b/services/libs/aster-std/src/fs/utils/dirent_visitor.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::InodeType;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/fs/utils/dirent_visitor.rs b/services/libs/aster-std/src/fs/utils/dirent_visitor.rs
--- a/services/libs/aster-std/src/fs/utils/dirent_visitor.rs
+++ b/services/libs/aster-std/src/fs/utils/dirent_visitor.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::InodeType;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/fs/utils/direntry_vec.rs b/services/libs/aster-std/src/fs/utils/direntry_vec.rs
--- a/services/libs/aster-std/src/fs/utils/direntry_vec.rs
+++ b/services/libs/aster-std/src/fs/utils/direntry_vec.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::Inode;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/fs/utils/direntry_vec.rs b/services/libs/aster-std/src/fs/utils/direntry_vec.rs
--- a/services/libs/aster-std/src/fs/utils/direntry_vec.rs
+++ b/services/libs/aster-std/src/fs/utils/direntry_vec.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::Inode;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/fs/utils/file_creation_mask.rs b/services/libs/aster-std/src/fs/utils/file_creation_mask.rs
--- a/services/libs/aster-std/src/fs/utils/file_creation_mask.rs
+++ b/services/libs/aster-std/src/fs/utils/file_creation_mask.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
/// A mask for the file mode of a newly-created file or directory.
///
/// This mask is always a subset of `0o777`.
diff --git a/services/libs/aster-std/src/fs/utils/file_creation_mask.rs b/services/libs/aster-std/src/fs/utils/file_creation_mask.rs
--- a/services/libs/aster-std/src/fs/utils/file_creation_mask.rs
+++ b/services/libs/aster-std/src/fs/utils/file_creation_mask.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
/// A mask for the file mode of a newly-created file or directory.
///
/// This mask is always a subset of `0o777`.
diff --git a/services/libs/aster-std/src/fs/utils/fs.rs b/services/libs/aster-std/src/fs/utils/fs.rs
--- a/services/libs/aster-std/src/fs/utils/fs.rs
+++ b/services/libs/aster-std/src/fs/utils/fs.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::Inode;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/fs/utils/fs.rs b/services/libs/aster-std/src/fs/utils/fs.rs
--- a/services/libs/aster-std/src/fs/utils/fs.rs
+++ b/services/libs/aster-std/src/fs/utils/fs.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::Inode;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/fs/utils/inode.rs b/services/libs/aster-std/src/fs/utils/inode.rs
--- a/services/libs/aster-std/src/fs/utils/inode.rs
+++ b/services/libs/aster-std/src/fs/utils/inode.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_rights::Full;
use core::time::Duration;
use core2::io::{Error as IoError, ErrorKind as IoErrorKind, Result as IoResult, Write};
diff --git a/services/libs/aster-std/src/fs/utils/inode.rs b/services/libs/aster-std/src/fs/utils/inode.rs
--- a/services/libs/aster-std/src/fs/utils/inode.rs
+++ b/services/libs/aster-std/src/fs/utils/inode.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_rights::Full;
use core::time::Duration;
use core2::io::{Error as IoError, ErrorKind as IoErrorKind, Result as IoResult, Write};
diff --git a/services/libs/aster-std/src/fs/utils/ioctl.rs b/services/libs/aster-std/src/fs/utils/ioctl.rs
--- a/services/libs/aster-std/src/fs/utils/ioctl.rs
+++ b/services/libs/aster-std/src/fs/utils/ioctl.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
#[repr(u32)]
diff --git a/services/libs/aster-std/src/fs/utils/ioctl.rs b/services/libs/aster-std/src/fs/utils/ioctl.rs
--- a/services/libs/aster-std/src/fs/utils/ioctl.rs
+++ b/services/libs/aster-std/src/fs/utils/ioctl.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
#[repr(u32)]
diff --git a/services/libs/aster-std/src/fs/utils/mod.rs b/services/libs/aster-std/src/fs/utils/mod.rs
--- a/services/libs/aster-std/src/fs/utils/mod.rs
+++ b/services/libs/aster-std/src/fs/utils/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! VFS components
pub use access_mode::AccessMode;
diff --git a/services/libs/aster-std/src/fs/utils/mod.rs b/services/libs/aster-std/src/fs/utils/mod.rs
--- a/services/libs/aster-std/src/fs/utils/mod.rs
+++ b/services/libs/aster-std/src/fs/utils/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! VFS components
pub use access_mode::AccessMode;
diff --git a/services/libs/aster-std/src/fs/utils/mount.rs b/services/libs/aster-std/src/fs/utils/mount.rs
--- a/services/libs/aster-std/src/fs/utils/mount.rs
+++ b/services/libs/aster-std/src/fs/utils/mount.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use super::{Dentry, DentryKey, FileSystem, InodeType};
diff --git a/services/libs/aster-std/src/fs/utils/mount.rs b/services/libs/aster-std/src/fs/utils/mount.rs
--- a/services/libs/aster-std/src/fs/utils/mount.rs
+++ b/services/libs/aster-std/src/fs/utils/mount.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use super::{Dentry, DentryKey, FileSystem, InodeType};
diff --git a/services/libs/aster-std/src/fs/utils/page_cache.rs b/services/libs/aster-std/src/fs/utils/page_cache.rs
--- a/services/libs/aster-std/src/fs/utils/page_cache.rs
+++ b/services/libs/aster-std/src/fs/utils/page_cache.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use crate::vm::vmo::{get_page_idx_range, Pager, Vmo, VmoFlags, VmoOptions};
use aster_rights::Full;
diff --git a/services/libs/aster-std/src/fs/utils/page_cache.rs b/services/libs/aster-std/src/fs/utils/page_cache.rs
--- a/services/libs/aster-std/src/fs/utils/page_cache.rs
+++ b/services/libs/aster-std/src/fs/utils/page_cache.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use crate::vm::vmo::{get_page_idx_range, Pager, Vmo, VmoFlags, VmoOptions};
use aster_rights::Full;
diff --git a/services/libs/aster-std/src/fs/utils/status_flags.rs b/services/libs/aster-std/src/fs/utils/status_flags.rs
--- a/services/libs/aster-std/src/fs/utils/status_flags.rs
+++ b/services/libs/aster-std/src/fs/utils/status_flags.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use bitflags::bitflags;
bitflags! {
diff --git a/services/libs/aster-std/src/fs/utils/status_flags.rs b/services/libs/aster-std/src/fs/utils/status_flags.rs
--- a/services/libs/aster-std/src/fs/utils/status_flags.rs
+++ b/services/libs/aster-std/src/fs/utils/status_flags.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use bitflags::bitflags;
bitflags! {
diff --git a/services/libs/aster-std/src/lib.rs b/services/libs/aster-std/src/lib.rs
--- a/services/libs/aster-std/src/lib.rs
+++ b/services/libs/aster-std/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The std library of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
diff --git a/services/libs/aster-std/src/lib.rs b/services/libs/aster-std/src/lib.rs
--- a/services/libs/aster-std/src/lib.rs
+++ b/services/libs/aster-std/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The std library of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
diff --git a/services/libs/aster-std/src/net/iface/any_socket.rs b/services/libs/aster-std/src/net/iface/any_socket.rs
--- a/services/libs/aster-std/src/net/iface/any_socket.rs
+++ b/services/libs/aster-std/src/net/iface/any_socket.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::Observer;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/net/iface/any_socket.rs b/services/libs/aster-std/src/net/iface/any_socket.rs
--- a/services/libs/aster-std/src/net/iface/any_socket.rs
+++ b/services/libs/aster-std/src/net/iface/any_socket.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::Observer;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/net/iface/common.rs b/services/libs/aster-std/src/net/iface/common.rs
--- a/services/libs/aster-std/src/net/iface/common.rs
+++ b/services/libs/aster-std/src/net/iface/common.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicU64, Ordering};
use super::Ipv4Address;
diff --git a/services/libs/aster-std/src/net/iface/common.rs b/services/libs/aster-std/src/net/iface/common.rs
--- a/services/libs/aster-std/src/net/iface/common.rs
+++ b/services/libs/aster-std/src/net/iface/common.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicU64, Ordering};
use super::Ipv4Address;
diff --git a/services/libs/aster-std/src/net/iface/loopback.rs b/services/libs/aster-std/src/net/iface/loopback.rs
--- a/services/libs/aster-std/src/net/iface/loopback.rs
+++ b/services/libs/aster-std/src/net/iface/loopback.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{IpAddress, Ipv4Address};
use crate::prelude::*;
use smoltcp::{
diff --git a/services/libs/aster-std/src/net/iface/loopback.rs b/services/libs/aster-std/src/net/iface/loopback.rs
--- a/services/libs/aster-std/src/net/iface/loopback.rs
+++ b/services/libs/aster-std/src/net/iface/loopback.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{IpAddress, Ipv4Address};
use crate::prelude::*;
use smoltcp::{
diff --git a/services/libs/aster-std/src/net/iface/mod.rs b/services/libs/aster-std/src/net/iface/mod.rs
--- a/services/libs/aster-std/src/net/iface/mod.rs
+++ b/services/libs/aster-std/src/net/iface/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use self::common::IfaceCommon;
use crate::prelude::*;
use smoltcp::iface::SocketSet;
diff --git a/services/libs/aster-std/src/net/iface/mod.rs b/services/libs/aster-std/src/net/iface/mod.rs
--- a/services/libs/aster-std/src/net/iface/mod.rs
+++ b/services/libs/aster-std/src/net/iface/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use self::common::IfaceCommon;
use crate::prelude::*;
use smoltcp::iface::SocketSet;
diff --git a/services/libs/aster-std/src/net/iface/time.rs b/services/libs/aster-std/src/net/iface/time.rs
--- a/services/libs/aster-std/src/net/iface/time.rs
+++ b/services/libs/aster-std/src/net/iface/time.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::timer::read_monotonic_milli_seconds;
pub(super) fn get_network_timestamp() -> smoltcp::time::Instant {
diff --git a/services/libs/aster-std/src/net/iface/time.rs b/services/libs/aster-std/src/net/iface/time.rs
--- a/services/libs/aster-std/src/net/iface/time.rs
+++ b/services/libs/aster-std/src/net/iface/time.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::timer::read_monotonic_milli_seconds;
pub(super) fn get_network_timestamp() -> smoltcp::time::Instant {
diff --git a/services/libs/aster-std/src/net/iface/util.rs b/services/libs/aster-std/src/net/iface/util.rs
--- a/services/libs/aster-std/src/net/iface/util.rs
+++ b/services/libs/aster-std/src/net/iface/util.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::timer::read_monotonic_milli_seconds;
use crate::{
diff --git a/services/libs/aster-std/src/net/iface/util.rs b/services/libs/aster-std/src/net/iface/util.rs
--- a/services/libs/aster-std/src/net/iface/util.rs
+++ b/services/libs/aster-std/src/net/iface/util.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::timer::read_monotonic_milli_seconds;
use crate::{
diff --git a/services/libs/aster-std/src/net/iface/virtio.rs b/services/libs/aster-std/src/net/iface/virtio.rs
--- a/services/libs/aster-std/src/net/iface/virtio.rs
+++ b/services/libs/aster-std/src/net/iface/virtio.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use aster_frame::sync::SpinLock;
use aster_network::AnyNetworkDevice;
diff --git a/services/libs/aster-std/src/net/iface/virtio.rs b/services/libs/aster-std/src/net/iface/virtio.rs
--- a/services/libs/aster-std/src/net/iface/virtio.rs
+++ b/services/libs/aster-std/src/net/iface/virtio.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use aster_frame::sync::SpinLock;
use aster_network::AnyNetworkDevice;
diff --git a/services/libs/aster-std/src/net/mod.rs b/services/libs/aster-std/src/net/mod.rs
--- a/services/libs/aster-std/src/net/mod.rs
+++ b/services/libs/aster-std/src/net/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{
net::iface::{Iface, IfaceLoopback, IfaceVirtio},
prelude::*,
diff --git a/services/libs/aster-std/src/net/mod.rs b/services/libs/aster-std/src/net/mod.rs
--- a/services/libs/aster-std/src/net/mod.rs
+++ b/services/libs/aster-std/src/net/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{
net::iface::{Iface, IfaceLoopback, IfaceVirtio},
prelude::*,
diff --git a/services/libs/aster-std/src/net/socket/ip/always_some.rs b/services/libs/aster-std/src/net/socket/ip/always_some.rs
--- a/services/libs/aster-std/src/net/socket/ip/always_some.rs
+++ b/services/libs/aster-std/src/net/socket/ip/always_some.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use core::ops::{Deref, DerefMut};
diff --git a/services/libs/aster-std/src/net/socket/ip/always_some.rs b/services/libs/aster-std/src/net/socket/ip/always_some.rs
--- a/services/libs/aster-std/src/net/socket/ip/always_some.rs
+++ b/services/libs/aster-std/src/net/socket/ip/always_some.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use core::ops::{Deref, DerefMut};
diff --git a/services/libs/aster-std/src/net/socket/ip/common.rs b/services/libs/aster-std/src/net/socket/ip/common.rs
--- a/services/libs/aster-std/src/net/socket/ip/common.rs
+++ b/services/libs/aster-std/src/net/socket/ip/common.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::net::iface::BindPortConfig;
use crate::net::iface::Iface;
use crate::net::iface::{AnyBoundSocket, AnyUnboundSocket};
diff --git a/services/libs/aster-std/src/net/socket/ip/common.rs b/services/libs/aster-std/src/net/socket/ip/common.rs
--- a/services/libs/aster-std/src/net/socket/ip/common.rs
+++ b/services/libs/aster-std/src/net/socket/ip/common.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::net::iface::BindPortConfig;
use crate::net::iface::Iface;
use crate::net::iface::{AnyBoundSocket, AnyUnboundSocket};
diff --git a/services/libs/aster-std/src/net/socket/ip/datagram/bound.rs b/services/libs/aster-std/src/net/socket/ip/datagram/bound.rs
--- a/services/libs/aster-std/src/net/socket/ip/datagram/bound.rs
+++ b/services/libs/aster-std/src/net/socket/ip/datagram/bound.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::{IoEvents, Observer};
use crate::net::iface::IpEndpoint;
diff --git a/services/libs/aster-std/src/net/socket/ip/datagram/bound.rs b/services/libs/aster-std/src/net/socket/ip/datagram/bound.rs
--- a/services/libs/aster-std/src/net/socket/ip/datagram/bound.rs
+++ b/services/libs/aster-std/src/net/socket/ip/datagram/bound.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::{IoEvents, Observer};
use crate::net::iface::IpEndpoint;
diff --git a/services/libs/aster-std/src/net/socket/ip/datagram/mod.rs b/services/libs/aster-std/src/net/socket/ip/datagram/mod.rs
--- a/services/libs/aster-std/src/net/socket/ip/datagram/mod.rs
+++ b/services/libs/aster-std/src/net/socket/ip/datagram/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicBool, Ordering};
use crate::events::IoEvents;
diff --git a/services/libs/aster-std/src/net/socket/ip/datagram/mod.rs b/services/libs/aster-std/src/net/socket/ip/datagram/mod.rs
--- a/services/libs/aster-std/src/net/socket/ip/datagram/mod.rs
+++ b/services/libs/aster-std/src/net/socket/ip/datagram/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicBool, Ordering};
use crate::events::IoEvents;
diff --git a/services/libs/aster-std/src/net/socket/ip/datagram/unbound.rs b/services/libs/aster-std/src/net/socket/ip/datagram/unbound.rs
--- a/services/libs/aster-std/src/net/socket/ip/datagram/unbound.rs
+++ b/services/libs/aster-std/src/net/socket/ip/datagram/unbound.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::IoEvents;
use crate::net::iface::IpEndpoint;
diff --git a/services/libs/aster-std/src/net/socket/ip/datagram/unbound.rs b/services/libs/aster-std/src/net/socket/ip/datagram/unbound.rs
--- a/services/libs/aster-std/src/net/socket/ip/datagram/unbound.rs
+++ b/services/libs/aster-std/src/net/socket/ip/datagram/unbound.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::IoEvents;
use crate::net::iface::IpEndpoint;
diff --git a/services/libs/aster-std/src/net/socket/ip/mod.rs b/services/libs/aster-std/src/net/socket/ip/mod.rs
--- a/services/libs/aster-std/src/net/socket/ip/mod.rs
+++ b/services/libs/aster-std/src/net/socket/ip/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod always_some;
mod common;
mod datagram;
diff --git a/services/libs/aster-std/src/net/socket/ip/mod.rs b/services/libs/aster-std/src/net/socket/ip/mod.rs
--- a/services/libs/aster-std/src/net/socket/ip/mod.rs
+++ b/services/libs/aster-std/src/net/socket/ip/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod always_some;
mod common;
mod datagram;
diff --git a/services/libs/aster-std/src/net/socket/ip/stream/connected.rs b/services/libs/aster-std/src/net/socket/ip/stream/connected.rs
--- a/services/libs/aster-std/src/net/socket/ip/stream/connected.rs
+++ b/services/libs/aster-std/src/net/socket/ip/stream/connected.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicBool, Ordering};
use crate::events::{IoEvents, Observer};
diff --git a/services/libs/aster-std/src/net/socket/ip/stream/connected.rs b/services/libs/aster-std/src/net/socket/ip/stream/connected.rs
--- a/services/libs/aster-std/src/net/socket/ip/stream/connected.rs
+++ b/services/libs/aster-std/src/net/socket/ip/stream/connected.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicBool, Ordering};
use crate::events::{IoEvents, Observer};
diff --git a/services/libs/aster-std/src/net/socket/ip/stream/connecting.rs b/services/libs/aster-std/src/net/socket/ip/stream/connecting.rs
--- a/services/libs/aster-std/src/net/socket/ip/stream/connecting.rs
+++ b/services/libs/aster-std/src/net/socket/ip/stream/connecting.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicBool, Ordering};
use alloc::sync::Arc;
diff --git a/services/libs/aster-std/src/net/socket/ip/stream/connecting.rs b/services/libs/aster-std/src/net/socket/ip/stream/connecting.rs
--- a/services/libs/aster-std/src/net/socket/ip/stream/connecting.rs
+++ b/services/libs/aster-std/src/net/socket/ip/stream/connecting.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicBool, Ordering};
use alloc::sync::Arc;
diff --git a/services/libs/aster-std/src/net/socket/ip/stream/init.rs b/services/libs/aster-std/src/net/socket/ip/stream/init.rs
--- a/services/libs/aster-std/src/net/socket/ip/stream/init.rs
+++ b/services/libs/aster-std/src/net/socket/ip/stream/init.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicBool, Ordering};
use crate::events::IoEvents;
diff --git a/services/libs/aster-std/src/net/socket/ip/stream/init.rs b/services/libs/aster-std/src/net/socket/ip/stream/init.rs
--- a/services/libs/aster-std/src/net/socket/ip/stream/init.rs
+++ b/services/libs/aster-std/src/net/socket/ip/stream/init.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicBool, Ordering};
use crate::events::IoEvents;
diff --git a/services/libs/aster-std/src/net/socket/ip/stream/listen.rs b/services/libs/aster-std/src/net/socket/ip/stream/listen.rs
--- a/services/libs/aster-std/src/net/socket/ip/stream/listen.rs
+++ b/services/libs/aster-std/src/net/socket/ip/stream/listen.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicBool, Ordering};
use crate::events::{IoEvents, Observer};
diff --git a/services/libs/aster-std/src/net/socket/ip/stream/listen.rs b/services/libs/aster-std/src/net/socket/ip/stream/listen.rs
--- a/services/libs/aster-std/src/net/socket/ip/stream/listen.rs
+++ b/services/libs/aster-std/src/net/socket/ip/stream/listen.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicBool, Ordering};
use crate::events::{IoEvents, Observer};
diff --git a/services/libs/aster-std/src/net/socket/ip/stream/mod.rs b/services/libs/aster-std/src/net/socket/ip/stream/mod.rs
--- a/services/libs/aster-std/src/net/socket/ip/stream/mod.rs
+++ b/services/libs/aster-std/src/net/socket/ip/stream/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::IoEvents;
use crate::fs::file_handle::FileLike;
use crate::fs::utils::StatusFlags;
diff --git a/services/libs/aster-std/src/net/socket/ip/stream/mod.rs b/services/libs/aster-std/src/net/socket/ip/stream/mod.rs
--- a/services/libs/aster-std/src/net/socket/ip/stream/mod.rs
+++ b/services/libs/aster-std/src/net/socket/ip/stream/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::IoEvents;
use crate::fs::file_handle::FileLike;
use crate::fs::utils::StatusFlags;
diff --git a/services/libs/aster-std/src/net/socket/ip/stream/options.rs b/services/libs/aster-std/src/net/socket/ip/stream/options.rs
--- a/services/libs/aster-std/src/net/socket/ip/stream/options.rs
+++ b/services/libs/aster-std/src/net/socket/ip/stream/options.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::impl_socket_options;
use super::CongestionControl;
diff --git a/services/libs/aster-std/src/net/socket/ip/stream/options.rs b/services/libs/aster-std/src/net/socket/ip/stream/options.rs
--- a/services/libs/aster-std/src/net/socket/ip/stream/options.rs
+++ b/services/libs/aster-std/src/net/socket/ip/stream/options.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::impl_socket_options;
use super::CongestionControl;
diff --git a/services/libs/aster-std/src/net/socket/ip/stream/util.rs b/services/libs/aster-std/src/net/socket/ip/stream/util.rs
--- a/services/libs/aster-std/src/net/socket/ip/stream/util.rs
+++ b/services/libs/aster-std/src/net/socket/ip/stream/util.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
#[derive(Debug, Clone, Copy, CopyGetters, Setters)]
diff --git a/services/libs/aster-std/src/net/socket/ip/stream/util.rs b/services/libs/aster-std/src/net/socket/ip/stream/util.rs
--- a/services/libs/aster-std/src/net/socket/ip/stream/util.rs
+++ b/services/libs/aster-std/src/net/socket/ip/stream/util.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
#[derive(Debug, Clone, Copy, CopyGetters, Setters)]
diff --git a/services/libs/aster-std/src/net/socket/mod.rs b/services/libs/aster-std/src/net/socket/mod.rs
--- a/services/libs/aster-std/src/net/socket/mod.rs
+++ b/services/libs/aster-std/src/net/socket/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{fs::file_handle::FileLike, prelude::*};
use self::options::SocketOption;
diff --git a/services/libs/aster-std/src/net/socket/mod.rs b/services/libs/aster-std/src/net/socket/mod.rs
--- a/services/libs/aster-std/src/net/socket/mod.rs
+++ b/services/libs/aster-std/src/net/socket/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{fs::file_handle::FileLike, prelude::*};
use self::options::SocketOption;
diff --git a/services/libs/aster-std/src/net/socket/options/macros.rs b/services/libs/aster-std/src/net/socket/options/macros.rs
--- a/services/libs/aster-std/src/net/socket/options/macros.rs
+++ b/services/libs/aster-std/src/net/socket/options/macros.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#[macro_export]
macro_rules! impl_socket_options {
($(
diff --git a/services/libs/aster-std/src/net/socket/options/macros.rs b/services/libs/aster-std/src/net/socket/options/macros.rs
--- a/services/libs/aster-std/src/net/socket/options/macros.rs
+++ b/services/libs/aster-std/src/net/socket/options/macros.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#[macro_export]
macro_rules! impl_socket_options {
($(
diff --git a/services/libs/aster-std/src/net/socket/options/mod.rs b/services/libs/aster-std/src/net/socket/options/mod.rs
--- a/services/libs/aster-std/src/net/socket/options/mod.rs
+++ b/services/libs/aster-std/src/net/socket/options/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::impl_socket_options;
use crate::prelude::*;
mod macros;
diff --git a/services/libs/aster-std/src/net/socket/options/mod.rs b/services/libs/aster-std/src/net/socket/options/mod.rs
--- a/services/libs/aster-std/src/net/socket/options/mod.rs
+++ b/services/libs/aster-std/src/net/socket/options/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::impl_socket_options;
use crate::prelude::*;
mod macros;
diff --git a/services/libs/aster-std/src/net/socket/unix/addr.rs b/services/libs/aster-std/src/net/socket/unix/addr.rs
--- a/services/libs/aster-std/src/net/socket/unix/addr.rs
+++ b/services/libs/aster-std/src/net/socket/unix/addr.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::utils::Dentry;
use crate::net::socket::util::socket_addr::SocketAddr;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/net/socket/unix/addr.rs b/services/libs/aster-std/src/net/socket/unix/addr.rs
--- a/services/libs/aster-std/src/net/socket/unix/addr.rs
+++ b/services/libs/aster-std/src/net/socket/unix/addr.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::utils::Dentry;
use crate::net::socket::util::socket_addr::SocketAddr;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/net/socket/unix/mod.rs b/services/libs/aster-std/src/net/socket/unix/mod.rs
--- a/services/libs/aster-std/src/net/socket/unix/mod.rs
+++ b/services/libs/aster-std/src/net/socket/unix/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod addr;
mod stream;
diff --git a/services/libs/aster-std/src/net/socket/unix/mod.rs b/services/libs/aster-std/src/net/socket/unix/mod.rs
--- a/services/libs/aster-std/src/net/socket/unix/mod.rs
+++ b/services/libs/aster-std/src/net/socket/unix/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod addr;
mod stream;
diff --git a/services/libs/aster-std/src/net/socket/unix/stream/connected.rs b/services/libs/aster-std/src/net/socket/unix/stream/connected.rs
--- a/services/libs/aster-std/src/net/socket/unix/stream/connected.rs
+++ b/services/libs/aster-std/src/net/socket/unix/stream/connected.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::endpoint::Endpoint;
use crate::events::IoEvents;
use crate::net::socket::{unix::addr::UnixSocketAddrBound, SockShutdownCmd};
diff --git a/services/libs/aster-std/src/net/socket/unix/stream/connected.rs b/services/libs/aster-std/src/net/socket/unix/stream/connected.rs
--- a/services/libs/aster-std/src/net/socket/unix/stream/connected.rs
+++ b/services/libs/aster-std/src/net/socket/unix/stream/connected.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::endpoint::Endpoint;
use crate::events::IoEvents;
use crate::net::socket::{unix::addr::UnixSocketAddrBound, SockShutdownCmd};
diff --git a/services/libs/aster-std/src/net/socket/unix/stream/endpoint.rs b/services/libs/aster-std/src/net/socket/unix/stream/endpoint.rs
--- a/services/libs/aster-std/src/net/socket/unix/stream/endpoint.rs
+++ b/services/libs/aster-std/src/net/socket/unix/stream/endpoint.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::IoEvents;
use crate::process::signal::Poller;
use crate::{
diff --git a/services/libs/aster-std/src/net/socket/unix/stream/endpoint.rs b/services/libs/aster-std/src/net/socket/unix/stream/endpoint.rs
--- a/services/libs/aster-std/src/net/socket/unix/stream/endpoint.rs
+++ b/services/libs/aster-std/src/net/socket/unix/stream/endpoint.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::IoEvents;
use crate::process::signal::Poller;
use crate::{
diff --git a/services/libs/aster-std/src/net/socket/unix/stream/init.rs b/services/libs/aster-std/src/net/socket/unix/stream/init.rs
--- a/services/libs/aster-std/src/net/socket/unix/stream/init.rs
+++ b/services/libs/aster-std/src/net/socket/unix/stream/init.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicBool, Ordering};
use crate::events::IoEvents;
diff --git a/services/libs/aster-std/src/net/socket/unix/stream/init.rs b/services/libs/aster-std/src/net/socket/unix/stream/init.rs
--- a/services/libs/aster-std/src/net/socket/unix/stream/init.rs
+++ b/services/libs/aster-std/src/net/socket/unix/stream/init.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicBool, Ordering};
use crate::events::IoEvents;
diff --git a/services/libs/aster-std/src/net/socket/unix/stream/listener.rs b/services/libs/aster-std/src/net/socket/unix/stream/listener.rs
--- a/services/libs/aster-std/src/net/socket/unix/stream/listener.rs
+++ b/services/libs/aster-std/src/net/socket/unix/stream/listener.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{connected::Connected, endpoint::Endpoint, UnixStreamSocket};
use crate::events::IoEvents;
use crate::fs::file_handle::FileLike;
diff --git a/services/libs/aster-std/src/net/socket/unix/stream/listener.rs b/services/libs/aster-std/src/net/socket/unix/stream/listener.rs
--- a/services/libs/aster-std/src/net/socket/unix/stream/listener.rs
+++ b/services/libs/aster-std/src/net/socket/unix/stream/listener.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{connected::Connected, endpoint::Endpoint, UnixStreamSocket};
use crate::events::IoEvents;
use crate::fs::file_handle::FileLike;
diff --git a/services/libs/aster-std/src/net/socket/unix/stream/mod.rs b/services/libs/aster-std/src/net/socket/unix/stream/mod.rs
--- a/services/libs/aster-std/src/net/socket/unix/stream/mod.rs
+++ b/services/libs/aster-std/src/net/socket/unix/stream/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod connected;
mod endpoint;
mod init;
diff --git a/services/libs/aster-std/src/net/socket/unix/stream/mod.rs b/services/libs/aster-std/src/net/socket/unix/stream/mod.rs
--- a/services/libs/aster-std/src/net/socket/unix/stream/mod.rs
+++ b/services/libs/aster-std/src/net/socket/unix/stream/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod connected;
mod endpoint;
mod init;
diff --git a/services/libs/aster-std/src/net/socket/unix/stream/socket.rs b/services/libs/aster-std/src/net/socket/unix/stream/socket.rs
--- a/services/libs/aster-std/src/net/socket/unix/stream/socket.rs
+++ b/services/libs/aster-std/src/net/socket/unix/stream/socket.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::IoEvents;
use crate::fs::file_handle::FileLike;
use crate::fs::fs_resolver::FsPath;
diff --git a/services/libs/aster-std/src/net/socket/unix/stream/socket.rs b/services/libs/aster-std/src/net/socket/unix/stream/socket.rs
--- a/services/libs/aster-std/src/net/socket/unix/stream/socket.rs
+++ b/services/libs/aster-std/src/net/socket/unix/stream/socket.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::IoEvents;
use crate::fs::file_handle::FileLike;
use crate::fs::fs_resolver::FsPath;
diff --git a/services/libs/aster-std/src/net/socket/util/mod.rs b/services/libs/aster-std/src/net/socket/util/mod.rs
--- a/services/libs/aster-std/src/net/socket/util/mod.rs
+++ b/services/libs/aster-std/src/net/socket/util/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod options;
pub mod send_recv_flags;
pub mod shutdown_cmd;
diff --git a/services/libs/aster-std/src/net/socket/util/mod.rs b/services/libs/aster-std/src/net/socket/util/mod.rs
--- a/services/libs/aster-std/src/net/socket/util/mod.rs
+++ b/services/libs/aster-std/src/net/socket/util/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod options;
pub mod send_recv_flags;
pub mod shutdown_cmd;
diff --git a/services/libs/aster-std/src/net/socket/util/options.rs b/services/libs/aster-std/src/net/socket/util/options.rs
--- a/services/libs/aster-std/src/net/socket/util/options.rs
+++ b/services/libs/aster-std/src/net/socket/util/options.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::time::Duration;
use crate::net::iface::{RECV_BUF_LEN, SEND_BUF_LEN};
diff --git a/services/libs/aster-std/src/net/socket/util/options.rs b/services/libs/aster-std/src/net/socket/util/options.rs
--- a/services/libs/aster-std/src/net/socket/util/options.rs
+++ b/services/libs/aster-std/src/net/socket/util/options.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::time::Duration;
use crate::net::iface::{RECV_BUF_LEN, SEND_BUF_LEN};
diff --git a/services/libs/aster-std/src/net/socket/util/send_recv_flags.rs b/services/libs/aster-std/src/net/socket/util/send_recv_flags.rs
--- a/services/libs/aster-std/src/net/socket/util/send_recv_flags.rs
+++ b/services/libs/aster-std/src/net/socket/util/send_recv_flags.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
bitflags! {
diff --git a/services/libs/aster-std/src/net/socket/util/send_recv_flags.rs b/services/libs/aster-std/src/net/socket/util/send_recv_flags.rs
--- a/services/libs/aster-std/src/net/socket/util/send_recv_flags.rs
+++ b/services/libs/aster-std/src/net/socket/util/send_recv_flags.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
bitflags! {
diff --git a/services/libs/aster-std/src/net/socket/util/shutdown_cmd.rs b/services/libs/aster-std/src/net/socket/util/shutdown_cmd.rs
--- a/services/libs/aster-std/src/net/socket/util/shutdown_cmd.rs
+++ b/services/libs/aster-std/src/net/socket/util/shutdown_cmd.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
/// Shutdown types
diff --git a/services/libs/aster-std/src/net/socket/util/shutdown_cmd.rs b/services/libs/aster-std/src/net/socket/util/shutdown_cmd.rs
--- a/services/libs/aster-std/src/net/socket/util/shutdown_cmd.rs
+++ b/services/libs/aster-std/src/net/socket/util/shutdown_cmd.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
/// Shutdown types
diff --git a/services/libs/aster-std/src/net/socket/util/socket_addr.rs b/services/libs/aster-std/src/net/socket/util/socket_addr.rs
--- a/services/libs/aster-std/src/net/socket/util/socket_addr.rs
+++ b/services/libs/aster-std/src/net/socket/util/socket_addr.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::net::iface::{IpAddress, Ipv4Address};
use crate::net::iface::{IpEndpoint, IpListenEndpoint};
use crate::net::socket::unix::UnixSocketAddr;
diff --git a/services/libs/aster-std/src/net/socket/util/socket_addr.rs b/services/libs/aster-std/src/net/socket/util/socket_addr.rs
--- a/services/libs/aster-std/src/net/socket/util/socket_addr.rs
+++ b/services/libs/aster-std/src/net/socket/util/socket_addr.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::net::iface::{IpAddress, Ipv4Address};
use crate::net::iface::{IpEndpoint, IpListenEndpoint};
use crate::net::socket::unix::UnixSocketAddr;
diff --git a/services/libs/aster-std/src/prelude.rs b/services/libs/aster-std/src/prelude.rs
--- a/services/libs/aster-std/src/prelude.rs
+++ b/services/libs/aster-std/src/prelude.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#![allow(unused)]
pub(crate) use alloc::boxed::Box;
diff --git a/services/libs/aster-std/src/prelude.rs b/services/libs/aster-std/src/prelude.rs
--- a/services/libs/aster-std/src/prelude.rs
+++ b/services/libs/aster-std/src/prelude.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#![allow(unused)]
pub(crate) use alloc::boxed::Box;
diff --git a/services/libs/aster-std/src/process/clone.rs b/services/libs/aster-std/src/process/clone.rs
--- a/services/libs/aster-std/src/process/clone.rs
+++ b/services/libs/aster-std/src/process/clone.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::posix_thread::{PosixThread, PosixThreadBuilder, PosixThreadExt, ThreadName};
use super::process_vm::ProcessVm;
use super::signal::sig_disposition::SigDispositions;
diff --git a/services/libs/aster-std/src/process/clone.rs b/services/libs/aster-std/src/process/clone.rs
--- a/services/libs/aster-std/src/process/clone.rs
+++ b/services/libs/aster-std/src/process/clone.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::posix_thread::{PosixThread, PosixThreadBuilder, PosixThreadExt, ThreadName};
use super::process_vm::ProcessVm;
use super::signal::sig_disposition::SigDispositions;
diff --git a/services/libs/aster-std/src/process/credentials/credentials_.rs b/services/libs/aster-std/src/process/credentials/credentials_.rs
--- a/services/libs/aster-std/src/process/credentials/credentials_.rs
+++ b/services/libs/aster-std/src/process/credentials/credentials_.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::group::AtomicGid;
use super::user::AtomicUid;
use super::{Gid, Uid};
diff --git a/services/libs/aster-std/src/process/credentials/credentials_.rs b/services/libs/aster-std/src/process/credentials/credentials_.rs
--- a/services/libs/aster-std/src/process/credentials/credentials_.rs
+++ b/services/libs/aster-std/src/process/credentials/credentials_.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::group::AtomicGid;
use super::user::AtomicUid;
use super::{Gid, Uid};
diff --git a/services/libs/aster-std/src/process/credentials/group.rs b/services/libs/aster-std/src/process/credentials/group.rs
--- a/services/libs/aster-std/src/process/credentials/group.rs
+++ b/services/libs/aster-std/src/process/credentials/group.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicU32, Ordering};
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/process/credentials/group.rs b/services/libs/aster-std/src/process/credentials/group.rs
--- a/services/libs/aster-std/src/process/credentials/group.rs
+++ b/services/libs/aster-std/src/process/credentials/group.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicU32, Ordering};
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/process/credentials/mod.rs b/services/libs/aster-std/src/process/credentials/mod.rs
--- a/services/libs/aster-std/src/process/credentials/mod.rs
+++ b/services/libs/aster-std/src/process/credentials/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod credentials_;
mod group;
mod static_cap;
diff --git a/services/libs/aster-std/src/process/credentials/mod.rs b/services/libs/aster-std/src/process/credentials/mod.rs
--- a/services/libs/aster-std/src/process/credentials/mod.rs
+++ b/services/libs/aster-std/src/process/credentials/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod credentials_;
mod group;
mod static_cap;
diff --git a/services/libs/aster-std/src/process/credentials/static_cap.rs b/services/libs/aster-std/src/process/credentials/static_cap.rs
--- a/services/libs/aster-std/src/process/credentials/static_cap.rs
+++ b/services/libs/aster-std/src/process/credentials/static_cap.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::credentials_::Credentials_;
use super::{Credentials, Gid, Uid};
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/process/credentials/static_cap.rs b/services/libs/aster-std/src/process/credentials/static_cap.rs
--- a/services/libs/aster-std/src/process/credentials/static_cap.rs
+++ b/services/libs/aster-std/src/process/credentials/static_cap.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::credentials_::Credentials_;
use super::{Credentials, Gid, Uid};
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/process/credentials/user.rs b/services/libs/aster-std/src/process/credentials/user.rs
--- a/services/libs/aster-std/src/process/credentials/user.rs
+++ b/services/libs/aster-std/src/process/credentials/user.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicU32, Ordering};
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/process/credentials/user.rs b/services/libs/aster-std/src/process/credentials/user.rs
--- a/services/libs/aster-std/src/process/credentials/user.rs
+++ b/services/libs/aster-std/src/process/credentials/user.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicU32, Ordering};
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/process/exit.rs b/services/libs/aster-std/src/process/exit.rs
--- a/services/libs/aster-std/src/process/exit.rs
+++ b/services/libs/aster-std/src/process/exit.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::process::posix_thread::PosixThreadExt;
use crate::process::signal::signals::kernel::KernelSignal;
use crate::{prelude::*, process::signal::constants::SIGCHLD};
diff --git a/services/libs/aster-std/src/process/exit.rs b/services/libs/aster-std/src/process/exit.rs
--- a/services/libs/aster-std/src/process/exit.rs
+++ b/services/libs/aster-std/src/process/exit.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::process::posix_thread::PosixThreadExt;
use crate::process::signal::signals::kernel::KernelSignal;
use crate::{prelude::*, process::signal::constants::SIGCHLD};
diff --git a/services/libs/aster-std/src/process/kill.rs b/services/libs/aster-std/src/process/kill.rs
--- a/services/libs/aster-std/src/process/kill.rs
+++ b/services/libs/aster-std/src/process/kill.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::posix_thread::PosixThreadExt;
use super::signal::signals::user::UserSignal;
use super::signal::signals::Signal;
diff --git a/services/libs/aster-std/src/process/kill.rs b/services/libs/aster-std/src/process/kill.rs
--- a/services/libs/aster-std/src/process/kill.rs
+++ b/services/libs/aster-std/src/process/kill.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::posix_thread::PosixThreadExt;
use super::signal::signals::user::UserSignal;
use super::signal::signals::Signal;
diff --git a/services/libs/aster-std/src/process/mod.rs b/services/libs/aster-std/src/process/mod.rs
--- a/services/libs/aster-std/src/process/mod.rs
+++ b/services/libs/aster-std/src/process/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod clone;
mod credentials;
mod exit;
diff --git a/services/libs/aster-std/src/process/mod.rs b/services/libs/aster-std/src/process/mod.rs
--- a/services/libs/aster-std/src/process/mod.rs
+++ b/services/libs/aster-std/src/process/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod clone;
mod credentials;
mod exit;
diff --git a/services/libs/aster-std/src/process/posix_thread/builder.rs b/services/libs/aster-std/src/process/posix_thread/builder.rs
--- a/services/libs/aster-std/src/process/posix_thread/builder.rs
+++ b/services/libs/aster-std/src/process/posix_thread/builder.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::user::UserSpace;
use crate::{
diff --git a/services/libs/aster-std/src/process/posix_thread/builder.rs b/services/libs/aster-std/src/process/posix_thread/builder.rs
--- a/services/libs/aster-std/src/process/posix_thread/builder.rs
+++ b/services/libs/aster-std/src/process/posix_thread/builder.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::user::UserSpace;
use crate::{
diff --git a/services/libs/aster-std/src/process/posix_thread/futex.rs b/services/libs/aster-std/src/process/posix_thread/futex.rs
--- a/services/libs/aster-std/src/process/posix_thread/futex.rs
+++ b/services/libs/aster-std/src/process/posix_thread/futex.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicBool, Ordering};
use aster_frame::cpu::num_cpus;
diff --git a/services/libs/aster-std/src/process/posix_thread/futex.rs b/services/libs/aster-std/src/process/posix_thread/futex.rs
--- a/services/libs/aster-std/src/process/posix_thread/futex.rs
+++ b/services/libs/aster-std/src/process/posix_thread/futex.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicBool, Ordering};
use aster_frame::cpu::num_cpus;
diff --git a/services/libs/aster-std/src/process/posix_thread/mod.rs b/services/libs/aster-std/src/process/posix_thread/mod.rs
--- a/services/libs/aster-std/src/process/posix_thread/mod.rs
+++ b/services/libs/aster-std/src/process/posix_thread/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::kill::SignalSenderIds;
use super::signal::sig_mask::SigMask;
use super::signal::sig_num::SigNum;
diff --git a/services/libs/aster-std/src/process/posix_thread/mod.rs b/services/libs/aster-std/src/process/posix_thread/mod.rs
--- a/services/libs/aster-std/src/process/posix_thread/mod.rs
+++ b/services/libs/aster-std/src/process/posix_thread/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::kill::SignalSenderIds;
use super::signal::sig_mask::SigMask;
use super::signal::sig_num::SigNum;
diff --git a/services/libs/aster-std/src/process/posix_thread/name.rs b/services/libs/aster-std/src/process/posix_thread/name.rs
--- a/services/libs/aster-std/src/process/posix_thread/name.rs
+++ b/services/libs/aster-std/src/process/posix_thread/name.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
pub const MAX_THREAD_NAME_LEN: usize = 16;
diff --git a/services/libs/aster-std/src/process/posix_thread/name.rs b/services/libs/aster-std/src/process/posix_thread/name.rs
--- a/services/libs/aster-std/src/process/posix_thread/name.rs
+++ b/services/libs/aster-std/src/process/posix_thread/name.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
pub const MAX_THREAD_NAME_LEN: usize = 16;
diff --git a/services/libs/aster-std/src/process/posix_thread/posix_thread_ext.rs b/services/libs/aster-std/src/process/posix_thread/posix_thread_ext.rs
--- a/services/libs/aster-std/src/process/posix_thread/posix_thread_ext.rs
+++ b/services/libs/aster-std/src/process/posix_thread/posix_thread_ext.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::{cpu::UserContext, user::UserSpace};
use crate::{
diff --git a/services/libs/aster-std/src/process/posix_thread/posix_thread_ext.rs b/services/libs/aster-std/src/process/posix_thread/posix_thread_ext.rs
--- a/services/libs/aster-std/src/process/posix_thread/posix_thread_ext.rs
+++ b/services/libs/aster-std/src/process/posix_thread/posix_thread_ext.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::{cpu::UserContext, user::UserSpace};
use crate::{
diff --git a/services/libs/aster-std/src/process/posix_thread/robust_list.rs b/services/libs/aster-std/src/process/posix_thread/robust_list.rs
--- a/services/libs/aster-std/src/process/posix_thread/robust_list.rs
+++ b/services/libs/aster-std/src/process/posix_thread/robust_list.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The implementation of robust list is from occlum.
use crate::{
diff --git a/services/libs/aster-std/src/process/posix_thread/robust_list.rs b/services/libs/aster-std/src/process/posix_thread/robust_list.rs
--- a/services/libs/aster-std/src/process/posix_thread/robust_list.rs
+++ b/services/libs/aster-std/src/process/posix_thread/robust_list.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The implementation of robust list is from occlum.
use crate::{
diff --git a/services/libs/aster-std/src/process/process/builder.rs b/services/libs/aster-std/src/process/process/builder.rs
--- a/services/libs/aster-std/src/process/process/builder.rs
+++ b/services/libs/aster-std/src/process/process/builder.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileTable;
use crate::fs::fs_resolver::FsResolver;
use crate::fs::utils::FileCreationMask;
diff --git a/services/libs/aster-std/src/process/process/builder.rs b/services/libs/aster-std/src/process/process/builder.rs
--- a/services/libs/aster-std/src/process/process/builder.rs
+++ b/services/libs/aster-std/src/process/process/builder.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileTable;
use crate::fs::fs_resolver::FsResolver;
use crate::fs::utils::FileCreationMask;
diff --git a/services/libs/aster-std/src/process/process/job_control.rs b/services/libs/aster-std/src/process/process/job_control.rs
--- a/services/libs/aster-std/src/process/process/job_control.rs
+++ b/services/libs/aster-std/src/process/process/job_control.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use crate::process::signal::constants::{SIGCONT, SIGHUP};
use crate::process::signal::signals::kernel::KernelSignal;
diff --git a/services/libs/aster-std/src/process/process/job_control.rs b/services/libs/aster-std/src/process/process/job_control.rs
--- a/services/libs/aster-std/src/process/process/job_control.rs
+++ b/services/libs/aster-std/src/process/process/job_control.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use crate::process::signal::constants::{SIGCONT, SIGHUP};
use crate::process::signal::signals::kernel::KernelSignal;
diff --git a/services/libs/aster-std/src/process/process/mod.rs b/services/libs/aster-std/src/process/process/mod.rs
--- a/services/libs/aster-std/src/process/process/mod.rs
+++ b/services/libs/aster-std/src/process/process/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::posix_thread::PosixThreadExt;
use super::process_vm::user_heap::UserHeap;
use super::process_vm::ProcessVm;
diff --git a/services/libs/aster-std/src/process/process/mod.rs b/services/libs/aster-std/src/process/process/mod.rs
--- a/services/libs/aster-std/src/process/process/mod.rs
+++ b/services/libs/aster-std/src/process/process/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::posix_thread::PosixThreadExt;
use super::process_vm::user_heap::UserHeap;
use super::process_vm::ProcessVm;
diff --git a/services/libs/aster-std/src/process/process/process_group.rs b/services/libs/aster-std/src/process/process/process_group.rs
--- a/services/libs/aster-std/src/process/process/process_group.rs
+++ b/services/libs/aster-std/src/process/process/process_group.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{Pgid, Pid, Process, Session};
use crate::prelude::*;
use crate::process::signal::signals::Signal;
diff --git a/services/libs/aster-std/src/process/process/process_group.rs b/services/libs/aster-std/src/process/process/process_group.rs
--- a/services/libs/aster-std/src/process/process/process_group.rs
+++ b/services/libs/aster-std/src/process/process/process_group.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{Pgid, Pid, Process, Session};
use crate::prelude::*;
use crate::process::signal::signals::Signal;
diff --git a/services/libs/aster-std/src/process/process/session.rs b/services/libs/aster-std/src/process/process/session.rs
--- a/services/libs/aster-std/src/process/process/session.rs
+++ b/services/libs/aster-std/src/process/process/session.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use super::{Pgid, Process, ProcessGroup, Sid, Terminal};
diff --git a/services/libs/aster-std/src/process/process/session.rs b/services/libs/aster-std/src/process/process/session.rs
--- a/services/libs/aster-std/src/process/process/session.rs
+++ b/services/libs/aster-std/src/process/process/session.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use super::{Pgid, Process, ProcessGroup, Sid, Terminal};
diff --git a/services/libs/aster-std/src/process/process/terminal.rs b/services/libs/aster-std/src/process/process/terminal.rs
--- a/services/libs/aster-std/src/process/process/terminal.rs
+++ b/services/libs/aster-std/src/process/process/terminal.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::inode_handle::FileIo;
use crate::prelude::*;
use crate::process::{process_table, Pgid, ProcessGroup};
diff --git a/services/libs/aster-std/src/process/process/terminal.rs b/services/libs/aster-std/src/process/process/terminal.rs
--- a/services/libs/aster-std/src/process/process/terminal.rs
+++ b/services/libs/aster-std/src/process/process/terminal.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::inode_handle::FileIo;
use crate::prelude::*;
use crate::process::{process_table, Pgid, ProcessGroup};
diff --git a/services/libs/aster-std/src/process/process_filter.rs b/services/libs/aster-std/src/process/process_filter.rs
--- a/services/libs/aster-std/src/process/process_filter.rs
+++ b/services/libs/aster-std/src/process/process_filter.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{Pgid, Pid};
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/process/process_filter.rs b/services/libs/aster-std/src/process/process_filter.rs
--- a/services/libs/aster-std/src/process/process_filter.rs
+++ b/services/libs/aster-std/src/process/process_filter.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{Pgid, Pid};
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/process/process_table.rs b/services/libs/aster-std/src/process/process_table.rs
--- a/services/libs/aster-std/src/process/process_table.rs
+++ b/services/libs/aster-std/src/process/process_table.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! A global table stores the pid to process mapping.
//! This table can be used to get process with pid.
//! TODO: progress group, thread all need similar mapping
diff --git a/services/libs/aster-std/src/process/process_table.rs b/services/libs/aster-std/src/process/process_table.rs
--- a/services/libs/aster-std/src/process/process_table.rs
+++ b/services/libs/aster-std/src/process/process_table.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! A global table stores the pid to process mapping.
//! This table can be used to get process with pid.
//! TODO: progress group, thread all need similar mapping
diff --git a/services/libs/aster-std/src/process/process_vm/mod.rs b/services/libs/aster-std/src/process/process_vm/mod.rs
--- a/services/libs/aster-std/src/process/process_vm/mod.rs
+++ b/services/libs/aster-std/src/process/process_vm/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! This module defines the UserVm of a process.
//! The UserSpace of a process only contains the virtual-physical memory mapping.
//! But we cannot know which vaddr is user heap, which vaddr is mmap areas.
diff --git a/services/libs/aster-std/src/process/process_vm/mod.rs b/services/libs/aster-std/src/process/process_vm/mod.rs
--- a/services/libs/aster-std/src/process/process_vm/mod.rs
+++ b/services/libs/aster-std/src/process/process_vm/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! This module defines the UserVm of a process.
//! The UserSpace of a process only contains the virtual-physical memory mapping.
//! But we cannot know which vaddr is user heap, which vaddr is mmap areas.
diff --git a/services/libs/aster-std/src/process/process_vm/user_heap.rs b/services/libs/aster-std/src/process/process_vm/user_heap.rs
--- a/services/libs/aster-std/src/process/process_vm/user_heap.rs
+++ b/services/libs/aster-std/src/process/process_vm/user_heap.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicUsize, Ordering};
use crate::vm::perms::VmPerms;
diff --git a/services/libs/aster-std/src/process/process_vm/user_heap.rs b/services/libs/aster-std/src/process/process_vm/user_heap.rs
--- a/services/libs/aster-std/src/process/process_vm/user_heap.rs
+++ b/services/libs/aster-std/src/process/process_vm/user_heap.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicUsize, Ordering};
use crate::vm::perms::VmPerms;
diff --git a/services/libs/aster-std/src/process/program_loader/elf/aux_vec.rs b/services/libs/aster-std/src/process/program_loader/elf/aux_vec.rs
--- a/services/libs/aster-std/src/process/program_loader/elf/aux_vec.rs
+++ b/services/libs/aster-std/src/process/program_loader/elf/aux_vec.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
/// This implementation is from occlum.
diff --git a/services/libs/aster-std/src/process/program_loader/elf/aux_vec.rs b/services/libs/aster-std/src/process/program_loader/elf/aux_vec.rs
--- a/services/libs/aster-std/src/process/program_loader/elf/aux_vec.rs
+++ b/services/libs/aster-std/src/process/program_loader/elf/aux_vec.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
/// This implementation is from occlum.
diff --git a/services/libs/aster-std/src/process/program_loader/elf/elf_file.rs b/services/libs/aster-std/src/process/program_loader/elf/elf_file.rs
--- a/services/libs/aster-std/src/process/program_loader/elf/elf_file.rs
+++ b/services/libs/aster-std/src/process/program_loader/elf/elf_file.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
/// A wrapper of xmas_elf's elf parsing
use xmas_elf::{
header::{self, Header, HeaderPt1, HeaderPt2, HeaderPt2_, Machine_, Type_},
diff --git a/services/libs/aster-std/src/process/program_loader/elf/elf_file.rs b/services/libs/aster-std/src/process/program_loader/elf/elf_file.rs
--- a/services/libs/aster-std/src/process/program_loader/elf/elf_file.rs
+++ b/services/libs/aster-std/src/process/program_loader/elf/elf_file.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
/// A wrapper of xmas_elf's elf parsing
use xmas_elf::{
header::{self, Header, HeaderPt1, HeaderPt2, HeaderPt2_, Machine_, Type_},
diff --git a/services/libs/aster-std/src/process/program_loader/elf/init_stack.rs b/services/libs/aster-std/src/process/program_loader/elf/init_stack.rs
--- a/services/libs/aster-std/src/process/program_loader/elf/init_stack.rs
+++ b/services/libs/aster-std/src/process/program_loader/elf/init_stack.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! This module defines the process initial stack.
//! The process initial stack, contains arguments, environmental variables and auxiliary vectors
//! The data layout of init stack can be seen in Figure 3.9 in https://uclibc.org/docs/psABI-x86_64.pdf
diff --git a/services/libs/aster-std/src/process/program_loader/elf/init_stack.rs b/services/libs/aster-std/src/process/program_loader/elf/init_stack.rs
--- a/services/libs/aster-std/src/process/program_loader/elf/init_stack.rs
+++ b/services/libs/aster-std/src/process/program_loader/elf/init_stack.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! This module defines the process initial stack.
//! The process initial stack, contains arguments, environmental variables and auxiliary vectors
//! The data layout of init stack can be seen in Figure 3.9 in https://uclibc.org/docs/psABI-x86_64.pdf
diff --git a/services/libs/aster-std/src/process/program_loader/elf/load_elf.rs b/services/libs/aster-std/src/process/program_loader/elf/load_elf.rs
--- a/services/libs/aster-std/src/process/program_loader/elf/load_elf.rs
+++ b/services/libs/aster-std/src/process/program_loader/elf/load_elf.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! This module is used to parse elf file content to get elf_load_info.
//! When create a process from elf file, we will use the elf_load_info to construct the VmSpace
diff --git a/services/libs/aster-std/src/process/program_loader/elf/load_elf.rs b/services/libs/aster-std/src/process/program_loader/elf/load_elf.rs
--- a/services/libs/aster-std/src/process/program_loader/elf/load_elf.rs
+++ b/services/libs/aster-std/src/process/program_loader/elf/load_elf.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! This module is used to parse elf file content to get elf_load_info.
//! When create a process from elf file, we will use the elf_load_info to construct the VmSpace
diff --git a/services/libs/aster-std/src/process/program_loader/elf/mod.rs b/services/libs/aster-std/src/process/program_loader/elf/mod.rs
--- a/services/libs/aster-std/src/process/program_loader/elf/mod.rs
+++ b/services/libs/aster-std/src/process/program_loader/elf/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod aux_vec;
mod elf_file;
mod init_stack;
diff --git a/services/libs/aster-std/src/process/program_loader/elf/mod.rs b/services/libs/aster-std/src/process/program_loader/elf/mod.rs
--- a/services/libs/aster-std/src/process/program_loader/elf/mod.rs
+++ b/services/libs/aster-std/src/process/program_loader/elf/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod aux_vec;
mod elf_file;
mod init_stack;
diff --git a/services/libs/aster-std/src/process/program_loader/mod.rs b/services/libs/aster-std/src/process/program_loader/mod.rs
--- a/services/libs/aster-std/src/process/program_loader/mod.rs
+++ b/services/libs/aster-std/src/process/program_loader/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod elf;
mod shebang;
diff --git a/services/libs/aster-std/src/process/program_loader/mod.rs b/services/libs/aster-std/src/process/program_loader/mod.rs
--- a/services/libs/aster-std/src/process/program_loader/mod.rs
+++ b/services/libs/aster-std/src/process/program_loader/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod elf;
mod shebang;
diff --git a/services/libs/aster-std/src/process/program_loader/shebang.rs b/services/libs/aster-std/src/process/program_loader/shebang.rs
--- a/services/libs/aster-std/src/process/program_loader/shebang.rs
+++ b/services/libs/aster-std/src/process/program_loader/shebang.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
/// Try to parse a buffer as a shebang line.
diff --git a/services/libs/aster-std/src/process/program_loader/shebang.rs b/services/libs/aster-std/src/process/program_loader/shebang.rs
--- a/services/libs/aster-std/src/process/program_loader/shebang.rs
+++ b/services/libs/aster-std/src/process/program_loader/shebang.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
/// Try to parse a buffer as a shebang line.
diff --git a/services/libs/aster-std/src/process/rlimit.rs b/services/libs/aster-std/src/process/rlimit.rs
--- a/services/libs/aster-std/src/process/rlimit.rs
+++ b/services/libs/aster-std/src/process/rlimit.rs
@@ -1,4 +1,4 @@
-//! This implementation is from occlum
+// SPDX-License-Identifier: MPL-2.0
#![allow(non_camel_case_types)]
diff --git a/services/libs/aster-std/src/process/rlimit.rs b/services/libs/aster-std/src/process/rlimit.rs
--- a/services/libs/aster-std/src/process/rlimit.rs
+++ b/services/libs/aster-std/src/process/rlimit.rs
@@ -1,4 +1,4 @@
-//! This implementation is from occlum
+// SPDX-License-Identifier: MPL-2.0
#![allow(non_camel_case_types)]
diff --git a/services/libs/aster-std/src/process/signal/c_types.rs b/services/libs/aster-std/src/process/signal/c_types.rs
--- a/services/libs/aster-std/src/process/signal/c_types.rs
+++ b/services/libs/aster-std/src/process/signal/c_types.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#![allow(non_camel_case_types)]
use core::mem;
diff --git a/services/libs/aster-std/src/process/signal/c_types.rs b/services/libs/aster-std/src/process/signal/c_types.rs
--- a/services/libs/aster-std/src/process/signal/c_types.rs
+++ b/services/libs/aster-std/src/process/signal/c_types.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#![allow(non_camel_case_types)]
use core::mem;
diff --git a/services/libs/aster-std/src/process/signal/constants.rs b/services/libs/aster-std/src/process/signal/constants.rs
--- a/services/libs/aster-std/src/process/signal/constants.rs
+++ b/services/libs/aster-std/src/process/signal/constants.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
/// Standard signals
pub(super) const MIN_STD_SIG_NUM: u8 = 1;
pub(super) const MAX_STD_SIG_NUM: u8 = 31; // inclusive
diff --git a/services/libs/aster-std/src/process/signal/constants.rs b/services/libs/aster-std/src/process/signal/constants.rs
--- a/services/libs/aster-std/src/process/signal/constants.rs
+++ b/services/libs/aster-std/src/process/signal/constants.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
/// Standard signals
pub(super) const MIN_STD_SIG_NUM: u8 = 1;
pub(super) const MAX_STD_SIG_NUM: u8 = 31; // inclusive
diff --git a/services/libs/aster-std/src/process/signal/events.rs b/services/libs/aster-std/src/process/signal/events.rs
--- a/services/libs/aster-std/src/process/signal/events.rs
+++ b/services/libs/aster-std/src/process/signal/events.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::{Events, EventsFilter};
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/process/signal/events.rs b/services/libs/aster-std/src/process/signal/events.rs
--- a/services/libs/aster-std/src/process/signal/events.rs
+++ b/services/libs/aster-std/src/process/signal/events.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::{Events, EventsFilter};
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/process/signal/mod.rs b/services/libs/aster-std/src/process/signal/mod.rs
--- a/services/libs/aster-std/src/process/signal/mod.rs
+++ b/services/libs/aster-std/src/process/signal/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod c_types;
pub mod constants;
mod events;
diff --git a/services/libs/aster-std/src/process/signal/mod.rs b/services/libs/aster-std/src/process/signal/mod.rs
--- a/services/libs/aster-std/src/process/signal/mod.rs
+++ b/services/libs/aster-std/src/process/signal/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod c_types;
pub mod constants;
mod events;
diff --git a/services/libs/aster-std/src/process/signal/pauser.rs b/services/libs/aster-std/src/process/signal/pauser.rs
--- a/services/libs/aster-std/src/process/signal/pauser.rs
+++ b/services/libs/aster-std/src/process/signal/pauser.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicBool, Ordering};
use core::time::Duration;
diff --git a/services/libs/aster-std/src/process/signal/pauser.rs b/services/libs/aster-std/src/process/signal/pauser.rs
--- a/services/libs/aster-std/src/process/signal/pauser.rs
+++ b/services/libs/aster-std/src/process/signal/pauser.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicBool, Ordering};
use core::time::Duration;
diff --git a/services/libs/aster-std/src/process/signal/poll.rs b/services/libs/aster-std/src/process/signal/poll.rs
--- a/services/libs/aster-std/src/process/signal/poll.rs
+++ b/services/libs/aster-std/src/process/signal/poll.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::IoEvents;
use crate::events::{Observer, Subject};
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/process/signal/poll.rs b/services/libs/aster-std/src/process/signal/poll.rs
--- a/services/libs/aster-std/src/process/signal/poll.rs
+++ b/services/libs/aster-std/src/process/signal/poll.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::events::IoEvents;
use crate::events::{Observer, Subject};
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/process/signal/sig_action.rs b/services/libs/aster-std/src/process/signal/sig_action.rs
--- a/services/libs/aster-std/src/process/signal/sig_action.rs
+++ b/services/libs/aster-std/src/process/signal/sig_action.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{c_types::sigaction_t, constants::*, sig_mask::SigMask, sig_num::SigNum};
use crate::prelude::*;
use bitflags::bitflags;
diff --git a/services/libs/aster-std/src/process/signal/sig_action.rs b/services/libs/aster-std/src/process/signal/sig_action.rs
--- a/services/libs/aster-std/src/process/signal/sig_action.rs
+++ b/services/libs/aster-std/src/process/signal/sig_action.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{c_types::sigaction_t, constants::*, sig_mask::SigMask, sig_num::SigNum};
use crate::prelude::*;
use bitflags::bitflags;
diff --git a/services/libs/aster-std/src/process/signal/sig_disposition.rs b/services/libs/aster-std/src/process/signal/sig_disposition.rs
--- a/services/libs/aster-std/src/process/signal/sig_disposition.rs
+++ b/services/libs/aster-std/src/process/signal/sig_disposition.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{constants::*, sig_action::SigAction, sig_num::SigNum};
#[derive(Copy, Clone)]
diff --git a/services/libs/aster-std/src/process/signal/sig_disposition.rs b/services/libs/aster-std/src/process/signal/sig_disposition.rs
--- a/services/libs/aster-std/src/process/signal/sig_disposition.rs
+++ b/services/libs/aster-std/src/process/signal/sig_disposition.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{constants::*, sig_action::SigAction, sig_num::SigNum};
#[derive(Copy, Clone)]
diff --git a/services/libs/aster-std/src/process/signal/sig_mask.rs b/services/libs/aster-std/src/process/signal/sig_mask.rs
--- a/services/libs/aster-std/src/process/signal/sig_mask.rs
+++ b/services/libs/aster-std/src/process/signal/sig_mask.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{constants::MIN_STD_SIG_NUM, sig_num::SigNum};
#[derive(Debug, Copy, Clone, Default, PartialEq, Eq)]
diff --git a/services/libs/aster-std/src/process/signal/sig_mask.rs b/services/libs/aster-std/src/process/signal/sig_mask.rs
--- a/services/libs/aster-std/src/process/signal/sig_mask.rs
+++ b/services/libs/aster-std/src/process/signal/sig_mask.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{constants::MIN_STD_SIG_NUM, sig_num::SigNum};
#[derive(Debug, Copy, Clone, Default, PartialEq, Eq)]
diff --git a/services/libs/aster-std/src/process/signal/sig_num.rs b/services/libs/aster-std/src/process/signal/sig_num.rs
--- a/services/libs/aster-std/src/process/signal/sig_num.rs
+++ b/services/libs/aster-std/src/process/signal/sig_num.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::constants::*;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/process/signal/sig_num.rs b/services/libs/aster-std/src/process/signal/sig_num.rs
--- a/services/libs/aster-std/src/process/signal/sig_num.rs
+++ b/services/libs/aster-std/src/process/signal/sig_num.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::constants::*;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/process/signal/sig_queues.rs b/services/libs/aster-std/src/process/signal/sig_queues.rs
--- a/services/libs/aster-std/src/process/signal/sig_queues.rs
+++ b/services/libs/aster-std/src/process/signal/sig_queues.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{constants::*, SigEvents, SigEventsFilter};
use crate::events::{Observer, Subject};
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/process/signal/sig_queues.rs b/services/libs/aster-std/src/process/signal/sig_queues.rs
--- a/services/libs/aster-std/src/process/signal/sig_queues.rs
+++ b/services/libs/aster-std/src/process/signal/sig_queues.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{constants::*, SigEvents, SigEventsFilter};
use crate::events::{Observer, Subject};
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/process/signal/sig_stack.rs b/services/libs/aster-std/src/process/signal/sig_stack.rs
--- a/services/libs/aster-std/src/process/signal/sig_stack.rs
+++ b/services/libs/aster-std/src/process/signal/sig_stack.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
/// User-provided signal stack. `SigStack` is per-thread, and each thread can have
diff --git a/services/libs/aster-std/src/process/signal/sig_stack.rs b/services/libs/aster-std/src/process/signal/sig_stack.rs
--- a/services/libs/aster-std/src/process/signal/sig_stack.rs
+++ b/services/libs/aster-std/src/process/signal/sig_stack.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
/// User-provided signal stack. `SigStack` is per-thread, and each thread can have
diff --git a/services/libs/aster-std/src/process/signal/signals/fault.rs b/services/libs/aster-std/src/process/signal/signals/fault.rs
--- a/services/libs/aster-std/src/process/signal/signals/fault.rs
+++ b/services/libs/aster-std/src/process/signal/signals/fault.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::cpu::{CpuException, CpuExceptionInfo};
use aster_frame::cpu::{
ALIGNMENT_CHECK, BOUND_RANGE_EXCEEDED, DIVIDE_BY_ZERO, GENERAL_PROTECTION_FAULT,
diff --git a/services/libs/aster-std/src/process/signal/signals/fault.rs b/services/libs/aster-std/src/process/signal/signals/fault.rs
--- a/services/libs/aster-std/src/process/signal/signals/fault.rs
+++ b/services/libs/aster-std/src/process/signal/signals/fault.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::cpu::{CpuException, CpuExceptionInfo};
use aster_frame::cpu::{
ALIGNMENT_CHECK, BOUND_RANGE_EXCEEDED, DIVIDE_BY_ZERO, GENERAL_PROTECTION_FAULT,
diff --git a/services/libs/aster-std/src/process/signal/signals/kernel.rs b/services/libs/aster-std/src/process/signal/signals/kernel.rs
--- a/services/libs/aster-std/src/process/signal/signals/kernel.rs
+++ b/services/libs/aster-std/src/process/signal/signals/kernel.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::Signal;
use crate::process::signal::c_types::siginfo_t;
use crate::process::signal::constants::SI_KERNEL;
diff --git a/services/libs/aster-std/src/process/signal/signals/kernel.rs b/services/libs/aster-std/src/process/signal/signals/kernel.rs
--- a/services/libs/aster-std/src/process/signal/signals/kernel.rs
+++ b/services/libs/aster-std/src/process/signal/signals/kernel.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::Signal;
use crate::process::signal::c_types::siginfo_t;
use crate::process::signal::constants::SI_KERNEL;
diff --git a/services/libs/aster-std/src/process/signal/signals/mod.rs b/services/libs/aster-std/src/process/signal/signals/mod.rs
--- a/services/libs/aster-std/src/process/signal/signals/mod.rs
+++ b/services/libs/aster-std/src/process/signal/signals/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod fault;
pub mod kernel;
pub mod user;
diff --git a/services/libs/aster-std/src/process/signal/signals/mod.rs b/services/libs/aster-std/src/process/signal/signals/mod.rs
--- a/services/libs/aster-std/src/process/signal/signals/mod.rs
+++ b/services/libs/aster-std/src/process/signal/signals/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub mod fault;
pub mod kernel;
pub mod user;
diff --git a/services/libs/aster-std/src/process/signal/signals/user.rs b/services/libs/aster-std/src/process/signal/signals/user.rs
--- a/services/libs/aster-std/src/process/signal/signals/user.rs
+++ b/services/libs/aster-std/src/process/signal/signals/user.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::Signal;
use crate::process::signal::c_types::siginfo_t;
use crate::process::signal::constants::{SI_QUEUE, SI_TKILL, SI_USER};
diff --git a/services/libs/aster-std/src/process/signal/signals/user.rs b/services/libs/aster-std/src/process/signal/signals/user.rs
--- a/services/libs/aster-std/src/process/signal/signals/user.rs
+++ b/services/libs/aster-std/src/process/signal/signals/user.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::Signal;
use crate::process::signal::c_types::siginfo_t;
use crate::process::signal::constants::{SI_QUEUE, SI_TKILL, SI_USER};
diff --git a/services/libs/aster-std/src/process/status.rs b/services/libs/aster-std/src/process/status.rs
--- a/services/libs/aster-std/src/process/status.rs
+++ b/services/libs/aster-std/src/process/status.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The process status
use super::TermStatus;
diff --git a/services/libs/aster-std/src/process/status.rs b/services/libs/aster-std/src/process/status.rs
--- a/services/libs/aster-std/src/process/status.rs
+++ b/services/libs/aster-std/src/process/status.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The process status
use super::TermStatus;
diff --git a/services/libs/aster-std/src/process/term_status.rs b/services/libs/aster-std/src/process/term_status.rs
--- a/services/libs/aster-std/src/process/term_status.rs
+++ b/services/libs/aster-std/src/process/term_status.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::signal::sig_num::SigNum;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
diff --git a/services/libs/aster-std/src/process/term_status.rs b/services/libs/aster-std/src/process/term_status.rs
--- a/services/libs/aster-std/src/process/term_status.rs
+++ b/services/libs/aster-std/src/process/term_status.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::signal::sig_num::SigNum;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
diff --git a/services/libs/aster-std/src/process/wait.rs b/services/libs/aster-std/src/process/wait.rs
--- a/services/libs/aster-std/src/process/wait.rs
+++ b/services/libs/aster-std/src/process/wait.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{prelude::*, process::process_table, thread::thread_table};
use super::{process_filter::ProcessFilter, ExitCode, Pid, Process};
diff --git a/services/libs/aster-std/src/process/wait.rs b/services/libs/aster-std/src/process/wait.rs
--- a/services/libs/aster-std/src/process/wait.rs
+++ b/services/libs/aster-std/src/process/wait.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{prelude::*, process::process_table, thread::thread_table};
use super::{process_filter::ProcessFilter, ExitCode, Pid, Process};
diff --git a/services/libs/aster-std/src/sched/mod.rs b/services/libs/aster-std/src/sched/mod.rs
--- a/services/libs/aster-std/src/sched/mod.rs
+++ b/services/libs/aster-std/src/sched/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod priority_scheduler;
// There may be multiple scheduling policies in the system,
diff --git a/services/libs/aster-std/src/sched/mod.rs b/services/libs/aster-std/src/sched/mod.rs
--- a/services/libs/aster-std/src/sched/mod.rs
+++ b/services/libs/aster-std/src/sched/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod priority_scheduler;
// There may be multiple scheduling policies in the system,
diff --git a/services/libs/aster-std/src/sched/priority_scheduler.rs b/services/libs/aster-std/src/sched/priority_scheduler.rs
--- a/services/libs/aster-std/src/sched/priority_scheduler.rs
+++ b/services/libs/aster-std/src/sched/priority_scheduler.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use aster_frame::task::{set_scheduler, Scheduler, Task, TaskAdapter};
use intrusive_collections::LinkedList;
diff --git a/services/libs/aster-std/src/sched/priority_scheduler.rs b/services/libs/aster-std/src/sched/priority_scheduler.rs
--- a/services/libs/aster-std/src/sched/priority_scheduler.rs
+++ b/services/libs/aster-std/src/sched/priority_scheduler.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use aster_frame::task::{set_scheduler, Scheduler, Task, TaskAdapter};
use intrusive_collections::LinkedList;
diff --git a/services/libs/aster-std/src/syscall/accept.rs b/services/libs/aster-std/src/syscall/accept.rs
--- a/services/libs/aster-std/src/syscall/accept.rs
+++ b/services/libs/aster-std/src/syscall/accept.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/accept.rs b/services/libs/aster-std/src/syscall/accept.rs
--- a/services/libs/aster-std/src/syscall/accept.rs
+++ b/services/libs/aster-std/src/syscall/accept.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/access.rs b/services/libs/aster-std/src/syscall/access.rs
--- a/services/libs/aster-std/src/syscall/access.rs
+++ b/services/libs/aster-std/src/syscall/access.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{constants::*, SyscallReturn};
use crate::{log_syscall_entry, prelude::*, syscall::SYS_ACCESS, util::read_cstring_from_user};
diff --git a/services/libs/aster-std/src/syscall/access.rs b/services/libs/aster-std/src/syscall/access.rs
--- a/services/libs/aster-std/src/syscall/access.rs
+++ b/services/libs/aster-std/src/syscall/access.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{constants::*, SyscallReturn};
use crate::{log_syscall_entry, prelude::*, syscall::SYS_ACCESS, util::read_cstring_from_user};
diff --git a/services/libs/aster-std/src/syscall/arch_prctl.rs b/services/libs/aster-std/src/syscall/arch_prctl.rs
--- a/services/libs/aster-std/src/syscall/arch_prctl.rs
+++ b/services/libs/aster-std/src/syscall/arch_prctl.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::cpu::UserContext;
use crate::syscall::SYS_ARCH_PRCTL;
diff --git a/services/libs/aster-std/src/syscall/arch_prctl.rs b/services/libs/aster-std/src/syscall/arch_prctl.rs
--- a/services/libs/aster-std/src/syscall/arch_prctl.rs
+++ b/services/libs/aster-std/src/syscall/arch_prctl.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::cpu::UserContext;
use crate::syscall::SYS_ARCH_PRCTL;
diff --git a/services/libs/aster-std/src/syscall/bind.rs b/services/libs/aster-std/src/syscall/bind.rs
--- a/services/libs/aster-std/src/syscall/bind.rs
+++ b/services/libs/aster-std/src/syscall/bind.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/bind.rs b/services/libs/aster-std/src/syscall/bind.rs
--- a/services/libs/aster-std/src/syscall/bind.rs
+++ b/services/libs/aster-std/src/syscall/bind.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/brk.rs b/services/libs/aster-std/src/syscall/brk.rs
--- a/services/libs/aster-std/src/syscall/brk.rs
+++ b/services/libs/aster-std/src/syscall/brk.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/brk.rs b/services/libs/aster-std/src/syscall/brk.rs
--- a/services/libs/aster-std/src/syscall/brk.rs
+++ b/services/libs/aster-std/src/syscall/brk.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/chdir.rs b/services/libs/aster-std/src/syscall/chdir.rs
--- a/services/libs/aster-std/src/syscall/chdir.rs
+++ b/services/libs/aster-std/src/syscall/chdir.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{
file_table::FileDescripter, fs_resolver::FsPath, inode_handle::InodeHandle, utils::InodeType,
};
diff --git a/services/libs/aster-std/src/syscall/chdir.rs b/services/libs/aster-std/src/syscall/chdir.rs
--- a/services/libs/aster-std/src/syscall/chdir.rs
+++ b/services/libs/aster-std/src/syscall/chdir.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{
file_table::FileDescripter, fs_resolver::FsPath, inode_handle::InodeHandle, utils::InodeType,
};
diff --git a/services/libs/aster-std/src/syscall/chmod.rs b/services/libs/aster-std/src/syscall/chmod.rs
--- a/services/libs/aster-std/src/syscall/chmod.rs
+++ b/services/libs/aster-std/src/syscall/chmod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{
file_table::FileDescripter,
fs_resolver::{FsPath, AT_FDCWD},
diff --git a/services/libs/aster-std/src/syscall/chmod.rs b/services/libs/aster-std/src/syscall/chmod.rs
--- a/services/libs/aster-std/src/syscall/chmod.rs
+++ b/services/libs/aster-std/src/syscall/chmod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{
file_table::FileDescripter,
fs_resolver::{FsPath, AT_FDCWD},
diff --git a/services/libs/aster-std/src/syscall/clock_gettime.rs b/services/libs/aster-std/src/syscall/clock_gettime.rs
--- a/services/libs/aster-std/src/syscall/clock_gettime.rs
+++ b/services/libs/aster-std/src/syscall/clock_gettime.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::SyscallReturn;
use super::SYS_CLOCK_GETTIME;
use crate::time::now_as_duration;
diff --git a/services/libs/aster-std/src/syscall/clock_gettime.rs b/services/libs/aster-std/src/syscall/clock_gettime.rs
--- a/services/libs/aster-std/src/syscall/clock_gettime.rs
+++ b/services/libs/aster-std/src/syscall/clock_gettime.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::SyscallReturn;
use super::SYS_CLOCK_GETTIME;
use crate::time::now_as_duration;
diff --git a/services/libs/aster-std/src/syscall/clock_nanosleep.rs b/services/libs/aster-std/src/syscall/clock_nanosleep.rs
--- a/services/libs/aster-std/src/syscall/clock_nanosleep.rs
+++ b/services/libs/aster-std/src/syscall/clock_nanosleep.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::time::Duration;
use super::SyscallReturn;
diff --git a/services/libs/aster-std/src/syscall/clock_nanosleep.rs b/services/libs/aster-std/src/syscall/clock_nanosleep.rs
--- a/services/libs/aster-std/src/syscall/clock_nanosleep.rs
+++ b/services/libs/aster-std/src/syscall/clock_nanosleep.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::time::Duration;
use super::SyscallReturn;
diff --git a/services/libs/aster-std/src/syscall/clone.rs b/services/libs/aster-std/src/syscall/clone.rs
--- a/services/libs/aster-std/src/syscall/clone.rs
+++ b/services/libs/aster-std/src/syscall/clone.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::cpu::UserContext;
use crate::log_syscall_entry;
diff --git a/services/libs/aster-std/src/syscall/clone.rs b/services/libs/aster-std/src/syscall/clone.rs
--- a/services/libs/aster-std/src/syscall/clone.rs
+++ b/services/libs/aster-std/src/syscall/clone.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::cpu::UserContext;
use crate::log_syscall_entry;
diff --git a/services/libs/aster-std/src/syscall/close.rs b/services/libs/aster-std/src/syscall/close.rs
--- a/services/libs/aster-std/src/syscall/close.rs
+++ b/services/libs/aster-std/src/syscall/close.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::SyscallReturn;
use super::SYS_CLOSE;
use crate::log_syscall_entry;
diff --git a/services/libs/aster-std/src/syscall/close.rs b/services/libs/aster-std/src/syscall/close.rs
--- a/services/libs/aster-std/src/syscall/close.rs
+++ b/services/libs/aster-std/src/syscall/close.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::SyscallReturn;
use super::SYS_CLOSE;
use crate::log_syscall_entry;
diff --git a/services/libs/aster-std/src/syscall/connect.rs b/services/libs/aster-std/src/syscall/connect.rs
--- a/services/libs/aster-std/src/syscall/connect.rs
+++ b/services/libs/aster-std/src/syscall/connect.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/connect.rs b/services/libs/aster-std/src/syscall/connect.rs
--- a/services/libs/aster-std/src/syscall/connect.rs
+++ b/services/libs/aster-std/src/syscall/connect.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/constants.rs b/services/libs/aster-std/src/syscall/constants.rs
--- a/services/libs/aster-std/src/syscall/constants.rs
+++ b/services/libs/aster-std/src/syscall/constants.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! constants used in syscall
/// LONGEST ALLOWED FILENAME
diff --git a/services/libs/aster-std/src/syscall/constants.rs b/services/libs/aster-std/src/syscall/constants.rs
--- a/services/libs/aster-std/src/syscall/constants.rs
+++ b/services/libs/aster-std/src/syscall/constants.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! constants used in syscall
/// LONGEST ALLOWED FILENAME
diff --git a/services/libs/aster-std/src/syscall/dup.rs b/services/libs/aster-std/src/syscall/dup.rs
--- a/services/libs/aster-std/src/syscall/dup.rs
+++ b/services/libs/aster-std/src/syscall/dup.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/dup.rs b/services/libs/aster-std/src/syscall/dup.rs
--- a/services/libs/aster-std/src/syscall/dup.rs
+++ b/services/libs/aster-std/src/syscall/dup.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/epoll.rs b/services/libs/aster-std/src/syscall/epoll.rs
--- a/services/libs/aster-std/src/syscall/epoll.rs
+++ b/services/libs/aster-std/src/syscall/epoll.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::time::Duration;
use crate::events::IoEvents;
diff --git a/services/libs/aster-std/src/syscall/epoll.rs b/services/libs/aster-std/src/syscall/epoll.rs
--- a/services/libs/aster-std/src/syscall/epoll.rs
+++ b/services/libs/aster-std/src/syscall/epoll.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::time::Duration;
use crate::events::IoEvents;
diff --git a/services/libs/aster-std/src/syscall/execve.rs b/services/libs/aster-std/src/syscall/execve.rs
--- a/services/libs/aster-std/src/syscall/execve.rs
+++ b/services/libs/aster-std/src/syscall/execve.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::cpu::UserContext;
use aster_rights::WriteOp;
diff --git a/services/libs/aster-std/src/syscall/execve.rs b/services/libs/aster-std/src/syscall/execve.rs
--- a/services/libs/aster-std/src/syscall/execve.rs
+++ b/services/libs/aster-std/src/syscall/execve.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::cpu::UserContext;
use aster_rights::WriteOp;
diff --git a/services/libs/aster-std/src/syscall/exit.rs b/services/libs/aster-std/src/syscall/exit.rs
--- a/services/libs/aster-std/src/syscall/exit.rs
+++ b/services/libs/aster-std/src/syscall/exit.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::process::posix_thread::PosixThreadExt;
use crate::process::TermStatus;
use crate::{log_syscall_entry, prelude::*};
diff --git a/services/libs/aster-std/src/syscall/exit.rs b/services/libs/aster-std/src/syscall/exit.rs
--- a/services/libs/aster-std/src/syscall/exit.rs
+++ b/services/libs/aster-std/src/syscall/exit.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::process::posix_thread::PosixThreadExt;
use crate::process::TermStatus;
use crate::{log_syscall_entry, prelude::*};
diff --git a/services/libs/aster-std/src/syscall/exit_group.rs b/services/libs/aster-std/src/syscall/exit_group.rs
--- a/services/libs/aster-std/src/syscall/exit_group.rs
+++ b/services/libs/aster-std/src/syscall/exit_group.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::process::{do_exit_group, TermStatus};
use crate::{log_syscall_entry, prelude::*};
diff --git a/services/libs/aster-std/src/syscall/exit_group.rs b/services/libs/aster-std/src/syscall/exit_group.rs
--- a/services/libs/aster-std/src/syscall/exit_group.rs
+++ b/services/libs/aster-std/src/syscall/exit_group.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::process::{do_exit_group, TermStatus};
use crate::{log_syscall_entry, prelude::*};
diff --git a/services/libs/aster-std/src/syscall/fcntl.rs b/services/libs/aster-std/src/syscall/fcntl.rs
--- a/services/libs/aster-std/src/syscall/fcntl.rs
+++ b/services/libs/aster-std/src/syscall/fcntl.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{SyscallReturn, SYS_FCNTL};
use crate::log_syscall_entry;
use crate::{
diff --git a/services/libs/aster-std/src/syscall/fcntl.rs b/services/libs/aster-std/src/syscall/fcntl.rs
--- a/services/libs/aster-std/src/syscall/fcntl.rs
+++ b/services/libs/aster-std/src/syscall/fcntl.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{SyscallReturn, SYS_FCNTL};
use crate::log_syscall_entry;
use crate::{
diff --git a/services/libs/aster-std/src/syscall/fork.rs b/services/libs/aster-std/src/syscall/fork.rs
--- a/services/libs/aster-std/src/syscall/fork.rs
+++ b/services/libs/aster-std/src/syscall/fork.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{
log_syscall_entry,
prelude::*,
diff --git a/services/libs/aster-std/src/syscall/fork.rs b/services/libs/aster-std/src/syscall/fork.rs
--- a/services/libs/aster-std/src/syscall/fork.rs
+++ b/services/libs/aster-std/src/syscall/fork.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{
log_syscall_entry,
prelude::*,
diff --git a/services/libs/aster-std/src/syscall/fsync.rs b/services/libs/aster-std/src/syscall/fsync.rs
--- a/services/libs/aster-std/src/syscall/fsync.rs
+++ b/services/libs/aster-std/src/syscall/fsync.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::{
fs::{file_table::FileDescripter, inode_handle::InodeHandle},
diff --git a/services/libs/aster-std/src/syscall/fsync.rs b/services/libs/aster-std/src/syscall/fsync.rs
--- a/services/libs/aster-std/src/syscall/fsync.rs
+++ b/services/libs/aster-std/src/syscall/fsync.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::{
fs::{file_table::FileDescripter, inode_handle::InodeHandle},
diff --git a/services/libs/aster-std/src/syscall/futex.rs b/services/libs/aster-std/src/syscall/futex.rs
--- a/services/libs/aster-std/src/syscall/futex.rs
+++ b/services/libs/aster-std/src/syscall/futex.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::process::posix_thread::futex::{
futex_op_and_flags_from_u32, futex_requeue, futex_wait, futex_wait_bitset, futex_wake,
futex_wake_bitset, FutexOp, FutexTimeout,
diff --git a/services/libs/aster-std/src/syscall/futex.rs b/services/libs/aster-std/src/syscall/futex.rs
--- a/services/libs/aster-std/src/syscall/futex.rs
+++ b/services/libs/aster-std/src/syscall/futex.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::process::posix_thread::futex::{
futex_op_and_flags_from_u32, futex_requeue, futex_wait, futex_wait_bitset, futex_wake,
futex_wake_bitset, FutexOp, FutexTimeout,
diff --git a/services/libs/aster-std/src/syscall/getcwd.rs b/services/libs/aster-std/src/syscall/getcwd.rs
--- a/services/libs/aster-std/src/syscall/getcwd.rs
+++ b/services/libs/aster-std/src/syscall/getcwd.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::util::write_bytes_to_user;
diff --git a/services/libs/aster-std/src/syscall/getcwd.rs b/services/libs/aster-std/src/syscall/getcwd.rs
--- a/services/libs/aster-std/src/syscall/getcwd.rs
+++ b/services/libs/aster-std/src/syscall/getcwd.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::util::write_bytes_to_user;
diff --git a/services/libs/aster-std/src/syscall/getdents64.rs b/services/libs/aster-std/src/syscall/getdents64.rs
--- a/services/libs/aster-std/src/syscall/getdents64.rs
+++ b/services/libs/aster-std/src/syscall/getdents64.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{
file_table::FileDescripter,
inode_handle::InodeHandle,
diff --git a/services/libs/aster-std/src/syscall/getdents64.rs b/services/libs/aster-std/src/syscall/getdents64.rs
--- a/services/libs/aster-std/src/syscall/getdents64.rs
+++ b/services/libs/aster-std/src/syscall/getdents64.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{
file_table::FileDescripter,
inode_handle::InodeHandle,
diff --git a/services/libs/aster-std/src/syscall/getegid.rs b/services/libs/aster-std/src/syscall/getegid.rs
--- a/services/libs/aster-std/src/syscall/getegid.rs
+++ b/services/libs/aster-std/src/syscall/getegid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::process::credentials;
diff --git a/services/libs/aster-std/src/syscall/getegid.rs b/services/libs/aster-std/src/syscall/getegid.rs
--- a/services/libs/aster-std/src/syscall/getegid.rs
+++ b/services/libs/aster-std/src/syscall/getegid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::process::credentials;
diff --git a/services/libs/aster-std/src/syscall/geteuid.rs b/services/libs/aster-std/src/syscall/geteuid.rs
--- a/services/libs/aster-std/src/syscall/geteuid.rs
+++ b/services/libs/aster-std/src/syscall/geteuid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{SyscallReturn, SYS_GETEUID};
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/geteuid.rs b/services/libs/aster-std/src/syscall/geteuid.rs
--- a/services/libs/aster-std/src/syscall/geteuid.rs
+++ b/services/libs/aster-std/src/syscall/geteuid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{SyscallReturn, SYS_GETEUID};
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/getgid.rs b/services/libs/aster-std/src/syscall/getgid.rs
--- a/services/libs/aster-std/src/syscall/getgid.rs
+++ b/services/libs/aster-std/src/syscall/getgid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{SyscallReturn, SYS_GETGID};
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/getgid.rs b/services/libs/aster-std/src/syscall/getgid.rs
--- a/services/libs/aster-std/src/syscall/getgid.rs
+++ b/services/libs/aster-std/src/syscall/getgid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{SyscallReturn, SYS_GETGID};
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/getgroups.rs b/services/libs/aster-std/src/syscall/getgroups.rs
--- a/services/libs/aster-std/src/syscall/getgroups.rs
+++ b/services/libs/aster-std/src/syscall/getgroups.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{SyscallReturn, SYS_GETGROUPS};
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/getgroups.rs b/services/libs/aster-std/src/syscall/getgroups.rs
--- a/services/libs/aster-std/src/syscall/getgroups.rs
+++ b/services/libs/aster-std/src/syscall/getgroups.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{SyscallReturn, SYS_GETGROUPS};
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/getpeername.rs b/services/libs/aster-std/src/syscall/getpeername.rs
--- a/services/libs/aster-std/src/syscall/getpeername.rs
+++ b/services/libs/aster-std/src/syscall/getpeername.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/getpeername.rs b/services/libs/aster-std/src/syscall/getpeername.rs
--- a/services/libs/aster-std/src/syscall/getpeername.rs
+++ b/services/libs/aster-std/src/syscall/getpeername.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/getpgrp.rs b/services/libs/aster-std/src/syscall/getpgrp.rs
--- a/services/libs/aster-std/src/syscall/getpgrp.rs
+++ b/services/libs/aster-std/src/syscall/getpgrp.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{SyscallReturn, SYS_GETPGRP};
use crate::{log_syscall_entry, prelude::*};
diff --git a/services/libs/aster-std/src/syscall/getpgrp.rs b/services/libs/aster-std/src/syscall/getpgrp.rs
--- a/services/libs/aster-std/src/syscall/getpgrp.rs
+++ b/services/libs/aster-std/src/syscall/getpgrp.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{SyscallReturn, SYS_GETPGRP};
use crate::{log_syscall_entry, prelude::*};
diff --git a/services/libs/aster-std/src/syscall/getpid.rs b/services/libs/aster-std/src/syscall/getpid.rs
--- a/services/libs/aster-std/src/syscall/getpid.rs
+++ b/services/libs/aster-std/src/syscall/getpid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{log_syscall_entry, prelude::*};
use crate::syscall::SYS_GETPID;
diff --git a/services/libs/aster-std/src/syscall/getpid.rs b/services/libs/aster-std/src/syscall/getpid.rs
--- a/services/libs/aster-std/src/syscall/getpid.rs
+++ b/services/libs/aster-std/src/syscall/getpid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{log_syscall_entry, prelude::*};
use crate::syscall::SYS_GETPID;
diff --git a/services/libs/aster-std/src/syscall/getppid.rs b/services/libs/aster-std/src/syscall/getppid.rs
--- a/services/libs/aster-std/src/syscall/getppid.rs
+++ b/services/libs/aster-std/src/syscall/getppid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/getppid.rs b/services/libs/aster-std/src/syscall/getppid.rs
--- a/services/libs/aster-std/src/syscall/getppid.rs
+++ b/services/libs/aster-std/src/syscall/getppid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/getrandom.rs b/services/libs/aster-std/src/syscall/getrandom.rs
--- a/services/libs/aster-std/src/syscall/getrandom.rs
+++ b/services/libs/aster-std/src/syscall/getrandom.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::device;
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/getrandom.rs b/services/libs/aster-std/src/syscall/getrandom.rs
--- a/services/libs/aster-std/src/syscall/getrandom.rs
+++ b/services/libs/aster-std/src/syscall/getrandom.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::device;
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/getresgid.rs b/services/libs/aster-std/src/syscall/getresgid.rs
--- a/services/libs/aster-std/src/syscall/getresgid.rs
+++ b/services/libs/aster-std/src/syscall/getresgid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{SyscallReturn, SYS_GETRESGID};
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/getresgid.rs b/services/libs/aster-std/src/syscall/getresgid.rs
--- a/services/libs/aster-std/src/syscall/getresgid.rs
+++ b/services/libs/aster-std/src/syscall/getresgid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{SyscallReturn, SYS_GETRESGID};
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/getresuid.rs b/services/libs/aster-std/src/syscall/getresuid.rs
--- a/services/libs/aster-std/src/syscall/getresuid.rs
+++ b/services/libs/aster-std/src/syscall/getresuid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{SyscallReturn, SYS_GETRESUID};
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/getresuid.rs b/services/libs/aster-std/src/syscall/getresuid.rs
--- a/services/libs/aster-std/src/syscall/getresuid.rs
+++ b/services/libs/aster-std/src/syscall/getresuid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{SyscallReturn, SYS_GETRESUID};
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/getsid.rs b/services/libs/aster-std/src/syscall/getsid.rs
--- a/services/libs/aster-std/src/syscall/getsid.rs
+++ b/services/libs/aster-std/src/syscall/getsid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::process::{process_table, Pid};
diff --git a/services/libs/aster-std/src/syscall/getsid.rs b/services/libs/aster-std/src/syscall/getsid.rs
--- a/services/libs/aster-std/src/syscall/getsid.rs
+++ b/services/libs/aster-std/src/syscall/getsid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::process::{process_table, Pid};
diff --git a/services/libs/aster-std/src/syscall/getsockname.rs b/services/libs/aster-std/src/syscall/getsockname.rs
--- a/services/libs/aster-std/src/syscall/getsockname.rs
+++ b/services/libs/aster-std/src/syscall/getsockname.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/getsockname.rs b/services/libs/aster-std/src/syscall/getsockname.rs
--- a/services/libs/aster-std/src/syscall/getsockname.rs
+++ b/services/libs/aster-std/src/syscall/getsockname.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/getsockopt.rs b/services/libs/aster-std/src/syscall/getsockopt.rs
--- a/services/libs/aster-std/src/syscall/getsockopt.rs
+++ b/services/libs/aster-std/src/syscall/getsockopt.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/getsockopt.rs b/services/libs/aster-std/src/syscall/getsockopt.rs
--- a/services/libs/aster-std/src/syscall/getsockopt.rs
+++ b/services/libs/aster-std/src/syscall/getsockopt.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/gettid.rs b/services/libs/aster-std/src/syscall/gettid.rs
--- a/services/libs/aster-std/src/syscall/gettid.rs
+++ b/services/libs/aster-std/src/syscall/gettid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{log_syscall_entry, prelude::*};
use crate::syscall::SYS_GETTID;
diff --git a/services/libs/aster-std/src/syscall/gettid.rs b/services/libs/aster-std/src/syscall/gettid.rs
--- a/services/libs/aster-std/src/syscall/gettid.rs
+++ b/services/libs/aster-std/src/syscall/gettid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{log_syscall_entry, prelude::*};
use crate::syscall::SYS_GETTID;
diff --git a/services/libs/aster-std/src/syscall/gettimeofday.rs b/services/libs/aster-std/src/syscall/gettimeofday.rs
--- a/services/libs/aster-std/src/syscall/gettimeofday.rs
+++ b/services/libs/aster-std/src/syscall/gettimeofday.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::SyscallReturn;
use super::SYS_GETTIMEOFDAY;
use crate::{
diff --git a/services/libs/aster-std/src/syscall/gettimeofday.rs b/services/libs/aster-std/src/syscall/gettimeofday.rs
--- a/services/libs/aster-std/src/syscall/gettimeofday.rs
+++ b/services/libs/aster-std/src/syscall/gettimeofday.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::SyscallReturn;
use super::SYS_GETTIMEOFDAY;
use crate::{
diff --git a/services/libs/aster-std/src/syscall/getuid.rs b/services/libs/aster-std/src/syscall/getuid.rs
--- a/services/libs/aster-std/src/syscall/getuid.rs
+++ b/services/libs/aster-std/src/syscall/getuid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{SyscallReturn, SYS_GETUID};
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/getuid.rs b/services/libs/aster-std/src/syscall/getuid.rs
--- a/services/libs/aster-std/src/syscall/getuid.rs
+++ b/services/libs/aster-std/src/syscall/getuid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{SyscallReturn, SYS_GETUID};
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/ioctl.rs b/services/libs/aster-std/src/syscall/ioctl.rs
--- a/services/libs/aster-std/src/syscall/ioctl.rs
+++ b/services/libs/aster-std/src/syscall/ioctl.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::fs::utils::IoctlCmd;
use crate::log_syscall_entry;
diff --git a/services/libs/aster-std/src/syscall/ioctl.rs b/services/libs/aster-std/src/syscall/ioctl.rs
--- a/services/libs/aster-std/src/syscall/ioctl.rs
+++ b/services/libs/aster-std/src/syscall/ioctl.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::fs::utils::IoctlCmd;
use crate::log_syscall_entry;
diff --git a/services/libs/aster-std/src/syscall/kill.rs b/services/libs/aster-std/src/syscall/kill.rs
--- a/services/libs/aster-std/src/syscall/kill.rs
+++ b/services/libs/aster-std/src/syscall/kill.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{SyscallReturn, SYS_KILL};
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/kill.rs b/services/libs/aster-std/src/syscall/kill.rs
--- a/services/libs/aster-std/src/syscall/kill.rs
+++ b/services/libs/aster-std/src/syscall/kill.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{SyscallReturn, SYS_KILL};
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/link.rs b/services/libs/aster-std/src/syscall/link.rs
--- a/services/libs/aster-std/src/syscall/link.rs
+++ b/services/libs/aster-std/src/syscall/link.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{
file_table::FileDescripter,
fs_resolver::{FsPath, AT_FDCWD},
diff --git a/services/libs/aster-std/src/syscall/link.rs b/services/libs/aster-std/src/syscall/link.rs
--- a/services/libs/aster-std/src/syscall/link.rs
+++ b/services/libs/aster-std/src/syscall/link.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{
file_table::FileDescripter,
fs_resolver::{FsPath, AT_FDCWD},
diff --git a/services/libs/aster-std/src/syscall/listen.rs b/services/libs/aster-std/src/syscall/listen.rs
--- a/services/libs/aster-std/src/syscall/listen.rs
+++ b/services/libs/aster-std/src/syscall/listen.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/listen.rs b/services/libs/aster-std/src/syscall/listen.rs
--- a/services/libs/aster-std/src/syscall/listen.rs
+++ b/services/libs/aster-std/src/syscall/listen.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/lseek.rs b/services/libs/aster-std/src/syscall/lseek.rs
--- a/services/libs/aster-std/src/syscall/lseek.rs
+++ b/services/libs/aster-std/src/syscall/lseek.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{file_table::FileDescripter, utils::SeekFrom};
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/lseek.rs b/services/libs/aster-std/src/syscall/lseek.rs
--- a/services/libs/aster-std/src/syscall/lseek.rs
+++ b/services/libs/aster-std/src/syscall/lseek.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{file_table::FileDescripter, utils::SeekFrom};
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/madvise.rs b/services/libs/aster-std/src/syscall/madvise.rs
--- a/services/libs/aster-std/src/syscall/madvise.rs
+++ b/services/libs/aster-std/src/syscall/madvise.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::util::read_bytes_from_user;
use crate::{log_syscall_entry, prelude::*};
diff --git a/services/libs/aster-std/src/syscall/madvise.rs b/services/libs/aster-std/src/syscall/madvise.rs
--- a/services/libs/aster-std/src/syscall/madvise.rs
+++ b/services/libs/aster-std/src/syscall/madvise.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::util::read_bytes_from_user;
use crate::{log_syscall_entry, prelude::*};
diff --git a/services/libs/aster-std/src/syscall/mkdir.rs b/services/libs/aster-std/src/syscall/mkdir.rs
--- a/services/libs/aster-std/src/syscall/mkdir.rs
+++ b/services/libs/aster-std/src/syscall/mkdir.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{
file_table::FileDescripter,
fs_resolver::{FsPath, AT_FDCWD},
diff --git a/services/libs/aster-std/src/syscall/mkdir.rs b/services/libs/aster-std/src/syscall/mkdir.rs
--- a/services/libs/aster-std/src/syscall/mkdir.rs
+++ b/services/libs/aster-std/src/syscall/mkdir.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{
file_table::FileDescripter,
fs_resolver::{FsPath, AT_FDCWD},
diff --git a/services/libs/aster-std/src/syscall/mmap.rs b/services/libs/aster-std/src/syscall/mmap.rs
--- a/services/libs/aster-std/src/syscall/mmap.rs
+++ b/services/libs/aster-std/src/syscall/mmap.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! This mod defines mmap flags and the handler to syscall mmap
use crate::fs::file_table::FileDescripter;
diff --git a/services/libs/aster-std/src/syscall/mmap.rs b/services/libs/aster-std/src/syscall/mmap.rs
--- a/services/libs/aster-std/src/syscall/mmap.rs
+++ b/services/libs/aster-std/src/syscall/mmap.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! This mod defines mmap flags and the handler to syscall mmap
use crate::fs::file_table::FileDescripter;
diff --git a/services/libs/aster-std/src/syscall/mod.rs b/services/libs/aster-std/src/syscall/mod.rs
--- a/services/libs/aster-std/src/syscall/mod.rs
+++ b/services/libs/aster-std/src/syscall/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Read the Cpu context content then dispatch syscall to corrsponding handler
//! The each sub module contains functions that handle real syscall logic.
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/mod.rs b/services/libs/aster-std/src/syscall/mod.rs
--- a/services/libs/aster-std/src/syscall/mod.rs
+++ b/services/libs/aster-std/src/syscall/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Read the Cpu context content then dispatch syscall to corrsponding handler
//! The each sub module contains functions that handle real syscall logic.
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/mprotect.rs b/services/libs/aster-std/src/syscall/mprotect.rs
--- a/services/libs/aster-std/src/syscall/mprotect.rs
+++ b/services/libs/aster-std/src/syscall/mprotect.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use align_ext::AlignExt;
use crate::{log_syscall_entry, prelude::*};
diff --git a/services/libs/aster-std/src/syscall/mprotect.rs b/services/libs/aster-std/src/syscall/mprotect.rs
--- a/services/libs/aster-std/src/syscall/mprotect.rs
+++ b/services/libs/aster-std/src/syscall/mprotect.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use align_ext::AlignExt;
use crate::{log_syscall_entry, prelude::*};
diff --git a/services/libs/aster-std/src/syscall/munmap.rs b/services/libs/aster-std/src/syscall/munmap.rs
--- a/services/libs/aster-std/src/syscall/munmap.rs
+++ b/services/libs/aster-std/src/syscall/munmap.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use align_ext::AlignExt;
use crate::log_syscall_entry;
diff --git a/services/libs/aster-std/src/syscall/munmap.rs b/services/libs/aster-std/src/syscall/munmap.rs
--- a/services/libs/aster-std/src/syscall/munmap.rs
+++ b/services/libs/aster-std/src/syscall/munmap.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use align_ext::AlignExt;
use crate::log_syscall_entry;
diff --git a/services/libs/aster-std/src/syscall/open.rs b/services/libs/aster-std/src/syscall/open.rs
--- a/services/libs/aster-std/src/syscall/open.rs
+++ b/services/libs/aster-std/src/syscall/open.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{
file_handle::FileLike,
file_table::FileDescripter,
diff --git a/services/libs/aster-std/src/syscall/open.rs b/services/libs/aster-std/src/syscall/open.rs
--- a/services/libs/aster-std/src/syscall/open.rs
+++ b/services/libs/aster-std/src/syscall/open.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{
file_handle::FileLike,
file_table::FileDescripter,
diff --git a/services/libs/aster-std/src/syscall/pause.rs b/services/libs/aster-std/src/syscall/pause.rs
--- a/services/libs/aster-std/src/syscall/pause.rs
+++ b/services/libs/aster-std/src/syscall/pause.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::process::signal::Pauser;
diff --git a/services/libs/aster-std/src/syscall/pause.rs b/services/libs/aster-std/src/syscall/pause.rs
--- a/services/libs/aster-std/src/syscall/pause.rs
+++ b/services/libs/aster-std/src/syscall/pause.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::process::signal::Pauser;
diff --git a/services/libs/aster-std/src/syscall/pipe.rs b/services/libs/aster-std/src/syscall/pipe.rs
--- a/services/libs/aster-std/src/syscall/pipe.rs
+++ b/services/libs/aster-std/src/syscall/pipe.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::fs::pipe::{PipeReader, PipeWriter};
use crate::fs::utils::{Channel, StatusFlags};
diff --git a/services/libs/aster-std/src/syscall/pipe.rs b/services/libs/aster-std/src/syscall/pipe.rs
--- a/services/libs/aster-std/src/syscall/pipe.rs
+++ b/services/libs/aster-std/src/syscall/pipe.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::fs::pipe::{PipeReader, PipeWriter};
use crate::fs::utils::{Channel, StatusFlags};
diff --git a/services/libs/aster-std/src/syscall/poll.rs b/services/libs/aster-std/src/syscall/poll.rs
--- a/services/libs/aster-std/src/syscall/poll.rs
+++ b/services/libs/aster-std/src/syscall/poll.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::cell::Cell;
use core::time::Duration;
diff --git a/services/libs/aster-std/src/syscall/poll.rs b/services/libs/aster-std/src/syscall/poll.rs
--- a/services/libs/aster-std/src/syscall/poll.rs
+++ b/services/libs/aster-std/src/syscall/poll.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::cell::Cell;
use core::time::Duration;
diff --git a/services/libs/aster-std/src/syscall/prctl.rs b/services/libs/aster-std/src/syscall/prctl.rs
--- a/services/libs/aster-std/src/syscall/prctl.rs
+++ b/services/libs/aster-std/src/syscall/prctl.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::process::posix_thread::PosixThreadExt;
diff --git a/services/libs/aster-std/src/syscall/prctl.rs b/services/libs/aster-std/src/syscall/prctl.rs
--- a/services/libs/aster-std/src/syscall/prctl.rs
+++ b/services/libs/aster-std/src/syscall/prctl.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::process::posix_thread::PosixThreadExt;
diff --git a/services/libs/aster-std/src/syscall/pread64.rs b/services/libs/aster-std/src/syscall/pread64.rs
--- a/services/libs/aster-std/src/syscall/pread64.rs
+++ b/services/libs/aster-std/src/syscall/pread64.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::fs::utils::SeekFrom;
use crate::util::write_bytes_to_user;
diff --git a/services/libs/aster-std/src/syscall/pread64.rs b/services/libs/aster-std/src/syscall/pread64.rs
--- a/services/libs/aster-std/src/syscall/pread64.rs
+++ b/services/libs/aster-std/src/syscall/pread64.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::fs::utils::SeekFrom;
use crate::util::write_bytes_to_user;
diff --git a/services/libs/aster-std/src/syscall/prlimit64.rs b/services/libs/aster-std/src/syscall/prlimit64.rs
--- a/services/libs/aster-std/src/syscall/prlimit64.rs
+++ b/services/libs/aster-std/src/syscall/prlimit64.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::process::ResourceType;
use crate::util::{read_val_from_user, write_val_to_user};
use crate::{log_syscall_entry, prelude::*, process::Pid};
diff --git a/services/libs/aster-std/src/syscall/prlimit64.rs b/services/libs/aster-std/src/syscall/prlimit64.rs
--- a/services/libs/aster-std/src/syscall/prlimit64.rs
+++ b/services/libs/aster-std/src/syscall/prlimit64.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::process::ResourceType;
use crate::util::{read_val_from_user, write_val_to_user};
use crate::{log_syscall_entry, prelude::*, process::Pid};
diff --git a/services/libs/aster-std/src/syscall/read.rs b/services/libs/aster-std/src/syscall/read.rs
--- a/services/libs/aster-std/src/syscall/read.rs
+++ b/services/libs/aster-std/src/syscall/read.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::util::write_bytes_to_user;
use crate::{fs::file_table::FileDescripter, prelude::*};
diff --git a/services/libs/aster-std/src/syscall/read.rs b/services/libs/aster-std/src/syscall/read.rs
--- a/services/libs/aster-std/src/syscall/read.rs
+++ b/services/libs/aster-std/src/syscall/read.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::util::write_bytes_to_user;
use crate::{fs::file_table::FileDescripter, prelude::*};
diff --git a/services/libs/aster-std/src/syscall/readlink.rs b/services/libs/aster-std/src/syscall/readlink.rs
--- a/services/libs/aster-std/src/syscall/readlink.rs
+++ b/services/libs/aster-std/src/syscall/readlink.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{
file_table::FileDescripter,
fs_resolver::{FsPath, AT_FDCWD},
diff --git a/services/libs/aster-std/src/syscall/readlink.rs b/services/libs/aster-std/src/syscall/readlink.rs
--- a/services/libs/aster-std/src/syscall/readlink.rs
+++ b/services/libs/aster-std/src/syscall/readlink.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{
file_table::FileDescripter,
fs_resolver::{FsPath, AT_FDCWD},
diff --git a/services/libs/aster-std/src/syscall/recvfrom.rs b/services/libs/aster-std/src/syscall/recvfrom.rs
--- a/services/libs/aster-std/src/syscall/recvfrom.rs
+++ b/services/libs/aster-std/src/syscall/recvfrom.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::log_syscall_entry;
use crate::net::socket::SendRecvFlags;
diff --git a/services/libs/aster-std/src/syscall/recvfrom.rs b/services/libs/aster-std/src/syscall/recvfrom.rs
--- a/services/libs/aster-std/src/syscall/recvfrom.rs
+++ b/services/libs/aster-std/src/syscall/recvfrom.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::log_syscall_entry;
use crate::net::socket::SendRecvFlags;
diff --git a/services/libs/aster-std/src/syscall/rename.rs b/services/libs/aster-std/src/syscall/rename.rs
--- a/services/libs/aster-std/src/syscall/rename.rs
+++ b/services/libs/aster-std/src/syscall/rename.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{
file_table::FileDescripter,
fs_resolver::{FsPath, AT_FDCWD},
diff --git a/services/libs/aster-std/src/syscall/rename.rs b/services/libs/aster-std/src/syscall/rename.rs
--- a/services/libs/aster-std/src/syscall/rename.rs
+++ b/services/libs/aster-std/src/syscall/rename.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{
file_table::FileDescripter,
fs_resolver::{FsPath, AT_FDCWD},
diff --git a/services/libs/aster-std/src/syscall/rmdir.rs b/services/libs/aster-std/src/syscall/rmdir.rs
--- a/services/libs/aster-std/src/syscall/rmdir.rs
+++ b/services/libs/aster-std/src/syscall/rmdir.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{
file_table::FileDescripter,
fs_resolver::{FsPath, AT_FDCWD},
diff --git a/services/libs/aster-std/src/syscall/rmdir.rs b/services/libs/aster-std/src/syscall/rmdir.rs
--- a/services/libs/aster-std/src/syscall/rmdir.rs
+++ b/services/libs/aster-std/src/syscall/rmdir.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{
file_table::FileDescripter,
fs_resolver::{FsPath, AT_FDCWD},
diff --git a/services/libs/aster-std/src/syscall/rt_sigaction.rs b/services/libs/aster-std/src/syscall/rt_sigaction.rs
--- a/services/libs/aster-std/src/syscall/rt_sigaction.rs
+++ b/services/libs/aster-std/src/syscall/rt_sigaction.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{
log_syscall_entry,
prelude::*,
diff --git a/services/libs/aster-std/src/syscall/rt_sigaction.rs b/services/libs/aster-std/src/syscall/rt_sigaction.rs
--- a/services/libs/aster-std/src/syscall/rt_sigaction.rs
+++ b/services/libs/aster-std/src/syscall/rt_sigaction.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{
log_syscall_entry,
prelude::*,
diff --git a/services/libs/aster-std/src/syscall/rt_sigprocmask.rs b/services/libs/aster-std/src/syscall/rt_sigprocmask.rs
--- a/services/libs/aster-std/src/syscall/rt_sigprocmask.rs
+++ b/services/libs/aster-std/src/syscall/rt_sigprocmask.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{SyscallReturn, SYS_RT_SIGPROCMASK};
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/rt_sigprocmask.rs b/services/libs/aster-std/src/syscall/rt_sigprocmask.rs
--- a/services/libs/aster-std/src/syscall/rt_sigprocmask.rs
+++ b/services/libs/aster-std/src/syscall/rt_sigprocmask.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{SyscallReturn, SYS_RT_SIGPROCMASK};
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/rt_sigreturn.rs b/services/libs/aster-std/src/syscall/rt_sigreturn.rs
--- a/services/libs/aster-std/src/syscall/rt_sigreturn.rs
+++ b/services/libs/aster-std/src/syscall/rt_sigreturn.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{
log_syscall_entry,
prelude::*,
diff --git a/services/libs/aster-std/src/syscall/rt_sigreturn.rs b/services/libs/aster-std/src/syscall/rt_sigreturn.rs
--- a/services/libs/aster-std/src/syscall/rt_sigreturn.rs
+++ b/services/libs/aster-std/src/syscall/rt_sigreturn.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{
log_syscall_entry,
prelude::*,
diff --git a/services/libs/aster-std/src/syscall/sched_yield.rs b/services/libs/aster-std/src/syscall/sched_yield.rs
--- a/services/libs/aster-std/src/syscall/sched_yield.rs
+++ b/services/libs/aster-std/src/syscall/sched_yield.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::thread::Thread;
use crate::{log_syscall_entry, prelude::*};
diff --git a/services/libs/aster-std/src/syscall/sched_yield.rs b/services/libs/aster-std/src/syscall/sched_yield.rs
--- a/services/libs/aster-std/src/syscall/sched_yield.rs
+++ b/services/libs/aster-std/src/syscall/sched_yield.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::thread::Thread;
use crate::{log_syscall_entry, prelude::*};
diff --git a/services/libs/aster-std/src/syscall/select.rs b/services/libs/aster-std/src/syscall/select.rs
--- a/services/libs/aster-std/src/syscall/select.rs
+++ b/services/libs/aster-std/src/syscall/select.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::time::Duration;
use crate::events::IoEvents;
diff --git a/services/libs/aster-std/src/syscall/select.rs b/services/libs/aster-std/src/syscall/select.rs
--- a/services/libs/aster-std/src/syscall/select.rs
+++ b/services/libs/aster-std/src/syscall/select.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::time::Duration;
use crate::events::IoEvents;
diff --git a/services/libs/aster-std/src/syscall/sendto.rs b/services/libs/aster-std/src/syscall/sendto.rs
--- a/services/libs/aster-std/src/syscall/sendto.rs
+++ b/services/libs/aster-std/src/syscall/sendto.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::log_syscall_entry;
use crate::net::socket::SendRecvFlags;
diff --git a/services/libs/aster-std/src/syscall/sendto.rs b/services/libs/aster-std/src/syscall/sendto.rs
--- a/services/libs/aster-std/src/syscall/sendto.rs
+++ b/services/libs/aster-std/src/syscall/sendto.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::log_syscall_entry;
use crate::net::socket::SendRecvFlags;
diff --git a/services/libs/aster-std/src/syscall/set_robust_list.rs b/services/libs/aster-std/src/syscall/set_robust_list.rs
--- a/services/libs/aster-std/src/syscall/set_robust_list.rs
+++ b/services/libs/aster-std/src/syscall/set_robust_list.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{SyscallReturn, SYS_SET_ROBUST_LIST};
use crate::{
log_syscall_entry,
diff --git a/services/libs/aster-std/src/syscall/set_robust_list.rs b/services/libs/aster-std/src/syscall/set_robust_list.rs
--- a/services/libs/aster-std/src/syscall/set_robust_list.rs
+++ b/services/libs/aster-std/src/syscall/set_robust_list.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{SyscallReturn, SYS_SET_ROBUST_LIST};
use crate::{
log_syscall_entry,
diff --git a/services/libs/aster-std/src/syscall/set_tid_address.rs b/services/libs/aster-std/src/syscall/set_tid_address.rs
--- a/services/libs/aster-std/src/syscall/set_tid_address.rs
+++ b/services/libs/aster-std/src/syscall/set_tid_address.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::SyscallReturn;
use super::SYS_SET_TID_ADDRESS;
use crate::process::posix_thread::PosixThreadExt;
diff --git a/services/libs/aster-std/src/syscall/set_tid_address.rs b/services/libs/aster-std/src/syscall/set_tid_address.rs
--- a/services/libs/aster-std/src/syscall/set_tid_address.rs
+++ b/services/libs/aster-std/src/syscall/set_tid_address.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::SyscallReturn;
use super::SYS_SET_TID_ADDRESS;
use crate::process::posix_thread::PosixThreadExt;
diff --git a/services/libs/aster-std/src/syscall/setfsgid.rs b/services/libs/aster-std/src/syscall/setfsgid.rs
--- a/services/libs/aster-std/src/syscall/setfsgid.rs
+++ b/services/libs/aster-std/src/syscall/setfsgid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::process::{credentials_mut, Gid};
diff --git a/services/libs/aster-std/src/syscall/setfsgid.rs b/services/libs/aster-std/src/syscall/setfsgid.rs
--- a/services/libs/aster-std/src/syscall/setfsgid.rs
+++ b/services/libs/aster-std/src/syscall/setfsgid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::process::{credentials_mut, Gid};
diff --git a/services/libs/aster-std/src/syscall/setfsuid.rs b/services/libs/aster-std/src/syscall/setfsuid.rs
--- a/services/libs/aster-std/src/syscall/setfsuid.rs
+++ b/services/libs/aster-std/src/syscall/setfsuid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::process::{credentials_mut, Uid};
diff --git a/services/libs/aster-std/src/syscall/setfsuid.rs b/services/libs/aster-std/src/syscall/setfsuid.rs
--- a/services/libs/aster-std/src/syscall/setfsuid.rs
+++ b/services/libs/aster-std/src/syscall/setfsuid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::process::{credentials_mut, Uid};
diff --git a/services/libs/aster-std/src/syscall/setgid.rs b/services/libs/aster-std/src/syscall/setgid.rs
--- a/services/libs/aster-std/src/syscall/setgid.rs
+++ b/services/libs/aster-std/src/syscall/setgid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::process::{credentials_mut, Gid};
diff --git a/services/libs/aster-std/src/syscall/setgid.rs b/services/libs/aster-std/src/syscall/setgid.rs
--- a/services/libs/aster-std/src/syscall/setgid.rs
+++ b/services/libs/aster-std/src/syscall/setgid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::process::{credentials_mut, Gid};
diff --git a/services/libs/aster-std/src/syscall/setgroups.rs b/services/libs/aster-std/src/syscall/setgroups.rs
--- a/services/libs/aster-std/src/syscall/setgroups.rs
+++ b/services/libs/aster-std/src/syscall/setgroups.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{SyscallReturn, SYS_SETGROUPS};
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/setgroups.rs b/services/libs/aster-std/src/syscall/setgroups.rs
--- a/services/libs/aster-std/src/syscall/setgroups.rs
+++ b/services/libs/aster-std/src/syscall/setgroups.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{SyscallReturn, SYS_SETGROUPS};
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/setpgid.rs b/services/libs/aster-std/src/syscall/setpgid.rs
--- a/services/libs/aster-std/src/syscall/setpgid.rs
+++ b/services/libs/aster-std/src/syscall/setpgid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::process::{process_table, Pgid, Pid};
diff --git a/services/libs/aster-std/src/syscall/setpgid.rs b/services/libs/aster-std/src/syscall/setpgid.rs
--- a/services/libs/aster-std/src/syscall/setpgid.rs
+++ b/services/libs/aster-std/src/syscall/setpgid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::process::{process_table, Pgid, Pid};
diff --git a/services/libs/aster-std/src/syscall/setregid.rs b/services/libs/aster-std/src/syscall/setregid.rs
--- a/services/libs/aster-std/src/syscall/setregid.rs
+++ b/services/libs/aster-std/src/syscall/setregid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::process::{credentials_mut, Gid};
diff --git a/services/libs/aster-std/src/syscall/setregid.rs b/services/libs/aster-std/src/syscall/setregid.rs
--- a/services/libs/aster-std/src/syscall/setregid.rs
+++ b/services/libs/aster-std/src/syscall/setregid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::process::{credentials_mut, Gid};
diff --git a/services/libs/aster-std/src/syscall/setresgid.rs b/services/libs/aster-std/src/syscall/setresgid.rs
--- a/services/libs/aster-std/src/syscall/setresgid.rs
+++ b/services/libs/aster-std/src/syscall/setresgid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::process::{credentials_mut, Gid};
diff --git a/services/libs/aster-std/src/syscall/setresgid.rs b/services/libs/aster-std/src/syscall/setresgid.rs
--- a/services/libs/aster-std/src/syscall/setresgid.rs
+++ b/services/libs/aster-std/src/syscall/setresgid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::process::{credentials_mut, Gid};
diff --git a/services/libs/aster-std/src/syscall/setresuid.rs b/services/libs/aster-std/src/syscall/setresuid.rs
--- a/services/libs/aster-std/src/syscall/setresuid.rs
+++ b/services/libs/aster-std/src/syscall/setresuid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::process::{credentials_mut, Uid};
diff --git a/services/libs/aster-std/src/syscall/setresuid.rs b/services/libs/aster-std/src/syscall/setresuid.rs
--- a/services/libs/aster-std/src/syscall/setresuid.rs
+++ b/services/libs/aster-std/src/syscall/setresuid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::process::{credentials_mut, Uid};
diff --git a/services/libs/aster-std/src/syscall/setreuid.rs b/services/libs/aster-std/src/syscall/setreuid.rs
--- a/services/libs/aster-std/src/syscall/setreuid.rs
+++ b/services/libs/aster-std/src/syscall/setreuid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::process::{credentials_mut, Uid};
diff --git a/services/libs/aster-std/src/syscall/setreuid.rs b/services/libs/aster-std/src/syscall/setreuid.rs
--- a/services/libs/aster-std/src/syscall/setreuid.rs
+++ b/services/libs/aster-std/src/syscall/setreuid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::process::{credentials_mut, Uid};
diff --git a/services/libs/aster-std/src/syscall/setsid.rs b/services/libs/aster-std/src/syscall/setsid.rs
--- a/services/libs/aster-std/src/syscall/setsid.rs
+++ b/services/libs/aster-std/src/syscall/setsid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/setsid.rs b/services/libs/aster-std/src/syscall/setsid.rs
--- a/services/libs/aster-std/src/syscall/setsid.rs
+++ b/services/libs/aster-std/src/syscall/setsid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/setsockopt.rs b/services/libs/aster-std/src/syscall/setsockopt.rs
--- a/services/libs/aster-std/src/syscall/setsockopt.rs
+++ b/services/libs/aster-std/src/syscall/setsockopt.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/setsockopt.rs b/services/libs/aster-std/src/syscall/setsockopt.rs
--- a/services/libs/aster-std/src/syscall/setsockopt.rs
+++ b/services/libs/aster-std/src/syscall/setsockopt.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/setuid.rs b/services/libs/aster-std/src/syscall/setuid.rs
--- a/services/libs/aster-std/src/syscall/setuid.rs
+++ b/services/libs/aster-std/src/syscall/setuid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{SyscallReturn, SYS_SETUID};
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/setuid.rs b/services/libs/aster-std/src/syscall/setuid.rs
--- a/services/libs/aster-std/src/syscall/setuid.rs
+++ b/services/libs/aster-std/src/syscall/setuid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::{SyscallReturn, SYS_SETUID};
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/shutdown.rs b/services/libs/aster-std/src/syscall/shutdown.rs
--- a/services/libs/aster-std/src/syscall/shutdown.rs
+++ b/services/libs/aster-std/src/syscall/shutdown.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::log_syscall_entry;
use crate::net::socket::SockShutdownCmd;
diff --git a/services/libs/aster-std/src/syscall/shutdown.rs b/services/libs/aster-std/src/syscall/shutdown.rs
--- a/services/libs/aster-std/src/syscall/shutdown.rs
+++ b/services/libs/aster-std/src/syscall/shutdown.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::log_syscall_entry;
use crate::net::socket::SockShutdownCmd;
diff --git a/services/libs/aster-std/src/syscall/sigaltstack.rs b/services/libs/aster-std/src/syscall/sigaltstack.rs
--- a/services/libs/aster-std/src/syscall/sigaltstack.rs
+++ b/services/libs/aster-std/src/syscall/sigaltstack.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::process::posix_thread::PosixThreadExt;
diff --git a/services/libs/aster-std/src/syscall/sigaltstack.rs b/services/libs/aster-std/src/syscall/sigaltstack.rs
--- a/services/libs/aster-std/src/syscall/sigaltstack.rs
+++ b/services/libs/aster-std/src/syscall/sigaltstack.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::process::posix_thread::PosixThreadExt;
diff --git a/services/libs/aster-std/src/syscall/socket.rs b/services/libs/aster-std/src/syscall/socket.rs
--- a/services/libs/aster-std/src/syscall/socket.rs
+++ b/services/libs/aster-std/src/syscall/socket.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_handle::FileLike;
use crate::net::socket::ip::{DatagramSocket, StreamSocket};
use crate::net::socket::unix::UnixStreamSocket;
diff --git a/services/libs/aster-std/src/syscall/socket.rs b/services/libs/aster-std/src/syscall/socket.rs
--- a/services/libs/aster-std/src/syscall/socket.rs
+++ b/services/libs/aster-std/src/syscall/socket.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_handle::FileLike;
use crate::net::socket::ip::{DatagramSocket, StreamSocket};
use crate::net::socket::unix::UnixStreamSocket;
diff --git a/services/libs/aster-std/src/syscall/socketpair.rs b/services/libs/aster-std/src/syscall/socketpair.rs
--- a/services/libs/aster-std/src/syscall/socketpair.rs
+++ b/services/libs/aster-std/src/syscall/socketpair.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::net::socket::unix::UnixStreamSocket;
use crate::util::net::{CSocketAddrFamily, Protocol, SockFlags, SockType, SOCK_TYPE_MASK};
diff --git a/services/libs/aster-std/src/syscall/socketpair.rs b/services/libs/aster-std/src/syscall/socketpair.rs
--- a/services/libs/aster-std/src/syscall/socketpair.rs
+++ b/services/libs/aster-std/src/syscall/socketpair.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::net::socket::unix::UnixStreamSocket;
use crate::util::net::{CSocketAddrFamily, Protocol, SockFlags, SockType, SOCK_TYPE_MASK};
diff --git a/services/libs/aster-std/src/syscall/stat.rs b/services/libs/aster-std/src/syscall/stat.rs
--- a/services/libs/aster-std/src/syscall/stat.rs
+++ b/services/libs/aster-std/src/syscall/stat.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{
file_table::FileDescripter,
fs_resolver::{FsPath, AT_FDCWD},
diff --git a/services/libs/aster-std/src/syscall/stat.rs b/services/libs/aster-std/src/syscall/stat.rs
--- a/services/libs/aster-std/src/syscall/stat.rs
+++ b/services/libs/aster-std/src/syscall/stat.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{
file_table::FileDescripter,
fs_resolver::{FsPath, AT_FDCWD},
diff --git a/services/libs/aster-std/src/syscall/statfs.rs b/services/libs/aster-std/src/syscall/statfs.rs
--- a/services/libs/aster-std/src/syscall/statfs.rs
+++ b/services/libs/aster-std/src/syscall/statfs.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{
file_table::FileDescripter,
fs_resolver::FsPath,
diff --git a/services/libs/aster-std/src/syscall/statfs.rs b/services/libs/aster-std/src/syscall/statfs.rs
--- a/services/libs/aster-std/src/syscall/statfs.rs
+++ b/services/libs/aster-std/src/syscall/statfs.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{
file_table::FileDescripter,
fs_resolver::FsPath,
diff --git a/services/libs/aster-std/src/syscall/symlink.rs b/services/libs/aster-std/src/syscall/symlink.rs
--- a/services/libs/aster-std/src/syscall/symlink.rs
+++ b/services/libs/aster-std/src/syscall/symlink.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{
file_table::FileDescripter,
fs_resolver::{FsPath, AT_FDCWD},
diff --git a/services/libs/aster-std/src/syscall/symlink.rs b/services/libs/aster-std/src/syscall/symlink.rs
--- a/services/libs/aster-std/src/syscall/symlink.rs
+++ b/services/libs/aster-std/src/syscall/symlink.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{
file_table::FileDescripter,
fs_resolver::{FsPath, AT_FDCWD},
diff --git a/services/libs/aster-std/src/syscall/sync.rs b/services/libs/aster-std/src/syscall/sync.rs
--- a/services/libs/aster-std/src/syscall/sync.rs
+++ b/services/libs/aster-std/src/syscall/sync.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/sync.rs b/services/libs/aster-std/src/syscall/sync.rs
--- a/services/libs/aster-std/src/syscall/sync.rs
+++ b/services/libs/aster-std/src/syscall/sync.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/tgkill.rs b/services/libs/aster-std/src/syscall/tgkill.rs
--- a/services/libs/aster-std/src/syscall/tgkill.rs
+++ b/services/libs/aster-std/src/syscall/tgkill.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::SyscallReturn;
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/tgkill.rs b/services/libs/aster-std/src/syscall/tgkill.rs
--- a/services/libs/aster-std/src/syscall/tgkill.rs
+++ b/services/libs/aster-std/src/syscall/tgkill.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::SyscallReturn;
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/time.rs b/services/libs/aster-std/src/syscall/time.rs
--- a/services/libs/aster-std/src/syscall/time.rs
+++ b/services/libs/aster-std/src/syscall/time.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::time::SystemTime;
diff --git a/services/libs/aster-std/src/syscall/time.rs b/services/libs/aster-std/src/syscall/time.rs
--- a/services/libs/aster-std/src/syscall/time.rs
+++ b/services/libs/aster-std/src/syscall/time.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::time::SystemTime;
diff --git a/services/libs/aster-std/src/syscall/umask.rs b/services/libs/aster-std/src/syscall/umask.rs
--- a/services/libs/aster-std/src/syscall/umask.rs
+++ b/services/libs/aster-std/src/syscall/umask.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::SyscallReturn;
use super::SYS_UMASK;
use crate::{log_syscall_entry, prelude::*};
diff --git a/services/libs/aster-std/src/syscall/umask.rs b/services/libs/aster-std/src/syscall/umask.rs
--- a/services/libs/aster-std/src/syscall/umask.rs
+++ b/services/libs/aster-std/src/syscall/umask.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::SyscallReturn;
use super::SYS_UMASK;
use crate::{log_syscall_entry, prelude::*};
diff --git a/services/libs/aster-std/src/syscall/uname.rs b/services/libs/aster-std/src/syscall/uname.rs
--- a/services/libs/aster-std/src/syscall/uname.rs
+++ b/services/libs/aster-std/src/syscall/uname.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{log_syscall_entry, prelude::*};
use crate::syscall::SYS_UNAME;
diff --git a/services/libs/aster-std/src/syscall/uname.rs b/services/libs/aster-std/src/syscall/uname.rs
--- a/services/libs/aster-std/src/syscall/uname.rs
+++ b/services/libs/aster-std/src/syscall/uname.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{log_syscall_entry, prelude::*};
use crate::syscall::SYS_UNAME;
diff --git a/services/libs/aster-std/src/syscall/unlink.rs b/services/libs/aster-std/src/syscall/unlink.rs
--- a/services/libs/aster-std/src/syscall/unlink.rs
+++ b/services/libs/aster-std/src/syscall/unlink.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{
file_table::FileDescripter,
fs_resolver::{FsPath, AT_FDCWD},
diff --git a/services/libs/aster-std/src/syscall/unlink.rs b/services/libs/aster-std/src/syscall/unlink.rs
--- a/services/libs/aster-std/src/syscall/unlink.rs
+++ b/services/libs/aster-std/src/syscall/unlink.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{
file_table::FileDescripter,
fs_resolver::{FsPath, AT_FDCWD},
diff --git a/services/libs/aster-std/src/syscall/utimens.rs b/services/libs/aster-std/src/syscall/utimens.rs
--- a/services/libs/aster-std/src/syscall/utimens.rs
+++ b/services/libs/aster-std/src/syscall/utimens.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{file_table::FileDescripter, fs_resolver::FsPath};
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/utimens.rs b/services/libs/aster-std/src/syscall/utimens.rs
--- a/services/libs/aster-std/src/syscall/utimens.rs
+++ b/services/libs/aster-std/src/syscall/utimens.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::{file_table::FileDescripter, fs_resolver::FsPath};
use crate::log_syscall_entry;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/syscall/wait4.rs b/services/libs/aster-std/src/syscall/wait4.rs
--- a/services/libs/aster-std/src/syscall/wait4.rs
+++ b/services/libs/aster-std/src/syscall/wait4.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{
log_syscall_entry,
process::{wait_child_exit, ProcessFilter},
diff --git a/services/libs/aster-std/src/syscall/wait4.rs b/services/libs/aster-std/src/syscall/wait4.rs
--- a/services/libs/aster-std/src/syscall/wait4.rs
+++ b/services/libs/aster-std/src/syscall/wait4.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{
log_syscall_entry,
process::{wait_child_exit, ProcessFilter},
diff --git a/services/libs/aster-std/src/syscall/waitid.rs b/services/libs/aster-std/src/syscall/waitid.rs
--- a/services/libs/aster-std/src/syscall/waitid.rs
+++ b/services/libs/aster-std/src/syscall/waitid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::process::{wait_child_exit, ProcessFilter};
use crate::{log_syscall_entry, prelude::*};
diff --git a/services/libs/aster-std/src/syscall/waitid.rs b/services/libs/aster-std/src/syscall/waitid.rs
--- a/services/libs/aster-std/src/syscall/waitid.rs
+++ b/services/libs/aster-std/src/syscall/waitid.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::process::{wait_child_exit, ProcessFilter};
use crate::{log_syscall_entry, prelude::*};
diff --git a/services/libs/aster-std/src/syscall/write.rs b/services/libs/aster-std/src/syscall/write.rs
--- a/services/libs/aster-std/src/syscall/write.rs
+++ b/services/libs/aster-std/src/syscall/write.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::{log_syscall_entry, prelude::*};
diff --git a/services/libs/aster-std/src/syscall/write.rs b/services/libs/aster-std/src/syscall/write.rs
--- a/services/libs/aster-std/src/syscall/write.rs
+++ b/services/libs/aster-std/src/syscall/write.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::{log_syscall_entry, prelude::*};
diff --git a/services/libs/aster-std/src/syscall/writev.rs b/services/libs/aster-std/src/syscall/writev.rs
--- a/services/libs/aster-std/src/syscall/writev.rs
+++ b/services/libs/aster-std/src/syscall/writev.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::{log_syscall_entry, prelude::*};
diff --git a/services/libs/aster-std/src/syscall/writev.rs b/services/libs/aster-std/src/syscall/writev.rs
--- a/services/libs/aster-std/src/syscall/writev.rs
+++ b/services/libs/aster-std/src/syscall/writev.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::fs::file_table::FileDescripter;
use crate::{log_syscall_entry, prelude::*};
diff --git a/services/libs/aster-std/src/thread/exception.rs b/services/libs/aster-std/src/thread/exception.rs
--- a/services/libs/aster-std/src/thread/exception.rs
+++ b/services/libs/aster-std/src/thread/exception.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use crate::process::signal::signals::fault::FaultSignal;
use crate::vm::page_fault_handler::PageFaultHandler;
diff --git a/services/libs/aster-std/src/thread/exception.rs b/services/libs/aster-std/src/thread/exception.rs
--- a/services/libs/aster-std/src/thread/exception.rs
+++ b/services/libs/aster-std/src/thread/exception.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use crate::process::signal::signals::fault::FaultSignal;
use crate::vm::page_fault_handler::PageFaultHandler;
diff --git a/services/libs/aster-std/src/thread/kernel_thread.rs b/services/libs/aster-std/src/thread/kernel_thread.rs
--- a/services/libs/aster-std/src/thread/kernel_thread.rs
+++ b/services/libs/aster-std/src/thread/kernel_thread.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::cpu::CpuSet;
use aster_frame::task::{Priority, TaskOptions};
diff --git a/services/libs/aster-std/src/thread/kernel_thread.rs b/services/libs/aster-std/src/thread/kernel_thread.rs
--- a/services/libs/aster-std/src/thread/kernel_thread.rs
+++ b/services/libs/aster-std/src/thread/kernel_thread.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::cpu::CpuSet;
use aster_frame::task::{Priority, TaskOptions};
diff --git a/services/libs/aster-std/src/thread/mod.rs b/services/libs/aster-std/src/thread/mod.rs
--- a/services/libs/aster-std/src/thread/mod.rs
+++ b/services/libs/aster-std/src/thread/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Posix thread implementation
use core::{
diff --git a/services/libs/aster-std/src/thread/mod.rs b/services/libs/aster-std/src/thread/mod.rs
--- a/services/libs/aster-std/src/thread/mod.rs
+++ b/services/libs/aster-std/src/thread/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Posix thread implementation
use core::{
diff --git a/services/libs/aster-std/src/thread/status.rs b/services/libs/aster-std/src/thread/status.rs
--- a/services/libs/aster-std/src/thread/status.rs
+++ b/services/libs/aster-std/src/thread/status.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum ThreadStatus {
Init,
diff --git a/services/libs/aster-std/src/thread/status.rs b/services/libs/aster-std/src/thread/status.rs
--- a/services/libs/aster-std/src/thread/status.rs
+++ b/services/libs/aster-std/src/thread/status.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum ThreadStatus {
Init,
diff --git a/services/libs/aster-std/src/thread/task.rs b/services/libs/aster-std/src/thread/task.rs
--- a/services/libs/aster-std/src/thread/task.rs
+++ b/services/libs/aster-std/src/thread/task.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::{
cpu::UserContext,
task::{preempt, Task, TaskOptions},
diff --git a/services/libs/aster-std/src/thread/task.rs b/services/libs/aster-std/src/thread/task.rs
--- a/services/libs/aster-std/src/thread/task.rs
+++ b/services/libs/aster-std/src/thread/task.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::{
cpu::UserContext,
task::{preempt, Task, TaskOptions},
diff --git a/services/libs/aster-std/src/thread/thread_table.rs b/services/libs/aster-std/src/thread/thread_table.rs
--- a/services/libs/aster-std/src/thread/thread_table.rs
+++ b/services/libs/aster-std/src/thread/thread_table.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use super::{Thread, Tid};
diff --git a/services/libs/aster-std/src/thread/thread_table.rs b/services/libs/aster-std/src/thread/thread_table.rs
--- a/services/libs/aster-std/src/thread/thread_table.rs
+++ b/services/libs/aster-std/src/thread/thread_table.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use super::{Thread, Tid};
diff --git a/services/libs/aster-std/src/thread/work_queue/mod.rs b/services/libs/aster-std/src/thread/work_queue/mod.rs
--- a/services/libs/aster-std/src/thread/work_queue/mod.rs
+++ b/services/libs/aster-std/src/thread/work_queue/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use aster_frame::cpu::CpuSet;
use spin::Once;
diff --git a/services/libs/aster-std/src/thread/work_queue/mod.rs b/services/libs/aster-std/src/thread/work_queue/mod.rs
--- a/services/libs/aster-std/src/thread/work_queue/mod.rs
+++ b/services/libs/aster-std/src/thread/work_queue/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use aster_frame::cpu::CpuSet;
use spin::Once;
diff --git a/services/libs/aster-std/src/thread/work_queue/simple_scheduler.rs b/services/libs/aster-std/src/thread/work_queue/simple_scheduler.rs
--- a/services/libs/aster-std/src/thread/work_queue/simple_scheduler.rs
+++ b/services/libs/aster-std/src/thread/work_queue/simple_scheduler.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::sync::Weak;
use super::worker_pool::{WorkerPool, WorkerScheduler};
diff --git a/services/libs/aster-std/src/thread/work_queue/simple_scheduler.rs b/services/libs/aster-std/src/thread/work_queue/simple_scheduler.rs
--- a/services/libs/aster-std/src/thread/work_queue/simple_scheduler.rs
+++ b/services/libs/aster-std/src/thread/work_queue/simple_scheduler.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::sync::Weak;
use super::worker_pool::{WorkerPool, WorkerScheduler};
diff --git a/services/libs/aster-std/src/thread/work_queue/work_item.rs b/services/libs/aster-std/src/thread/work_queue/work_item.rs
--- a/services/libs/aster-std/src/thread/work_queue/work_item.rs
+++ b/services/libs/aster-std/src/thread/work_queue/work_item.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use aster_frame::cpu::CpuSet;
use core::sync::atomic::AtomicBool;
diff --git a/services/libs/aster-std/src/thread/work_queue/work_item.rs b/services/libs/aster-std/src/thread/work_queue/work_item.rs
--- a/services/libs/aster-std/src/thread/work_queue/work_item.rs
+++ b/services/libs/aster-std/src/thread/work_queue/work_item.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use aster_frame::cpu::CpuSet;
use core::sync::atomic::AtomicBool;
diff --git a/services/libs/aster-std/src/thread/work_queue/worker.rs b/services/libs/aster-std/src/thread/work_queue/worker.rs
--- a/services/libs/aster-std/src/thread/work_queue/worker.rs
+++ b/services/libs/aster-std/src/thread/work_queue/worker.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::worker_pool::WorkerPool;
use crate::prelude::*;
use crate::thread::kernel_thread::{KernelThreadExt, ThreadOptions};
diff --git a/services/libs/aster-std/src/thread/work_queue/worker.rs b/services/libs/aster-std/src/thread/work_queue/worker.rs
--- a/services/libs/aster-std/src/thread/work_queue/worker.rs
+++ b/services/libs/aster-std/src/thread/work_queue/worker.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::worker_pool::WorkerPool;
use crate::prelude::*;
use crate::thread::kernel_thread::{KernelThreadExt, ThreadOptions};
diff --git a/services/libs/aster-std/src/thread/work_queue/worker_pool.rs b/services/libs/aster-std/src/thread/work_queue/worker_pool.rs
--- a/services/libs/aster-std/src/thread/work_queue/worker_pool.rs
+++ b/services/libs/aster-std/src/thread/work_queue/worker_pool.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicBool, Ordering};
use super::{simple_scheduler::SimpleScheduler, worker::Worker, WorkItem, WorkPriority, WorkQueue};
diff --git a/services/libs/aster-std/src/thread/work_queue/worker_pool.rs b/services/libs/aster-std/src/thread/work_queue/worker_pool.rs
--- a/services/libs/aster-std/src/thread/work_queue/worker_pool.rs
+++ b/services/libs/aster-std/src/thread/work_queue/worker_pool.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::sync::atomic::{AtomicBool, Ordering};
use super::{simple_scheduler::SimpleScheduler, worker::Worker, WorkItem, WorkPriority, WorkQueue};
diff --git a/services/libs/aster-std/src/time/mod.rs b/services/libs/aster-std/src/time/mod.rs
--- a/services/libs/aster-std/src/time/mod.rs
+++ b/services/libs/aster-std/src/time/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#![allow(non_camel_case_types)]
use core::time::Duration;
diff --git a/services/libs/aster-std/src/time/mod.rs b/services/libs/aster-std/src/time/mod.rs
--- a/services/libs/aster-std/src/time/mod.rs
+++ b/services/libs/aster-std/src/time/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
#![allow(non_camel_case_types)]
use core::time::Duration;
diff --git a/services/libs/aster-std/src/time/system_time.rs b/services/libs/aster-std/src/time/system_time.rs
--- a/services/libs/aster-std/src/time/system_time.rs
+++ b/services/libs/aster-std/src/time/system_time.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_time::{read_monotonic_time, read_start_time};
use core::time::Duration;
use time::{Date, Month, PrimitiveDateTime, Time};
diff --git a/services/libs/aster-std/src/time/system_time.rs b/services/libs/aster-std/src/time/system_time.rs
--- a/services/libs/aster-std/src/time/system_time.rs
+++ b/services/libs/aster-std/src/time/system_time.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_time::{read_monotonic_time, read_start_time};
use core::time::Duration;
use time::{Date, Month, PrimitiveDateTime, Time};
diff --git a/services/libs/aster-std/src/util/mod.rs b/services/libs/aster-std/src/util/mod.rs
--- a/services/libs/aster-std/src/util/mod.rs
+++ b/services/libs/aster-std/src/util/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use aster_frame::vm::VmIo;
pub mod net;
diff --git a/services/libs/aster-std/src/util/mod.rs b/services/libs/aster-std/src/util/mod.rs
--- a/services/libs/aster-std/src/util/mod.rs
+++ b/services/libs/aster-std/src/util/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use aster_frame::vm::VmIo;
pub mod net;
diff --git a/services/libs/aster-std/src/util/net/addr.rs b/services/libs/aster-std/src/util/net/addr.rs
--- a/services/libs/aster-std/src/util/net/addr.rs
+++ b/services/libs/aster-std/src/util/net/addr.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::net::iface::Ipv4Address;
use crate::net::socket::unix::UnixSocketAddr;
use crate::net::socket::SocketAddr;
diff --git a/services/libs/aster-std/src/util/net/addr.rs b/services/libs/aster-std/src/util/net/addr.rs
--- a/services/libs/aster-std/src/util/net/addr.rs
+++ b/services/libs/aster-std/src/util/net/addr.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::net::iface::Ipv4Address;
use crate::net::socket::unix::UnixSocketAddr;
use crate::net::socket::SocketAddr;
diff --git a/services/libs/aster-std/src/util/net/mod.rs b/services/libs/aster-std/src/util/net/mod.rs
--- a/services/libs/aster-std/src/util/net/mod.rs
+++ b/services/libs/aster-std/src/util/net/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod addr;
mod options;
mod socket;
diff --git a/services/libs/aster-std/src/util/net/mod.rs b/services/libs/aster-std/src/util/net/mod.rs
--- a/services/libs/aster-std/src/util/net/mod.rs
+++ b/services/libs/aster-std/src/util/net/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
mod addr;
mod options;
mod socket;
diff --git a/services/libs/aster-std/src/util/net/options/mod.rs b/services/libs/aster-std/src/util/net/options/mod.rs
--- a/services/libs/aster-std/src/util/net/options/mod.rs
+++ b/services/libs/aster-std/src/util/net/options/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! This module introduces utilities to support Linux get/setsockopt syscalls.
//!
//! These two syscalls are used to get/set options for a socket. These options can be at different
diff --git a/services/libs/aster-std/src/util/net/options/mod.rs b/services/libs/aster-std/src/util/net/options/mod.rs
--- a/services/libs/aster-std/src/util/net/options/mod.rs
+++ b/services/libs/aster-std/src/util/net/options/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! This module introduces utilities to support Linux get/setsockopt syscalls.
//!
//! These two syscalls are used to get/set options for a socket. These options can be at different
diff --git a/services/libs/aster-std/src/util/net/options/socket.rs b/services/libs/aster-std/src/util/net/options/socket.rs
--- a/services/libs/aster-std/src/util/net/options/socket.rs
+++ b/services/libs/aster-std/src/util/net/options/socket.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::RawSocketOption;
use crate::net::socket::options::{
Error, Linger, RecvBuf, ReuseAddr, ReusePort, SendBuf, SocketOption,
diff --git a/services/libs/aster-std/src/util/net/options/socket.rs b/services/libs/aster-std/src/util/net/options/socket.rs
--- a/services/libs/aster-std/src/util/net/options/socket.rs
+++ b/services/libs/aster-std/src/util/net/options/socket.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::RawSocketOption;
use crate::net::socket::options::{
Error, Linger, RecvBuf, ReuseAddr, ReusePort, SendBuf, SocketOption,
diff --git a/services/libs/aster-std/src/util/net/options/tcp.rs b/services/libs/aster-std/src/util/net/options/tcp.rs
--- a/services/libs/aster-std/src/util/net/options/tcp.rs
+++ b/services/libs/aster-std/src/util/net/options/tcp.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::RawSocketOption;
use crate::impl_raw_socket_option;
use crate::net::socket::ip::stream::options::{Congestion, MaxSegment, NoDelay, WindowClamp};
diff --git a/services/libs/aster-std/src/util/net/options/tcp.rs b/services/libs/aster-std/src/util/net/options/tcp.rs
--- a/services/libs/aster-std/src/util/net/options/tcp.rs
+++ b/services/libs/aster-std/src/util/net/options/tcp.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::RawSocketOption;
use crate::impl_raw_socket_option;
use crate::net::socket::ip::stream::options::{Congestion, MaxSegment, NoDelay, WindowClamp};
diff --git a/services/libs/aster-std/src/util/net/options/utils.rs b/services/libs/aster-std/src/util/net/options/utils.rs
--- a/services/libs/aster-std/src/util/net/options/utils.rs
+++ b/services/libs/aster-std/src/util/net/options/utils.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::net::socket::ip::stream::CongestionControl;
use crate::net::socket::LingerOption;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/util/net/options/utils.rs b/services/libs/aster-std/src/util/net/options/utils.rs
--- a/services/libs/aster-std/src/util/net/options/utils.rs
+++ b/services/libs/aster-std/src/util/net/options/utils.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::net::socket::ip::stream::CongestionControl;
use crate::net::socket::LingerOption;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/util/net/socket.rs b/services/libs/aster-std/src/util/net/socket.rs
--- a/services/libs/aster-std/src/util/net/socket.rs
+++ b/services/libs/aster-std/src/util/net/socket.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
/// Standard well-defined IP protocols.
diff --git a/services/libs/aster-std/src/util/net/socket.rs b/services/libs/aster-std/src/util/net/socket.rs
--- a/services/libs/aster-std/src/util/net/socket.rs
+++ b/services/libs/aster-std/src/util/net/socket.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
/// Standard well-defined IP protocols.
diff --git a/services/libs/aster-std/src/vdso.rs b/services/libs/aster-std/src/vdso.rs
--- a/services/libs/aster-std/src/vdso.rs
+++ b/services/libs/aster-std/src/vdso.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The Virtual Dynamic Shared Object (VDSO) module enables user space applications to access kernel space routines
//! without the need for context switching. This is particularly useful for frequently invoked operations such as
//! obtaining the current time, which can be more efficiently handled within the user space.
diff --git a/services/libs/aster-std/src/vdso.rs b/services/libs/aster-std/src/vdso.rs
--- a/services/libs/aster-std/src/vdso.rs
+++ b/services/libs/aster-std/src/vdso.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The Virtual Dynamic Shared Object (VDSO) module enables user space applications to access kernel space routines
//! without the need for context switching. This is particularly useful for frequently invoked operations such as
//! obtaining the current time, which can be more efficiently handled within the user space.
diff --git a/services/libs/aster-std/src/vm/mod.rs b/services/libs/aster-std/src/vm/mod.rs
--- a/services/libs/aster-std/src/vm/mod.rs
+++ b/services/libs/aster-std/src/vm/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Virtual memory (VM).
//!
//! There are two primary VM abstractions:
diff --git a/services/libs/aster-std/src/vm/mod.rs b/services/libs/aster-std/src/vm/mod.rs
--- a/services/libs/aster-std/src/vm/mod.rs
+++ b/services/libs/aster-std/src/vm/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Virtual memory (VM).
//!
//! There are two primary VM abstractions:
diff --git a/services/libs/aster-std/src/vm/page_fault_handler.rs b/services/libs/aster-std/src/vm/page_fault_handler.rs
--- a/services/libs/aster-std/src/vm/page_fault_handler.rs
+++ b/services/libs/aster-std/src/vm/page_fault_handler.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
/// This trait is implemented by structs which can handle a user space page fault.
diff --git a/services/libs/aster-std/src/vm/page_fault_handler.rs b/services/libs/aster-std/src/vm/page_fault_handler.rs
--- a/services/libs/aster-std/src/vm/page_fault_handler.rs
+++ b/services/libs/aster-std/src/vm/page_fault_handler.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
/// This trait is implemented by structs which can handle a user space page fault.
diff --git a/services/libs/aster-std/src/vm/perms.rs b/services/libs/aster-std/src/vm/perms.rs
--- a/services/libs/aster-std/src/vm/perms.rs
+++ b/services/libs/aster-std/src/vm/perms.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::vm::VmPerm;
use aster_rights::Rights;
use bitflags::bitflags;
diff --git a/services/libs/aster-std/src/vm/perms.rs b/services/libs/aster-std/src/vm/perms.rs
--- a/services/libs/aster-std/src/vm/perms.rs
+++ b/services/libs/aster-std/src/vm/perms.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::vm::VmPerm;
use aster_rights::Rights;
use bitflags::bitflags;
diff --git a/services/libs/aster-std/src/vm/vmar/dyn_cap.rs b/services/libs/aster-std/src/vm/vmar/dyn_cap.rs
--- a/services/libs/aster-std/src/vm/vmar/dyn_cap.rs
+++ b/services/libs/aster-std/src/vm/vmar/dyn_cap.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::vm::{Vaddr, VmIo};
use aster_rights::Rights;
use core::ops::Range;
diff --git a/services/libs/aster-std/src/vm/vmar/dyn_cap.rs b/services/libs/aster-std/src/vm/vmar/dyn_cap.rs
--- a/services/libs/aster-std/src/vm/vmar/dyn_cap.rs
+++ b/services/libs/aster-std/src/vm/vmar/dyn_cap.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::vm::{Vaddr, VmIo};
use aster_rights::Rights;
use core::ops::Range;
diff --git a/services/libs/aster-std/src/vm/vmar/mod.rs b/services/libs/aster-std/src/vm/vmar/mod.rs
--- a/services/libs/aster-std/src/vm/vmar/mod.rs
+++ b/services/libs/aster-std/src/vm/vmar/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Virtual Memory Address Regions (VMARs).
mod dyn_cap;
diff --git a/services/libs/aster-std/src/vm/vmar/mod.rs b/services/libs/aster-std/src/vm/vmar/mod.rs
--- a/services/libs/aster-std/src/vm/vmar/mod.rs
+++ b/services/libs/aster-std/src/vm/vmar/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Virtual Memory Address Regions (VMARs).
mod dyn_cap;
diff --git a/services/libs/aster-std/src/vm/vmar/options.rs b/services/libs/aster-std/src/vm/vmar/options.rs
--- a/services/libs/aster-std/src/vm/vmar/options.rs
+++ b/services/libs/aster-std/src/vm/vmar/options.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Options for allocating child VMARs.
use aster_frame::config::PAGE_SIZE;
diff --git a/services/libs/aster-std/src/vm/vmar/options.rs b/services/libs/aster-std/src/vm/vmar/options.rs
--- a/services/libs/aster-std/src/vm/vmar/options.rs
+++ b/services/libs/aster-std/src/vm/vmar/options.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Options for allocating child VMARs.
use aster_frame::config::PAGE_SIZE;
diff --git a/services/libs/aster-std/src/vm/vmar/static_cap.rs b/services/libs/aster-std/src/vm/vmar/static_cap.rs
--- a/services/libs/aster-std/src/vm/vmar/static_cap.rs
+++ b/services/libs/aster-std/src/vm/vmar/static_cap.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::ops::Range;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/vm/vmar/static_cap.rs b/services/libs/aster-std/src/vm/vmar/static_cap.rs
--- a/services/libs/aster-std/src/vm/vmar/static_cap.rs
+++ b/services/libs/aster-std/src/vm/vmar/static_cap.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::ops::Range;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/vm/vmar/vm_mapping.rs b/services/libs/aster-std/src/vm/vmar/vm_mapping.rs
--- a/services/libs/aster-std/src/vm/vmar/vm_mapping.rs
+++ b/services/libs/aster-std/src/vm/vmar/vm_mapping.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use aster_frame::sync::Mutex;
use aster_frame::vm::{VmFrame, VmFrameVec, VmIo, VmMapOptions, VmPerm, VmSpace};
diff --git a/services/libs/aster-std/src/vm/vmar/vm_mapping.rs b/services/libs/aster-std/src/vm/vmar/vm_mapping.rs
--- a/services/libs/aster-std/src/vm/vmar/vm_mapping.rs
+++ b/services/libs/aster-std/src/vm/vmar/vm_mapping.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use aster_frame::sync::Mutex;
use aster_frame::vm::{VmFrame, VmFrameVec, VmIo, VmMapOptions, VmPerm, VmSpace};
diff --git a/services/libs/aster-std/src/vm/vmo/dyn_cap.rs b/services/libs/aster-std/src/vm/vmo/dyn_cap.rs
--- a/services/libs/aster-std/src/vm/vmo/dyn_cap.rs
+++ b/services/libs/aster-std/src/vm/vmo/dyn_cap.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::ops::Range;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/vm/vmo/dyn_cap.rs b/services/libs/aster-std/src/vm/vmo/dyn_cap.rs
--- a/services/libs/aster-std/src/vm/vmo/dyn_cap.rs
+++ b/services/libs/aster-std/src/vm/vmo/dyn_cap.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::ops::Range;
use crate::prelude::*;
diff --git a/services/libs/aster-std/src/vm/vmo/mod.rs b/services/libs/aster-std/src/vm/vmo/mod.rs
--- a/services/libs/aster-std/src/vm/vmo/mod.rs
+++ b/services/libs/aster-std/src/vm/vmo/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Virtual Memory Objects (VMOs).
use core::ops::Range;
diff --git a/services/libs/aster-std/src/vm/vmo/mod.rs b/services/libs/aster-std/src/vm/vmo/mod.rs
--- a/services/libs/aster-std/src/vm/vmo/mod.rs
+++ b/services/libs/aster-std/src/vm/vmo/mod.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Virtual Memory Objects (VMOs).
use core::ops::Range;
diff --git a/services/libs/aster-std/src/vm/vmo/options.rs b/services/libs/aster-std/src/vm/vmo/options.rs
--- a/services/libs/aster-std/src/vm/vmo/options.rs
+++ b/services/libs/aster-std/src/vm/vmo/options.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Options for allocating root and child VMOs.
use core::marker::PhantomData;
diff --git a/services/libs/aster-std/src/vm/vmo/options.rs b/services/libs/aster-std/src/vm/vmo/options.rs
--- a/services/libs/aster-std/src/vm/vmo/options.rs
+++ b/services/libs/aster-std/src/vm/vmo/options.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Options for allocating root and child VMOs.
use core::marker::PhantomData;
diff --git a/services/libs/aster-std/src/vm/vmo/pager.rs b/services/libs/aster-std/src/vm/vmo/pager.rs
--- a/services/libs/aster-std/src/vm/vmo/pager.rs
+++ b/services/libs/aster-std/src/vm/vmo/pager.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use aster_frame::vm::VmFrame;
diff --git a/services/libs/aster-std/src/vm/vmo/pager.rs b/services/libs/aster-std/src/vm/vmo/pager.rs
--- a/services/libs/aster-std/src/vm/vmo/pager.rs
+++ b/services/libs/aster-std/src/vm/vmo/pager.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use aster_frame::vm::VmFrame;
diff --git a/services/libs/aster-std/src/vm/vmo/static_cap.rs b/services/libs/aster-std/src/vm/vmo/static_cap.rs
--- a/services/libs/aster-std/src/vm/vmo/static_cap.rs
+++ b/services/libs/aster-std/src/vm/vmo/static_cap.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use aster_frame::vm::VmIo;
use aster_rights_proc::require;
diff --git a/services/libs/aster-std/src/vm/vmo/static_cap.rs b/services/libs/aster-std/src/vm/vmo/static_cap.rs
--- a/services/libs/aster-std/src/vm/vmo/static_cap.rs
+++ b/services/libs/aster-std/src/vm/vmo/static_cap.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::prelude::*;
use aster_frame::vm::VmIo;
use aster_rights_proc::require;
diff --git a/services/libs/aster-util/src/coeff.rs b/services/libs/aster-util/src/coeff.rs
--- a/services/libs/aster-util/src/coeff.rs
+++ b/services/libs/aster-util/src/coeff.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! This module provides an abstraction `Coeff` to server for efficient and accurate calculation
//! of fraction multiplication.
diff --git a/services/libs/aster-util/src/coeff.rs b/services/libs/aster-util/src/coeff.rs
--- a/services/libs/aster-util/src/coeff.rs
+++ b/services/libs/aster-util/src/coeff.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! This module provides an abstraction `Coeff` to server for efficient and accurate calculation
//! of fraction multiplication.
diff --git a/services/libs/aster-util/src/dup.rs b/services/libs/aster-util/src/dup.rs
--- a/services/libs/aster-util/src/dup.rs
+++ b/services/libs/aster-util/src/dup.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
/// This trait is a _fallible_ version of `Clone`.
///
/// If any object of a type `T` is duplicable, then `T` should implement
diff --git a/services/libs/aster-util/src/dup.rs b/services/libs/aster-util/src/dup.rs
--- a/services/libs/aster-util/src/dup.rs
+++ b/services/libs/aster-util/src/dup.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
/// This trait is a _fallible_ version of `Clone`.
///
/// If any object of a type `T` is duplicable, then `T` should implement
diff --git a/services/libs/aster-util/src/id_allocator.rs b/services/libs/aster-util/src/id_allocator.rs
--- a/services/libs/aster-util/src/id_allocator.rs
+++ b/services/libs/aster-util/src/id_allocator.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use bitvec::prelude::BitVec;
use core::fmt::Debug;
diff --git a/services/libs/aster-util/src/id_allocator.rs b/services/libs/aster-util/src/id_allocator.rs
--- a/services/libs/aster-util/src/id_allocator.rs
+++ b/services/libs/aster-util/src/id_allocator.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use bitvec::prelude::BitVec;
use core::fmt::Debug;
diff --git a/services/libs/aster-util/src/lib.rs b/services/libs/aster-util/src/lib.rs
--- a/services/libs/aster-util/src/lib.rs
+++ b/services/libs/aster-util/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The util of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
diff --git a/services/libs/aster-util/src/lib.rs b/services/libs/aster-util/src/lib.rs
--- a/services/libs/aster-util/src/lib.rs
+++ b/services/libs/aster-util/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The util of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
diff --git a/services/libs/aster-util/src/safe_ptr.rs b/services/libs/aster-util/src/safe_ptr.rs
--- a/services/libs/aster-util/src/safe_ptr.rs
+++ b/services/libs/aster-util/src/safe_ptr.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::vm::Paddr;
use aster_frame::vm::{HasPaddr, VmIo};
use aster_frame::Result;
diff --git a/services/libs/aster-util/src/safe_ptr.rs b/services/libs/aster-util/src/safe_ptr.rs
--- a/services/libs/aster-util/src/safe_ptr.rs
+++ b/services/libs/aster-util/src/safe_ptr.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use aster_frame::vm::Paddr;
use aster_frame::vm::{HasPaddr, VmIo};
use aster_frame::Result;
diff --git a/services/libs/aster-util/src/slot_vec.rs b/services/libs/aster-util/src/slot_vec.rs
--- a/services/libs/aster-util/src/slot_vec.rs
+++ b/services/libs/aster-util/src/slot_vec.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::vec::Vec;
/// SlotVec is the variant of Vector.
diff --git a/services/libs/aster-util/src/slot_vec.rs b/services/libs/aster-util/src/slot_vec.rs
--- a/services/libs/aster-util/src/slot_vec.rs
+++ b/services/libs/aster-util/src/slot_vec.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use alloc::vec::Vec;
/// SlotVec is the variant of Vector.
diff --git a/services/libs/aster-util/src/union_read_ptr.rs b/services/libs/aster-util/src/union_read_ptr.rs
--- a/services/libs/aster-util/src/union_read_ptr.rs
+++ b/services/libs/aster-util/src/union_read_ptr.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::marker::PhantomData;
use pod::Pod;
diff --git a/services/libs/aster-util/src/union_read_ptr.rs b/services/libs/aster-util/src/union_read_ptr.rs
--- a/services/libs/aster-util/src/union_read_ptr.rs
+++ b/services/libs/aster-util/src/union_read_ptr.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use core::marker::PhantomData;
use pod::Pod;
diff --git a/services/libs/comp-sys/cargo-component/analysis/src/conf.rs b/services/libs/comp-sys/cargo-component/analysis/src/conf.rs
--- a/services/libs/comp-sys/cargo-component/analysis/src/conf.rs
+++ b/services/libs/comp-sys/cargo-component/analysis/src/conf.rs
@@ -1,3 +1,6 @@
+// Licensed under the Apache License, Version 2.0 or the MIT License.
+// Copyright (C) 2023-2024 Ant Group.
+
use std::collections::{BTreeMap, HashSet};
use std::{env, fs, io, path::PathBuf};
diff --git a/services/libs/comp-sys/cargo-component/analysis/src/conf.rs b/services/libs/comp-sys/cargo-component/analysis/src/conf.rs
--- a/services/libs/comp-sys/cargo-component/analysis/src/conf.rs
+++ b/services/libs/comp-sys/cargo-component/analysis/src/conf.rs
@@ -1,3 +1,6 @@
+// Licensed under the Apache License, Version 2.0 or the MIT License.
+// Copyright (C) 2023-2024 Ant Group.
+
use std::collections::{BTreeMap, HashSet};
use std::{env, fs, io, path::PathBuf};
diff --git a/services/libs/comp-sys/cargo-component/analysis/src/lib.rs b/services/libs/comp-sys/cargo-component/analysis/src/lib.rs
--- a/services/libs/comp-sys/cargo-component/analysis/src/lib.rs
+++ b/services/libs/comp-sys/cargo-component/analysis/src/lib.rs
@@ -1,3 +1,6 @@
+// Licensed under the Apache License, Version 2.0 or the MIT License.
+// Copyright (C) 2023-2024 Ant Group.
+
#![feature(rustc_private)]
extern crate rustc_ast;
diff --git a/services/libs/comp-sys/cargo-component/analysis/src/lib.rs b/services/libs/comp-sys/cargo-component/analysis/src/lib.rs
--- a/services/libs/comp-sys/cargo-component/analysis/src/lib.rs
+++ b/services/libs/comp-sys/cargo-component/analysis/src/lib.rs
@@ -1,3 +1,6 @@
+// Licensed under the Apache License, Version 2.0 or the MIT License.
+// Copyright (C) 2023-2024 Ant Group.
+
#![feature(rustc_private)]
extern crate rustc_ast;
diff --git a/services/libs/comp-sys/cargo-component/build.rs b/services/libs/comp-sys/cargo-component/build.rs
--- a/services/libs/comp-sys/cargo-component/build.rs
+++ b/services/libs/comp-sys/cargo-component/build.rs
@@ -1,4 +1,7 @@
-//! This implementation is from rust-clippy
+// Licensed under the Apache License, Version 2.0 or the MIT License.
+// Copyright (C) 2023-2024 Ant Group.
+
+// This implementation is from rust clippy. We modified the code.
fn main() {
// Forward the profile to the main compilation
diff --git a/services/libs/comp-sys/cargo-component/build.rs b/services/libs/comp-sys/cargo-component/build.rs
--- a/services/libs/comp-sys/cargo-component/build.rs
+++ b/services/libs/comp-sys/cargo-component/build.rs
@@ -1,4 +1,7 @@
-//! This implementation is from rust-clippy
+// Licensed under the Apache License, Version 2.0 or the MIT License.
+// Copyright (C) 2023-2024 Ant Group.
+
+// This implementation is from rust clippy. We modified the code.
fn main() {
// Forward the profile to the main compilation
diff --git a/services/libs/comp-sys/cargo-component/src/driver.rs b/services/libs/comp-sys/cargo-component/src/driver.rs
--- a/services/libs/comp-sys/cargo-component/src/driver.rs
+++ b/services/libs/comp-sys/cargo-component/src/driver.rs
@@ -1,7 +1,8 @@
-//! Licensed under the Apache License, Version 2.0 or the MIT License.
-//! Copyright (C) 2023 Ant Group.
+// Licensed under the Apache License, Version 2.0 or the MIT License.
+// Copyright (C) 2023-2024 Ant Group.
+
+// This implementation is from rust clippy. We modified the code.
-//! This implementation is from rust clippy. We modified the code.
#![feature(rustc_private)]
#![feature(once_cell)]
diff --git a/services/libs/comp-sys/cargo-component/src/driver.rs b/services/libs/comp-sys/cargo-component/src/driver.rs
--- a/services/libs/comp-sys/cargo-component/src/driver.rs
+++ b/services/libs/comp-sys/cargo-component/src/driver.rs
@@ -1,7 +1,8 @@
-//! Licensed under the Apache License, Version 2.0 or the MIT License.
-//! Copyright (C) 2023 Ant Group.
+// Licensed under the Apache License, Version 2.0 or the MIT License.
+// Copyright (C) 2023-2024 Ant Group.
+
+// This implementation is from rust clippy. We modified the code.
-//! This implementation is from rust clippy. We modified the code.
#![feature(rustc_private)]
#![feature(once_cell)]
diff --git a/services/libs/comp-sys/cargo-component/src/main.rs b/services/libs/comp-sys/cargo-component/src/main.rs
--- a/services/libs/comp-sys/cargo-component/src/main.rs
+++ b/services/libs/comp-sys/cargo-component/src/main.rs
@@ -1,7 +1,7 @@
-//! Licensed under the Apache License, Version 2.0 or the MIT License.
-//! Copyright (C) 2023 Ant Group.
+// Licensed under the Apache License, Version 2.0 or the MIT License.
+// Copyright (C) 2023-2024 Ant Group.
-//! This implementation is from rust clippy. We modified the code.
+// This implementation is from rust clippy. We modified the code.
use std::env;
use std::path::PathBuf;
diff --git a/services/libs/comp-sys/cargo-component/src/main.rs b/services/libs/comp-sys/cargo-component/src/main.rs
--- a/services/libs/comp-sys/cargo-component/src/main.rs
+++ b/services/libs/comp-sys/cargo-component/src/main.rs
@@ -1,7 +1,7 @@
-//! Licensed under the Apache License, Version 2.0 or the MIT License.
-//! Copyright (C) 2023 Ant Group.
+// Licensed under the Apache License, Version 2.0 or the MIT License.
+// Copyright (C) 2023-2024 Ant Group.
-//! This implementation is from rust clippy. We modified the code.
+// This implementation is from rust clippy. We modified the code.
use std::env;
use std::path::PathBuf;
diff --git a/services/libs/comp-sys/cargo-component/tests/duplicate_lib_name.rs b/services/libs/comp-sys/cargo-component/tests/duplicate_lib_name.rs
--- a/services/libs/comp-sys/cargo-component/tests/duplicate_lib_name.rs
+++ b/services/libs/comp-sys/cargo-component/tests/duplicate_lib_name.rs
@@ -1,3 +1,6 @@
+// Licensed under the Apache License, Version 2.0 or the MIT License.
+// Copyright (C) 2023-2024 Ant Group.
+
//! This test checks that if two components have same name, the compiler will panic.
#![feature(once_cell)]
diff --git a/services/libs/comp-sys/cargo-component/tests/missing_toml.rs b/services/libs/comp-sys/cargo-component/tests/missing_toml.rs
--- a/services/libs/comp-sys/cargo-component/tests/missing_toml.rs
+++ b/services/libs/comp-sys/cargo-component/tests/missing_toml.rs
@@ -1,3 +1,6 @@
+// Licensed under the Apache License, Version 2.0 or the MIT License.
+// Copyright (C) 2023-2024 Ant Group.
+
//! This test checks that if Components.toml is missed, the compiler will panic.
#![feature(once_cell)]
diff --git a/services/libs/comp-sys/cargo-component/tests/reexport.rs b/services/libs/comp-sys/cargo-component/tests/reexport.rs
--- a/services/libs/comp-sys/cargo-component/tests/reexport.rs
+++ b/services/libs/comp-sys/cargo-component/tests/reexport.rs
@@ -1,3 +1,6 @@
+// Licensed under the Apache License, Version 2.0 or the MIT License.
+// Copyright (C) 2023-2024 Ant Group.
+
//! This test checks that if cargo-component can control reexported entry points.
#![feature(once_cell)]
diff --git a/services/libs/comp-sys/cargo-component/tests/regression.rs b/services/libs/comp-sys/cargo-component/tests/regression.rs
--- a/services/libs/comp-sys/cargo-component/tests/regression.rs
+++ b/services/libs/comp-sys/cargo-component/tests/regression.rs
@@ -1,3 +1,6 @@
+// Licensed under the Apache License, Version 2.0 or the MIT License.
+// Copyright (C) 2023-2024 Ant Group.
+
//! This test checks that visiting controlled resources in whitelist is allowed.
#![feature(once_cell)]
diff --git a/services/libs/comp-sys/cargo-component/tests/test_utils/mod.rs b/services/libs/comp-sys/cargo-component/tests/test_utils/mod.rs
--- a/services/libs/comp-sys/cargo-component/tests/test_utils/mod.rs
+++ b/services/libs/comp-sys/cargo-component/tests/test_utils/mod.rs
@@ -1,3 +1,6 @@
+// Licensed under the Apache License, Version 2.0 or the MIT License.
+// Copyright (C) 2023-2024 Ant Group.
+
#![allow(unused)]
use std::path::PathBuf;
diff --git a/services/libs/comp-sys/cargo-component/tests/trait_method.rs b/services/libs/comp-sys/cargo-component/tests/trait_method.rs
--- a/services/libs/comp-sys/cargo-component/tests/trait_method.rs
+++ b/services/libs/comp-sys/cargo-component/tests/trait_method.rs
@@ -1,3 +1,6 @@
+// Licensed under the Apache License, Version 2.0 or the MIT License.
+// Copyright (C) 2023-2024 Ant Group.
+
//! This test checks that if cargo-component can control method and trait method
#![feature(once_cell)]
diff --git a/services/libs/comp-sys/cargo-component/tests/violate_policy.rs b/services/libs/comp-sys/cargo-component/tests/violate_policy.rs
--- a/services/libs/comp-sys/cargo-component/tests/violate_policy.rs
+++ b/services/libs/comp-sys/cargo-component/tests/violate_policy.rs
@@ -1,4 +1,8 @@
-//! This test checks that if controlled resource not in whitelist is visited, cargo-component will report warning message.
+// Licensed under the Apache License, Version 2.0 or the MIT License.
+// Copyright (C) 2023-2024 Ant Group.
+
+//! This test checks that if controlled resource not in whitelist is visited, cargo-component will
+//! report warning message.
#![feature(once_cell)]
diff --git a/services/libs/comp-sys/component-macro/src/init_comp.rs b/services/libs/comp-sys/component-macro/src/init_comp.rs
--- a/services/libs/comp-sys/component-macro/src/init_comp.rs
+++ b/services/libs/comp-sys/component-macro/src/init_comp.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use proc_macro2::{TokenStream, TokenTree};
use quote::{ToTokens, TokenStreamExt};
use syn::parse::Parse;
diff --git a/services/libs/comp-sys/component-macro/src/init_comp.rs b/services/libs/comp-sys/component-macro/src/init_comp.rs
--- a/services/libs/comp-sys/component-macro/src/init_comp.rs
+++ b/services/libs/comp-sys/component-macro/src/init_comp.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use proc_macro2::{TokenStream, TokenTree};
use quote::{ToTokens, TokenStreamExt};
use syn::parse::Parse;
diff --git a/services/libs/comp-sys/component-macro/src/lib.rs b/services/libs/comp-sys/component-macro/src/lib.rs
--- a/services/libs/comp-sys/component-macro/src/lib.rs
+++ b/services/libs/comp-sys/component-macro/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//!This crate defines the component system related macros.
//!
diff --git a/services/libs/comp-sys/component-macro/src/lib.rs b/services/libs/comp-sys/component-macro/src/lib.rs
--- a/services/libs/comp-sys/component-macro/src/lib.rs
+++ b/services/libs/comp-sys/component-macro/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//!This crate defines the component system related macros.
//!
diff --git a/services/libs/comp-sys/component-macro/src/priority.rs b/services/libs/comp-sys/component-macro/src/priority.rs
--- a/services/libs/comp-sys/component-macro/src/priority.rs
+++ b/services/libs/comp-sys/component-macro/src/priority.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use std::{collections::HashMap, fs::File, io::Read, ops::Add, process::Command, str::FromStr};
use json::JsonValue;
diff --git a/services/libs/comp-sys/component-macro/src/priority.rs b/services/libs/comp-sys/component-macro/src/priority.rs
--- a/services/libs/comp-sys/component-macro/src/priority.rs
+++ b/services/libs/comp-sys/component-macro/src/priority.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use std::{collections::HashMap, fs::File, io::Read, ops::Add, process::Command, str::FromStr};
use json::JsonValue;
diff --git a/services/libs/comp-sys/component/src/lib.rs b/services/libs/comp-sys/component/src/lib.rs
--- a/services/libs/comp-sys/component/src/lib.rs
+++ b/services/libs/comp-sys/component/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Component system
//!
diff --git a/services/libs/comp-sys/component/src/lib.rs b/services/libs/comp-sys/component/src/lib.rs
--- a/services/libs/comp-sys/component/src/lib.rs
+++ b/services/libs/comp-sys/component/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Component system
//!
diff --git a/services/libs/comp-sys/component/tests/init-order/first-init/src/lib.rs b/services/libs/comp-sys/component/tests/init-order/first-init/src/lib.rs
--- a/services/libs/comp-sys/component/tests/init-order/first-init/src/lib.rs
+++ b/services/libs/comp-sys/component/tests/init-order/first-init/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::Relaxed;
diff --git a/services/libs/comp-sys/component/tests/init-order/second-init/src/lib.rs b/services/libs/comp-sys/component/tests/init-order/second-init/src/lib.rs
--- a/services/libs/comp-sys/component/tests/init-order/second-init/src/lib.rs
+++ b/services/libs/comp-sys/component/tests/init-order/second-init/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use std::sync::atomic::{Ordering::Relaxed, AtomicBool};
use component::init_component;
diff --git a/services/libs/comp-sys/component/tests/init-order/second-init/tests/test.rs b/services/libs/comp-sys/component/tests/init-order/second-init/tests/test.rs
--- a/services/libs/comp-sys/component/tests/init-order/second-init/tests/test.rs
+++ b/services/libs/comp-sys/component/tests/init-order/second-init/tests/test.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use second_init::HAS_INIT;
use std::sync::atomic::Ordering::Relaxed;
diff --git a/services/libs/comp-sys/component/tests/init-order/src/main.rs b/services/libs/comp-sys/component/tests/init-order/src/main.rs
--- a/services/libs/comp-sys/component/tests/init-order/src/main.rs
+++ b/services/libs/comp-sys/component/tests/init-order/src/main.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use std::sync::atomic::{Ordering::Relaxed, AtomicBool};
use component::init_component;
diff --git a/services/libs/comp-sys/component/tests/init-order/tests/test.rs b/services/libs/comp-sys/component/tests/init-order/tests/test.rs
--- a/services/libs/comp-sys/component/tests/init-order/tests/test.rs
+++ b/services/libs/comp-sys/component/tests/init-order/tests/test.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use first_init::HAS_INIT;
use component::init_component;
use std::sync::atomic::Ordering::Relaxed;
diff --git a/services/libs/comp-sys/controlled/src/lib.rs b/services/libs/comp-sys/controlled/src/lib.rs
--- a/services/libs/comp-sys/controlled/src/lib.rs
+++ b/services/libs/comp-sys/controlled/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! This crate defines two attribute macros `controlled` and `uncontrolled`.
//! This two macros are attached to functions or static variables to enable crate level access control.
//! To use these two macros, a crate must at first registers a tool named `component_access_control`,
diff --git a/services/libs/comp-sys/controlled/src/lib.rs b/services/libs/comp-sys/controlled/src/lib.rs
--- a/services/libs/comp-sys/controlled/src/lib.rs
+++ b/services/libs/comp-sys/controlled/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! This crate defines two attribute macros `controlled` and `uncontrolled`.
//! This two macros are attached to functions or static variables to enable crate level access control.
//! To use these two macros, a crate must at first registers a tool named `component_access_control`,
diff --git a/services/libs/cpio-decoder/src/error.rs b/services/libs/cpio-decoder/src/error.rs
--- a/services/libs/cpio-decoder/src/error.rs
+++ b/services/libs/cpio-decoder/src/error.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub type Result<T> = core::result::Result<T, self::Error>;
/// Errors of CPIO decoder.
diff --git a/services/libs/cpio-decoder/src/error.rs b/services/libs/cpio-decoder/src/error.rs
--- a/services/libs/cpio-decoder/src/error.rs
+++ b/services/libs/cpio-decoder/src/error.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
pub type Result<T> = core::result::Result<T, self::Error>;
/// Errors of CPIO decoder.
diff --git a/services/libs/cpio-decoder/src/lib.rs b/services/libs/cpio-decoder/src/lib.rs
--- a/services/libs/cpio-decoder/src/lib.rs
+++ b/services/libs/cpio-decoder/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! A safe Rust CPIO (the newc format) decoder.
//!
//! # Example
diff --git a/services/libs/cpio-decoder/src/lib.rs b/services/libs/cpio-decoder/src/lib.rs
--- a/services/libs/cpio-decoder/src/lib.rs
+++ b/services/libs/cpio-decoder/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! A safe Rust CPIO (the newc format) decoder.
//!
//! # Example
diff --git a/services/libs/cpio-decoder/src/test.rs b/services/libs/cpio-decoder/src/test.rs
--- a/services/libs/cpio-decoder/src/test.rs
+++ b/services/libs/cpio-decoder/src/test.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use super::error::*;
use super::{CpioDecoder, FileType};
use lending_iterator::LendingIterator;
diff --git a/services/libs/int-to-c-enum/derive/src/lib.rs b/services/libs/int-to-c-enum/derive/src/lib.rs
--- a/services/libs/int-to-c-enum/derive/src/lib.rs
+++ b/services/libs/int-to-c-enum/derive/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use proc_macro2::{Ident, TokenStream};
use quote::{format_ident, quote, TokenStreamExt};
use syn::{parse_macro_input, Attribute, Data, DataEnum, DeriveInput, Generics};
diff --git a/services/libs/int-to-c-enum/derive/src/lib.rs b/services/libs/int-to-c-enum/derive/src/lib.rs
--- a/services/libs/int-to-c-enum/derive/src/lib.rs
+++ b/services/libs/int-to-c-enum/derive/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use proc_macro2::{Ident, TokenStream};
use quote::{format_ident, quote, TokenStreamExt};
use syn::{parse_macro_input, Attribute, Data, DataEnum, DeriveInput, Generics};
diff --git a/services/libs/int-to-c-enum/src/lib.rs b/services/libs/int-to-c-enum/src/lib.rs
--- a/services/libs/int-to-c-enum/src/lib.rs
+++ b/services/libs/int-to-c-enum/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! This crate provides a derive macro named TryFromInt. This macro can be used to automatically implement TryFrom trait
//! for [C-like enums](https://doc.rust-lang.org/stable/rust-by-example/custom_types/enum/c_like.html).
//!
diff --git a/services/libs/int-to-c-enum/src/lib.rs b/services/libs/int-to-c-enum/src/lib.rs
--- a/services/libs/int-to-c-enum/src/lib.rs
+++ b/services/libs/int-to-c-enum/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! This crate provides a derive macro named TryFromInt. This macro can be used to automatically implement TryFrom trait
//! for [C-like enums](https://doc.rust-lang.org/stable/rust-by-example/custom_types/enum/c_like.html).
//!
diff --git a/services/libs/int-to-c-enum/tests/regression.rs b/services/libs/int-to-c-enum/tests/regression.rs
--- a/services/libs/int-to-c-enum/tests/regression.rs
+++ b/services/libs/int-to-c-enum/tests/regression.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use int_to_c_enum::TryFromInt;
#[derive(TryFromInt, Debug, PartialEq, Eq)]
diff --git a/services/libs/keyable-arc/src/lib.rs b/services/libs/keyable-arc/src/lib.rs
--- a/services/libs/keyable-arc/src/lib.rs
+++ b/services/libs/keyable-arc/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Same as the standard `Arc`, except that it can be used as the key type of a hash table.
//!
//! # Motivation
diff --git a/services/libs/keyable-arc/src/lib.rs b/services/libs/keyable-arc/src/lib.rs
--- a/services/libs/keyable-arc/src/lib.rs
+++ b/services/libs/keyable-arc/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Same as the standard `Arc`, except that it can be used as the key type of a hash table.
//!
//! # Motivation
diff --git a/services/libs/typeflags-util/src/assert.rs b/services/libs/typeflags-util/src/assert.rs
--- a/services/libs/typeflags-util/src/assert.rs
+++ b/services/libs/typeflags-util/src/assert.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! define macro assert_type_same
use crate::same::SameAs;
diff --git a/services/libs/typeflags-util/src/assert.rs b/services/libs/typeflags-util/src/assert.rs
--- a/services/libs/typeflags-util/src/assert.rs
+++ b/services/libs/typeflags-util/src/assert.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! define macro assert_type_same
use crate::same::SameAs;
diff --git a/services/libs/typeflags-util/src/bool.rs b/services/libs/typeflags-util/src/bool.rs
--- a/services/libs/typeflags-util/src/bool.rs
+++ b/services/libs/typeflags-util/src/bool.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Type level bools
pub use core::ops::BitAnd as And;
diff --git a/services/libs/typeflags-util/src/bool.rs b/services/libs/typeflags-util/src/bool.rs
--- a/services/libs/typeflags-util/src/bool.rs
+++ b/services/libs/typeflags-util/src/bool.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Type level bools
pub use core::ops::BitAnd as And;
diff --git a/services/libs/typeflags-util/src/extend.rs b/services/libs/typeflags-util/src/extend.rs
--- a/services/libs/typeflags-util/src/extend.rs
+++ b/services/libs/typeflags-util/src/extend.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{Cons, Nil};
/// This trait will extend a set with another item.
diff --git a/services/libs/typeflags-util/src/extend.rs b/services/libs/typeflags-util/src/extend.rs
--- a/services/libs/typeflags-util/src/extend.rs
+++ b/services/libs/typeflags-util/src/extend.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use crate::{Cons, Nil};
/// This trait will extend a set with another item.
diff --git a/services/libs/typeflags-util/src/if_.rs b/services/libs/typeflags-util/src/if_.rs
--- a/services/libs/typeflags-util/src/if_.rs
+++ b/services/libs/typeflags-util/src/if_.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Type Level If
use crate::bool::{False, True};
diff --git a/services/libs/typeflags-util/src/if_.rs b/services/libs/typeflags-util/src/if_.rs
--- a/services/libs/typeflags-util/src/if_.rs
+++ b/services/libs/typeflags-util/src/if_.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Type Level If
use crate::bool::{False, True};
diff --git a/services/libs/typeflags-util/src/lib.rs b/services/libs/typeflags-util/src/lib.rs
--- a/services/libs/typeflags-util/src/lib.rs
+++ b/services/libs/typeflags-util/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The content of this crate is from another project CapComp.
//! This crate defines common type level operations, like SameAsOp, and Bool type operations.
//! Besides, this crate defines operations to deal with type sets, like SetContain and SetInclude.
diff --git a/services/libs/typeflags-util/src/lib.rs b/services/libs/typeflags-util/src/lib.rs
--- a/services/libs/typeflags-util/src/lib.rs
+++ b/services/libs/typeflags-util/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! The content of this crate is from another project CapComp.
//! This crate defines common type level operations, like SameAsOp, and Bool type operations.
//! Besides, this crate defines operations to deal with type sets, like SetContain and SetInclude.
diff --git a/services/libs/typeflags-util/src/same.rs b/services/libs/typeflags-util/src/same.rs
--- a/services/libs/typeflags-util/src/same.rs
+++ b/services/libs/typeflags-util/src/same.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Traits used to check if two types are the same, returning a Bool.
//! This check happens at compile time
diff --git a/services/libs/typeflags-util/src/same.rs b/services/libs/typeflags-util/src/same.rs
--- a/services/libs/typeflags-util/src/same.rs
+++ b/services/libs/typeflags-util/src/same.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Traits used to check if two types are the same, returning a Bool.
//! This check happens at compile time
diff --git a/services/libs/typeflags-util/src/set.rs b/services/libs/typeflags-util/src/set.rs
--- a/services/libs/typeflags-util/src/set.rs
+++ b/services/libs/typeflags-util/src/set.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Common types and traits to deal with type-level sets
use core::marker::PhantomData;
diff --git a/services/libs/typeflags-util/src/set.rs b/services/libs/typeflags-util/src/set.rs
--- a/services/libs/typeflags-util/src/set.rs
+++ b/services/libs/typeflags-util/src/set.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//! Common types and traits to deal with type-level sets
use core::marker::PhantomData;
diff --git a/services/libs/typeflags/src/flag_set.rs b/services/libs/typeflags/src/flag_set.rs
--- a/services/libs/typeflags/src/flag_set.rs
+++ b/services/libs/typeflags/src/flag_set.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use itertools::Itertools;
use proc_macro2::{Ident, TokenStream};
use quote::{quote, TokenStreamExt};
diff --git a/services/libs/typeflags/src/flag_set.rs b/services/libs/typeflags/src/flag_set.rs
--- a/services/libs/typeflags/src/flag_set.rs
+++ b/services/libs/typeflags/src/flag_set.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use itertools::Itertools;
use proc_macro2::{Ident, TokenStream};
use quote::{quote, TokenStreamExt};
diff --git a/services/libs/typeflags/src/lib.rs b/services/libs/typeflags/src/lib.rs
--- a/services/libs/typeflags/src/lib.rs
+++ b/services/libs/typeflags/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//!This crate defines the procedural macro typeflags to implement capability for Asterinas.
//! When using this crate, typeflags-util should also be added as dependency.
//! This is due to typeflgas is a proc-macro crate, which is only allowed to export proc-macro interfaces.
diff --git a/services/libs/typeflags/src/lib.rs b/services/libs/typeflags/src/lib.rs
--- a/services/libs/typeflags/src/lib.rs
+++ b/services/libs/typeflags/src/lib.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
//!This crate defines the procedural macro typeflags to implement capability for Asterinas.
//! When using this crate, typeflags-util should also be added as dependency.
//! This is due to typeflgas is a proc-macro crate, which is only allowed to export proc-macro interfaces.
diff --git a/services/libs/typeflags/src/type_flag.rs b/services/libs/typeflags/src/type_flag.rs
--- a/services/libs/typeflags/src/type_flag.rs
+++ b/services/libs/typeflags/src/type_flag.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use proc_macro2::TokenStream;
use quote::quote;
use syn::{
diff --git a/services/libs/typeflags/src/type_flag.rs b/services/libs/typeflags/src/type_flag.rs
--- a/services/libs/typeflags/src/type_flag.rs
+++ b/services/libs/typeflags/src/type_flag.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use proc_macro2::TokenStream;
use quote::quote;
use syn::{
diff --git a/services/libs/typeflags/src/util.rs b/services/libs/typeflags/src/util.rs
--- a/services/libs/typeflags/src/util.rs
+++ b/services/libs/typeflags/src/util.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use proc_macro2::{Ident, TokenStream};
use quote::{quote, TokenStreamExt};
diff --git a/services/libs/typeflags/src/util.rs b/services/libs/typeflags/src/util.rs
--- a/services/libs/typeflags/src/util.rs
+++ b/services/libs/typeflags/src/util.rs
@@ -1,3 +1,5 @@
+// SPDX-License-Identifier: MPL-2.0
+
use proc_macro2::{Ident, TokenStream};
use quote::{quote, TokenStreamExt};
diff --git a/tools/bump_version.sh b/tools/bump_version.sh
--- a/tools/bump_version.sh
+++ b/tools/bump_version.sh
@@ -1,5 +1,7 @@
#!/bin/bash
+# SPDX-License-Identifier: MPL-2.0
+
# This script is used to update Asterinas version numbers in all relevant files in the repository.
# Usage: ./tools/bump_version.sh <new_version>
diff --git a/tools/bump_version.sh b/tools/bump_version.sh
--- a/tools/bump_version.sh
+++ b/tools/bump_version.sh
@@ -1,5 +1,7 @@
#!/bin/bash
+# SPDX-License-Identifier: MPL-2.0
+
# This script is used to update Asterinas version numbers in all relevant files in the repository.
# Usage: ./tools/bump_version.sh <new_version>
diff --git a/tools/docker/Dockerfile.ubuntu22.04 b/tools/docker/Dockerfile.ubuntu22.04
--- a/tools/docker/Dockerfile.ubuntu22.04
+++ b/tools/docker/Dockerfile.ubuntu22.04
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
FROM ubuntu:22.04 as build-base
SHELL ["/bin/bash", "-c"]
diff --git a/tools/docker/Dockerfile.ubuntu22.04 b/tools/docker/Dockerfile.ubuntu22.04
--- a/tools/docker/Dockerfile.ubuntu22.04
+++ b/tools/docker/Dockerfile.ubuntu22.04
@@ -1,3 +1,5 @@
+# SPDX-License-Identifier: MPL-2.0
+
FROM ubuntu:22.04 as build-base
SHELL ["/bin/bash", "-c"]
diff --git a/tools/docker/run_dev_container.sh b/tools/docker/run_dev_container.sh
--- a/tools/docker/run_dev_container.sh
+++ b/tools/docker/run_dev_container.sh
@@ -1,5 +1,7 @@
#!/bin/bash
+# SPDX-License-Identifier: MPL-2.0
+
set -e
SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
diff --git a/tools/docker/run_dev_container.sh b/tools/docker/run_dev_container.sh
--- a/tools/docker/run_dev_container.sh
+++ b/tools/docker/run_dev_container.sh
@@ -1,5 +1,7 @@
#!/bin/bash
+# SPDX-License-Identifier: MPL-2.0
+
set -e
SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
|
As a side note, the MPL license is unfortunately hard-coded to allow implicit upgrades when the Mozilla Foundation releases a new license version. Not sure if we like that or not (or at least accept it).
> 10.2. Effect of New Versions
>
> You may distribute the Covered Software under the terms of the version
> of the License under which You originally received the Covered Software,
> or under the terms of any subsequent version published by the license
> steward.
A similar statement in GPL-2.0 instead offers two choices, i.e., `GPL-2.0-only` or `GPL-2.0-or-later`.
> 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
> Each version is given a distinguishing version number. *If the Program specifies a version number of this License which applies to it and "any later version",* you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
Linux uses `GPL-2.0-only` because there are some problems with GPL-3.0, or at least Linus Torvalds does not like GPL-3.0.
|
2024-01-03T06:45:56Z
|
8d456ebe8fc200fc11c75654fdca2f0dd896e656
|
asterinas/asterinas
|
diff --git a/.github/workflows/cargo_check.yml b/.github/workflows/cargo_check.yml
--- a/.github/workflows/cargo_check.yml
+++ b/.github/workflows/cargo_check.yml
@@ -10,9 +10,9 @@ jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 10
- container: jinuxdev/jinux:0.2.2
+ container: asterinas/asterinas:0.2.2
steps:
- - run: echo "Running in jinuxdev/jinux:0.2.2"
+ - run: echo "Running in asterinas/asterinas:0.2.2"
- uses: actions/checkout@v3
diff --git a/.github/workflows/integration_test.yml b/.github/workflows/integration_test.yml
--- a/.github/workflows/integration_test.yml
+++ b/.github/workflows/integration_test.yml
@@ -10,9 +10,9 @@ jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 30
- container: jinuxdev/jinux:0.2.2
+ container: asterinas/asterinas:0.2.2
steps:
- - run: echo "Running in jinuxdev/jinux:0.2.2"
+ - run: echo "Running in asterinas/asterinas:0.2.2"
- uses: actions/checkout@v3
diff --git a/.github/workflows/unit_test.yml b/.github/workflows/unit_test.yml
--- a/.github/workflows/unit_test.yml
+++ b/.github/workflows/unit_test.yml
@@ -10,9 +10,9 @@ jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 15
- container: jinuxdev/jinux:0.2.2
+ container: asterinas/asterinas:0.2.2
steps:
- - run: echo "Running in jinuxdev/jinux:0.2.2"
+ - run: echo "Running in asterinas/asterinas:0.2.2"
- uses: actions/checkout@v3
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -113,6 +113,250 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16"
+[[package]]
+name = "aster-block"
+version = "0.1.0"
+dependencies = [
+ "aster-frame",
+ "aster-util",
+ "bitflags 1.3.2",
+ "component",
+ "lazy_static",
+ "log",
+ "spin 0.9.8",
+]
+
+[[package]]
+name = "aster-console"
+version = "0.1.0"
+dependencies = [
+ "aster-frame",
+ "aster-util",
+ "bitflags 1.3.2",
+ "component",
+ "log",
+ "spin 0.9.8",
+]
+
+[[package]]
+name = "aster-frame"
+version = "0.1.0"
+dependencies = [
+ "acpi",
+ "align_ext",
+ "aml",
+ "bit_field",
+ "bitflags 1.3.2",
+ "bitvec",
+ "buddy_system_allocator",
+ "cfg-if",
+ "gimli",
+ "inherit-methods-macro",
+ "int-to-c-enum",
+ "intrusive-collections",
+ "ktest",
+ "lazy_static",
+ "log",
+ "multiboot2",
+ "pod",
+ "rsdp",
+ "spin 0.9.8",
+ "static_assertions",
+ "tdx-guest",
+ "trapframe",
+ "unwinding",
+ "volatile",
+ "x86",
+ "x86_64",
+]
+
+[[package]]
+name = "aster-frame-x86-boot-linux-setup"
+version = "0.1.0"
+dependencies = [
+ "uart_16550",
+ "xmas-elf",
+]
+
+[[package]]
+name = "aster-framebuffer"
+version = "0.1.0"
+dependencies = [
+ "aster-frame",
+ "component",
+ "font8x8",
+ "log",
+ "spin 0.9.8",
+]
+
+[[package]]
+name = "aster-input"
+version = "0.1.0"
+dependencies = [
+ "aster-frame",
+ "aster-rights",
+ "aster-util",
+ "bitflags 1.3.2",
+ "component",
+ "lazy_static",
+ "log",
+ "spin 0.9.8",
+ "virtio-input-decoder",
+]
+
+[[package]]
+name = "aster-network"
+version = "0.1.0"
+dependencies = [
+ "align_ext",
+ "aster-frame",
+ "aster-rights",
+ "aster-util",
+ "bitflags 1.3.2",
+ "bytes",
+ "component",
+ "int-to-c-enum",
+ "log",
+ "pod",
+ "ringbuf",
+ "smoltcp",
+ "spin 0.9.8",
+]
+
+[[package]]
+name = "aster-rights"
+version = "0.1.0"
+dependencies = [
+ "aster-rights-proc",
+ "bitflags 1.3.2",
+ "typeflags",
+ "typeflags-util",
+]
+
+[[package]]
+name = "aster-rights-proc"
+version = "0.1.0"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "aster-runner"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "clap",
+ "glob",
+ "rand",
+ "xmas-elf",
+]
+
+[[package]]
+name = "aster-std"
+version = "0.1.0"
+dependencies = [
+ "align_ext",
+ "ascii",
+ "aster-block",
+ "aster-console",
+ "aster-frame",
+ "aster-input",
+ "aster-network",
+ "aster-rights",
+ "aster-rights-proc",
+ "aster-time",
+ "aster-util",
+ "aster-virtio",
+ "bitflags 1.3.2",
+ "controlled",
+ "core2",
+ "cpio-decoder",
+ "getrandom",
+ "int-to-c-enum",
+ "intrusive-collections",
+ "keyable-arc",
+ "ktest",
+ "lazy_static",
+ "lending-iterator",
+ "libflate",
+ "log",
+ "lru",
+ "pod",
+ "ringbuf",
+ "smoltcp",
+ "spin 0.9.8",
+ "tdx-guest",
+ "time",
+ "typeflags",
+ "typeflags-util",
+ "virtio-input-decoder",
+ "vte",
+ "xmas-elf",
+]
+
+[[package]]
+name = "aster-time"
+version = "0.1.0"
+dependencies = [
+ "aster-frame",
+ "aster-util",
+ "component",
+ "log",
+ "spin 0.9.8",
+]
+
+[[package]]
+name = "aster-util"
+version = "0.1.0"
+dependencies = [
+ "aster-frame",
+ "aster-rights",
+ "aster-rights-proc",
+ "bitvec",
+ "ktest",
+ "pod",
+ "typeflags-util",
+]
+
+[[package]]
+name = "aster-virtio"
+version = "0.1.0"
+dependencies = [
+ "align_ext",
+ "aster-block",
+ "aster-console",
+ "aster-frame",
+ "aster-input",
+ "aster-network",
+ "aster-rights",
+ "aster-util",
+ "bit_field",
+ "bitflags 1.3.2",
+ "bytes",
+ "component",
+ "int-to-c-enum",
+ "log",
+ "pod",
+ "smoltcp",
+ "spin 0.9.8",
+ "typeflags-util",
+ "virtio-input-decoder",
+]
+
+[[package]]
+name = "asterinas"
+version = "0.2.2"
+dependencies = [
+ "aster-frame",
+ "aster-framebuffer",
+ "aster-std",
+ "aster-time",
+ "component",
+ "x86_64",
+]
+
[[package]]
name = "atomic-polyfill"
version = "0.1.11"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -603,250 +847,6 @@ dependencies = [
"either",
]
-[[package]]
-name = "jinux"
-version = "0.2.2"
-dependencies = [
- "component",
- "jinux-frame",
- "jinux-framebuffer",
- "jinux-std",
- "jinux-time",
- "x86_64",
-]
-
-[[package]]
-name = "jinux-block"
-version = "0.1.0"
-dependencies = [
- "bitflags 1.3.2",
- "component",
- "jinux-frame",
- "jinux-util",
- "lazy_static",
- "log",
- "spin 0.9.8",
-]
-
-[[package]]
-name = "jinux-console"
-version = "0.1.0"
-dependencies = [
- "bitflags 1.3.2",
- "component",
- "jinux-frame",
- "jinux-util",
- "log",
- "spin 0.9.8",
-]
-
-[[package]]
-name = "jinux-frame"
-version = "0.1.0"
-dependencies = [
- "acpi",
- "align_ext",
- "aml",
- "bit_field",
- "bitflags 1.3.2",
- "bitvec",
- "buddy_system_allocator",
- "cfg-if",
- "gimli",
- "inherit-methods-macro",
- "int-to-c-enum",
- "intrusive-collections",
- "ktest",
- "lazy_static",
- "log",
- "multiboot2",
- "pod",
- "rsdp",
- "spin 0.9.8",
- "static_assertions",
- "tdx-guest",
- "trapframe",
- "unwinding",
- "volatile",
- "x86",
- "x86_64",
-]
-
-[[package]]
-name = "jinux-frame-x86-boot-linux-setup"
-version = "0.1.0"
-dependencies = [
- "uart_16550",
- "xmas-elf",
-]
-
-[[package]]
-name = "jinux-framebuffer"
-version = "0.1.0"
-dependencies = [
- "component",
- "font8x8",
- "jinux-frame",
- "log",
- "spin 0.9.8",
-]
-
-[[package]]
-name = "jinux-input"
-version = "0.1.0"
-dependencies = [
- "bitflags 1.3.2",
- "component",
- "jinux-frame",
- "jinux-rights",
- "jinux-util",
- "lazy_static",
- "log",
- "spin 0.9.8",
- "virtio-input-decoder",
-]
-
-[[package]]
-name = "jinux-network"
-version = "0.1.0"
-dependencies = [
- "align_ext",
- "bitflags 1.3.2",
- "bytes",
- "component",
- "int-to-c-enum",
- "jinux-frame",
- "jinux-rights",
- "jinux-util",
- "log",
- "pod",
- "ringbuf",
- "smoltcp",
- "spin 0.9.8",
-]
-
-[[package]]
-name = "jinux-rights"
-version = "0.1.0"
-dependencies = [
- "bitflags 1.3.2",
- "jinux-rights-proc",
- "typeflags",
- "typeflags-util",
-]
-
-[[package]]
-name = "jinux-rights-proc"
-version = "0.1.0"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 1.0.109",
-]
-
-[[package]]
-name = "jinux-runner"
-version = "0.1.0"
-dependencies = [
- "anyhow",
- "clap",
- "glob",
- "rand",
- "xmas-elf",
-]
-
-[[package]]
-name = "jinux-std"
-version = "0.1.0"
-dependencies = [
- "align_ext",
- "ascii",
- "bitflags 1.3.2",
- "controlled",
- "core2",
- "cpio-decoder",
- "getrandom",
- "int-to-c-enum",
- "intrusive-collections",
- "jinux-block",
- "jinux-console",
- "jinux-frame",
- "jinux-input",
- "jinux-network",
- "jinux-rights",
- "jinux-rights-proc",
- "jinux-time",
- "jinux-util",
- "jinux-virtio",
- "keyable-arc",
- "ktest",
- "lazy_static",
- "lending-iterator",
- "libflate",
- "log",
- "lru",
- "pod",
- "ringbuf",
- "smoltcp",
- "spin 0.9.8",
- "tdx-guest",
- "time",
- "typeflags",
- "typeflags-util",
- "virtio-input-decoder",
- "vte",
- "xmas-elf",
-]
-
-[[package]]
-name = "jinux-time"
-version = "0.1.0"
-dependencies = [
- "component",
- "jinux-frame",
- "jinux-util",
- "log",
- "spin 0.9.8",
-]
-
-[[package]]
-name = "jinux-util"
-version = "0.1.0"
-dependencies = [
- "bitvec",
- "jinux-frame",
- "jinux-rights",
- "jinux-rights-proc",
- "ktest",
- "pod",
- "typeflags-util",
-]
-
-[[package]]
-name = "jinux-virtio"
-version = "0.1.0"
-dependencies = [
- "align_ext",
- "bit_field",
- "bitflags 1.3.2",
- "bytes",
- "component",
- "int-to-c-enum",
- "jinux-block",
- "jinux-console",
- "jinux-frame",
- "jinux-input",
- "jinux-network",
- "jinux-rights",
- "jinux-util",
- "log",
- "pod",
- "smoltcp",
- "spin 0.9.8",
- "typeflags-util",
- "virtio-input-decoder",
-]
-
[[package]]
name = "json"
version = "0.12.4"
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -33,8 +33,8 @@ panic = "unwind"
members = [
"runner",
- "framework/jinux-frame",
- "framework/jinux-frame/src/arch/x86/boot/linux_boot/setup",
+ "framework/aster-frame",
+ "framework/aster-frame/src/arch/x86/boot/linux_boot/setup",
"framework/libs/align_ext",
"framework/libs/ktest",
"framework/libs/tdx-guest",
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -1,45 +1,45 @@
-# Jinux
+# Asterinas
-Jinux is a _secure_, _fast_, and _general-purpose_ OS kernel, written in Rust and providing Linux-compatible ABI.
+Asterinas is a _secure_, _fast_, and _general-purpose_ OS kernel, written in Rust and providing Linux-compatible ABI.
-Jinux is designed and implemented with an emphasis on security, rendering it highly attractive for usage scenarios where Linux ABI is indispensable, but Linux itself is deemed insecure given its sheer size of TCB and its nature of being memory unsafe. An instance of such usage is employing Jinux as the guest OS for VM TEEs (e.g., [AMD SEV](https://www.amd.com/en/developer/sev.html) and [Intel TDX](https://www.intel.com/content/www/us/en/developer/articles/technical/intel-trust-domain-extensions.html)).
+Asterinas is designed and implemented with an emphasis on security, rendering it highly attractive for usage scenarios where Linux ABI is indispensable, but Linux itself is deemed insecure given its sheer size of TCB and its nature of being memory unsafe. An instance of such usage is employing Asterinas as the guest OS for VM TEEs (e.g., [AMD SEV](https://www.amd.com/en/developer/sev.html) and [Intel TDX](https://www.intel.com/content/www/us/en/developer/articles/technical/intel-trust-domain-extensions.html)).
-## What's unique about Jinux
+## What's unique about Asterinas
-Jinux is a _zero-cost_, _least-privilege_ OS kernel. A least-privilege OS is one that adheres to the principle of least privileges, which mandates that every unit (e.g., a subsystem, a module, a function, or even an object) of the OS has the minimum authority and permissions required to perform its tasks. This approach reduces the security risk associated with any single element's bugs or flaws. By "zero-cost", we means the same as in Rust's philosophy of zero-cost abstractions, which emphasizes that high-level abstractions (like those that enable least privilege principles) should be available to developers to use, but not come at the cost of performance. Thus, a zero-cost, least-privilege OS enhances its security without compromising its performance.
+Asterinas is a _zero-cost_, _least-privilege_ OS kernel. A least-privilege OS is one that adheres to the principle of least privileges, which mandates that every unit (e.g., a subsystem, a module, a function, or even an object) of the OS has the minimum authority and permissions required to perform its tasks. This approach reduces the security risk associated with any single element's bugs or flaws. By "zero-cost", we means the same as in Rust's philosophy of zero-cost abstractions, which emphasizes that high-level abstractions (like those that enable least privilege principles) should be available to developers to use, but not come at the cost of performance. Thus, a zero-cost, least-privilege OS enhances its security without compromising its performance.
Some prior OSes do abide by the [principle of least privilege](https://en.wikipedia.org/wiki/Principle_of_least_privilege), but come with considerable performance costs. Take [seL4](https://sel4.systems/) as an example. A [seL4-based multi-server OS](https://docs.sel4.systems/projects/camkes/) minimizes the scope of the OS running in the privileged CPU mode to the seL4 microkernel. The bulk of OS functionalities are implemented by process-based servers, which are separated by process boundary and only allowed to communicate with each other through well-defined interfaces, usually based on RPC. Each service can only access kernel resources represented by [seL4 capabilities](), each of which is restricted with respect to its scope and permissions. All these security measures contribute to the enhanced security of the OS, but result in a considerable runtime costs due to context switching, message passing, and runtime checks.
-Jinux is unique in practicing the principle of least privilege without sacrificing the performance. This is achieved by realizing the full potential of Rust, which, compared to the traditional system programming language like C/C++, offers unique features like an expressive type system, memory safety with unsafe extensions, powerful macros, and a customizable toolchain. By leveraging these unique features, Jinux is able to construct zero-cost abstractions that enable least privileges at the following three levels.
+Asterinas is unique in practicing the principle of least privilege without sacrificing the performance. This is achieved by realizing the full potential of Rust, which, compared to the traditional system programming language like C/C++, offers unique features like an expressive type system, memory safety with unsafe extensions, powerful macros, and a customizable toolchain. By leveraging these unique features, Asterinas is able to construct zero-cost abstractions that enable least privileges at the following three levels.
-1. The architectural level. Jinux is architected as a _framekernel_, where the entire OS resides in a single address space and unsafe Rust code is restricted to a tiny portion of the OS called Jinux Framework. The Framework exposes safe APIs to the rest of Jinux, which implements the most of OS functionalities in safe Rust code completely. Thanks to the framekernel architecture, Jinux's TCB for memory safety is minimized.
+1. The architectural level. Asterinas is architected as a _framekernel_, where the entire OS resides in a single address space and unsafe Rust code is restricted to a tiny portion of the OS called Asterinas Framework. The Framework exposes safe APIs to the rest of Asterinas, which implements the most of OS functionalities in safe Rust code completely. Thanks to the framekernel architecture, Asterinas's TCB for memory safety is minimized.

-2. The component level. Upon Jinux Framework is a set of OS components, each of which is responsible for a particular OS functionality, feature, or device. These OS components are Rust crates with two traits: (1) containing safe Rust code, as demanded by the framekernel architecture, and (2) being governed by Jinux Component System, which can enforce a fine-grained access control to their public APIs. The access control policy is specified in a configuration file and enforced at compile time, using a static analysis tool.
+2. The component level. Upon Asterinas Framework is a set of OS components, each of which is responsible for a particular OS functionality, feature, or device. These OS components are Rust crates with two traits: (1) containing safe Rust code, as demanded by the framekernel architecture, and (2) being governed by Asterinas Component System, which can enforce a fine-grained access control to their public APIs. The access control policy is specified in a configuration file and enforced at compile time, using a static analysis tool.
-3. The object level. Jinux promotes the philosophy of _everything-is-a-capability_, which means all kernel resources, from files to threads, from virtual memory to physical pages, should be accessed through [capabilities](https://en.wikipedia.org/wiki/Capability-based_security). In Jinux, capabilities are implemented as Rust objects that are constrained in their creation, acquisition, and usage. One common form of capabilities is those with access rights. Wherever possible, access rights are encoded in types (rather than values) so that they can be checked at compile time, eliminating any runtime costs.
+3. The object level. Asterinas promotes the philosophy of _everything-is-a-capability_, which means all kernel resources, from files to threads, from virtual memory to physical pages, should be accessed through [capabilities](https://en.wikipedia.org/wiki/Capability-based_security). In Asterinas, capabilities are implemented as Rust objects that are constrained in their creation, acquisition, and usage. One common form of capabilities is those with access rights. Wherever possible, access rights are encoded in types (rather than values) so that they can be checked at compile time, eliminating any runtime costs.
-As a zero-cost, least-privilege OS, Jinux provides the best of both worlds: the performance of a monolithic kernel and the security of a microkernel. Like a monolithic kernel, the different parts of Jinux can communicate with the most efficient means, e.g., function calls and memory sharing. In the same spirit as a microkernel, the fundamental security properties of the OS depend on a minimum amount of code (i.e., Jinux Framework).
+As a zero-cost, least-privilege OS, Asterinas provides the best of both worlds: the performance of a monolithic kernel and the security of a microkernel. Like a monolithic kernel, the different parts of Asterinas can communicate with the most efficient means, e.g., function calls and memory sharing. In the same spirit as a microkernel, the fundamental security properties of the OS depend on a minimum amount of code (i.e., Asterinas Framework).
-## Build, test and debug Jinux
+## Build, test and debug Asterinas
While most of the code is written in Rust, the project-scope build process is governed by Makefile. The development environment is managed with Docker. Please ensure Docker is installed and can be run without sudo privilege.
### Preparation
-1. Download the latest source code of jinux.
+1. Download the latest source code of asterinas.
```bash
git clone [repository url]
```
2. After downloading the source code, run the following command to pull the development image.
```bash
-docker pull jinuxdev/jinux:0.2.2
+docker pull asterinas/asterinas:0.2.2
```
3. Start the development container.
```bash
-docker run -it --privileged --network=host --device=/dev/kvm -v `pwd`:/root/jinux jinuxdev/jinux:0.2.2
+docker run -it --privileged --network=host --device=/dev/kvm -v `pwd`:/root/asterinas asterinas/asterinas:0.2.2
```
**All build and test commands should be run inside the development container.**
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -70,14 +70,14 @@ Nevertheless, you could enter the directory of a specific crate and invoke `carg
#### Kernel mode unit tests
-We can run unit tests in kernel mode for crates like `jinux-frame` or `jinux-std`. This is powered by our [ktest](framework/libs/ktest) framework.
+We can run unit tests in kernel mode for crates like `aster-frame` or `aster-std`. This is powered by our [ktest](framework/libs/ktest) framework.
```bash
make run KTEST=1
```
You could also specify tests in a crate or a subset of tests to run.
```bash
-make run KTEST=1 KTEST_WHITELIST=failing_assertion,jinux_frame::test::expect_panic KTEST_CRATES=jinux-frame
+make run KTEST=1 KTEST_WHITELIST=failing_assertion,aster_frame::test::expect_panic KTEST_CRATES=aster-frame
```
#### Component check
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -96,33 +96,33 @@ cargo component-check
#### Regression Test
-This command will automatically run Jinux with the test binaries in `regression/apps` directory.
+This command will automatically run Asterinas with the test binaries in `regression/apps` directory.
```bash
make run AUTO_TEST=regression
```
#### Syscall Test
-This command will build the syscall test binary and automatically run Jinux with the tests using QEMU.
+This command will build the syscall test binary and automatically run Asterinas with the tests using QEMU.
```bash
make run AUTO_TEST=syscall
```
-Alternatively, if you wish to test it interactively inside a shell in Jinux.
+Alternatively, if you wish to test it interactively inside a shell in Asterinas.
```bash
make run BUILD_SYSCALL_TEST=1
```
-Then, we can run the following script using the Jinux shell to run all syscall test cases.
+Then, we can run the following script using the Asterinas shell to run all syscall test cases.
```bash
/opt/syscall_test/run_syscall_test.sh
```
### Debug
-To debug Jinux using [QEMU GDB remote debugging](https://qemu-project.gitlab.io/qemu/system/gdb.html), you could compile Jinux in debug mode, start a Jinux instance and run the GDB interactive shell in another terminal.
+To debug Asterinas using [QEMU GDB remote debugging](https://qemu-project.gitlab.io/qemu/system/gdb.html), you could compile Asterinas in debug mode, start a Asterinas instance and run the GDB interactive shell in another terminal.
-To start a QEMU Jinux VM and wait for debugging connection:
+To start a QEMU Asterinas VM and wait for debugging connection:
```bash
make run GDB_SERVER=1 ENABLE_KVM=0
```
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -132,33 +132,33 @@ To get the GDB interactive shell:
make run GDB_CLIENT=1
```
-Currently, the Jinux runner's debugging interface is exposed by unix socket. Thus there shouldn't be multiple debugging instances in the same container. To add debug symbols for the underlying infrastructures such as UEFI firmware or bootloader, please check the runner's source code for details.
+Currently, the Asterinas runner's debugging interface is exposed by unix socket. Thus there shouldn't be multiple debugging instances in the same container. To add debug symbols for the underlying infrastructures such as UEFI firmware or bootloader, please check the runner's source code for details.
## Code organization
-The codebase of Jinux is organized as below.
+The codebase of Asterinas is organized as below.
-* `runner/`: creating a bootable Jinux kernel image along with an initramfs image. It also supports `cargo run` since it is the only package with `main()`.
-* `kernel/`: defining the entry point of the Jinux kernel.
-* `framework/`: the privileged half of Jinux (allowed to use `unsafe` keyword)
- * `jinux-frame`: providing the safe Rust abstractions for low-level resources like CPU, memory, interrupts, etc;
+* `runner/`: creating a bootable Asterinas kernel image along with an initramfs image. It also supports `cargo run` since it is the only package with `main()`.
+* `kernel/`: defining the entry point of the Asterinas kernel.
+* `framework/`: the privileged half of Asterinas (allowed to use `unsafe` keyword)
+ * `aster-frame`: providing the safe Rust abstractions for low-level resources like CPU, memory, interrupts, etc;
* `libs`: Privileged libraries.
-* `services/`: the unprivileged half of Jinux (not allowed to use `unsafe` directly), implementing most of the OS functionalities.
- * `comps/`: Jinux OS components;
- * `libs/`: Jinux OS libraries;
- * `jinux-std`: this is where system calls are implemented. Currently, this crate is too big. It will eventually be decomposed into smaller crates.
+* `services/`: the unprivileged half of Asterinas (not allowed to use `unsafe` directly), implementing most of the OS functionalities.
+ * `comps/`: Asterinas OS components;
+ * `libs/`: Asterinas OS libraries;
+ * `aster-std`: this is where system calls are implemented. Currently, this crate is too big. It will eventually be decomposed into smaller crates.
* `tests/`: providing integration tests written in Rust.
* `regression/`: providing user-space tests written in C.
-* `docs/`: The Jinux book (needs a major update).
+* `docs/`: The Asterinas book (needs a major update).
## Development status
-Jinux is under active development. The list below summarizes the progress of important planned features.
+Asterinas is under active development. The list below summarizes the progress of important planned features.
* Technical novelty
- - [X] Jinux Framework
- - [X] Jinux Component System
- - [X] Jinux Capabilities
+ - [X] Asterinas Framework
+ - [X] Asterinas Component System
+ - [X] Asterinas Capabilities
* High-level stuff
* Process management
- [X] Essential system calls (fork, execve, etc.)
diff --git a/docs/src/README.md b/docs/src/README.md
--- a/docs/src/README.md
+++ b/docs/src/README.md
@@ -79,24 +79,24 @@ relational databases:
[Oracle and IBM are losing ground as Chinese vendors catch up with their US counterparts](https://www.theregister.com/2022/07/06/international_database_vendors_are_losing/).
Can such success stories be repeated in the field of OSes? I think so.
There are some China's home-grown OSes like [openKylin](https://www.openkylin.top/index.php?lang=en), but all of them are based on Linux and lack a self-developed
-OS _kernel_. The long-term goal of Jinux is to fill this key missing core of the home-grown OSes.
+OS _kernel_. The long-term goal of Asterinas is to fill this key missing core of the home-grown OSes.
## Architecture Overview
-Here is an overview of the architecture of Jinux.
+Here is an overview of the architecture of Asterinas.

## Features
-**1. Security by design.** Security is our top priority in the design of Jinux. As such, we adopt the widely acknowledged security best practice of [least privilege principle](https://en.wikipedia.org/wiki/Principle_of_least_privilege) and enforce it in a fashion that leverages the full strengths of Rust. To do so, we partition Jinux into two halves: a _privileged_ OS core and _unprivileged_ OS components. All OS components are written entirely in _safe_ Rust and only the privileged OS core
+**1. Security by design.** Security is our top priority in the design of Asterinas. As such, we adopt the widely acknowledged security best practice of [least privilege principle](https://en.wikipedia.org/wiki/Principle_of_least_privilege) and enforce it in a fashion that leverages the full strengths of Rust. To do so, we partition Asterinas into two halves: a _privileged_ OS core and _unprivileged_ OS components. All OS components are written entirely in _safe_ Rust and only the privileged OS core
is allowed to have _unsafe_ Rust code. Furthermore, we propose the idea of _everything-is-a-capability_, which elevates the status of [capabilities](https://en.wikipedia.org/wiki/Capability-based_security) to the level of a ubiquitous security primitive used throughout the OS. We make novel use of Rust's advanced features (e.g., [type-level programming](https://willcrichton.net/notes/type-level-programming/)) to make capabilities more accessible and efficient. The net result is improved security and uncompromised performance.
-**2. Trustworthy OS-level virtualization.** OS-level virtualization mechanisms (like Linux's cgroups and namespaces) enable containers, a more lightweight and arguably more popular alternative to virtual machines (VMs). But there is one problem with containers: they are not as secure as VMs (see [StackExchange](https://security.stackexchange.com/questions/169642/what-makes-docker-more-secure-than-vms-or-bare-metal), [LWN](https://lwn.net/Articles/796700/), and [AWS](https://docs.aws.amazon.com/AmazonECS/latest/bestpracticesguide/security-tasks-containers.html)). There is a real risk that malicious containers may exploit privilege escalation bugs in the OS kernel to attack the host. [A study](https://dl.acm.org/doi/10.1145/3274694.3274720) found that 11 out of 88 kernel exploits are effective in breaking the container sandbox. The seemingly inherent insecurity of OS kernels leads to a new breed of container implementations (e.g., [Kata](https://katacontainers.io/) and [gVisor](https://gvisor.dev/)) that are based on VMs, instead of kernels, for isolation and sandboxing. We argue that this unfortunate retreat from OS-level virtualization to VM-based one is unwarranted---if the OS kernels are secure enough. And this is exactly what we plan to achieve with Jinux. We aim to provide a trustworthy OS-level virtualization mechanism on Jinux.
+**2. Trustworthy OS-level virtualization.** OS-level virtualization mechanisms (like Linux's cgroups and namespaces) enable containers, a more lightweight and arguably more popular alternative to virtual machines (VMs). But there is one problem with containers: they are not as secure as VMs (see [StackExchange](https://security.stackexchange.com/questions/169642/what-makes-docker-more-secure-than-vms-or-bare-metal), [LWN](https://lwn.net/Articles/796700/), and [AWS](https://docs.aws.amazon.com/AmazonECS/latest/bestpracticesguide/security-tasks-containers.html)). There is a real risk that malicious containers may exploit privilege escalation bugs in the OS kernel to attack the host. [A study](https://dl.acm.org/doi/10.1145/3274694.3274720) found that 11 out of 88 kernel exploits are effective in breaking the container sandbox. The seemingly inherent insecurity of OS kernels leads to a new breed of container implementations (e.g., [Kata](https://katacontainers.io/) and [gVisor](https://gvisor.dev/)) that are based on VMs, instead of kernels, for isolation and sandboxing. We argue that this unfortunate retreat from OS-level virtualization to VM-based one is unwarranted---if the OS kernels are secure enough. And this is exactly what we plan to achieve with Asterinas. We aim to provide a trustworthy OS-level virtualization mechanism on Asterinas.
-**3. Fast user-mode development.** Traditional OS kernels like Linux are hard to develop, test, and debug. Kernel development involves countless rounds of programming, failing, and rebooting on bare-metal or virtual machines. This way of life is unproductive and painful. Such a pain point is also recognized and partially addressed by [research work](https://www.usenix.org/conference/fast21/presentation/miller), but we think we can do more. In this spirit, we design the OS core to provide high-level APIs that are largely independent of the underlying hardware and implement it with two targets: one target is as part of a regular OS in kernel space and the other is as a library OS in user space. This way, all the OS components of Jinux, which are stacked above the OS core, can be developed, tested, and debugged in user space, which is more friendly to developers than kernel space.
+**3. Fast user-mode development.** Traditional OS kernels like Linux are hard to develop, test, and debug. Kernel development involves countless rounds of programming, failing, and rebooting on bare-metal or virtual machines. This way of life is unproductive and painful. Such a pain point is also recognized and partially addressed by [research work](https://www.usenix.org/conference/fast21/presentation/miller), but we think we can do more. In this spirit, we design the OS core to provide high-level APIs that are largely independent of the underlying hardware and implement it with two targets: one target is as part of a regular OS in kernel space and the other is as a library OS in user space. This way, all the OS components of Asterinas, which are stacked above the OS core, can be developed, tested, and debugged in user space, which is more friendly to developers than kernel space.
-**4. High-fidelity Linux ABI.** An OS without usable applications is useless. So we believe it is important for Jinux to fit in an established and thriving ecosystem of software, such as the one around Linux. This is why we conclude that Jinux should aim at implementing high-fidelity Linux ABI, including the system calls, the proc file system, etc.
+**4. High-fidelity Linux ABI.** An OS without usable applications is useless. So we believe it is important for Asterinas to fit in an established and thriving ecosystem of software, such as the one around Linux. This is why we conclude that Asterinas should aim at implementing high-fidelity Linux ABI, including the system calls, the proc file system, etc.
**5. TEEs as top-tier targets.** (Todo)
diff --git a/docs/src/capabilities/zero_cost_capabilities.md b/docs/src/capabilities/zero_cost_capabilities.md
--- a/docs/src/capabilities/zero_cost_capabilities.md
+++ b/docs/src/capabilities/zero_cost_capabilities.md
@@ -351,7 +351,7 @@ mod test {
### Implement access rights with typeflags
-The `Jinux-rights/lib.rs` file implements access rights.
+The `aster-rights/lib.rs` file implements access rights.
```rust
//! Access rights.
diff --git a/framework/README.md b/framework/README.md
--- a/framework/README.md
+++ b/framework/README.md
@@ -1,20 +1,20 @@
-# Jinux Framework
+# Asterinas Framework
-Jinux Framework is a Rust OS framework that facilitates the development of and innovation in OS kernels written in Rust.
+Asterinas Framework is a Rust OS framework that facilitates the development of and innovation in OS kernels written in Rust.
## An overview
-Jinux Framework provides a solid foundation for Rust developers to build their own OS kernels. While Jinux Framework origins from Jinux, the first ever framekernel, Jinux Framework is well suited for building OS kernels of any architecture, be it a framekernel, a monolithic kernel, or a microkernel.
+Asterinas Framework provides a solid foundation for Rust developers to build their own OS kernels. While Asterinas Framework origins from Asterinas, the first ever framekernel, Asterinas Framework is well suited for building OS kernels of any architecture, be it a framekernel, a monolithic kernel, or a microkernel.
-Jinux Framework offers the following key values.
+Asterinas Framework offers the following key values.
-1. **Lowering the entry bar for OS innovation.** Building an OS from scratch is not easy. Not to mention a novel one. Before adding any novel or interesting feature, an OS developer must first have something runnable, which must include basic functionalities for managing CPU, memory, and interrupts. Jinux Framework has laid this groundwork so that OS developers do not have to deal with the most low-level, error-prone, architecture-specific aspects of OS development themselves.
+1. **Lowering the entry bar for OS innovation.** Building an OS from scratch is not easy. Not to mention a novel one. Before adding any novel or interesting feature, an OS developer must first have something runnable, which must include basic functionalities for managing CPU, memory, and interrupts. Asterinas Framework has laid this groundwork so that OS developers do not have to deal with the most low-level, error-prone, architecture-specific aspects of OS development themselves.
-2. **Enhancing the memory safety of Rust OSes.** Jinux Framework encapsulates low-level, machine-oriented unsafe Rust code into high-level, machine-agnostic safe APIs. These APIs are carefully designed and implemented to be sound and minimal, ensuring the memory safety of any safe Rust callers. Our experience in building Jinux has shown that Jinux Framework is powerful enough to allow a feature-rich, Linux-compatible kernel to be completely written in safe Rust, including its device drivers.
+2. **Enhancing the memory safety of Rust OSes.** Asterinas Framework encapsulates low-level, machine-oriented unsafe Rust code into high-level, machine-agnostic safe APIs. These APIs are carefully designed and implemented to be sound and minimal, ensuring the memory safety of any safe Rust callers. Our experience in building Asterinas has shown that Asterinas Framework is powerful enough to allow a feature-rich, Linux-compatible kernel to be completely written in safe Rust, including its device drivers.
-3. **Promoting code reuse across Rust OS projects.** Shipped as crates, Rust code can be reused across projects---except when they are OSes. A crate that implements a feature or driver for OS A can hardly be reused by OS B because the crate must be [`no_std`](https://docs.rust-embedded.org/book/intro/no-std.html#summary) and depend on the infrastructure APIs provided by OS A, which are obviously different from that provided by OS B. This incompatibility problem can be resolved by Jinux Framework as it can serve as a common ground across different Rust OS projects, as long as they are built upon Jinux Framework.
+3. **Promoting code reuse across Rust OS projects.** Shipped as crates, Rust code can be reused across projects---except when they are OSes. A crate that implements a feature or driver for OS A can hardly be reused by OS B because the crate must be [`no_std`](https://docs.rust-embedded.org/book/intro/no-std.html#summary) and depend on the infrastructure APIs provided by OS A, which are obviously different from that provided by OS B. This incompatibility problem can be resolved by Asterinas Framework as it can serve as a common ground across different Rust OS projects, as long as they are built upon Asterinas Framework.
-4. **Boost productivity with user-mode development.** Traditionally, developing a kernel feature involves countless rounds of coding, failing, and rebooting on bare-metal or virtual machines, which is a painfully slow process. Jinux Framework accelerates the process by allowing high-level OS features like file systems and network stacks to be quickly tested in user mode, making the experience of OS development as smooth as that of application development. To support user-mode development, Jinux Framework is implemented for the Linux platform, in addition to bare-mental or virtual machine environments.
+4. **Boost productivity with user-mode development.** Traditionally, developing a kernel feature involves countless rounds of coding, failing, and rebooting on bare-metal or virtual machines, which is a painfully slow process. Asterinas Framework accelerates the process by allowing high-level OS features like file systems and network stacks to be quickly tested in user mode, making the experience of OS development as smooth as that of application development. To support user-mode development, Asterinas Framework is implemented for the Linux platform, in addition to bare-mental or virtual machine environments.
## Framework APIs
diff --git a/framework/jinux-frame/Cargo.toml b/framework/aster-frame/Cargo.toml
--- a/framework/jinux-frame/Cargo.toml
+++ b/framework/aster-frame/Cargo.toml
@@ -13,17 +13,17 @@ bitvec = { version = "1.0", default-features = false, features = ["alloc"] }
buddy_system_allocator = "0.9.0"
cfg-if = "1.0"
gimli = { version = "0.28", default-features = false, features = ["read-core"] }
-inherit-methods-macro = { git = "https://github.com/jinzhao-dev/inherit-methods-macro", rev = "98f7e3e" }
+inherit-methods-macro = { git = "https://github.com/asterinas/inherit-methods-macro", rev = "98f7e3e" }
int-to-c-enum = { path = "../../services/libs/int-to-c-enum" }
intrusive-collections = "0.9.5"
ktest = { path = "../libs/ktest" }
lazy_static = { version = "1.0", features = ["spin_no_std"] }
log = "0.4"
-pod = { git = "https://github.com/jinzhao-dev/pod", rev = "d7dba56" }
+pod = { git = "https://github.com/asterinas/pod", rev = "d7dba56" }
spin = "0.9.4"
static_assertions = "1.1.0"
tdx-guest = { path = "../libs/tdx-guest", optional = true }
-trapframe = { git = "https://github.com/jinzhao-dev/trapframe-rs", rev = "9758a83" }
+trapframe = { git = "https://github.com/asterinas/trapframe-rs", rev = "2f37590" }
unwinding = { version = "0.2.1", default-features = false, features = ["fde-static", "hide-trace", "panic", "personality", "unwinder"] }
volatile = { version = "0.4.5", features = ["unstable"] }
diff --git a/framework/jinux-frame/src/boot/mod.rs b/framework/aster-frame/src/boot/mod.rs
--- a/framework/jinux-frame/src/boot/mod.rs
+++ b/framework/aster-frame/src/boot/mod.rs
@@ -103,17 +103,17 @@ pub fn init() {
/// Call the framework-user defined entrypoint of the actual kernel.
///
-/// Any kernel that uses the jinux-frame crate should define a function named
-/// `jinux_main` as the entrypoint.
-pub fn call_jinux_main() -> ! {
+/// Any kernel that uses the aster-frame crate should define a function named
+/// `aster_main` as the entrypoint.
+pub fn call_aster_main() -> ! {
#[cfg(not(ktest))]
unsafe {
// The entry point of kernel code, which should be defined by the package that
- // uses jinux-frame.
+ // uses aster-frame.
extern "Rust" {
- fn jinux_main() -> !;
+ fn aster_main() -> !;
}
- jinux_main();
+ aster_main();
}
#[cfg(ktest)]
{
diff --git a/framework/libs/ktest/src/lib.rs b/framework/libs/ktest/src/lib.rs
--- a/framework/libs/ktest/src/lib.rs
+++ b/framework/libs/ktest/src/lib.rs
@@ -1,10 +1,10 @@
-//! # The kernel mode testing framework of Jinux.
+//! # The kernel mode testing framework of Asterinas.
//!
//! `ktest` stands for kernel-mode testing framework. Its goal is to provide a
//! `cargo test`-like experience for any `#![no_std]` bare metal crates.
//!
-//! In Jinux, all the tests written in the source tree of the crates will be run
-//! immediately after the initialization of jinux-frame. Thus you can use any
+//! In Asterinas, all the tests written in the source tree of the crates will be run
+//! immediately after the initialization of aster-frame. Thus you can use any
//! feature provided by the frame including the heap allocator, etc.
//!
//! By all means, ktest is an individule crate that only requires:
diff --git a/framework/libs/ktest/src/lib.rs b/framework/libs/ktest/src/lib.rs
--- a/framework/libs/ktest/src/lib.rs
+++ b/framework/libs/ktest/src/lib.rs
@@ -39,7 +39,7 @@
//! }
//! ```
//!
-//! And also, any crates using the ktest framework should be linked with jinux-frame
+//! And also, any crates using the ktest framework should be linked with aster-frame
//! and import the `ktest` crate:
//!
//! ```toml
diff --git a/framework/libs/ktest/src/lib.rs b/framework/libs/ktest/src/lib.rs
--- a/framework/libs/ktest/src/lib.rs
+++ b/framework/libs/ktest/src/lib.rs
@@ -67,14 +67,14 @@
//! This is achieved by a whitelist filter on the test name.
//!
//! ```bash
-//! make run KTEST=1 KTEST_WHITELIST=failing_assertion,jinux_frame::test::expect_panic
+//! make run KTEST=1 KTEST_WHITELIST=failing_assertion,aster_frame::test::expect_panic
//! ```
//!
//! `KTEST_CRATES` variable is used to specify in which crates the tests to be run.
//! This is achieved by conditionally compiling the test module using the `#[cfg]`.
//!
//! ```bash
-//! make run KTEST=1 KTEST_CRATES=jinux-frame
+//! make run KTEST=1 KTEST_CRATES=aster-frame
//! ``
//!
//! We support the `#[should_panic]` attribute just in the same way as the standard
diff --git a/regression/apps/signal_c/signal_test.c b/regression/apps/signal_c/signal_test.c
--- a/regression/apps/signal_c/signal_test.c
+++ b/regression/apps/signal_c/signal_test.c
@@ -184,7 +184,7 @@ int test_handle_sigfpe() {
c = div_maybe_zero(a, b);
fxsave(y);
- // jinux does not save and restore fpregs now, so we emit this check.
+ // Asterinas does not save and restore fpregs now, so we emit this check.
// if (memcmp(x, y, 512) != 0) {
// THROW_ERROR("floating point registers are modified");
// }
diff --git a/regression/syscall_test/Makefile b/regression/syscall_test/Makefile
--- a/regression/syscall_test/Makefile
+++ b/regression/syscall_test/Makefile
@@ -3,8 +3,8 @@ TESTS ?= open_test read_test statfs_test chmod_test pty_test uidgid_test vdso_cl
MKFILE_PATH := $(abspath $(lastword $(MAKEFILE_LIST)))
CUR_DIR := $(patsubst %/,%,$(dir $(MKFILE_PATH)))
BUILD_DIR ?= $(CUR_DIR)/../build
-ifdef JINUX_PREBUILT_SYSCALL_TEST
- BIN_DIR := $(JINUX_PREBUILT_SYSCALL_TEST)
+ifdef ASTER_PREBUILT_SYSCALL_TEST
+ BIN_DIR := $(ASTER_PREBUILT_SYSCALL_TEST)
else
BIN_DIR := $(BUILD_DIR)/syscall_test_bins
SRC_DIR := $(BUILD_DIR)/gvisor_src
diff --git a/regression/syscall_test/Makefile b/regression/syscall_test/Makefile
--- a/regression/syscall_test/Makefile
+++ b/regression/syscall_test/Makefile
@@ -21,7 +21,7 @@ all: $(TESTS)
$(TESTS): $(BIN_DIR) $(TARGET_DIR)
@cp -f $</$@ $(TARGET_DIR)/tests
-ifndef JINUX_PREBUILT_SYSCALL_TEST
+ifndef ASTER_PREBUILT_SYSCALL_TEST
$(BIN_DIR): $(SRC_DIR)
@if ! type bazel > /dev/null; then \
echo "bazel is not installed, please run $(CUR_DIR)/install_bazel.sh with sudo permission to install it."; \
diff --git a/regression/syscall_test/Makefile b/regression/syscall_test/Makefile
--- a/regression/syscall_test/Makefile
+++ b/regression/syscall_test/Makefile
@@ -33,7 +33,7 @@ $(BIN_DIR): $(SRC_DIR)
$(SRC_DIR):
@rm -rf $@ && mkdir -p $@
- @cd $@ && git clone -b 20200921.0 https://github.com/jinzhao-dev/gvisor.git .
+ @cd $@ && git clone -b 20200921.0 https://github.com/asterinas/gvisor.git .
endif
$(TARGET_DIR): $(RUN_BASH) $(BLOCK_LIST)
diff --git a/runner/src/main.rs b/runner/src/main.rs
--- a/runner/src/main.rs
+++ b/runner/src/main.rs
@@ -1,8 +1,8 @@
-//! jinux-runner is the Jinux runner script to ease the pain of running
-//! and testing Jinux inside a QEMU VM. It should be built and run as the
+//! aster-runner is the Asterinas runner script to ease the pain of running
+//! and testing Asterinas inside a QEMU VM. It should be built and run as the
//! cargo runner: https://doc.rust-lang.org/cargo/reference/config.html
//!
-//! The runner will generate the filesystem image for starting Jinux. If
+//! The runner will generate the filesystem image for starting Asterinas. If
//! we should use the runner in the default mode, which invokes QEMU with
//! a GRUB boot device image, the runner would be responsible for generating
//! the appropriate kernel image and the boot device image. It also supports
diff --git a/services/libs/jinux-std/src/driver/mod.rs b/services/libs/aster-std/src/driver/mod.rs
--- a/services/libs/jinux-std/src/driver/mod.rs
+++ b/services/libs/aster-std/src/driver/mod.rs
@@ -2,14 +2,14 @@ use log::info;
pub fn init() {
// print all the input device to make sure input crate will compile
- for (name, _) in jinux_input::all_devices() {
+ for (name, _) in aster_input::all_devices() {
info!("Found Input device, name:{}", name);
}
}
#[allow(unused)]
fn block_device_test() {
- for (_, device) in jinux_block::all_devices() {
+ for (_, device) in aster_block::all_devices() {
let mut write_buffer = [0u8; 512];
let mut read_buffer = [0u8; 512];
info!("write_buffer address:{:x}", write_buffer.as_ptr() as usize);
diff --git a/services/libs/jinux-std/src/vm/vmar/options.rs b/services/libs/aster-std/src/vm/vmar/options.rs
--- a/services/libs/jinux-std/src/vm/vmar/options.rs
+++ b/services/libs/aster-std/src/vm/vmar/options.rs
@@ -139,8 +139,8 @@ mod test {
use crate::vm::perms::VmPerms;
use crate::vm::vmo::VmoRightsOp;
use crate::vm::{vmar::ROOT_VMAR_HIGHEST_ADDR, vmo::VmoOptions};
- use jinux_frame::vm::VmIo;
- use jinux_rights::Full;
+ use aster_frame::vm::VmIo;
+ use aster_rights::Full;
#[ktest]
fn root_vmar() {
diff --git a/services/libs/jinux-std/src/vm/vmo/options.rs b/services/libs/aster-std/src/vm/vmo/options.rs
--- a/services/libs/jinux-std/src/vm/vmo/options.rs
+++ b/services/libs/aster-std/src/vm/vmo/options.rs
@@ -519,8 +519,8 @@ impl VmoChildType for VmoCowChild {}
#[if_cfg_ktest]
mod test {
use super::*;
- use jinux_frame::vm::VmIo;
- use jinux_rights::Full;
+ use aster_frame::vm::VmIo;
+ use aster_rights::Full;
#[ktest]
fn alloc_vmo() {
diff --git a/services/libs/jinux-util/Cargo.toml b/services/libs/aster-util/Cargo.toml
--- a/services/libs/jinux-util/Cargo.toml
+++ b/services/libs/aster-util/Cargo.toml
@@ -1,16 +1,16 @@
[package]
-name = "jinux-util"
+name = "aster-util"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
-jinux-frame = { path = "../../../framework/jinux-frame" }
-pod = { git = "https://github.com/jinzhao-dev/pod", rev = "d7dba56" }
+aster-frame = { path = "../../../framework/aster-frame" }
+pod = { git = "https://github.com/asterinas/pod", rev = "d7dba56" }
typeflags-util = { path = "../typeflags-util" }
-jinux-rights-proc = { path = "../jinux-rights-proc" }
-jinux-rights = { path = "../jinux-rights" }
+aster-rights-proc = { path = "../aster-rights-proc" }
+aster-rights = { path = "../aster-rights" }
bitvec = { version = "1.0", default-features = false, features = ["alloc"] }
ktest = { path = "../../../framework/libs/ktest" }
[features]
diff --git a/tools/docker/Dockerfile.ubuntu22.04 b/tools/docker/Dockerfile.ubuntu22.04
--- a/tools/docker/Dockerfile.ubuntu22.04
+++ b/tools/docker/Dockerfile.ubuntu22.04
@@ -226,7 +226,7 @@ RUN apt clean && rm -rf /var/lib/apt/lists/*
# Prepare the system call test suite
COPY --from=syscall_test /root/syscall_test/build/syscall_test_bins /root/syscall_test_bins
-ENV JINUX_PREBUILT_SYSCALL_TEST=/root/syscall_test_bins
+ENV ASTER_PREBUILT_SYSCALL_TEST=/root/syscall_test_bins
# Install QEMU built from the previous stages
COPY --from=qemu /usr/local/qemu /usr/local/qemu
diff --git a/tools/docker/README.md b/tools/docker/README.md
--- a/tools/docker/README.md
+++ b/tools/docker/README.md
@@ -1,35 +1,35 @@
-# Jinux Development Docker Images
+# Asterinas Development Docker Images
-Jinux development Docker images are provided to facilitate developing and testing Jinux project. These images can be found in the [jinuxdev/jinux](https://hub.docker.com/r/jinuxdev/jinux/) repository on DockerHub.
+Asterinas development Docker images are provided to facilitate developing and testing Asterinas project. These images can be found in the [asterinas/asterinas](https://hub.docker.com/r/asterinas/asterinas/) repository on DockerHub.
## Building Docker Images
-To build a Docker image for Jinux and test it on your local machine, navigate to the root directory of the Jinux source code tree and execute the following command:
+To build a Docker image for Asterinas and test it on your local machine, navigate to the root directory of the Asterinas source code tree and execute the following command:
```bash
docker buildx build \
-f tools/docker/Dockerfile.ubuntu22.04 \
- --build-arg JINUX_RUST_VERSION=$RUST_VERSION \
- -t jinuxdev/jinux:$JINUX_VERSION \
+ --build-arg ASTER_RUST_VERSION=$RUST_VERSION \
+ -t asterinas/asterinas:$ASTER_VERSION \
.
```
The meanings of the two environment variables in the command are as follows:
-- `$JINUX_VERSION`: Represents the version number of Jinux. You can find this in the `VERSION` file.
+- `$ASTER_VERSION`: Represents the version number of Asterinas. You can find this in the `VERSION` file.
- `$RUST_VERSION`: Denotes the required Rust toolchain version, as specified in the `rust-toolchain` file.
## Tagging Docker Images
-It's essential for each Jinux Docker image to have a distinct tag. By convention, the tag is assigned with the version number of the Jinux project itself. This methodology ensures clear correspondence between a commit of the source code and its respective Docker image.
+It's essential for each Asterinas Docker image to have a distinct tag. By convention, the tag is assigned with the version number of the Asterinas project itself. This methodology ensures clear correspondence between a commit of the source code and its respective Docker image.
If a commit needs to create a new Docker image, it should
1. Update the Dockerfile as well as other materials relevant to the Docker image, and
-2. Run [`tools/bump_version.sh`](../bump_version.sh) tool to update the Jinux project's version number.
+2. Run [`tools/bump_version.sh`](../bump_version.sh) tool to update the Asterinas project's version number.
For bug fixes or small changes, increment the last number of a [SemVer](https://semver.org/) by one. For major features or releases, increment the second number. All changes made in the two steps should be included in the commit.
## Uploading Docker Images
-New versions of Jinux's Docker images are automatically uploaded to DockerHub through Github Actions. Simply submit your PR that updates Jinux's Docker image for review. After getting the project maintainers' approval, the [Docker image building workflow](../../.github/workflows/docker_build.yml) will be started, building the new Docker image and pushing it to DockerHub.
\ No newline at end of file
+New versions of Asterinas's Docker images are automatically uploaded to DockerHub through Github Actions. Simply submit your PR that updates Asterinas's Docker image for review. After getting the project maintainers' approval, the [Docker image building workflow](../../.github/workflows/docker_build.yml) will be started, building the new Docker image and pushing it to DockerHub.
\ No newline at end of file
|
[
"551"
] |
0.2
|
6dbf5d560deafea0dcec228e4cb2d5e53c756174
|
Rename the project name from Jinux to Asterinas
The project's official name will be Asterinas. The renaming process consists of the following steps:
1. The Github repo will be renamed to `asterinas` and moved to the `asterinas` Github org.
2. The DockerHub Image will be moved to `asterinas/asterinas`.
3. All occurrences of `Jinux` in the codebase should be renamed to `Asterinas`.
4. All occurrences of `jinux-` (or `jinux_`) as in the codebase should be renamed to `aster-` (or `aster_`).
5. The ascii-art LOGO should be replaced accordingly.
We will make the project open source as long as we are given the green light by the management. Renaming will be done the first day when the project is open sourced.
|
asterinas__asterinas-561
| 561
|
diff --git a/.cargo/config.toml b/.cargo/config.toml
--- a/.cargo/config.toml
+++ b/.cargo/config.toml
@@ -1,6 +1,6 @@
[target.'cfg(target_os = "none")']
-runner = "cargo run --package jinux-runner --"
+runner = "cargo run --package aster-runner --"
[alias]
kcheck = "check --target x86_64-custom.json -Zbuild-std=core,alloc,compiler_builtins -Zbuild-std-features=compiler-builtins-mem"
diff --git a/.cargo/config.toml b/.cargo/config.toml
--- a/.cargo/config.toml
+++ b/.cargo/config.toml
@@ -1,6 +1,6 @@
[target.'cfg(target_os = "none")']
-runner = "cargo run --package jinux-runner --"
+runner = "cargo run --package aster-runner --"
[alias]
kcheck = "check --target x86_64-custom.json -Zbuild-std=core,alloc,compiler_builtins -Zbuild-std-features=compiler-builtins-mem"
diff --git a/.github/workflows/cargo_check.yml b/.github/workflows/cargo_check.yml
--- a/.github/workflows/cargo_check.yml
+++ b/.github/workflows/cargo_check.yml
@@ -10,9 +10,9 @@ jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 10
- container: jinuxdev/jinux:0.2.2
+ container: asterinas/asterinas:0.2.2
steps:
- - run: echo "Running in jinuxdev/jinux:0.2.2"
+ - run: echo "Running in asterinas/asterinas:0.2.2"
- uses: actions/checkout@v3
diff --git a/.github/workflows/docker_build.yml b/.github/workflows/docker_build.yml
--- a/.github/workflows/docker_build.yml
+++ b/.github/workflows/docker_build.yml
@@ -26,7 +26,7 @@ jobs:
- name: Fetch versions in the repo
id: fetch-versions
run: |
- echo "jinux_version=$( cat VERSION )" >> "$GITHUB_OUTPUT"
+ echo "aster_version=$( cat VERSION )" >> "$GITHUB_OUTPUT"
echo "rust_version=$( grep -m1 -o 'nightly-[0-9]\+-[0-9]\+-[0-9]\+' rust-toolchain.toml )" >> "$GITHUB_OUTPUT"
- name: Build and push
diff --git a/.github/workflows/docker_build.yml b/.github/workflows/docker_build.yml
--- a/.github/workflows/docker_build.yml
+++ b/.github/workflows/docker_build.yml
@@ -26,7 +26,7 @@ jobs:
- name: Fetch versions in the repo
id: fetch-versions
run: |
- echo "jinux_version=$( cat VERSION )" >> "$GITHUB_OUTPUT"
+ echo "aster_version=$( cat VERSION )" >> "$GITHUB_OUTPUT"
echo "rust_version=$( grep -m1 -o 'nightly-[0-9]\+-[0-9]\+-[0-9]\+' rust-toolchain.toml )" >> "$GITHUB_OUTPUT"
- name: Build and push
diff --git a/.github/workflows/docker_build.yml b/.github/workflows/docker_build.yml
--- a/.github/workflows/docker_build.yml
+++ b/.github/workflows/docker_build.yml
@@ -36,6 +36,6 @@ jobs:
file: ./tools/docker/Dockerfile.ubuntu22.04
platforms: linux/amd64
push: true
- tags: jinuxdev/jinux:${{ steps.fetch-versions.outputs.jinux_version }}
+ tags: asterinas/asterinas:${{ steps.fetch-versions.outputs.aster_version }}
build-args: |
- "JINUX_RUST_VERSION=${{ steps.fetch-versions.outputs.rust_version }}"
+ "ASTER_RUST_VERSION=${{ steps.fetch-versions.outputs.rust_version }}"
diff --git a/.github/workflows/docker_build.yml b/.github/workflows/docker_build.yml
--- a/.github/workflows/docker_build.yml
+++ b/.github/workflows/docker_build.yml
@@ -36,6 +36,6 @@ jobs:
file: ./tools/docker/Dockerfile.ubuntu22.04
platforms: linux/amd64
push: true
- tags: jinuxdev/jinux:${{ steps.fetch-versions.outputs.jinux_version }}
+ tags: asterinas/asterinas:${{ steps.fetch-versions.outputs.aster_version }}
build-args: |
- "JINUX_RUST_VERSION=${{ steps.fetch-versions.outputs.rust_version }}"
+ "ASTER_RUST_VERSION=${{ steps.fetch-versions.outputs.rust_version }}"
diff --git a/.github/workflows/integration_test.yml b/.github/workflows/integration_test.yml
--- a/.github/workflows/integration_test.yml
+++ b/.github/workflows/integration_test.yml
@@ -10,9 +10,9 @@ jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 30
- container: jinuxdev/jinux:0.2.2
+ container: asterinas/asterinas:0.2.2
steps:
- - run: echo "Running in jinuxdev/jinux:0.2.2"
+ - run: echo "Running in asterinas/asterinas:0.2.2"
- uses: actions/checkout@v3
diff --git a/.github/workflows/unit_test.yml b/.github/workflows/unit_test.yml
--- a/.github/workflows/unit_test.yml
+++ b/.github/workflows/unit_test.yml
@@ -10,9 +10,9 @@ jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 15
- container: jinuxdev/jinux:0.2.2
+ container: asterinas/asterinas:0.2.2
steps:
- - run: echo "Running in jinuxdev/jinux:0.2.2"
+ - run: echo "Running in asterinas/asterinas:0.2.2"
- uses: actions/checkout@v3
diff --git a/COPYRIGHT b/COPYRIGHT
--- a/COPYRIGHT
+++ b/COPYRIGHT
@@ -1,9 +1,9 @@
-The Jinux project licensed under the GNU General Public License version 2.
+The Asterinas project licensed under the GNU General Public License version 2.
-Copyrights in the Jinux project are retained by their contributors. No
-copyright assignment is required to contribute to the Jinux project.
+Copyrights in the Asterinas project are retained by their contributors. No
+copyright assignment is required to contribute to the Asterinas project.
For full authorship information, see the version control history.
-Please note that certain files or directories within the Jinux project may
+Please note that certain files or directories within the Asterinas project may
contain explicit copyright notices and/or license notices differ
from the project's general license terms.
diff --git a/COPYRIGHT b/COPYRIGHT
--- a/COPYRIGHT
+++ b/COPYRIGHT
@@ -1,9 +1,9 @@
-The Jinux project licensed under the GNU General Public License version 2.
+The Asterinas project licensed under the GNU General Public License version 2.
-Copyrights in the Jinux project are retained by their contributors. No
-copyright assignment is required to contribute to the Jinux project.
+Copyrights in the Asterinas project are retained by their contributors. No
+copyright assignment is required to contribute to the Asterinas project.
For full authorship information, see the version control history.
-Please note that certain files or directories within the Jinux project may
+Please note that certain files or directories within the Asterinas project may
contain explicit copyright notices and/or license notices differ
from the project's general license terms.
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -113,6 +113,250 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16"
+[[package]]
+name = "aster-block"
+version = "0.1.0"
+dependencies = [
+ "aster-frame",
+ "aster-util",
+ "bitflags 1.3.2",
+ "component",
+ "lazy_static",
+ "log",
+ "spin 0.9.8",
+]
+
+[[package]]
+name = "aster-console"
+version = "0.1.0"
+dependencies = [
+ "aster-frame",
+ "aster-util",
+ "bitflags 1.3.2",
+ "component",
+ "log",
+ "spin 0.9.8",
+]
+
+[[package]]
+name = "aster-frame"
+version = "0.1.0"
+dependencies = [
+ "acpi",
+ "align_ext",
+ "aml",
+ "bit_field",
+ "bitflags 1.3.2",
+ "bitvec",
+ "buddy_system_allocator",
+ "cfg-if",
+ "gimli",
+ "inherit-methods-macro",
+ "int-to-c-enum",
+ "intrusive-collections",
+ "ktest",
+ "lazy_static",
+ "log",
+ "multiboot2",
+ "pod",
+ "rsdp",
+ "spin 0.9.8",
+ "static_assertions",
+ "tdx-guest",
+ "trapframe",
+ "unwinding",
+ "volatile",
+ "x86",
+ "x86_64",
+]
+
+[[package]]
+name = "aster-frame-x86-boot-linux-setup"
+version = "0.1.0"
+dependencies = [
+ "uart_16550",
+ "xmas-elf",
+]
+
+[[package]]
+name = "aster-framebuffer"
+version = "0.1.0"
+dependencies = [
+ "aster-frame",
+ "component",
+ "font8x8",
+ "log",
+ "spin 0.9.8",
+]
+
+[[package]]
+name = "aster-input"
+version = "0.1.0"
+dependencies = [
+ "aster-frame",
+ "aster-rights",
+ "aster-util",
+ "bitflags 1.3.2",
+ "component",
+ "lazy_static",
+ "log",
+ "spin 0.9.8",
+ "virtio-input-decoder",
+]
+
+[[package]]
+name = "aster-network"
+version = "0.1.0"
+dependencies = [
+ "align_ext",
+ "aster-frame",
+ "aster-rights",
+ "aster-util",
+ "bitflags 1.3.2",
+ "bytes",
+ "component",
+ "int-to-c-enum",
+ "log",
+ "pod",
+ "ringbuf",
+ "smoltcp",
+ "spin 0.9.8",
+]
+
+[[package]]
+name = "aster-rights"
+version = "0.1.0"
+dependencies = [
+ "aster-rights-proc",
+ "bitflags 1.3.2",
+ "typeflags",
+ "typeflags-util",
+]
+
+[[package]]
+name = "aster-rights-proc"
+version = "0.1.0"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+]
+
+[[package]]
+name = "aster-runner"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "clap",
+ "glob",
+ "rand",
+ "xmas-elf",
+]
+
+[[package]]
+name = "aster-std"
+version = "0.1.0"
+dependencies = [
+ "align_ext",
+ "ascii",
+ "aster-block",
+ "aster-console",
+ "aster-frame",
+ "aster-input",
+ "aster-network",
+ "aster-rights",
+ "aster-rights-proc",
+ "aster-time",
+ "aster-util",
+ "aster-virtio",
+ "bitflags 1.3.2",
+ "controlled",
+ "core2",
+ "cpio-decoder",
+ "getrandom",
+ "int-to-c-enum",
+ "intrusive-collections",
+ "keyable-arc",
+ "ktest",
+ "lazy_static",
+ "lending-iterator",
+ "libflate",
+ "log",
+ "lru",
+ "pod",
+ "ringbuf",
+ "smoltcp",
+ "spin 0.9.8",
+ "tdx-guest",
+ "time",
+ "typeflags",
+ "typeflags-util",
+ "virtio-input-decoder",
+ "vte",
+ "xmas-elf",
+]
+
+[[package]]
+name = "aster-time"
+version = "0.1.0"
+dependencies = [
+ "aster-frame",
+ "aster-util",
+ "component",
+ "log",
+ "spin 0.9.8",
+]
+
+[[package]]
+name = "aster-util"
+version = "0.1.0"
+dependencies = [
+ "aster-frame",
+ "aster-rights",
+ "aster-rights-proc",
+ "bitvec",
+ "ktest",
+ "pod",
+ "typeflags-util",
+]
+
+[[package]]
+name = "aster-virtio"
+version = "0.1.0"
+dependencies = [
+ "align_ext",
+ "aster-block",
+ "aster-console",
+ "aster-frame",
+ "aster-input",
+ "aster-network",
+ "aster-rights",
+ "aster-util",
+ "bit_field",
+ "bitflags 1.3.2",
+ "bytes",
+ "component",
+ "int-to-c-enum",
+ "log",
+ "pod",
+ "smoltcp",
+ "spin 0.9.8",
+ "typeflags-util",
+ "virtio-input-decoder",
+]
+
+[[package]]
+name = "asterinas"
+version = "0.2.2"
+dependencies = [
+ "aster-frame",
+ "aster-framebuffer",
+ "aster-std",
+ "aster-time",
+ "component",
+ "x86_64",
+]
+
[[package]]
name = "atomic-polyfill"
version = "0.1.11"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -552,7 +796,7 @@ dependencies = [
[[package]]
name = "inherit-methods-macro"
version = "0.1.0"
-source = "git+https://github.com/jinzhao-dev/inherit-methods-macro?rev=98f7e3e#98f7e3eb9efdac98faf5a7076f154f30894b9b02"
+source = "git+https://github.com/asterinas/inherit-methods-macro?rev=98f7e3e#98f7e3eb9efdac98faf5a7076f154f30894b9b02"
dependencies = [
"darling",
"proc-macro2",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -552,7 +796,7 @@ dependencies = [
[[package]]
name = "inherit-methods-macro"
version = "0.1.0"
-source = "git+https://github.com/jinzhao-dev/inherit-methods-macro?rev=98f7e3e#98f7e3eb9efdac98faf5a7076f154f30894b9b02"
+source = "git+https://github.com/asterinas/inherit-methods-macro?rev=98f7e3e#98f7e3eb9efdac98faf5a7076f154f30894b9b02"
dependencies = [
"darling",
"proc-macro2",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -603,250 +847,6 @@ dependencies = [
"either",
]
-[[package]]
-name = "jinux"
-version = "0.2.2"
-dependencies = [
- "component",
- "jinux-frame",
- "jinux-framebuffer",
- "jinux-std",
- "jinux-time",
- "x86_64",
-]
-
-[[package]]
-name = "jinux-block"
-version = "0.1.0"
-dependencies = [
- "bitflags 1.3.2",
- "component",
- "jinux-frame",
- "jinux-util",
- "lazy_static",
- "log",
- "spin 0.9.8",
-]
-
-[[package]]
-name = "jinux-console"
-version = "0.1.0"
-dependencies = [
- "bitflags 1.3.2",
- "component",
- "jinux-frame",
- "jinux-util",
- "log",
- "spin 0.9.8",
-]
-
-[[package]]
-name = "jinux-frame"
-version = "0.1.0"
-dependencies = [
- "acpi",
- "align_ext",
- "aml",
- "bit_field",
- "bitflags 1.3.2",
- "bitvec",
- "buddy_system_allocator",
- "cfg-if",
- "gimli",
- "inherit-methods-macro",
- "int-to-c-enum",
- "intrusive-collections",
- "ktest",
- "lazy_static",
- "log",
- "multiboot2",
- "pod",
- "rsdp",
- "spin 0.9.8",
- "static_assertions",
- "tdx-guest",
- "trapframe",
- "unwinding",
- "volatile",
- "x86",
- "x86_64",
-]
-
-[[package]]
-name = "jinux-frame-x86-boot-linux-setup"
-version = "0.1.0"
-dependencies = [
- "uart_16550",
- "xmas-elf",
-]
-
-[[package]]
-name = "jinux-framebuffer"
-version = "0.1.0"
-dependencies = [
- "component",
- "font8x8",
- "jinux-frame",
- "log",
- "spin 0.9.8",
-]
-
-[[package]]
-name = "jinux-input"
-version = "0.1.0"
-dependencies = [
- "bitflags 1.3.2",
- "component",
- "jinux-frame",
- "jinux-rights",
- "jinux-util",
- "lazy_static",
- "log",
- "spin 0.9.8",
- "virtio-input-decoder",
-]
-
-[[package]]
-name = "jinux-network"
-version = "0.1.0"
-dependencies = [
- "align_ext",
- "bitflags 1.3.2",
- "bytes",
- "component",
- "int-to-c-enum",
- "jinux-frame",
- "jinux-rights",
- "jinux-util",
- "log",
- "pod",
- "ringbuf",
- "smoltcp",
- "spin 0.9.8",
-]
-
-[[package]]
-name = "jinux-rights"
-version = "0.1.0"
-dependencies = [
- "bitflags 1.3.2",
- "jinux-rights-proc",
- "typeflags",
- "typeflags-util",
-]
-
-[[package]]
-name = "jinux-rights-proc"
-version = "0.1.0"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn 1.0.109",
-]
-
-[[package]]
-name = "jinux-runner"
-version = "0.1.0"
-dependencies = [
- "anyhow",
- "clap",
- "glob",
- "rand",
- "xmas-elf",
-]
-
-[[package]]
-name = "jinux-std"
-version = "0.1.0"
-dependencies = [
- "align_ext",
- "ascii",
- "bitflags 1.3.2",
- "controlled",
- "core2",
- "cpio-decoder",
- "getrandom",
- "int-to-c-enum",
- "intrusive-collections",
- "jinux-block",
- "jinux-console",
- "jinux-frame",
- "jinux-input",
- "jinux-network",
- "jinux-rights",
- "jinux-rights-proc",
- "jinux-time",
- "jinux-util",
- "jinux-virtio",
- "keyable-arc",
- "ktest",
- "lazy_static",
- "lending-iterator",
- "libflate",
- "log",
- "lru",
- "pod",
- "ringbuf",
- "smoltcp",
- "spin 0.9.8",
- "tdx-guest",
- "time",
- "typeflags",
- "typeflags-util",
- "virtio-input-decoder",
- "vte",
- "xmas-elf",
-]
-
-[[package]]
-name = "jinux-time"
-version = "0.1.0"
-dependencies = [
- "component",
- "jinux-frame",
- "jinux-util",
- "log",
- "spin 0.9.8",
-]
-
-[[package]]
-name = "jinux-util"
-version = "0.1.0"
-dependencies = [
- "bitvec",
- "jinux-frame",
- "jinux-rights",
- "jinux-rights-proc",
- "ktest",
- "pod",
- "typeflags-util",
-]
-
-[[package]]
-name = "jinux-virtio"
-version = "0.1.0"
-dependencies = [
- "align_ext",
- "bit_field",
- "bitflags 1.3.2",
- "bytes",
- "component",
- "int-to-c-enum",
- "jinux-block",
- "jinux-console",
- "jinux-frame",
- "jinux-input",
- "jinux-network",
- "jinux-rights",
- "jinux-util",
- "log",
- "pod",
- "smoltcp",
- "spin 0.9.8",
- "typeflags-util",
- "virtio-input-decoder",
-]
-
[[package]]
name = "json"
version = "0.12.4"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -918,7 +918,7 @@ checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3"
[[package]]
name = "libflate"
version = "1.4.0"
-source = "git+https://github.com/jinzhao-dev/libflate?rev=b781da6#b781da6b6841e380f4cfa3529d5070afad56ea32"
+source = "git+https://github.com/asterinas/libflate?rev=b781da6#b781da6b6841e380f4cfa3529d5070afad56ea32"
dependencies = [
"adler32",
"core2",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -918,7 +918,7 @@ checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3"
[[package]]
name = "libflate"
version = "1.4.0"
-source = "git+https://github.com/jinzhao-dev/libflate?rev=b781da6#b781da6b6841e380f4cfa3529d5070afad56ea32"
+source = "git+https://github.com/asterinas/libflate?rev=b781da6#b781da6b6841e380f4cfa3529d5070afad56ea32"
dependencies = [
"adler32",
"core2",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -929,7 +929,7 @@ dependencies = [
[[package]]
name = "libflate_lz77"
version = "1.2.0"
-source = "git+https://github.com/jinzhao-dev/libflate?rev=b781da6#b781da6b6841e380f4cfa3529d5070afad56ea32"
+source = "git+https://github.com/asterinas/libflate?rev=b781da6#b781da6b6841e380f4cfa3529d5070afad56ea32"
dependencies = [
"core2",
"hashbrown 0.13.2",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -929,7 +929,7 @@ dependencies = [
[[package]]
name = "libflate_lz77"
version = "1.2.0"
-source = "git+https://github.com/jinzhao-dev/libflate?rev=b781da6#b781da6b6841e380f4cfa3529d5070afad56ea32"
+source = "git+https://github.com/asterinas/libflate?rev=b781da6#b781da6b6841e380f4cfa3529d5070afad56ea32"
dependencies = [
"core2",
"hashbrown 0.13.2",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1059,7 +1059,7 @@ checksum = "de3145af08024dea9fa9914f381a17b8fc6034dfb00f3a84013f7ff43f29ed4c"
[[package]]
name = "pod"
version = "0.1.0"
-source = "git+https://github.com/jinzhao-dev/pod?rev=d7dba56#d7dba56cc202a10d483b60aba4f734b1f49cb37b"
+source = "git+https://github.com/asterinas/pod?rev=d7dba56#d7dba56cc202a10d483b60aba4f734b1f49cb37b"
dependencies = [
"pod-derive",
]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1059,7 +1059,7 @@ checksum = "de3145af08024dea9fa9914f381a17b8fc6034dfb00f3a84013f7ff43f29ed4c"
[[package]]
name = "pod"
version = "0.1.0"
-source = "git+https://github.com/jinzhao-dev/pod?rev=d7dba56#d7dba56cc202a10d483b60aba4f734b1f49cb37b"
+source = "git+https://github.com/asterinas/pod?rev=d7dba56#d7dba56cc202a10d483b60aba4f734b1f49cb37b"
dependencies = [
"pod-derive",
]
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1067,7 +1067,7 @@ dependencies = [
[[package]]
name = "pod-derive"
version = "0.1.0"
-source = "git+https://github.com/jinzhao-dev/pod?rev=d7dba56#d7dba56cc202a10d483b60aba4f734b1f49cb37b"
+source = "git+https://github.com/asterinas/pod?rev=d7dba56#d7dba56cc202a10d483b60aba4f734b1f49cb37b"
dependencies = [
"proc-macro2",
"quote",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1067,7 +1067,7 @@ dependencies = [
[[package]]
name = "pod-derive"
version = "0.1.0"
-source = "git+https://github.com/jinzhao-dev/pod?rev=d7dba56#d7dba56cc202a10d483b60aba4f734b1f49cb37b"
+source = "git+https://github.com/asterinas/pod?rev=d7dba56#d7dba56cc202a10d483b60aba4f734b1f49cb37b"
dependencies = [
"proc-macro2",
"quote",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1428,7 +1428,7 @@ dependencies = [
[[package]]
name = "trapframe"
version = "0.9.0"
-source = "git+https://github.com/jinzhao-dev/trapframe-rs?rev=9758a83#9758a83f769c8f4df35413c7ad28ef42c270187e"
+source = "git+https://github.com/asterinas/trapframe-rs?rev=2f37590#2f375901398508edb554deb2f84749153a59bb4a"
dependencies = [
"log",
"pod",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1428,7 +1428,7 @@ dependencies = [
[[package]]
name = "trapframe"
version = "0.9.0"
-source = "git+https://github.com/jinzhao-dev/trapframe-rs?rev=9758a83#9758a83f769c8f4df35413c7ad28ef42c270187e"
+source = "git+https://github.com/asterinas/trapframe-rs?rev=2f37590#2f375901398508edb554deb2f84749153a59bb4a"
dependencies = [
"log",
"pod",
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,21 +1,21 @@
[package]
-name = "jinux"
+name = "asterinas"
version = "0.2.2"
edition = "2021"
[[bin]]
-name = "jinux"
+name = "asterinas"
path = "kernel/main.rs"
[dependencies]
-jinux-frame = { path = "framework/jinux-frame" }
-jinux-std = { path = "services/libs/jinux-std" }
+aster-frame = { path = "framework/aster-frame" }
+aster-std = { path = "services/libs/aster-std" }
component = { path = "services/libs/comp-sys/component" }
[dev-dependencies]
x86_64 = "0.14.2"
-jinux-time = { path = "services/comps/time" }
-jinux-framebuffer = { path = "services/comps/framebuffer" }
+aster-time = { path = "services/comps/time" }
+aster-framebuffer = { path = "services/comps/framebuffer" }
[profile.dev]
opt-level = 0
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,21 +1,21 @@
[package]
-name = "jinux"
+name = "asterinas"
version = "0.2.2"
edition = "2021"
[[bin]]
-name = "jinux"
+name = "asterinas"
path = "kernel/main.rs"
[dependencies]
-jinux-frame = { path = "framework/jinux-frame" }
-jinux-std = { path = "services/libs/jinux-std" }
+aster-frame = { path = "framework/aster-frame" }
+aster-std = { path = "services/libs/aster-std" }
component = { path = "services/libs/comp-sys/component" }
[dev-dependencies]
x86_64 = "0.14.2"
-jinux-time = { path = "services/comps/time" }
-jinux-framebuffer = { path = "services/comps/framebuffer" }
+aster-time = { path = "services/comps/time" }
+aster-framebuffer = { path = "services/comps/framebuffer" }
[profile.dev]
opt-level = 0
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -33,8 +33,8 @@ panic = "unwind"
members = [
"runner",
- "framework/jinux-frame",
- "framework/jinux-frame/src/arch/x86/boot/linux_boot/setup",
+ "framework/aster-frame",
+ "framework/aster-frame/src/arch/x86/boot/linux_boot/setup",
"framework/libs/align_ext",
"framework/libs/ktest",
"framework/libs/tdx-guest",
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -48,10 +48,10 @@ members = [
"services/libs/cpio-decoder",
"services/libs/int-to-c-enum",
"services/libs/int-to-c-enum/derive",
- "services/libs/jinux-rights",
- "services/libs/jinux-rights-proc",
- "services/libs/jinux-std",
- "services/libs/jinux-util",
+ "services/libs/aster-rights",
+ "services/libs/aster-rights-proc",
+ "services/libs/aster-std",
+ "services/libs/aster-util",
"services/libs/keyable-arc",
"services/libs/typeflags",
"services/libs/typeflags-util",
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -48,10 +48,10 @@ members = [
"services/libs/cpio-decoder",
"services/libs/int-to-c-enum",
"services/libs/int-to-c-enum/derive",
- "services/libs/jinux-rights",
- "services/libs/jinux-rights-proc",
- "services/libs/jinux-std",
- "services/libs/jinux-util",
+ "services/libs/aster-rights",
+ "services/libs/aster-rights-proc",
+ "services/libs/aster-std",
+ "services/libs/aster-util",
"services/libs/keyable-arc",
"services/libs/typeflags",
"services/libs/typeflags-util",
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -65,4 +65,4 @@ exclude = [
]
[features]
-intel_tdx = ["jinux-frame/intel_tdx", "jinux-std/intel_tdx"]
+intel_tdx = ["aster-frame/intel_tdx", "aster-std/intel_tdx"]
diff --git a/Cargo.toml b/Cargo.toml
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -65,4 +65,4 @@ exclude = [
]
[features]
-intel_tdx = ["jinux-frame/intel_tdx", "jinux-std/intel_tdx"]
+intel_tdx = ["aster-frame/intel_tdx", "aster-std/intel_tdx"]
diff --git a/Components.toml b/Components.toml
--- a/Components.toml
+++ b/Components.toml
@@ -1,14 +1,14 @@
# template
[components]
-std = { name = "jinux-std" }
-virtio = { name = "jinux-virtio" }
-input = { name = "jinux-input" }
-block = { name = "jinux-block" }
-console = { name = "jinux-console" }
-time = { name = "jinux-time" }
-framebuffer = { name = "jinux-framebuffer" }
-network = { name = "jinux-network" }
-main = { name = "jinux" }
+std = { name = "aster-std" }
+virtio = { name = "aster-virtio" }
+input = { name = "aster-input" }
+block = { name = "aster-block" }
+console = { name = "aster-console" }
+time = { name = "aster-time" }
+framebuffer = { name = "aster-framebuffer" }
+network = { name = "aster-network" }
+main = { name = "asterinas" }
[whitelist]
[whitelist.std.run_first_process]
diff --git a/Components.toml b/Components.toml
--- a/Components.toml
+++ b/Components.toml
@@ -1,14 +1,14 @@
# template
[components]
-std = { name = "jinux-std" }
-virtio = { name = "jinux-virtio" }
-input = { name = "jinux-input" }
-block = { name = "jinux-block" }
-console = { name = "jinux-console" }
-time = { name = "jinux-time" }
-framebuffer = { name = "jinux-framebuffer" }
-network = { name = "jinux-network" }
-main = { name = "jinux" }
+std = { name = "aster-std" }
+virtio = { name = "aster-virtio" }
+input = { name = "aster-input" }
+block = { name = "aster-block" }
+console = { name = "aster-console" }
+time = { name = "aster-time" }
+framebuffer = { name = "aster-framebuffer" }
+network = { name = "aster-network" }
+main = { name = "asterinas" }
[whitelist]
[whitelist.std.run_first_process]
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -1,4 +1,4 @@
-# Make varaiables and defaults, you should refer to jinux-runner for more details
+# Make varaiables and defaults, you should refer to aster-runner for more details
AUTO_TEST ?= none
BOOT_METHOD ?= qemu-grub
BOOT_PROTOCOL ?= multiboot2
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -1,4 +1,4 @@
-# Make varaiables and defaults, you should refer to jinux-runner for more details
+# Make varaiables and defaults, you should refer to aster-runner for more details
AUTO_TEST ?= none
BOOT_METHOD ?= qemu-grub
BOOT_PROTOCOL ?= multiboot2
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -92,8 +92,8 @@ USERMODE_TESTABLE := \
services/libs/cpio-decoder \
services/libs/int-to-c-enum \
services/libs/int-to-c-enum/derive \
- services/libs/jinux-rights \
- services/libs/jinux-rights-proc \
+ services/libs/aster-rights \
+ services/libs/aster-rights-proc \
services/libs/keyable-arc \
services/libs/typeflags \
services/libs/typeflags-util
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -92,8 +92,8 @@ USERMODE_TESTABLE := \
services/libs/cpio-decoder \
services/libs/int-to-c-enum \
services/libs/int-to-c-enum/derive \
- services/libs/jinux-rights \
- services/libs/jinux-rights-proc \
+ services/libs/aster-rights \
+ services/libs/aster-rights-proc \
services/libs/keyable-arc \
services/libs/typeflags \
services/libs/typeflags-util
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -1,45 +1,45 @@
-# Jinux
+# Asterinas
-Jinux is a _secure_, _fast_, and _general-purpose_ OS kernel, written in Rust and providing Linux-compatible ABI.
+Asterinas is a _secure_, _fast_, and _general-purpose_ OS kernel, written in Rust and providing Linux-compatible ABI.
-Jinux is designed and implemented with an emphasis on security, rendering it highly attractive for usage scenarios where Linux ABI is indispensable, but Linux itself is deemed insecure given its sheer size of TCB and its nature of being memory unsafe. An instance of such usage is employing Jinux as the guest OS for VM TEEs (e.g., [AMD SEV](https://www.amd.com/en/developer/sev.html) and [Intel TDX](https://www.intel.com/content/www/us/en/developer/articles/technical/intel-trust-domain-extensions.html)).
+Asterinas is designed and implemented with an emphasis on security, rendering it highly attractive for usage scenarios where Linux ABI is indispensable, but Linux itself is deemed insecure given its sheer size of TCB and its nature of being memory unsafe. An instance of such usage is employing Asterinas as the guest OS for VM TEEs (e.g., [AMD SEV](https://www.amd.com/en/developer/sev.html) and [Intel TDX](https://www.intel.com/content/www/us/en/developer/articles/technical/intel-trust-domain-extensions.html)).
-## What's unique about Jinux
+## What's unique about Asterinas
-Jinux is a _zero-cost_, _least-privilege_ OS kernel. A least-privilege OS is one that adheres to the principle of least privileges, which mandates that every unit (e.g., a subsystem, a module, a function, or even an object) of the OS has the minimum authority and permissions required to perform its tasks. This approach reduces the security risk associated with any single element's bugs or flaws. By "zero-cost", we means the same as in Rust's philosophy of zero-cost abstractions, which emphasizes that high-level abstractions (like those that enable least privilege principles) should be available to developers to use, but not come at the cost of performance. Thus, a zero-cost, least-privilege OS enhances its security without compromising its performance.
+Asterinas is a _zero-cost_, _least-privilege_ OS kernel. A least-privilege OS is one that adheres to the principle of least privileges, which mandates that every unit (e.g., a subsystem, a module, a function, or even an object) of the OS has the minimum authority and permissions required to perform its tasks. This approach reduces the security risk associated with any single element's bugs or flaws. By "zero-cost", we means the same as in Rust's philosophy of zero-cost abstractions, which emphasizes that high-level abstractions (like those that enable least privilege principles) should be available to developers to use, but not come at the cost of performance. Thus, a zero-cost, least-privilege OS enhances its security without compromising its performance.
Some prior OSes do abide by the [principle of least privilege](https://en.wikipedia.org/wiki/Principle_of_least_privilege), but come with considerable performance costs. Take [seL4](https://sel4.systems/) as an example. A [seL4-based multi-server OS](https://docs.sel4.systems/projects/camkes/) minimizes the scope of the OS running in the privileged CPU mode to the seL4 microkernel. The bulk of OS functionalities are implemented by process-based servers, which are separated by process boundary and only allowed to communicate with each other through well-defined interfaces, usually based on RPC. Each service can only access kernel resources represented by [seL4 capabilities](), each of which is restricted with respect to its scope and permissions. All these security measures contribute to the enhanced security of the OS, but result in a considerable runtime costs due to context switching, message passing, and runtime checks.
-Jinux is unique in practicing the principle of least privilege without sacrificing the performance. This is achieved by realizing the full potential of Rust, which, compared to the traditional system programming language like C/C++, offers unique features like an expressive type system, memory safety with unsafe extensions, powerful macros, and a customizable toolchain. By leveraging these unique features, Jinux is able to construct zero-cost abstractions that enable least privileges at the following three levels.
+Asterinas is unique in practicing the principle of least privilege without sacrificing the performance. This is achieved by realizing the full potential of Rust, which, compared to the traditional system programming language like C/C++, offers unique features like an expressive type system, memory safety with unsafe extensions, powerful macros, and a customizable toolchain. By leveraging these unique features, Asterinas is able to construct zero-cost abstractions that enable least privileges at the following three levels.
-1. The architectural level. Jinux is architected as a _framekernel_, where the entire OS resides in a single address space and unsafe Rust code is restricted to a tiny portion of the OS called Jinux Framework. The Framework exposes safe APIs to the rest of Jinux, which implements the most of OS functionalities in safe Rust code completely. Thanks to the framekernel architecture, Jinux's TCB for memory safety is minimized.
+1. The architectural level. Asterinas is architected as a _framekernel_, where the entire OS resides in a single address space and unsafe Rust code is restricted to a tiny portion of the OS called Asterinas Framework. The Framework exposes safe APIs to the rest of Asterinas, which implements the most of OS functionalities in safe Rust code completely. Thanks to the framekernel architecture, Asterinas's TCB for memory safety is minimized.

-2. The component level. Upon Jinux Framework is a set of OS components, each of which is responsible for a particular OS functionality, feature, or device. These OS components are Rust crates with two traits: (1) containing safe Rust code, as demanded by the framekernel architecture, and (2) being governed by Jinux Component System, which can enforce a fine-grained access control to their public APIs. The access control policy is specified in a configuration file and enforced at compile time, using a static analysis tool.
+2. The component level. Upon Asterinas Framework is a set of OS components, each of which is responsible for a particular OS functionality, feature, or device. These OS components are Rust crates with two traits: (1) containing safe Rust code, as demanded by the framekernel architecture, and (2) being governed by Asterinas Component System, which can enforce a fine-grained access control to their public APIs. The access control policy is specified in a configuration file and enforced at compile time, using a static analysis tool.
-3. The object level. Jinux promotes the philosophy of _everything-is-a-capability_, which means all kernel resources, from files to threads, from virtual memory to physical pages, should be accessed through [capabilities](https://en.wikipedia.org/wiki/Capability-based_security). In Jinux, capabilities are implemented as Rust objects that are constrained in their creation, acquisition, and usage. One common form of capabilities is those with access rights. Wherever possible, access rights are encoded in types (rather than values) so that they can be checked at compile time, eliminating any runtime costs.
+3. The object level. Asterinas promotes the philosophy of _everything-is-a-capability_, which means all kernel resources, from files to threads, from virtual memory to physical pages, should be accessed through [capabilities](https://en.wikipedia.org/wiki/Capability-based_security). In Asterinas, capabilities are implemented as Rust objects that are constrained in their creation, acquisition, and usage. One common form of capabilities is those with access rights. Wherever possible, access rights are encoded in types (rather than values) so that they can be checked at compile time, eliminating any runtime costs.
-As a zero-cost, least-privilege OS, Jinux provides the best of both worlds: the performance of a monolithic kernel and the security of a microkernel. Like a monolithic kernel, the different parts of Jinux can communicate with the most efficient means, e.g., function calls and memory sharing. In the same spirit as a microkernel, the fundamental security properties of the OS depend on a minimum amount of code (i.e., Jinux Framework).
+As a zero-cost, least-privilege OS, Asterinas provides the best of both worlds: the performance of a monolithic kernel and the security of a microkernel. Like a monolithic kernel, the different parts of Asterinas can communicate with the most efficient means, e.g., function calls and memory sharing. In the same spirit as a microkernel, the fundamental security properties of the OS depend on a minimum amount of code (i.e., Asterinas Framework).
-## Build, test and debug Jinux
+## Build, test and debug Asterinas
While most of the code is written in Rust, the project-scope build process is governed by Makefile. The development environment is managed with Docker. Please ensure Docker is installed and can be run without sudo privilege.
### Preparation
-1. Download the latest source code of jinux.
+1. Download the latest source code of asterinas.
```bash
git clone [repository url]
```
2. After downloading the source code, run the following command to pull the development image.
```bash
-docker pull jinuxdev/jinux:0.2.2
+docker pull asterinas/asterinas:0.2.2
```
3. Start the development container.
```bash
-docker run -it --privileged --network=host --device=/dev/kvm -v `pwd`:/root/jinux jinuxdev/jinux:0.2.2
+docker run -it --privileged --network=host --device=/dev/kvm -v `pwd`:/root/asterinas asterinas/asterinas:0.2.2
```
**All build and test commands should be run inside the development container.**
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -70,14 +70,14 @@ Nevertheless, you could enter the directory of a specific crate and invoke `carg
#### Kernel mode unit tests
-We can run unit tests in kernel mode for crates like `jinux-frame` or `jinux-std`. This is powered by our [ktest](framework/libs/ktest) framework.
+We can run unit tests in kernel mode for crates like `aster-frame` or `aster-std`. This is powered by our [ktest](framework/libs/ktest) framework.
```bash
make run KTEST=1
```
You could also specify tests in a crate or a subset of tests to run.
```bash
-make run KTEST=1 KTEST_WHITELIST=failing_assertion,jinux_frame::test::expect_panic KTEST_CRATES=jinux-frame
+make run KTEST=1 KTEST_WHITELIST=failing_assertion,aster_frame::test::expect_panic KTEST_CRATES=aster-frame
```
#### Component check
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -96,33 +96,33 @@ cargo component-check
#### Regression Test
-This command will automatically run Jinux with the test binaries in `regression/apps` directory.
+This command will automatically run Asterinas with the test binaries in `regression/apps` directory.
```bash
make run AUTO_TEST=regression
```
#### Syscall Test
-This command will build the syscall test binary and automatically run Jinux with the tests using QEMU.
+This command will build the syscall test binary and automatically run Asterinas with the tests using QEMU.
```bash
make run AUTO_TEST=syscall
```
-Alternatively, if you wish to test it interactively inside a shell in Jinux.
+Alternatively, if you wish to test it interactively inside a shell in Asterinas.
```bash
make run BUILD_SYSCALL_TEST=1
```
-Then, we can run the following script using the Jinux shell to run all syscall test cases.
+Then, we can run the following script using the Asterinas shell to run all syscall test cases.
```bash
/opt/syscall_test/run_syscall_test.sh
```
### Debug
-To debug Jinux using [QEMU GDB remote debugging](https://qemu-project.gitlab.io/qemu/system/gdb.html), you could compile Jinux in debug mode, start a Jinux instance and run the GDB interactive shell in another terminal.
+To debug Asterinas using [QEMU GDB remote debugging](https://qemu-project.gitlab.io/qemu/system/gdb.html), you could compile Asterinas in debug mode, start a Asterinas instance and run the GDB interactive shell in another terminal.
-To start a QEMU Jinux VM and wait for debugging connection:
+To start a QEMU Asterinas VM and wait for debugging connection:
```bash
make run GDB_SERVER=1 ENABLE_KVM=0
```
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -132,33 +132,33 @@ To get the GDB interactive shell:
make run GDB_CLIENT=1
```
-Currently, the Jinux runner's debugging interface is exposed by unix socket. Thus there shouldn't be multiple debugging instances in the same container. To add debug symbols for the underlying infrastructures such as UEFI firmware or bootloader, please check the runner's source code for details.
+Currently, the Asterinas runner's debugging interface is exposed by unix socket. Thus there shouldn't be multiple debugging instances in the same container. To add debug symbols for the underlying infrastructures such as UEFI firmware or bootloader, please check the runner's source code for details.
## Code organization
-The codebase of Jinux is organized as below.
+The codebase of Asterinas is organized as below.
-* `runner/`: creating a bootable Jinux kernel image along with an initramfs image. It also supports `cargo run` since it is the only package with `main()`.
-* `kernel/`: defining the entry point of the Jinux kernel.
-* `framework/`: the privileged half of Jinux (allowed to use `unsafe` keyword)
- * `jinux-frame`: providing the safe Rust abstractions for low-level resources like CPU, memory, interrupts, etc;
+* `runner/`: creating a bootable Asterinas kernel image along with an initramfs image. It also supports `cargo run` since it is the only package with `main()`.
+* `kernel/`: defining the entry point of the Asterinas kernel.
+* `framework/`: the privileged half of Asterinas (allowed to use `unsafe` keyword)
+ * `aster-frame`: providing the safe Rust abstractions for low-level resources like CPU, memory, interrupts, etc;
* `libs`: Privileged libraries.
-* `services/`: the unprivileged half of Jinux (not allowed to use `unsafe` directly), implementing most of the OS functionalities.
- * `comps/`: Jinux OS components;
- * `libs/`: Jinux OS libraries;
- * `jinux-std`: this is where system calls are implemented. Currently, this crate is too big. It will eventually be decomposed into smaller crates.
+* `services/`: the unprivileged half of Asterinas (not allowed to use `unsafe` directly), implementing most of the OS functionalities.
+ * `comps/`: Asterinas OS components;
+ * `libs/`: Asterinas OS libraries;
+ * `aster-std`: this is where system calls are implemented. Currently, this crate is too big. It will eventually be decomposed into smaller crates.
* `tests/`: providing integration tests written in Rust.
* `regression/`: providing user-space tests written in C.
-* `docs/`: The Jinux book (needs a major update).
+* `docs/`: The Asterinas book (needs a major update).
## Development status
-Jinux is under active development. The list below summarizes the progress of important planned features.
+Asterinas is under active development. The list below summarizes the progress of important planned features.
* Technical novelty
- - [X] Jinux Framework
- - [X] Jinux Component System
- - [X] Jinux Capabilities
+ - [X] Asterinas Framework
+ - [X] Asterinas Component System
+ - [X] Asterinas Capabilities
* High-level stuff
* Process management
- [X] Essential system calls (fork, execve, etc.)
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -231,6 +231,6 @@ Jinux is under active development. The list below summarizes the progress of imp
## License
-The Jinux project is proudly released as a free software
+The Asterinas project is proudly released as a free software
under the license of [GNU General Public License version 2](LICENSE-GPL).
See [COPYRIGHT](COPYRIGHT) for details.
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -231,6 +231,6 @@ Jinux is under active development. The list below summarizes the progress of imp
## License
-The Jinux project is proudly released as a free software
+The Asterinas project is proudly released as a free software
under the license of [GNU General Public License version 2](LICENSE-GPL).
See [COPYRIGHT](COPYRIGHT) for details.
diff --git a/build.rs b/build.rs
--- a/build.rs
+++ b/build.rs
@@ -5,7 +5,7 @@ fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
let linker_script_path = if target == "x86_64" {
PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap())
.join("framework")
- .join("jinux-frame")
+ .join("aster-frame")
.join("src")
.join("arch")
.join("x86")
diff --git a/build.rs b/build.rs
--- a/build.rs
+++ b/build.rs
@@ -5,7 +5,7 @@ fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
let linker_script_path = if target == "x86_64" {
PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap())
.join("framework")
- .join("jinux-frame")
+ .join("aster-frame")
.join("src")
.join("arch")
.join("x86")
diff --git a/docs/README.md b/docs/README.md
--- a/docs/README.md
+++ b/docs/README.md
@@ -1,4 +1,4 @@
-# Jinux Documentation
+# Asterinas Documentation
The documentation is rendered as a book with [mdBook](https://rust-lang.github.io/mdBook/),
which can be installed with `cargo`.
diff --git a/docs/README.md b/docs/README.md
--- a/docs/README.md
+++ b/docs/README.md
@@ -1,4 +1,4 @@
-# Jinux Documentation
+# Asterinas Documentation
The documentation is rendered as a book with [mdBook](https://rust-lang.github.io/mdBook/),
which can be installed with `cargo`.
diff --git a/docs/book.toml b/docs/book.toml
--- a/docs/book.toml
+++ b/docs/book.toml
@@ -3,7 +3,7 @@ authors = ["Tate, Hongliang Tian"]
language = "en"
multilingual = false
src = "src"
-title = "Jinux: A Secure, Fast, and Modern OS in Rust"
+title = "Asterinas: A Secure, Fast, and Modern OS in Rust"
[rust]
edition = "2021"
diff --git a/docs/book.toml b/docs/book.toml
--- a/docs/book.toml
+++ b/docs/book.toml
@@ -3,7 +3,7 @@ authors = ["Tate, Hongliang Tian"]
language = "en"
multilingual = false
src = "src"
-title = "Jinux: A Secure, Fast, and Modern OS in Rust"
+title = "Asterinas: A Secure, Fast, and Modern OS in Rust"
[rust]
edition = "2021"
diff --git a/docs/src/README.md b/docs/src/README.md
--- a/docs/src/README.md
+++ b/docs/src/README.md
@@ -14,7 +14,7 @@
# Introduction
-This document describes Jinux, a secure, fast, and modern OS written in Rust.
+This document describes Asterinas, a secure, fast, and modern OS written in Rust.
As the project is a work in progress, this document is by no means complete.
Despite the incompleteness, this evolving document serves several important purposes:
diff --git a/docs/src/README.md b/docs/src/README.md
--- a/docs/src/README.md
+++ b/docs/src/README.md
@@ -14,7 +14,7 @@
# Introduction
-This document describes Jinux, a secure, fast, and modern OS written in Rust.
+This document describes Asterinas, a secure, fast, and modern OS written in Rust.
As the project is a work in progress, this document is by no means complete.
Despite the incompleteness, this evolving document serves several important purposes:
diff --git a/docs/src/README.md b/docs/src/README.md
--- a/docs/src/README.md
+++ b/docs/src/README.md
@@ -50,7 +50,7 @@ OSes, e.g., [Kerla](https://github.com/nuta/kerla),
and [zCore](https://github.com/rcore-os/zCore). Despite their varying degrees of
success, none of them are general-purpose, industrial-strength OSes that are or
will ever be competitive with Linux. Eventually, a winner will emerge out of this
-market of Rust OSes, and Jinux is our bet for this competition.
+market of Rust OSes, and Asterinas is our bet for this competition.
Second, Rust OSes are a perfect fit for
[Trusted Execution Environments (TEEs)](https://en.wikipedia.org/wiki/Trusted_execution_environment).
diff --git a/docs/src/README.md b/docs/src/README.md
--- a/docs/src/README.md
+++ b/docs/src/README.md
@@ -50,7 +50,7 @@ OSes, e.g., [Kerla](https://github.com/nuta/kerla),
and [zCore](https://github.com/rcore-os/zCore). Despite their varying degrees of
success, none of them are general-purpose, industrial-strength OSes that are or
will ever be competitive with Linux. Eventually, a winner will emerge out of this
-market of Rust OSes, and Jinux is our bet for this competition.
+market of Rust OSes, and Asterinas is our bet for this competition.
Second, Rust OSes are a perfect fit for
[Trusted Execution Environments (TEEs)](https://en.wikipedia.org/wiki/Trusted_execution_environment).
diff --git a/docs/src/README.md b/docs/src/README.md
--- a/docs/src/README.md
+++ b/docs/src/README.md
@@ -79,24 +79,24 @@ relational databases:
[Oracle and IBM are losing ground as Chinese vendors catch up with their US counterparts](https://www.theregister.com/2022/07/06/international_database_vendors_are_losing/).
Can such success stories be repeated in the field of OSes? I think so.
There are some China's home-grown OSes like [openKylin](https://www.openkylin.top/index.php?lang=en), but all of them are based on Linux and lack a self-developed
-OS _kernel_. The long-term goal of Jinux is to fill this key missing core of the home-grown OSes.
+OS _kernel_. The long-term goal of Asterinas is to fill this key missing core of the home-grown OSes.
## Architecture Overview
-Here is an overview of the architecture of Jinux.
+Here is an overview of the architecture of Asterinas.

## Features
-**1. Security by design.** Security is our top priority in the design of Jinux. As such, we adopt the widely acknowledged security best practice of [least privilege principle](https://en.wikipedia.org/wiki/Principle_of_least_privilege) and enforce it in a fashion that leverages the full strengths of Rust. To do so, we partition Jinux into two halves: a _privileged_ OS core and _unprivileged_ OS components. All OS components are written entirely in _safe_ Rust and only the privileged OS core
+**1. Security by design.** Security is our top priority in the design of Asterinas. As such, we adopt the widely acknowledged security best practice of [least privilege principle](https://en.wikipedia.org/wiki/Principle_of_least_privilege) and enforce it in a fashion that leverages the full strengths of Rust. To do so, we partition Asterinas into two halves: a _privileged_ OS core and _unprivileged_ OS components. All OS components are written entirely in _safe_ Rust and only the privileged OS core
is allowed to have _unsafe_ Rust code. Furthermore, we propose the idea of _everything-is-a-capability_, which elevates the status of [capabilities](https://en.wikipedia.org/wiki/Capability-based_security) to the level of a ubiquitous security primitive used throughout the OS. We make novel use of Rust's advanced features (e.g., [type-level programming](https://willcrichton.net/notes/type-level-programming/)) to make capabilities more accessible and efficient. The net result is improved security and uncompromised performance.
-**2. Trustworthy OS-level virtualization.** OS-level virtualization mechanisms (like Linux's cgroups and namespaces) enable containers, a more lightweight and arguably more popular alternative to virtual machines (VMs). But there is one problem with containers: they are not as secure as VMs (see [StackExchange](https://security.stackexchange.com/questions/169642/what-makes-docker-more-secure-than-vms-or-bare-metal), [LWN](https://lwn.net/Articles/796700/), and [AWS](https://docs.aws.amazon.com/AmazonECS/latest/bestpracticesguide/security-tasks-containers.html)). There is a real risk that malicious containers may exploit privilege escalation bugs in the OS kernel to attack the host. [A study](https://dl.acm.org/doi/10.1145/3274694.3274720) found that 11 out of 88 kernel exploits are effective in breaking the container sandbox. The seemingly inherent insecurity of OS kernels leads to a new breed of container implementations (e.g., [Kata](https://katacontainers.io/) and [gVisor](https://gvisor.dev/)) that are based on VMs, instead of kernels, for isolation and sandboxing. We argue that this unfortunate retreat from OS-level virtualization to VM-based one is unwarranted---if the OS kernels are secure enough. And this is exactly what we plan to achieve with Jinux. We aim to provide a trustworthy OS-level virtualization mechanism on Jinux.
+**2. Trustworthy OS-level virtualization.** OS-level virtualization mechanisms (like Linux's cgroups and namespaces) enable containers, a more lightweight and arguably more popular alternative to virtual machines (VMs). But there is one problem with containers: they are not as secure as VMs (see [StackExchange](https://security.stackexchange.com/questions/169642/what-makes-docker-more-secure-than-vms-or-bare-metal), [LWN](https://lwn.net/Articles/796700/), and [AWS](https://docs.aws.amazon.com/AmazonECS/latest/bestpracticesguide/security-tasks-containers.html)). There is a real risk that malicious containers may exploit privilege escalation bugs in the OS kernel to attack the host. [A study](https://dl.acm.org/doi/10.1145/3274694.3274720) found that 11 out of 88 kernel exploits are effective in breaking the container sandbox. The seemingly inherent insecurity of OS kernels leads to a new breed of container implementations (e.g., [Kata](https://katacontainers.io/) and [gVisor](https://gvisor.dev/)) that are based on VMs, instead of kernels, for isolation and sandboxing. We argue that this unfortunate retreat from OS-level virtualization to VM-based one is unwarranted---if the OS kernels are secure enough. And this is exactly what we plan to achieve with Asterinas. We aim to provide a trustworthy OS-level virtualization mechanism on Asterinas.
-**3. Fast user-mode development.** Traditional OS kernels like Linux are hard to develop, test, and debug. Kernel development involves countless rounds of programming, failing, and rebooting on bare-metal or virtual machines. This way of life is unproductive and painful. Such a pain point is also recognized and partially addressed by [research work](https://www.usenix.org/conference/fast21/presentation/miller), but we think we can do more. In this spirit, we design the OS core to provide high-level APIs that are largely independent of the underlying hardware and implement it with two targets: one target is as part of a regular OS in kernel space and the other is as a library OS in user space. This way, all the OS components of Jinux, which are stacked above the OS core, can be developed, tested, and debugged in user space, which is more friendly to developers than kernel space.
+**3. Fast user-mode development.** Traditional OS kernels like Linux are hard to develop, test, and debug. Kernel development involves countless rounds of programming, failing, and rebooting on bare-metal or virtual machines. This way of life is unproductive and painful. Such a pain point is also recognized and partially addressed by [research work](https://www.usenix.org/conference/fast21/presentation/miller), but we think we can do more. In this spirit, we design the OS core to provide high-level APIs that are largely independent of the underlying hardware and implement it with two targets: one target is as part of a regular OS in kernel space and the other is as a library OS in user space. This way, all the OS components of Asterinas, which are stacked above the OS core, can be developed, tested, and debugged in user space, which is more friendly to developers than kernel space.
-**4. High-fidelity Linux ABI.** An OS without usable applications is useless. So we believe it is important for Jinux to fit in an established and thriving ecosystem of software, such as the one around Linux. This is why we conclude that Jinux should aim at implementing high-fidelity Linux ABI, including the system calls, the proc file system, etc.
+**4. High-fidelity Linux ABI.** An OS without usable applications is useless. So we believe it is important for Asterinas to fit in an established and thriving ecosystem of software, such as the one around Linux. This is why we conclude that Asterinas should aim at implementing high-fidelity Linux ABI, including the system calls, the proc file system, etc.
**5. TEEs as top-tier targets.** (Todo)
diff --git a/docs/src/capabilities/README.md b/docs/src/capabilities/README.md
--- a/docs/src/capabilities/README.md
+++ b/docs/src/capabilities/README.md
@@ -20,12 +20,12 @@ capabilities in a limited fashion, mostly as a means to limit the access from
external users (e.g., via syscall), rather than a mechanism to enforce advanced
security policies internally (e.g., module-level isolation).
-So we ask this question: is it possible to use capabilities as a _ubitiquous_ security primitive throughout Jinux to enhance the security and robustness of the
+So we ask this question: is it possible to use capabilities as a _ubitiquous_ security primitive throughout Asterinas to enhance the security and robustness of the
OS? Specifically, we propose a new principle called "_everything is a capability_".
Here, "everything" refers to any type of OS resource, internal or external alike.
In traditional OSes, treating everything as a capability is unrewarding
because (1) capabilities themselves are unreliable due to memory safety problems
-, and (2) capabilities are no free lunch as they incur memory and CPU overheads. But these arguments may no longer stand in a well-designed Rust OS like Jinux.
+, and (2) capabilities are no free lunch as they incur memory and CPU overheads. But these arguments may no longer stand in a well-designed Rust OS like Asterinas.
Because the odds of memory safety bugs are minimized and
advanced Rust features like type-level programming allow us to implement
capabilities as a zero-cost abstraction.
diff --git a/docs/src/capabilities/README.md b/docs/src/capabilities/README.md
--- a/docs/src/capabilities/README.md
+++ b/docs/src/capabilities/README.md
@@ -20,12 +20,12 @@ capabilities in a limited fashion, mostly as a means to limit the access from
external users (e.g., via syscall), rather than a mechanism to enforce advanced
security policies internally (e.g., module-level isolation).
-So we ask this question: is it possible to use capabilities as a _ubitiquous_ security primitive throughout Jinux to enhance the security and robustness of the
+So we ask this question: is it possible to use capabilities as a _ubitiquous_ security primitive throughout Asterinas to enhance the security and robustness of the
OS? Specifically, we propose a new principle called "_everything is a capability_".
Here, "everything" refers to any type of OS resource, internal or external alike.
In traditional OSes, treating everything as a capability is unrewarding
because (1) capabilities themselves are unreliable due to memory safety problems
-, and (2) capabilities are no free lunch as they incur memory and CPU overheads. But these arguments may no longer stand in a well-designed Rust OS like Jinux.
+, and (2) capabilities are no free lunch as they incur memory and CPU overheads. But these arguments may no longer stand in a well-designed Rust OS like Asterinas.
Because the odds of memory safety bugs are minimized and
advanced Rust features like type-level programming allow us to implement
capabilities as a zero-cost abstraction.
diff --git a/docs/src/capabilities/zero_cost_capabilities.md b/docs/src/capabilities/zero_cost_capabilities.md
--- a/docs/src/capabilities/zero_cost_capabilities.md
+++ b/docs/src/capabilities/zero_cost_capabilities.md
@@ -1,6 +1,6 @@
# Zero-Cost Capabilities
-To strengthen the security of Jinux, we aim to implement all kinds of OS resources
+To strengthen the security of Asterinas, we aim to implement all kinds of OS resources
as capabilities. As the capabilities are going to be used throughout the OS,
it is highly desirable to minimize their costs. For this purpose,
we want to implement capabilities as a _zero-cost abstraction_.
diff --git a/docs/src/capabilities/zero_cost_capabilities.md b/docs/src/capabilities/zero_cost_capabilities.md
--- a/docs/src/capabilities/zero_cost_capabilities.md
+++ b/docs/src/capabilities/zero_cost_capabilities.md
@@ -1,6 +1,6 @@
# Zero-Cost Capabilities
-To strengthen the security of Jinux, we aim to implement all kinds of OS resources
+To strengthen the security of Asterinas, we aim to implement all kinds of OS resources
as capabilities. As the capabilities are going to be used throughout the OS,
it is highly desirable to minimize their costs. For this purpose,
we want to implement capabilities as a _zero-cost abstraction_.
diff --git a/docs/src/capabilities/zero_cost_capabilities.md b/docs/src/capabilities/zero_cost_capabilities.md
--- a/docs/src/capabilities/zero_cost_capabilities.md
+++ b/docs/src/capabilities/zero_cost_capabilities.md
@@ -351,7 +351,7 @@ mod test {
### Implement access rights with typeflags
-The `Jinux-rights/lib.rs` file implements access rights.
+The `aster-rights/lib.rs` file implements access rights.
```rust
//! Access rights.
diff --git a/docs/src/capabilities/zero_cost_capabilities.md b/docs/src/capabilities/zero_cost_capabilities.md
--- a/docs/src/capabilities/zero_cost_capabilities.md
+++ b/docs/src/capabilities/zero_cost_capabilities.md
@@ -376,7 +376,7 @@ typeflags! {
}
```
-The `Jinux-rights-proc/lib.rs` file implements the `require` procedural macro.
+The `aster-rights-proc/lib.rs` file implements the `require` procedural macro.
See the channel capability example later for how `require` is used.
```rust
diff --git a/docs/src/capabilities/zero_cost_capabilities.md b/docs/src/capabilities/zero_cost_capabilities.md
--- a/docs/src/capabilities/zero_cost_capabilities.md
+++ b/docs/src/capabilities/zero_cost_capabilities.md
@@ -376,7 +376,7 @@ typeflags! {
}
```
-The `Jinux-rights-proc/lib.rs` file implements the `require` procedural macro.
+The `aster-rights-proc/lib.rs` file implements the `require` procedural macro.
See the channel capability example later for how `require` is used.
```rust
diff --git a/docs/src/privilege_separation/README.md b/docs/src/privilege_separation/README.md
--- a/docs/src/privilege_separation/README.md
+++ b/docs/src/privilege_separation/README.md
@@ -1,15 +1,15 @@
# Privilege Separation
-One fundamental design goal of Jinux is to support _privilege separation_, i.e., the separation between the privileged OS core and the unprivileged OS components. The privileged portion is allowed to use `unsafe` keyword to carry out dangerous tasks like accessing CPU registers, manipulating stack frames, and doing MMIO or PIO. In contrast, the unprivileged portion, which forms the majority of the OS, must be free from `unsafe` code. With privilege separation, the memory safety of Jinux can be boiled down to the correctness of the privileged OS core, regardless of the correctness of the unprivileged OS components, thus reducing the size of TCB significantly.
+One fundamental design goal of Asterinas is to support _privilege separation_, i.e., the separation between the privileged OS core and the unprivileged OS components. The privileged portion is allowed to use `unsafe` keyword to carry out dangerous tasks like accessing CPU registers, manipulating stack frames, and doing MMIO or PIO. In contrast, the unprivileged portion, which forms the majority of the OS, must be free from `unsafe` code. With privilege separation, the memory safety of Asterinas can be boiled down to the correctness of the privileged OS core, regardless of the correctness of the unprivileged OS components, thus reducing the size of TCB significantly.
To put privilege separation into perspective, let's compare the architectures
-of the monolithic kernels, microkernels, and Jinux.
+of the monolithic kernels, microkernels, and Asterinas.

The diagram above highlights the characteristics of different OS architectures
in terms of communication overheads and the TCB for memory safety.
-Thanks to privilege separation, Jinux promises the benefit of being _as safe as a microkernel and as fast as a monolithic kernel_.
+Thanks to privilege separation, Asterinas promises the benefit of being _as safe as a microkernel and as fast as a monolithic kernel_.
Privilege separation is an interesting research problem, prompting us to
answer a series of technical questions.
diff --git a/docs/src/privilege_separation/README.md b/docs/src/privilege_separation/README.md
--- a/docs/src/privilege_separation/README.md
+++ b/docs/src/privilege_separation/README.md
@@ -1,15 +1,15 @@
# Privilege Separation
-One fundamental design goal of Jinux is to support _privilege separation_, i.e., the separation between the privileged OS core and the unprivileged OS components. The privileged portion is allowed to use `unsafe` keyword to carry out dangerous tasks like accessing CPU registers, manipulating stack frames, and doing MMIO or PIO. In contrast, the unprivileged portion, which forms the majority of the OS, must be free from `unsafe` code. With privilege separation, the memory safety of Jinux can be boiled down to the correctness of the privileged OS core, regardless of the correctness of the unprivileged OS components, thus reducing the size of TCB significantly.
+One fundamental design goal of Asterinas is to support _privilege separation_, i.e., the separation between the privileged OS core and the unprivileged OS components. The privileged portion is allowed to use `unsafe` keyword to carry out dangerous tasks like accessing CPU registers, manipulating stack frames, and doing MMIO or PIO. In contrast, the unprivileged portion, which forms the majority of the OS, must be free from `unsafe` code. With privilege separation, the memory safety of Asterinas can be boiled down to the correctness of the privileged OS core, regardless of the correctness of the unprivileged OS components, thus reducing the size of TCB significantly.
To put privilege separation into perspective, let's compare the architectures
-of the monolithic kernels, microkernels, and Jinux.
+of the monolithic kernels, microkernels, and Asterinas.

The diagram above highlights the characteristics of different OS architectures
in terms of communication overheads and the TCB for memory safety.
-Thanks to privilege separation, Jinux promises the benefit of being _as safe as a microkernel and as fast as a monolithic kernel_.
+Thanks to privilege separation, Asterinas promises the benefit of being _as safe as a microkernel and as fast as a monolithic kernel_.
Privilege separation is an interesting research problem, prompting us to
answer a series of technical questions.
diff --git a/docs/src/privilege_separation/pci_virtio_drivers.md b/docs/src/privilege_separation/pci_virtio_drivers.md
--- a/docs/src/privilege_separation/pci_virtio_drivers.md
+++ b/docs/src/privilege_separation/pci_virtio_drivers.md
@@ -22,7 +22,7 @@ Here are some of the elements in PCI-based Virtio devices that may involve `unsa
### Privileged part
```rust
-// file: jinux-core-libs/pci-io-port/lib.rs
+// file: aster-core-libs/pci-io-port/lib.rs
use x86::IoPort;
/// The I/O port to write an address in the PCI
diff --git a/docs/src/privilege_separation/pci_virtio_drivers.md b/docs/src/privilege_separation/pci_virtio_drivers.md
--- a/docs/src/privilege_separation/pci_virtio_drivers.md
+++ b/docs/src/privilege_separation/pci_virtio_drivers.md
@@ -22,7 +22,7 @@ Here are some of the elements in PCI-based Virtio devices that may involve `unsa
### Privileged part
```rust
-// file: jinux-core-libs/pci-io-port/lib.rs
+// file: aster-core-libs/pci-io-port/lib.rs
use x86::IoPort;
/// The I/O port to write an address in the PCI
diff --git a/docs/src/privilege_separation/pci_virtio_drivers.md b/docs/src/privilege_separation/pci_virtio_drivers.md
--- a/docs/src/privilege_separation/pci_virtio_drivers.md
+++ b/docs/src/privilege_separation/pci_virtio_drivers.md
@@ -49,7 +49,7 @@ pub const PCI_DATA_PORT: IoPort<u32> = {
### Unprivileged part
```rust
-// file: jinux-comps/pci/lib.rs
+// file: aster-comps/pci/lib.rs
use pci_io_port::{PCI_ADDR_PORT, PCI_DATA_PORT};
/// The PCI configuration space, which enables the discovery,
diff --git a/docs/src/privilege_separation/pci_virtio_drivers.md b/docs/src/privilege_separation/pci_virtio_drivers.md
--- a/docs/src/privilege_separation/pci_virtio_drivers.md
+++ b/docs/src/privilege_separation/pci_virtio_drivers.md
@@ -49,7 +49,7 @@ pub const PCI_DATA_PORT: IoPort<u32> = {
### Unprivileged part
```rust
-// file: jinux-comps/pci/lib.rs
+// file: aster-comps/pci/lib.rs
use pci_io_port::{PCI_ADDR_PORT, PCI_DATA_PORT};
/// The PCI configuration space, which enables the discovery,
diff --git a/docs/src/privilege_separation/pci_virtio_drivers.md b/docs/src/privilege_separation/pci_virtio_drivers.md
--- a/docs/src/privilege_separation/pci_virtio_drivers.md
+++ b/docs/src/privilege_separation/pci_virtio_drivers.md
@@ -128,7 +128,7 @@ pub struct PciCapabilities {
Most code of Virtio drivers can be unprivileged thanks to the abstractions of `VmPager` and `VmCell` provided by the OS core.
```rust
-// file: jinux-comp-libs/virtio/transport.rs
+// file: aster-comp-libs/virtio/transport.rs
/// The transport layer for configuring a Virtio device.
pub struct VirtioTransport {
diff --git a/docs/src/privilege_separation/pci_virtio_drivers.md b/docs/src/privilege_separation/pci_virtio_drivers.md
--- a/docs/src/privilege_separation/pci_virtio_drivers.md
+++ b/docs/src/privilege_separation/pci_virtio_drivers.md
@@ -128,7 +128,7 @@ pub struct PciCapabilities {
Most code of Virtio drivers can be unprivileged thanks to the abstractions of `VmPager` and `VmCell` provided by the OS core.
```rust
-// file: jinux-comp-libs/virtio/transport.rs
+// file: aster-comp-libs/virtio/transport.rs
/// The transport layer for configuring a Virtio device.
pub struct VirtioTransport {
diff --git a/docs/src/privilege_separation/syscall_workflow.md b/docs/src/privilege_separation/syscall_workflow.md
--- a/docs/src/privilege_separation/syscall_workflow.md
+++ b/docs/src/privilege_separation/syscall_workflow.md
@@ -138,7 +138,7 @@ impl<T, P: Write> UserPtr<T, P> {
}
```
-The examples reveal two important considerations in designing Jinux:
+The examples reveal two important considerations in designing Asterinas:
1. Exposing _truly_ safe APIs. The privileged OS core must expose _truly safe_ APIs: however buggy or silly the unprivileged OS components may be written, they must _not_ cause undefined behaviors.
2. Handling _arbitrary_ pointers safely. The safe API of the OS core must provide a safe way to deal with arbitrary pointers.
diff --git a/docs/src/privilege_separation/syscall_workflow.md b/docs/src/privilege_separation/syscall_workflow.md
--- a/docs/src/privilege_separation/syscall_workflow.md
+++ b/docs/src/privilege_separation/syscall_workflow.md
@@ -138,7 +138,7 @@ impl<T, P: Write> UserPtr<T, P> {
}
```
-The examples reveal two important considerations in designing Jinux:
+The examples reveal two important considerations in designing Asterinas:
1. Exposing _truly_ safe APIs. The privileged OS core must expose _truly safe_ APIs: however buggy or silly the unprivileged OS components may be written, they must _not_ cause undefined behaviors.
2. Handling _arbitrary_ pointers safely. The safe API of the OS core must provide a safe way to deal with arbitrary pointers.
diff --git a/docs/src/privilege_separation/syscall_workflow.md b/docs/src/privilege_separation/syscall_workflow.md
--- a/docs/src/privilege_separation/syscall_workflow.md
+++ b/docs/src/privilege_separation/syscall_workflow.md
@@ -146,15 +146,15 @@ With the two points in mind, let's get back to our main goal of privilege separa
## Code organization with privilege separation
-Our first step is to separate privileged and unprivileged code in the codebase of Jinux. For our purpose of demonstrating a syscall handling framework, a minimal codebase may look like the following.
+Our first step is to separate privileged and unprivileged code in the codebase of Asterinas. For our purpose of demonstrating a syscall handling framework, a minimal codebase may look like the following.
```text
.
-├── jinux
+├── asterinas
│ ├── src
│ │ └── main.rs
│ └── Cargo.toml
-├── jinux-core
+├── aster-core
│ ├── src
│ │ ├── lib.rs
│ │ ├── syscall_handler.rs
diff --git a/docs/src/privilege_separation/syscall_workflow.md b/docs/src/privilege_separation/syscall_workflow.md
--- a/docs/src/privilege_separation/syscall_workflow.md
+++ b/docs/src/privilege_separation/syscall_workflow.md
@@ -146,15 +146,15 @@ With the two points in mind, let's get back to our main goal of privilege separa
## Code organization with privilege separation
-Our first step is to separate privileged and unprivileged code in the codebase of Jinux. For our purpose of demonstrating a syscall handling framework, a minimal codebase may look like the following.
+Our first step is to separate privileged and unprivileged code in the codebase of Asterinas. For our purpose of demonstrating a syscall handling framework, a minimal codebase may look like the following.
```text
.
-├── jinux
+├── asterinas
│ ├── src
│ │ └── main.rs
│ └── Cargo.toml
-├── jinux-core
+├── aster-core
│ ├── src
│ │ ├── lib.rs
│ │ ├── syscall_handler.rs
diff --git a/docs/src/privilege_separation/syscall_workflow.md b/docs/src/privilege_separation/syscall_workflow.md
--- a/docs/src/privilege_separation/syscall_workflow.md
+++ b/docs/src/privilege_separation/syscall_workflow.md
@@ -162,7 +162,7 @@ Our first step is to separate privileged and unprivileged code in the codebase o
│ │ ├── vmo.rs
│ │ └── vmar.rs
│ └── Cargo.toml
-├── jinux-core-libs
+├── aster-core-libs
│ ├── linux-abi-types
│ │ ├── src
│ │ │ └── lib.rs
diff --git a/docs/src/privilege_separation/syscall_workflow.md b/docs/src/privilege_separation/syscall_workflow.md
--- a/docs/src/privilege_separation/syscall_workflow.md
+++ b/docs/src/privilege_separation/syscall_workflow.md
@@ -162,7 +162,7 @@ Our first step is to separate privileged and unprivileged code in the codebase o
│ │ ├── vmo.rs
│ │ └── vmar.rs
│ └── Cargo.toml
-├── jinux-core-libs
+├── aster-core-libs
│ ├── linux-abi-types
│ │ ├── src
│ │ │ └── lib.rs
diff --git a/docs/src/privilege_separation/syscall_workflow.md b/docs/src/privilege_separation/syscall_workflow.md
--- a/docs/src/privilege_separation/syscall_workflow.md
+++ b/docs/src/privilege_separation/syscall_workflow.md
@@ -171,34 +171,34 @@ Our first step is to separate privileged and unprivileged code in the codebase o
│ ├── src
│ │ └── lib.rs
│ └── Cargo.toml
-├── jinux-comps
+├── aster-comps
│ └── linux-syscall
│ ├── src
│ │ └── lib.rs
│ └── Cargo.toml
-└── jinux-comp-libs
+└── aster-comp-libs
└── linux-abi
├── src
│ └── lib.rs
└── Cargo.toml
```
-The ultimate build target of the codebase is the `jinux` crate, which is an OS kernel that consists of a privileged OS core (crate `jinux-core`) and multiple OS components (the crates under `jinux-comps/`).
+The ultimate build target of the codebase is the `asterinas` crate, which is an OS kernel that consists of a privileged OS core (crate `aster-core`) and multiple OS components (the crates under `aster-comps/`).
-For the sake of privilege separation, only crate `jinux` and `jinux-core` along with the crates under `jinux-core-libs` are allowed to use the `unsafe` keyword. To the contrary, the crates under `jinux-comps/` along with their dependent crates under `jinux-comp-libs/` are not allowed to use `unsafe` directly; they may only borrow the superpower of `unsafe` by using the safe API exposed by `jinux-core` or the crates under `jinux-core-libs`. To summarize, the memory safety of the OS only relies on a small and well-defined TCB that constitutes the `jinux` and `jinux-core` crate plus the crates under `jinux-core-libs/`.
+For the sake of privilege separation, only crate `asterinas` and `aster-core` along with the crates under `aster-core-libs` are allowed to use the `unsafe` keyword. To the contrary, the crates under `aster-comps/` along with their dependent crates under `aster-comp-libs/` are not allowed to use `unsafe` directly; they may only borrow the superpower of `unsafe` by using the safe API exposed by `aster-core` or the crates under `aster-core-libs`. To summarize, the memory safety of the OS only relies on a small and well-defined TCB that constitutes the `asterinas` and `aster-core` crate plus the crates under `aster-core-libs/`.
-Under this setting, all implementation of system calls goes to the `linux-syscall` crate. We are about to show that the _safe_ API provided by `jinux-core` is powerful enough to enable the _safe_ implementation of `linux-syscall`.
+Under this setting, all implementation of system calls goes to the `linux-syscall` crate. We are about to show that the _safe_ API provided by `aster-core` is powerful enough to enable the _safe_ implementation of `linux-syscall`.
-## Crate `jinux-core`
+## Crate `aster-core`
-For our purposes here, the two most relevant APIs provided by `jinux-core` is the abstraction for syscall handlers and virtual memory (VM).
+For our purposes here, the two most relevant APIs provided by `aster-core` is the abstraction for syscall handlers and virtual memory (VM).
### Syscall handlers
The `SyscallHandler` abstraction enables the OS core to hide the low-level, architectural-dependent aspects of syscall handling workflow (e.g., user-kernel switching and CPU register manipulation) and allow the unprivileged OS components to implement system calls.
```rust
-// file: jinux-core/src/syscall_handler.rs
+// file: aster-core/src/syscall_handler.rs
pub trait SyscallHandler {
fn handle_syscall(&self, ctx: &mut SyscallContext);
diff --git a/docs/src/privilege_separation/syscall_workflow.md b/docs/src/privilege_separation/syscall_workflow.md
--- a/docs/src/privilege_separation/syscall_workflow.md
+++ b/docs/src/privilege_separation/syscall_workflow.md
@@ -171,34 +171,34 @@ Our first step is to separate privileged and unprivileged code in the codebase o
│ ├── src
│ │ └── lib.rs
│ └── Cargo.toml
-├── jinux-comps
+├── aster-comps
│ └── linux-syscall
│ ├── src
│ │ └── lib.rs
│ └── Cargo.toml
-└── jinux-comp-libs
+└── aster-comp-libs
└── linux-abi
├── src
│ └── lib.rs
└── Cargo.toml
```
-The ultimate build target of the codebase is the `jinux` crate, which is an OS kernel that consists of a privileged OS core (crate `jinux-core`) and multiple OS components (the crates under `jinux-comps/`).
+The ultimate build target of the codebase is the `asterinas` crate, which is an OS kernel that consists of a privileged OS core (crate `aster-core`) and multiple OS components (the crates under `aster-comps/`).
-For the sake of privilege separation, only crate `jinux` and `jinux-core` along with the crates under `jinux-core-libs` are allowed to use the `unsafe` keyword. To the contrary, the crates under `jinux-comps/` along with their dependent crates under `jinux-comp-libs/` are not allowed to use `unsafe` directly; they may only borrow the superpower of `unsafe` by using the safe API exposed by `jinux-core` or the crates under `jinux-core-libs`. To summarize, the memory safety of the OS only relies on a small and well-defined TCB that constitutes the `jinux` and `jinux-core` crate plus the crates under `jinux-core-libs/`.
+For the sake of privilege separation, only crate `asterinas` and `aster-core` along with the crates under `aster-core-libs` are allowed to use the `unsafe` keyword. To the contrary, the crates under `aster-comps/` along with their dependent crates under `aster-comp-libs/` are not allowed to use `unsafe` directly; they may only borrow the superpower of `unsafe` by using the safe API exposed by `aster-core` or the crates under `aster-core-libs`. To summarize, the memory safety of the OS only relies on a small and well-defined TCB that constitutes the `asterinas` and `aster-core` crate plus the crates under `aster-core-libs/`.
-Under this setting, all implementation of system calls goes to the `linux-syscall` crate. We are about to show that the _safe_ API provided by `jinux-core` is powerful enough to enable the _safe_ implementation of `linux-syscall`.
+Under this setting, all implementation of system calls goes to the `linux-syscall` crate. We are about to show that the _safe_ API provided by `aster-core` is powerful enough to enable the _safe_ implementation of `linux-syscall`.
-## Crate `jinux-core`
+## Crate `aster-core`
-For our purposes here, the two most relevant APIs provided by `jinux-core` is the abstraction for syscall handlers and virtual memory (VM).
+For our purposes here, the two most relevant APIs provided by `aster-core` is the abstraction for syscall handlers and virtual memory (VM).
### Syscall handlers
The `SyscallHandler` abstraction enables the OS core to hide the low-level, architectural-dependent aspects of syscall handling workflow (e.g., user-kernel switching and CPU register manipulation) and allow the unprivileged OS components to implement system calls.
```rust
-// file: jinux-core/src/syscall_handler.rs
+// file: aster-core/src/syscall_handler.rs
pub trait SyscallHandler {
fn handle_syscall(&self, ctx: &mut SyscallContext);
diff --git a/docs/src/privilege_separation/syscall_workflow.md b/docs/src/privilege_separation/syscall_workflow.md
--- a/docs/src/privilege_separation/syscall_workflow.md
+++ b/docs/src/privilege_separation/syscall_workflow.md
@@ -243,8 +243,8 @@ an important concept that we will elaborate on later. Basically, they are capabi
Here we demonstrate how to leverage the APIs of `ksos-core` to implement system calls with safe Rust code in crate `linux-syscall`.
```rust
-// file: jinux-comps/linux-syscall/src/lib.rs
-use jinux_core::{SyscallContext, SyscallHandler, Vmar};
+// file: aster-comps/linux-syscall/src/lib.rs
+use aster_core::{SyscallContext, SyscallHandler, Vmar};
use linux_abi::{SyscallNum::*, UserPtr, RawFd, RawTimeVal, RawTimeZone};
pub struct SampleHandler;
diff --git a/docs/src/privilege_separation/syscall_workflow.md b/docs/src/privilege_separation/syscall_workflow.md
--- a/docs/src/privilege_separation/syscall_workflow.md
+++ b/docs/src/privilege_separation/syscall_workflow.md
@@ -243,8 +243,8 @@ an important concept that we will elaborate on later. Basically, they are capabi
Here we demonstrate how to leverage the APIs of `ksos-core` to implement system calls with safe Rust code in crate `linux-syscall`.
```rust
-// file: jinux-comps/linux-syscall/src/lib.rs
-use jinux_core::{SyscallContext, SyscallHandler, Vmar};
+// file: aster-comps/linux-syscall/src/lib.rs
+use aster_core::{SyscallContext, SyscallHandler, Vmar};
use linux_abi::{SyscallNum::*, UserPtr, RawFd, RawTimeVal, RawTimeZone};
pub struct SampleHandler;
diff --git a/docs/src/privilege_separation/syscall_workflow.md b/docs/src/privilege_separation/syscall_workflow.md
--- a/docs/src/privilege_separation/syscall_workflow.md
+++ b/docs/src/privilege_separation/syscall_workflow.md
@@ -315,7 +315,7 @@ impl SampleHandler {
This crate defines a marker trait `Pod`, which represents plain-old data.
```rust
-/// file: jinux-core-libs/pod/src/lib.rs
+/// file: aster-core-libs/pod/src/lib.rs
/// A marker trait for plain old data (POD).
///
diff --git a/docs/src/privilege_separation/syscall_workflow.md b/docs/src/privilege_separation/syscall_workflow.md
--- a/docs/src/privilege_separation/syscall_workflow.md
+++ b/docs/src/privilege_separation/syscall_workflow.md
@@ -315,7 +315,7 @@ impl SampleHandler {
This crate defines a marker trait `Pod`, which represents plain-old data.
```rust
-/// file: jinux-core-libs/pod/src/lib.rs
+/// file: aster-core-libs/pod/src/lib.rs
/// A marker trait for plain old data (POD).
///
diff --git a/docs/src/privilege_separation/syscall_workflow.md b/docs/src/privilege_separation/syscall_workflow.md
--- a/docs/src/privilege_separation/syscall_workflow.md
+++ b/docs/src/privilege_separation/syscall_workflow.md
@@ -388,7 +388,7 @@ unsafe impl<T: Pod, const N> [T; N] for Pod {}
## Crate `linux-abi-type`
```rust
-// file: jinux-core-libs/linux-abi-types
+// file: aster-core-libs/linux-abi-types
use pod::Pod;
pub type RawFd = i32;
diff --git a/docs/src/privilege_separation/syscall_workflow.md b/docs/src/privilege_separation/syscall_workflow.md
--- a/docs/src/privilege_separation/syscall_workflow.md
+++ b/docs/src/privilege_separation/syscall_workflow.md
@@ -388,7 +388,7 @@ unsafe impl<T: Pod, const N> [T; N] for Pod {}
## Crate `linux-abi-type`
```rust
-// file: jinux-core-libs/linux-abi-types
+// file: aster-core-libs/linux-abi-types
use pod::Pod;
pub type RawFd = i32;
diff --git a/docs/src/privilege_separation/syscall_workflow.md b/docs/src/privilege_separation/syscall_workflow.md
--- a/docs/src/privilege_separation/syscall_workflow.md
+++ b/docs/src/privilege_separation/syscall_workflow.md
@@ -404,7 +404,7 @@ unsafe impl Pod for RawTimeVal {}
## Crate `linux-abi`
```rust
-// file: jinux-comp-libs/linux-abi
+// file: aster-comp-libs/linux-abi
pub use linux_abi_types::*;
pub enum SyscallNum {
diff --git a/docs/src/privilege_separation/syscall_workflow.md b/docs/src/privilege_separation/syscall_workflow.md
--- a/docs/src/privilege_separation/syscall_workflow.md
+++ b/docs/src/privilege_separation/syscall_workflow.md
@@ -404,7 +404,7 @@ unsafe impl Pod for RawTimeVal {}
## Crate `linux-abi`
```rust
-// file: jinux-comp-libs/linux-abi
+// file: aster-comp-libs/linux-abi
pub use linux_abi_types::*;
pub enum SyscallNum {
diff --git a/framework/README.md b/framework/README.md
--- a/framework/README.md
+++ b/framework/README.md
@@ -1,20 +1,20 @@
-# Jinux Framework
+# Asterinas Framework
-Jinux Framework is a Rust OS framework that facilitates the development of and innovation in OS kernels written in Rust.
+Asterinas Framework is a Rust OS framework that facilitates the development of and innovation in OS kernels written in Rust.
## An overview
-Jinux Framework provides a solid foundation for Rust developers to build their own OS kernels. While Jinux Framework origins from Jinux, the first ever framekernel, Jinux Framework is well suited for building OS kernels of any architecture, be it a framekernel, a monolithic kernel, or a microkernel.
+Asterinas Framework provides a solid foundation for Rust developers to build their own OS kernels. While Asterinas Framework origins from Asterinas, the first ever framekernel, Asterinas Framework is well suited for building OS kernels of any architecture, be it a framekernel, a monolithic kernel, or a microkernel.
-Jinux Framework offers the following key values.
+Asterinas Framework offers the following key values.
-1. **Lowering the entry bar for OS innovation.** Building an OS from scratch is not easy. Not to mention a novel one. Before adding any novel or interesting feature, an OS developer must first have something runnable, which must include basic functionalities for managing CPU, memory, and interrupts. Jinux Framework has laid this groundwork so that OS developers do not have to deal with the most low-level, error-prone, architecture-specific aspects of OS development themselves.
+1. **Lowering the entry bar for OS innovation.** Building an OS from scratch is not easy. Not to mention a novel one. Before adding any novel or interesting feature, an OS developer must first have something runnable, which must include basic functionalities for managing CPU, memory, and interrupts. Asterinas Framework has laid this groundwork so that OS developers do not have to deal with the most low-level, error-prone, architecture-specific aspects of OS development themselves.
-2. **Enhancing the memory safety of Rust OSes.** Jinux Framework encapsulates low-level, machine-oriented unsafe Rust code into high-level, machine-agnostic safe APIs. These APIs are carefully designed and implemented to be sound and minimal, ensuring the memory safety of any safe Rust callers. Our experience in building Jinux has shown that Jinux Framework is powerful enough to allow a feature-rich, Linux-compatible kernel to be completely written in safe Rust, including its device drivers.
+2. **Enhancing the memory safety of Rust OSes.** Asterinas Framework encapsulates low-level, machine-oriented unsafe Rust code into high-level, machine-agnostic safe APIs. These APIs are carefully designed and implemented to be sound and minimal, ensuring the memory safety of any safe Rust callers. Our experience in building Asterinas has shown that Asterinas Framework is powerful enough to allow a feature-rich, Linux-compatible kernel to be completely written in safe Rust, including its device drivers.
-3. **Promoting code reuse across Rust OS projects.** Shipped as crates, Rust code can be reused across projects---except when they are OSes. A crate that implements a feature or driver for OS A can hardly be reused by OS B because the crate must be [`no_std`](https://docs.rust-embedded.org/book/intro/no-std.html#summary) and depend on the infrastructure APIs provided by OS A, which are obviously different from that provided by OS B. This incompatibility problem can be resolved by Jinux Framework as it can serve as a common ground across different Rust OS projects, as long as they are built upon Jinux Framework.
+3. **Promoting code reuse across Rust OS projects.** Shipped as crates, Rust code can be reused across projects---except when they are OSes. A crate that implements a feature or driver for OS A can hardly be reused by OS B because the crate must be [`no_std`](https://docs.rust-embedded.org/book/intro/no-std.html#summary) and depend on the infrastructure APIs provided by OS A, which are obviously different from that provided by OS B. This incompatibility problem can be resolved by Asterinas Framework as it can serve as a common ground across different Rust OS projects, as long as they are built upon Asterinas Framework.
-4. **Boost productivity with user-mode development.** Traditionally, developing a kernel feature involves countless rounds of coding, failing, and rebooting on bare-metal or virtual machines, which is a painfully slow process. Jinux Framework accelerates the process by allowing high-level OS features like file systems and network stacks to be quickly tested in user mode, making the experience of OS development as smooth as that of application development. To support user-mode development, Jinux Framework is implemented for the Linux platform, in addition to bare-mental or virtual machine environments.
+4. **Boost productivity with user-mode development.** Traditionally, developing a kernel feature involves countless rounds of coding, failing, and rebooting on bare-metal or virtual machines, which is a painfully slow process. Asterinas Framework accelerates the process by allowing high-level OS features like file systems and network stacks to be quickly tested in user mode, making the experience of OS development as smooth as that of application development. To support user-mode development, Asterinas Framework is implemented for the Linux platform, in addition to bare-mental or virtual machine environments.
## Framework APIs
diff --git a/framework/jinux-frame/Cargo.toml b/framework/aster-frame/Cargo.toml
--- a/framework/jinux-frame/Cargo.toml
+++ b/framework/aster-frame/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "jinux-frame"
+name = "aster-frame"
version = "0.1.0"
edition = "2021"
diff --git a/framework/jinux-frame/Cargo.toml b/framework/aster-frame/Cargo.toml
--- a/framework/jinux-frame/Cargo.toml
+++ b/framework/aster-frame/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "jinux-frame"
+name = "aster-frame"
version = "0.1.0"
edition = "2021"
diff --git a/framework/jinux-frame/Cargo.toml b/framework/aster-frame/Cargo.toml
--- a/framework/jinux-frame/Cargo.toml
+++ b/framework/aster-frame/Cargo.toml
@@ -13,17 +13,17 @@ bitvec = { version = "1.0", default-features = false, features = ["alloc"] }
buddy_system_allocator = "0.9.0"
cfg-if = "1.0"
gimli = { version = "0.28", default-features = false, features = ["read-core"] }
-inherit-methods-macro = { git = "https://github.com/jinzhao-dev/inherit-methods-macro", rev = "98f7e3e" }
+inherit-methods-macro = { git = "https://github.com/asterinas/inherit-methods-macro", rev = "98f7e3e" }
int-to-c-enum = { path = "../../services/libs/int-to-c-enum" }
intrusive-collections = "0.9.5"
ktest = { path = "../libs/ktest" }
lazy_static = { version = "1.0", features = ["spin_no_std"] }
log = "0.4"
-pod = { git = "https://github.com/jinzhao-dev/pod", rev = "d7dba56" }
+pod = { git = "https://github.com/asterinas/pod", rev = "d7dba56" }
spin = "0.9.4"
static_assertions = "1.1.0"
tdx-guest = { path = "../libs/tdx-guest", optional = true }
-trapframe = { git = "https://github.com/jinzhao-dev/trapframe-rs", rev = "9758a83" }
+trapframe = { git = "https://github.com/asterinas/trapframe-rs", rev = "2f37590" }
unwinding = { version = "0.2.1", default-features = false, features = ["fde-static", "hide-trace", "panic", "personality", "unwinder"] }
volatile = { version = "0.4.5", features = ["unstable"] }
diff --git a/framework/jinux-frame/build.rs b/framework/aster-frame/build.rs
--- a/framework/jinux-frame/build.rs
+++ b/framework/aster-frame/build.rs
@@ -32,7 +32,7 @@ fn build_linux_setup_header(
let cargo = std::env::var("CARGO").unwrap();
let mut cmd = std::process::Command::new(cargo);
- cmd.arg("install").arg("jinux-frame-x86-boot-linux-setup");
+ cmd.arg("install").arg("aster-frame-x86-boot-linux-setup");
cmd.arg("--debug");
cmd.arg("--locked");
cmd.arg("--path").arg(setup_crate_dir.to_str().unwrap());
diff --git a/framework/jinux-frame/build.rs b/framework/aster-frame/build.rs
--- a/framework/jinux-frame/build.rs
+++ b/framework/aster-frame/build.rs
@@ -32,7 +32,7 @@ fn build_linux_setup_header(
let cargo = std::env::var("CARGO").unwrap();
let mut cmd = std::process::Command::new(cargo);
- cmd.arg("install").arg("jinux-frame-x86-boot-linux-setup");
+ cmd.arg("install").arg("aster-frame-x86-boot-linux-setup");
cmd.arg("--debug");
cmd.arg("--locked");
cmd.arg("--path").arg(setup_crate_dir.to_str().unwrap());
diff --git a/framework/jinux-frame/src/arch/x86/boot/linux_boot/boot_params.rs b/framework/aster-frame/src/arch/x86/boot/linux_boot/boot_params.rs
--- a/framework/jinux-frame/src/arch/x86/boot/linux_boot/boot_params.rs
+++ b/framework/aster-frame/src/arch/x86/boot/linux_boot/boot_params.rs
@@ -3,7 +3,7 @@
//! The bootloader will deliver the address of the `BootParams` struct
//! as the argument of the kernel entrypoint. So we must define a Linux
//! ABI compatible struct in Rust, despite that most of the fields are
-//! currently not needed by Jinux.
+//! currently not needed by Asterinas.
//!
#[derive(Copy, Clone, Debug)]
diff --git a/framework/jinux-frame/src/arch/x86/boot/linux_boot/boot_params.rs b/framework/aster-frame/src/arch/x86/boot/linux_boot/boot_params.rs
--- a/framework/jinux-frame/src/arch/x86/boot/linux_boot/boot_params.rs
+++ b/framework/aster-frame/src/arch/x86/boot/linux_boot/boot_params.rs
@@ -3,7 +3,7 @@
//! The bootloader will deliver the address of the `BootParams` struct
//! as the argument of the kernel entrypoint. So we must define a Linux
//! ABI compatible struct in Rust, despite that most of the fields are
-//! currently not needed by Jinux.
+//! currently not needed by Asterinas.
//!
#[derive(Copy, Clone, Debug)]
diff --git a/framework/jinux-frame/src/arch/x86/boot/linux_boot/mod.rs b/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs
--- a/framework/jinux-frame/src/arch/x86/boot/linux_boot/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs
@@ -152,5 +152,5 @@ unsafe extern "sysv64" fn __linux64_boot(params_ptr: *const boot_params::BootPar
init_framebuffer_info,
init_memory_regions,
);
- crate::boot::call_jinux_main();
+ crate::boot::call_aster_main();
}
diff --git a/framework/jinux-frame/src/arch/x86/boot/linux_boot/mod.rs b/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs
--- a/framework/jinux-frame/src/arch/x86/boot/linux_boot/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs
@@ -152,5 +152,5 @@ unsafe extern "sysv64" fn __linux64_boot(params_ptr: *const boot_params::BootPar
init_framebuffer_info,
init_memory_regions,
);
- crate::boot::call_jinux_main();
+ crate::boot::call_aster_main();
}
diff --git a/framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/Cargo.toml b/framework/aster-frame/src/arch/x86/boot/linux_boot/setup/Cargo.toml
--- a/framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/Cargo.toml
+++ b/framework/aster-frame/src/arch/x86/boot/linux_boot/setup/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "jinux-frame-x86-boot-linux-setup"
+name = "aster-frame-x86-boot-linux-setup"
version = "0.1.0"
edition = "2021"
diff --git a/framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/Cargo.toml b/framework/aster-frame/src/arch/x86/boot/linux_boot/setup/Cargo.toml
--- a/framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/Cargo.toml
+++ b/framework/aster-frame/src/arch/x86/boot/linux_boot/setup/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "jinux-frame-x86-boot-linux-setup"
+name = "aster-frame-x86-boot-linux-setup"
version = "0.1.0"
edition = "2021"
diff --git a/framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/src/header.S b/framework/aster-frame/src/arch/x86/boot/linux_boot/setup/src/header.S
--- a/framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/src/header.S
+++ b/framework/aster-frame/src/arch/x86/boot/linux_boot/setup/src/header.S
@@ -9,8 +9,8 @@
// Some of the fields filled with a 0xab* values should be filled
// by the runner, which is the only tool after building and can
// access the info of the payload.
-// Jinux will use only a few of these fields, and some of them
-// are filled by the loader and will be read by Jinux.
+// Asterinas will use only a few of these fields, and some of them
+// are filled by the loader and will be read by Asterinas.
CODE32_START = 0x100000
diff --git a/framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/src/header.S b/framework/aster-frame/src/arch/x86/boot/linux_boot/setup/src/header.S
--- a/framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/src/header.S
+++ b/framework/aster-frame/src/arch/x86/boot/linux_boot/setup/src/header.S
@@ -9,8 +9,8 @@
// Some of the fields filled with a 0xab* values should be filled
// by the runner, which is the only tool after building and can
// access the info of the payload.
-// Jinux will use only a few of these fields, and some of them
-// are filled by the loader and will be read by Jinux.
+// Asterinas will use only a few of these fields, and some of them
+// are filled by the loader and will be read by Asterinas.
CODE32_START = 0x100000
diff --git a/framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/src/loader.rs b/framework/aster-frame/src/arch/x86/boot/linux_boot/setup/src/loader.rs
--- a/framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/src/loader.rs
+++ b/framework/aster-frame/src/arch/x86/boot/linux_boot/setup/src/loader.rs
@@ -24,6 +24,6 @@ pub fn load_elf(file: &[u8]) -> u32 {
}
}
- // Return the Linux 32-bit Boot Protocol entry point defined by Jinux.
+ // Return the Linux 32-bit Boot Protocol entry point defined by Asterinas.
0x8001000
}
diff --git a/framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/src/loader.rs b/framework/aster-frame/src/arch/x86/boot/linux_boot/setup/src/loader.rs
--- a/framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/src/loader.rs
+++ b/framework/aster-frame/src/arch/x86/boot/linux_boot/setup/src/loader.rs
@@ -24,6 +24,6 @@ pub fn load_elf(file: &[u8]) -> u32 {
}
}
- // Return the Linux 32-bit Boot Protocol entry point defined by Jinux.
+ // Return the Linux 32-bit Boot Protocol entry point defined by Asterinas.
0x8001000
}
diff --git a/framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/src/main.rs b/framework/aster-frame/src/arch/x86/boot/linux_boot/setup/src/main.rs
--- a/framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/src/main.rs
+++ b/framework/aster-frame/src/arch/x86/boot/linux_boot/setup/src/main.rs
@@ -9,7 +9,7 @@ use core::arch::{asm, global_asm};
global_asm!(include_str!("header.S"));
-unsafe fn call_jinux_entrypoint(entrypoint: u32, boot_params_ptr: u32) -> ! {
+unsafe fn call_aster_entrypoint(entrypoint: u32, boot_params_ptr: u32) -> ! {
asm!("mov esi, {}", in(reg) boot_params_ptr);
asm!("mov eax, {}", in(reg) entrypoint);
asm!("jmp eax");
diff --git a/framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/src/main.rs b/framework/aster-frame/src/arch/x86/boot/linux_boot/setup/src/main.rs
--- a/framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/src/main.rs
+++ b/framework/aster-frame/src/arch/x86/boot/linux_boot/setup/src/main.rs
@@ -9,7 +9,7 @@ use core::arch::{asm, global_asm};
global_asm!(include_str!("header.S"));
-unsafe fn call_jinux_entrypoint(entrypoint: u32, boot_params_ptr: u32) -> ! {
+unsafe fn call_aster_entrypoint(entrypoint: u32, boot_params_ptr: u32) -> ! {
asm!("mov esi, {}", in(reg) boot_params_ptr);
asm!("mov eax, {}", in(reg) entrypoint);
asm!("jmp eax");
diff --git a/framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/src/main.rs b/framework/aster-frame/src/arch/x86/boot/linux_boot/setup/src/main.rs
--- a/framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/src/main.rs
+++ b/framework/aster-frame/src/arch/x86/boot/linux_boot/setup/src/main.rs
@@ -34,7 +34,7 @@ pub extern "cdecl" fn _rust_setup_entry(boot_params_ptr: u32) -> ! {
println!("[setup] entrypoint: {:#x}", entrypoint);
// Safety: the entrypoint and the ptr is valid.
- unsafe { call_jinux_entrypoint(entrypoint, boot_params_ptr) };
+ unsafe { call_aster_entrypoint(entrypoint, boot_params_ptr) };
}
#[panic_handler]
diff --git a/framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/src/main.rs b/framework/aster-frame/src/arch/x86/boot/linux_boot/setup/src/main.rs
--- a/framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/src/main.rs
+++ b/framework/aster-frame/src/arch/x86/boot/linux_boot/setup/src/main.rs
@@ -34,7 +34,7 @@ pub extern "cdecl" fn _rust_setup_entry(boot_params_ptr: u32) -> ! {
println!("[setup] entrypoint: {:#x}", entrypoint);
// Safety: the entrypoint and the ptr is valid.
- unsafe { call_jinux_entrypoint(entrypoint, boot_params_ptr) };
+ unsafe { call_aster_entrypoint(entrypoint, boot_params_ptr) };
}
#[panic_handler]
diff --git a/framework/jinux-frame/src/arch/x86/boot/mod.rs b/framework/aster-frame/src/arch/x86/boot/mod.rs
--- a/framework/jinux-frame/src/arch/x86/boot/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/mod.rs
@@ -1,4 +1,4 @@
-//! The x86 boot module defines the entrypoints of Jinux and
+//! The x86 boot module defines the entrypoints of Asterinas and
//! the corresponding headers for different x86 boot protocols.
//!
//! We directly support
diff --git a/framework/jinux-frame/src/arch/x86/boot/mod.rs b/framework/aster-frame/src/arch/x86/boot/mod.rs
--- a/framework/jinux-frame/src/arch/x86/boot/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/mod.rs
@@ -1,4 +1,4 @@
-//! The x86 boot module defines the entrypoints of Jinux and
+//! The x86 boot module defines the entrypoints of Asterinas and
//! the corresponding headers for different x86 boot protocols.
//!
//! We directly support
diff --git a/framework/jinux-frame/src/arch/x86/boot/mod.rs b/framework/aster-frame/src/arch/x86/boot/mod.rs
--- a/framework/jinux-frame/src/arch/x86/boot/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/mod.rs
@@ -9,7 +9,7 @@
//!
//! without any additional configurations.
//!
-//! Jinux diffrentiates the boot protocol by the entry point
+//! Asterinas diffrentiates the boot protocol by the entry point
//! chosen by the boot loader. In each entry point function,
//! the universal callback registeration method from
//! `crate::boot` will be called. Thus the initialization of
diff --git a/framework/jinux-frame/src/arch/x86/boot/mod.rs b/framework/aster-frame/src/arch/x86/boot/mod.rs
--- a/framework/jinux-frame/src/arch/x86/boot/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/mod.rs
@@ -9,7 +9,7 @@
//!
//! without any additional configurations.
//!
-//! Jinux diffrentiates the boot protocol by the entry point
+//! Asterinas diffrentiates the boot protocol by the entry point
//! chosen by the boot loader. In each entry point function,
//! the universal callback registeration method from
//! `crate::boot` will be called. Thus the initialization of
diff --git a/framework/jinux-frame/src/arch/x86/boot/multiboot/mod.rs b/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs
--- a/framework/jinux-frame/src/arch/x86/boot/multiboot/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs
@@ -339,5 +339,5 @@ unsafe extern "sysv64" fn __multiboot_entry(boot_magic: u32, boot_params: u64) -
init_framebuffer_info,
init_memory_regions,
);
- crate::boot::call_jinux_main();
+ crate::boot::call_aster_main();
}
diff --git a/framework/jinux-frame/src/arch/x86/boot/multiboot/mod.rs b/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs
--- a/framework/jinux-frame/src/arch/x86/boot/multiboot/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs
@@ -339,5 +339,5 @@ unsafe extern "sysv64" fn __multiboot_entry(boot_magic: u32, boot_params: u64) -
init_framebuffer_info,
init_memory_regions,
);
- crate::boot::call_jinux_main();
+ crate::boot::call_aster_main();
}
diff --git a/framework/jinux-frame/src/arch/x86/boot/multiboot2/mod.rs b/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs
--- a/framework/jinux-frame/src/arch/x86/boot/multiboot2/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs
@@ -172,5 +172,5 @@ unsafe extern "sysv64" fn __multiboot2_entry(boot_magic: u32, boot_params: u64)
init_framebuffer_info,
init_memory_regions,
);
- crate::boot::call_jinux_main();
+ crate::boot::call_aster_main();
}
diff --git a/framework/jinux-frame/src/arch/x86/boot/multiboot2/mod.rs b/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs
--- a/framework/jinux-frame/src/arch/x86/boot/multiboot2/mod.rs
+++ b/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs
@@ -172,5 +172,5 @@ unsafe extern "sysv64" fn __multiboot2_entry(boot_magic: u32, boot_params: u64)
init_framebuffer_info,
init_memory_regions,
);
- crate::boot::call_jinux_main();
+ crate::boot::call_aster_main();
}
diff --git a/framework/jinux-frame/src/boot/kcmdline.rs b/framework/aster-frame/src/boot/kcmdline.rs
--- a/framework/jinux-frame/src/boot/kcmdline.rs
+++ b/framework/aster-frame/src/boot/kcmdline.rs
@@ -1,6 +1,6 @@
//! The module to parse kernel command-line arguments.
//!
-//! The format of the Jinux command line string conforms
+//! The format of the Asterinas command line string conforms
//! to the Linux kernel command line rules:
//!
//! https://www.kernel.org/doc/html/v6.4/admin-guide/kernel-parameters.html
diff --git a/framework/jinux-frame/src/boot/kcmdline.rs b/framework/aster-frame/src/boot/kcmdline.rs
--- a/framework/jinux-frame/src/boot/kcmdline.rs
+++ b/framework/aster-frame/src/boot/kcmdline.rs
@@ -1,6 +1,6 @@
//! The module to parse kernel command-line arguments.
//!
-//! The format of the Jinux command line string conforms
+//! The format of the Asterinas command line string conforms
//! to the Linux kernel command line rules:
//!
//! https://www.kernel.org/doc/html/v6.4/admin-guide/kernel-parameters.html
diff --git a/framework/jinux-frame/src/boot/mod.rs b/framework/aster-frame/src/boot/mod.rs
--- a/framework/jinux-frame/src/boot/mod.rs
+++ b/framework/aster-frame/src/boot/mod.rs
@@ -60,7 +60,7 @@ macro_rules! define_global_static_boot_arguments {
///
/// For the introduction of a new boot protocol, the entry point could be a novel
/// one. The entry point function should register all the boot initialization
- /// methods before `jinux_main` is called. A boot initialization method takes a
+ /// methods before `aster_main` is called. A boot initialization method takes a
/// reference of the global static boot information variable and initialize it,
/// so that the boot information it represents could be accessed in the kernel
/// anywhere.
diff --git a/framework/jinux-frame/src/boot/mod.rs b/framework/aster-frame/src/boot/mod.rs
--- a/framework/jinux-frame/src/boot/mod.rs
+++ b/framework/aster-frame/src/boot/mod.rs
@@ -60,7 +60,7 @@ macro_rules! define_global_static_boot_arguments {
///
/// For the introduction of a new boot protocol, the entry point could be a novel
/// one. The entry point function should register all the boot initialization
- /// methods before `jinux_main` is called. A boot initialization method takes a
+ /// methods before `aster_main` is called. A boot initialization method takes a
/// reference of the global static boot information variable and initialize it,
/// so that the boot information it represents could be accessed in the kernel
/// anywhere.
diff --git a/framework/jinux-frame/src/boot/mod.rs b/framework/aster-frame/src/boot/mod.rs
--- a/framework/jinux-frame/src/boot/mod.rs
+++ b/framework/aster-frame/src/boot/mod.rs
@@ -103,17 +103,17 @@ pub fn init() {
/// Call the framework-user defined entrypoint of the actual kernel.
///
-/// Any kernel that uses the jinux-frame crate should define a function named
-/// `jinux_main` as the entrypoint.
-pub fn call_jinux_main() -> ! {
+/// Any kernel that uses the aster-frame crate should define a function named
+/// `aster_main` as the entrypoint.
+pub fn call_aster_main() -> ! {
#[cfg(not(ktest))]
unsafe {
// The entry point of kernel code, which should be defined by the package that
- // uses jinux-frame.
+ // uses aster-frame.
extern "Rust" {
- fn jinux_main() -> !;
+ fn aster_main() -> !;
}
- jinux_main();
+ aster_main();
}
#[cfg(ktest)]
{
diff --git a/framework/jinux-frame/src/lib.rs b/framework/aster-frame/src/lib.rs
--- a/framework/jinux-frame/src/lib.rs
+++ b/framework/aster-frame/src/lib.rs
@@ -1,4 +1,4 @@
-//! The framework part of Jinux.
+//! The framework part of Asterinas.
#![feature(alloc_error_handler)]
#![feature(const_maybe_uninit_zeroed)]
#![feature(const_mut_refs)]
diff --git a/framework/jinux-frame/src/lib.rs b/framework/aster-frame/src/lib.rs
--- a/framework/jinux-frame/src/lib.rs
+++ b/framework/aster-frame/src/lib.rs
@@ -1,4 +1,4 @@
-//! The framework part of Jinux.
+//! The framework part of Asterinas.
#![feature(alloc_error_handler)]
#![feature(const_maybe_uninit_zeroed)]
#![feature(const_mut_refs)]
diff --git a/framework/jinux-frame/src/sync/rwlock.rs b/framework/aster-frame/src/sync/rwlock.rs
--- a/framework/jinux-frame/src/sync/rwlock.rs
+++ b/framework/aster-frame/src/sync/rwlock.rs
@@ -57,7 +57,7 @@ use crate::trap::DisabledLocalIrqGuard;
/// # Examples
///
/// ```
-/// use jinux_frame::sync::RwLock;
+/// use aster_frame::sync::RwLock;
///
/// let lock = RwLock::new(5)
///
diff --git a/framework/jinux-frame/src/sync/rwlock.rs b/framework/aster-frame/src/sync/rwlock.rs
--- a/framework/jinux-frame/src/sync/rwlock.rs
+++ b/framework/aster-frame/src/sync/rwlock.rs
@@ -57,7 +57,7 @@ use crate::trap::DisabledLocalIrqGuard;
/// # Examples
///
/// ```
-/// use jinux_frame::sync::RwLock;
+/// use aster_frame::sync::RwLock;
///
/// let lock = RwLock::new(5)
///
diff --git a/framework/jinux-frame/src/sync/rwmutex.rs b/framework/aster-frame/src/sync/rwmutex.rs
--- a/framework/jinux-frame/src/sync/rwmutex.rs
+++ b/framework/aster-frame/src/sync/rwmutex.rs
@@ -46,7 +46,7 @@ use super::WaitQueue;
/// # Examples
///
/// ```
-/// use jinux_frame::sync::RwMutex;
+/// use aster_frame::sync::RwMutex;
///
/// let mutex = RwMutex::new(5)
///
diff --git a/framework/jinux-frame/src/sync/rwmutex.rs b/framework/aster-frame/src/sync/rwmutex.rs
--- a/framework/jinux-frame/src/sync/rwmutex.rs
+++ b/framework/aster-frame/src/sync/rwmutex.rs
@@ -46,7 +46,7 @@ use super::WaitQueue;
/// # Examples
///
/// ```
-/// use jinux_frame::sync::RwMutex;
+/// use aster_frame::sync::RwMutex;
///
/// let mutex = RwMutex::new(5)
///
diff --git a/framework/jinux-frame/src/trap/irq.rs b/framework/aster-frame/src/trap/irq.rs
--- a/framework/jinux-frame/src/trap/irq.rs
+++ b/framework/aster-frame/src/trap/irq.rs
@@ -98,7 +98,7 @@ impl Drop for IrqLine {
/// # Example
///
/// ``rust
-/// use jinux_frame::irq;
+/// use aster_frame::irq;
///
/// {
/// let _ = irq::disable_local();
diff --git a/framework/jinux-frame/src/trap/irq.rs b/framework/aster-frame/src/trap/irq.rs
--- a/framework/jinux-frame/src/trap/irq.rs
+++ b/framework/aster-frame/src/trap/irq.rs
@@ -98,7 +98,7 @@ impl Drop for IrqLine {
/// # Example
///
/// ``rust
-/// use jinux_frame::irq;
+/// use aster_frame::irq;
///
/// {
/// let _ = irq::disable_local();
diff --git a/framework/jinux-frame/src/user.rs b/framework/aster-frame/src/user.rs
--- a/framework/jinux-frame/src/user.rs
+++ b/framework/aster-frame/src/user.rs
@@ -48,7 +48,7 @@ impl UserSpace {
/// Specific architectures need to implement this trait. This should only used in `UserMode`
///
-/// Only visible in jinux-frame
+/// Only visible in aster-frame
pub(crate) trait UserContextApiInternal {
/// Starts executing in the user mode.
fn execute(&mut self) -> UserEvent;
diff --git a/framework/jinux-frame/src/user.rs b/framework/aster-frame/src/user.rs
--- a/framework/jinux-frame/src/user.rs
+++ b/framework/aster-frame/src/user.rs
@@ -48,7 +48,7 @@ impl UserSpace {
/// Specific architectures need to implement this trait. This should only used in `UserMode`
///
-/// Only visible in jinux-frame
+/// Only visible in aster-frame
pub(crate) trait UserContextApiInternal {
/// Starts executing in the user mode.
fn execute(&mut self) -> UserEvent;
diff --git a/framework/jinux-frame/src/user.rs b/framework/aster-frame/src/user.rs
--- a/framework/jinux-frame/src/user.rs
+++ b/framework/aster-frame/src/user.rs
@@ -98,7 +98,7 @@ pub trait UserContextApi {
/// Here is a sample code on how to use `UserMode`.
///
/// ```no_run
-/// use jinux_frame::task::Task;
+/// use aster_frame::task::Task;
///
/// let current = Task::current();
/// let user_space = current.user_space()
diff --git a/framework/jinux-frame/src/user.rs b/framework/aster-frame/src/user.rs
--- a/framework/jinux-frame/src/user.rs
+++ b/framework/aster-frame/src/user.rs
@@ -98,7 +98,7 @@ pub trait UserContextApi {
/// Here is a sample code on how to use `UserMode`.
///
/// ```no_run
-/// use jinux_frame::task::Task;
+/// use aster_frame::task::Task;
///
/// let current = Task::current();
/// let user_space = current.user_space()
diff --git a/framework/jinux-frame/src/vm/mod.rs b/framework/aster-frame/src/vm/mod.rs
--- a/framework/jinux-frame/src/vm/mod.rs
+++ b/framework/aster-frame/src/vm/mod.rs
@@ -54,12 +54,12 @@ pub const fn is_page_aligned(p: usize) -> bool {
(p & (PAGE_SIZE - 1)) == 0
}
-/// Convert physical address to virtual address using offset, only available inside jinux-frame
+/// Convert physical address to virtual address using offset, only available inside aster-frame
pub(crate) fn paddr_to_vaddr(pa: usize) -> usize {
pa + PHYS_OFFSET
}
-/// Only available inside jinux-frame
+/// Only available inside aster-frame
pub(crate) static MEMORY_REGIONS: Once<Vec<MemoryRegion>> = Once::new();
pub static FRAMEBUFFER_REGIONS: Once<Vec<MemoryRegion>> = Once::new();
diff --git a/framework/jinux-frame/src/vm/mod.rs b/framework/aster-frame/src/vm/mod.rs
--- a/framework/jinux-frame/src/vm/mod.rs
+++ b/framework/aster-frame/src/vm/mod.rs
@@ -54,12 +54,12 @@ pub const fn is_page_aligned(p: usize) -> bool {
(p & (PAGE_SIZE - 1)) == 0
}
-/// Convert physical address to virtual address using offset, only available inside jinux-frame
+/// Convert physical address to virtual address using offset, only available inside aster-frame
pub(crate) fn paddr_to_vaddr(pa: usize) -> usize {
pa + PHYS_OFFSET
}
-/// Only available inside jinux-frame
+/// Only available inside aster-frame
pub(crate) static MEMORY_REGIONS: Once<Vec<MemoryRegion>> = Once::new();
pub static FRAMEBUFFER_REGIONS: Once<Vec<MemoryRegion>> = Once::new();
diff --git a/framework/libs/ktest/src/lib.rs b/framework/libs/ktest/src/lib.rs
--- a/framework/libs/ktest/src/lib.rs
+++ b/framework/libs/ktest/src/lib.rs
@@ -1,10 +1,10 @@
-//! # The kernel mode testing framework of Jinux.
+//! # The kernel mode testing framework of Asterinas.
//!
//! `ktest` stands for kernel-mode testing framework. Its goal is to provide a
//! `cargo test`-like experience for any `#![no_std]` bare metal crates.
//!
-//! In Jinux, all the tests written in the source tree of the crates will be run
-//! immediately after the initialization of jinux-frame. Thus you can use any
+//! In Asterinas, all the tests written in the source tree of the crates will be run
+//! immediately after the initialization of aster-frame. Thus you can use any
//! feature provided by the frame including the heap allocator, etc.
//!
//! By all means, ktest is an individule crate that only requires:
diff --git a/framework/libs/ktest/src/lib.rs b/framework/libs/ktest/src/lib.rs
--- a/framework/libs/ktest/src/lib.rs
+++ b/framework/libs/ktest/src/lib.rs
@@ -39,7 +39,7 @@
//! }
//! ```
//!
-//! And also, any crates using the ktest framework should be linked with jinux-frame
+//! And also, any crates using the ktest framework should be linked with aster-frame
//! and import the `ktest` crate:
//!
//! ```toml
diff --git a/framework/libs/ktest/src/lib.rs b/framework/libs/ktest/src/lib.rs
--- a/framework/libs/ktest/src/lib.rs
+++ b/framework/libs/ktest/src/lib.rs
@@ -67,14 +67,14 @@
//! This is achieved by a whitelist filter on the test name.
//!
//! ```bash
-//! make run KTEST=1 KTEST_WHITELIST=failing_assertion,jinux_frame::test::expect_panic
+//! make run KTEST=1 KTEST_WHITELIST=failing_assertion,aster_frame::test::expect_panic
//! ```
//!
//! `KTEST_CRATES` variable is used to specify in which crates the tests to be run.
//! This is achieved by conditionally compiling the test module using the `#[cfg]`.
//!
//! ```bash
-//! make run KTEST=1 KTEST_CRATES=jinux-frame
+//! make run KTEST=1 KTEST_CRATES=aster-frame
//! ``
//!
//! We support the `#[should_panic]` attribute just in the same way as the standard
diff --git a/kernel/main.rs b/kernel/main.rs
--- a/kernel/main.rs
+++ b/kernel/main.rs
@@ -1,17 +1,17 @@
#![no_std]
#![no_main]
-// The `export_name` attribute for the `jinux_main` entrypoint requires the removal of safety check.
+// The `export_name` attribute for the `aster_main` entrypoint requires the removal of safety check.
// Please be aware that the kernel is not allowed to introduce any other unsafe operations.
// #![forbid(unsafe_code)]
-extern crate jinux_frame;
+extern crate aster_frame;
-use jinux_frame::early_println;
+use aster_frame::early_println;
-#[export_name = "jinux_main"]
+#[export_name = "aster_main"]
pub fn main() -> ! {
- jinux_frame::init();
- early_println!("[kernel] finish init jinux_frame");
+ aster_frame::init();
+ early_println!("[kernel] finish init aster_frame");
component::init_all(component::parse_metadata!()).unwrap();
- jinux_std::init();
- jinux_std::run_first_process();
+ aster_std::init();
+ aster_std::run_first_process();
}
diff --git a/kernel/main.rs b/kernel/main.rs
--- a/kernel/main.rs
+++ b/kernel/main.rs
@@ -1,17 +1,17 @@
#![no_std]
#![no_main]
-// The `export_name` attribute for the `jinux_main` entrypoint requires the removal of safety check.
+// The `export_name` attribute for the `aster_main` entrypoint requires the removal of safety check.
// Please be aware that the kernel is not allowed to introduce any other unsafe operations.
// #![forbid(unsafe_code)]
-extern crate jinux_frame;
+extern crate aster_frame;
-use jinux_frame::early_println;
+use aster_frame::early_println;
-#[export_name = "jinux_main"]
+#[export_name = "aster_main"]
pub fn main() -> ! {
- jinux_frame::init();
- early_println!("[kernel] finish init jinux_frame");
+ aster_frame::init();
+ early_println!("[kernel] finish init aster_frame");
component::init_all(component::parse_metadata!()).unwrap();
- jinux_std::init();
- jinux_std::run_first_process();
+ aster_std::init();
+ aster_std::run_first_process();
}
diff --git a/regression/Makefile b/regression/Makefile
--- a/regression/Makefile
+++ b/regression/Makefile
@@ -39,7 +39,7 @@ $(INITRAMFS)/lib/x86_64-linux-gnu:
@cp -L /lib/x86_64-linux-gnu/libz.so.1 $@
@cp -L /usr/local/benchmark/iperf/lib/libiperf.so.0 $@
@# TODO: use a custom compiled vdso.so file in the future.
- @git clone https://github.com/jinzhao-dev/linux_vdso.git
+ @git clone https://github.com/asterinas/linux_vdso.git
@cd ./linux_vdso && git checkout 2a6d2db 2>/dev/null
@cp -L ./linux_vdso/vdso64.so $@
@rm -rf ./linux_vdso
diff --git a/regression/Makefile b/regression/Makefile
--- a/regression/Makefile
+++ b/regression/Makefile
@@ -39,7 +39,7 @@ $(INITRAMFS)/lib/x86_64-linux-gnu:
@cp -L /lib/x86_64-linux-gnu/libz.so.1 $@
@cp -L /usr/local/benchmark/iperf/lib/libiperf.so.0 $@
@# TODO: use a custom compiled vdso.so file in the future.
- @git clone https://github.com/jinzhao-dev/linux_vdso.git
+ @git clone https://github.com/asterinas/linux_vdso.git
@cd ./linux_vdso && git checkout 2a6d2db 2>/dev/null
@cp -L ./linux_vdso/vdso64.so $@
@rm -rf ./linux_vdso
diff --git a/regression/apps/scripts/shell_cmd.sh b/regression/apps/scripts/shell_cmd.sh
--- a/regression/apps/scripts/shell_cmd.sh
+++ b/regression/apps/scripts/shell_cmd.sh
@@ -31,7 +31,7 @@ find . -name "*shell_cmd*"
mkdir foo
rmdir foo
-echo "Hello world from jinux" > hello.txt
+echo "Hello world from asterinas" > hello.txt
rm hello.txt
cd ..
diff --git a/regression/apps/scripts/shell_cmd.sh b/regression/apps/scripts/shell_cmd.sh
--- a/regression/apps/scripts/shell_cmd.sh
+++ b/regression/apps/scripts/shell_cmd.sh
@@ -31,7 +31,7 @@ find . -name "*shell_cmd*"
mkdir foo
rmdir foo
-echo "Hello world from jinux" > hello.txt
+echo "Hello world from asterinas" > hello.txt
rm hello.txt
cd ..
diff --git a/regression/apps/signal_c/signal_test.c b/regression/apps/signal_c/signal_test.c
--- a/regression/apps/signal_c/signal_test.c
+++ b/regression/apps/signal_c/signal_test.c
@@ -184,7 +184,7 @@ int test_handle_sigfpe() {
c = div_maybe_zero(a, b);
fxsave(y);
- // jinux does not save and restore fpregs now, so we emit this check.
+ // Asterinas does not save and restore fpregs now, so we emit this check.
// if (memcmp(x, y, 512) != 0) {
// THROW_ERROR("floating point registers are modified");
// }
diff --git a/regression/syscall_test/Makefile b/regression/syscall_test/Makefile
--- a/regression/syscall_test/Makefile
+++ b/regression/syscall_test/Makefile
@@ -3,8 +3,8 @@ TESTS ?= open_test read_test statfs_test chmod_test pty_test uidgid_test vdso_cl
MKFILE_PATH := $(abspath $(lastword $(MAKEFILE_LIST)))
CUR_DIR := $(patsubst %/,%,$(dir $(MKFILE_PATH)))
BUILD_DIR ?= $(CUR_DIR)/../build
-ifdef JINUX_PREBUILT_SYSCALL_TEST
- BIN_DIR := $(JINUX_PREBUILT_SYSCALL_TEST)
+ifdef ASTER_PREBUILT_SYSCALL_TEST
+ BIN_DIR := $(ASTER_PREBUILT_SYSCALL_TEST)
else
BIN_DIR := $(BUILD_DIR)/syscall_test_bins
SRC_DIR := $(BUILD_DIR)/gvisor_src
diff --git a/regression/syscall_test/Makefile b/regression/syscall_test/Makefile
--- a/regression/syscall_test/Makefile
+++ b/regression/syscall_test/Makefile
@@ -21,7 +21,7 @@ all: $(TESTS)
$(TESTS): $(BIN_DIR) $(TARGET_DIR)
@cp -f $</$@ $(TARGET_DIR)/tests
-ifndef JINUX_PREBUILT_SYSCALL_TEST
+ifndef ASTER_PREBUILT_SYSCALL_TEST
$(BIN_DIR): $(SRC_DIR)
@if ! type bazel > /dev/null; then \
echo "bazel is not installed, please run $(CUR_DIR)/install_bazel.sh with sudo permission to install it."; \
diff --git a/regression/syscall_test/Makefile b/regression/syscall_test/Makefile
--- a/regression/syscall_test/Makefile
+++ b/regression/syscall_test/Makefile
@@ -33,7 +33,7 @@ $(BIN_DIR): $(SRC_DIR)
$(SRC_DIR):
@rm -rf $@ && mkdir -p $@
- @cd $@ && git clone -b 20200921.0 https://github.com/jinzhao-dev/gvisor.git .
+ @cd $@ && git clone -b 20200921.0 https://github.com/asterinas/gvisor.git .
endif
$(TARGET_DIR): $(RUN_BASH) $(BLOCK_LIST)
diff --git a/runner/Cargo.toml b/runner/Cargo.toml
--- a/runner/Cargo.toml
+++ b/runner/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "jinux-runner"
+name = "aster-runner"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
diff --git a/runner/Cargo.toml b/runner/Cargo.toml
--- a/runner/Cargo.toml
+++ b/runner/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "jinux-runner"
+name = "aster-runner"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
diff --git a/runner/grub/grub.cfg.template b/runner/grub/grub.cfg.template
--- a/runner/grub/grub.cfg.template
+++ b/runner/grub/grub.cfg.template
@@ -7,7 +7,7 @@
set timeout_style=#GRUB_TIMEOUT_STYLE#
set timeout=#GRUB_TIMEOUT#
-menuentry 'jinux' {
+menuentry 'asterinas' {
#GRUB_CMD_KERNEL# #KERNEL# #KERNEL_COMMAND_LINE#
#GRUB_CMD_INITRAMFS# /boot/initramfs.cpio.gz
boot
diff --git a/runner/grub/grub.cfg.template b/runner/grub/grub.cfg.template
--- a/runner/grub/grub.cfg.template
+++ b/runner/grub/grub.cfg.template
@@ -7,7 +7,7 @@
set timeout_style=#GRUB_TIMEOUT_STYLE#
set timeout=#GRUB_TIMEOUT#
-menuentry 'jinux' {
+menuentry 'asterinas' {
#GRUB_CMD_KERNEL# #KERNEL# #KERNEL_COMMAND_LINE#
#GRUB_CMD_INITRAMFS# /boot/initramfs.cpio.gz
boot
diff --git a/runner/src/gdb.rs b/runner/src/gdb.rs
--- a/runner/src/gdb.rs
+++ b/runner/src/gdb.rs
@@ -21,7 +21,7 @@ pub fn run_gdb_client(path: &PathBuf, gdb_grub: bool) {
let mut gdb_cmd = Command::new("gdb");
// Set the architecture, otherwise GDB will complain about.
gdb_cmd.arg("-ex").arg("set arch i386:x86-64:intel");
- let grub_script = "/tmp/jinux-gdb-grub-script";
+ let grub_script = "/tmp/aster-gdb-grub-script";
if gdb_grub {
let grub_dir = PathBuf::from(qemu_grub_efi::GRUB_PREFIX)
.join("lib")
diff --git a/runner/src/gdb.rs b/runner/src/gdb.rs
--- a/runner/src/gdb.rs
+++ b/runner/src/gdb.rs
@@ -21,7 +21,7 @@ pub fn run_gdb_client(path: &PathBuf, gdb_grub: bool) {
let mut gdb_cmd = Command::new("gdb");
// Set the architecture, otherwise GDB will complain about.
gdb_cmd.arg("-ex").arg("set arch i386:x86-64:intel");
- let grub_script = "/tmp/jinux-gdb-grub-script";
+ let grub_script = "/tmp/aster-gdb-grub-script";
if gdb_grub {
let grub_dir = PathBuf::from(qemu_grub_efi::GRUB_PREFIX)
.join("lib")
diff --git a/runner/src/gdb.rs b/runner/src/gdb.rs
--- a/runner/src/gdb.rs
+++ b/runner/src/gdb.rs
@@ -41,7 +41,7 @@ pub fn run_gdb_client(path: &PathBuf, gdb_grub: bool) {
for line in lines {
if line.contains("target remote :1234") {
// Connect to the GDB server.
- writeln!(f, "target remote /tmp/jinux-gdb-socket").unwrap();
+ writeln!(f, "target remote /tmp/aster-gdb-socket").unwrap();
} else {
writeln!(f, "{}", line).unwrap();
}
diff --git a/runner/src/gdb.rs b/runner/src/gdb.rs
--- a/runner/src/gdb.rs
+++ b/runner/src/gdb.rs
@@ -41,7 +41,7 @@ pub fn run_gdb_client(path: &PathBuf, gdb_grub: bool) {
for line in lines {
if line.contains("target remote :1234") {
// Connect to the GDB server.
- writeln!(f, "target remote /tmp/jinux-gdb-socket").unwrap();
+ writeln!(f, "target remote /tmp/aster-gdb-socket").unwrap();
} else {
writeln!(f, "{}", line).unwrap();
}
diff --git a/runner/src/gdb.rs b/runner/src/gdb.rs
--- a/runner/src/gdb.rs
+++ b/runner/src/gdb.rs
@@ -53,7 +53,7 @@ pub fn run_gdb_client(path: &PathBuf, gdb_grub: bool) {
// Connect to the GDB server.
gdb_cmd
.arg("-ex")
- .arg("target remote /tmp/jinux-gdb-socket");
+ .arg("target remote /tmp/aster-gdb-socket");
}
// Connect to the GDB server and run.
println!("running:{:#?}", gdb_cmd);
diff --git a/runner/src/gdb.rs b/runner/src/gdb.rs
--- a/runner/src/gdb.rs
+++ b/runner/src/gdb.rs
@@ -53,7 +53,7 @@ pub fn run_gdb_client(path: &PathBuf, gdb_grub: bool) {
// Connect to the GDB server.
gdb_cmd
.arg("-ex")
- .arg("target remote /tmp/jinux-gdb-socket");
+ .arg("target remote /tmp/aster-gdb-socket");
}
// Connect to the GDB server and run.
println!("running:{:#?}", gdb_cmd);
diff --git a/runner/src/machine/qemu_grub_efi/linux_boot.rs b/runner/src/machine/qemu_grub_efi/linux_boot.rs
--- a/runner/src/machine/qemu_grub_efi/linux_boot.rs
+++ b/runner/src/machine/qemu_grub_efi/linux_boot.rs
@@ -47,7 +47,7 @@ fn header_to_raw_binary(elf_file: &[u8]) -> Vec<u8> {
/// This function sould be used when generating the Linux x86 Boot setup header.
/// Some fields in the Linux x86 Boot setup header should be filled after assembled.
/// And the filled fields must have the bytes with values of 0xAB. See
-/// `framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/src/header.S` for more
+/// `framework/aster-frame/src/arch/x86/boot/linux_boot/setup/src/header.S` for more
/// info on this mechanism.
fn fill_header_field(header: &mut [u8], offset: usize, value: &[u8]) {
let size = value.len();
diff --git a/runner/src/machine/qemu_grub_efi/linux_boot.rs b/runner/src/machine/qemu_grub_efi/linux_boot.rs
--- a/runner/src/machine/qemu_grub_efi/linux_boot.rs
+++ b/runner/src/machine/qemu_grub_efi/linux_boot.rs
@@ -47,7 +47,7 @@ fn header_to_raw_binary(elf_file: &[u8]) -> Vec<u8> {
/// This function sould be used when generating the Linux x86 Boot setup header.
/// Some fields in the Linux x86 Boot setup header should be filled after assembled.
/// And the filled fields must have the bytes with values of 0xAB. See
-/// `framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/src/header.S` for more
+/// `framework/aster-frame/src/arch/x86/boot/linux_boot/setup/src/header.S` for more
/// info on this mechanism.
fn fill_header_field(header: &mut [u8], offset: usize, value: &[u8]) {
let size = value.len();
diff --git a/runner/src/machine/qemu_grub_efi/mod.rs b/runner/src/machine/qemu_grub_efi/mod.rs
--- a/runner/src/machine/qemu_grub_efi/mod.rs
+++ b/runner/src/machine/qemu_grub_efi/mod.rs
@@ -70,13 +70,13 @@ pub const GRUB_PREFIX: &str = "/usr/local/grub";
pub const GRUB_VERSION: &str = "x86_64-efi";
pub fn create_bootdev_image(
- jinux_path: PathBuf,
+ atser_path: PathBuf,
initramfs_path: PathBuf,
grub_cfg: String,
protocol: BootProtocol,
release_mode: bool,
) -> PathBuf {
- let target_dir = jinux_path.parent().unwrap();
+ let target_dir = atser_path.parent().unwrap();
let iso_root = target_dir.join("iso_root");
// Clear or make the iso dir.
diff --git a/runner/src/machine/qemu_grub_efi/mod.rs b/runner/src/machine/qemu_grub_efi/mod.rs
--- a/runner/src/machine/qemu_grub_efi/mod.rs
+++ b/runner/src/machine/qemu_grub_efi/mod.rs
@@ -70,13 +70,13 @@ pub const GRUB_PREFIX: &str = "/usr/local/grub";
pub const GRUB_VERSION: &str = "x86_64-efi";
pub fn create_bootdev_image(
- jinux_path: PathBuf,
+ atser_path: PathBuf,
initramfs_path: PathBuf,
grub_cfg: String,
protocol: BootProtocol,
release_mode: bool,
) -> PathBuf {
- let target_dir = jinux_path.parent().unwrap();
+ let target_dir = atser_path.parent().unwrap();
let iso_root = target_dir.join("iso_root");
// Clear or make the iso dir.
diff --git a/runner/src/machine/qemu_grub_efi/mod.rs b/runner/src/machine/qemu_grub_efi/mod.rs
--- a/runner/src/machine/qemu_grub_efi/mod.rs
+++ b/runner/src/machine/qemu_grub_efi/mod.rs
@@ -96,24 +96,24 @@ pub fn create_bootdev_image(
BootProtocol::Linux => {
// Find the setup header in the build script output directory.
let bs_out_dir = if release_mode {
- glob("target/x86_64-custom/release/build/jinux-frame-*").unwrap()
+ glob("target/x86_64-custom/release/build/aster-frame-*").unwrap()
} else {
- glob("target/x86_64-custom/debug/build/jinux-frame-*").unwrap()
+ glob("target/x86_64-custom/debug/build/aster-frame-*").unwrap()
};
let header_path = Path::new(bs_out_dir.into_iter().next().unwrap().unwrap().as_path())
.join("out")
.join("bin")
- .join("jinux-frame-x86-boot-linux-setup");
+ .join("aster-frame-x86-boot-linux-setup");
// Make the `bzImage`-compatible kernel image and place it in the boot directory.
- let target_path = iso_root.join("boot").join("jinuz");
- linux_boot::make_bzimage(&target_path, &jinux_path.as_path(), &header_path.as_path())
+ let target_path = iso_root.join("boot").join("asterinaz");
+ linux_boot::make_bzimage(&target_path, &atser_path.as_path(), &header_path.as_path())
.unwrap();
target_path
}
BootProtocol::Multiboot | BootProtocol::Multiboot2 => {
// Copy the kernel image to the boot directory.
- let target_path = iso_root.join("boot").join("jinux");
- fs::copy(&jinux_path, &target_path).unwrap();
+ let target_path = iso_root.join("boot").join("atserinas");
+ fs::copy(&atser_path, &target_path).unwrap();
target_path
}
};
diff --git a/runner/src/machine/qemu_grub_efi/mod.rs b/runner/src/machine/qemu_grub_efi/mod.rs
--- a/runner/src/machine/qemu_grub_efi/mod.rs
+++ b/runner/src/machine/qemu_grub_efi/mod.rs
@@ -96,24 +96,24 @@ pub fn create_bootdev_image(
BootProtocol::Linux => {
// Find the setup header in the build script output directory.
let bs_out_dir = if release_mode {
- glob("target/x86_64-custom/release/build/jinux-frame-*").unwrap()
+ glob("target/x86_64-custom/release/build/aster-frame-*").unwrap()
} else {
- glob("target/x86_64-custom/debug/build/jinux-frame-*").unwrap()
+ glob("target/x86_64-custom/debug/build/aster-frame-*").unwrap()
};
let header_path = Path::new(bs_out_dir.into_iter().next().unwrap().unwrap().as_path())
.join("out")
.join("bin")
- .join("jinux-frame-x86-boot-linux-setup");
+ .join("aster-frame-x86-boot-linux-setup");
// Make the `bzImage`-compatible kernel image and place it in the boot directory.
- let target_path = iso_root.join("boot").join("jinuz");
- linux_boot::make_bzimage(&target_path, &jinux_path.as_path(), &header_path.as_path())
+ let target_path = iso_root.join("boot").join("asterinaz");
+ linux_boot::make_bzimage(&target_path, &atser_path.as_path(), &header_path.as_path())
.unwrap();
target_path
}
BootProtocol::Multiboot | BootProtocol::Multiboot2 => {
// Copy the kernel image to the boot directory.
- let target_path = iso_root.join("boot").join("jinux");
- fs::copy(&jinux_path, &target_path).unwrap();
+ let target_path = iso_root.join("boot").join("atserinas");
+ fs::copy(&atser_path, &target_path).unwrap();
target_path
}
};
diff --git a/runner/src/machine/qemu_grub_efi/mod.rs b/runner/src/machine/qemu_grub_efi/mod.rs
--- a/runner/src/machine/qemu_grub_efi/mod.rs
+++ b/runner/src/machine/qemu_grub_efi/mod.rs
@@ -164,15 +164,15 @@ pub fn generate_grub_cfg(
let buffer = match protocol {
BootProtocol::Multiboot => buffer
.replace("#GRUB_CMD_KERNEL#", "multiboot")
- .replace("#KERNEL#", "/boot/jinux")
+ .replace("#KERNEL#", "/boot/atserinas")
.replace("#GRUB_CMD_INITRAMFS#", "module --nounzip"),
BootProtocol::Multiboot2 => buffer
.replace("#GRUB_CMD_KERNEL#", "multiboot2")
- .replace("#KERNEL#", "/boot/jinux")
+ .replace("#KERNEL#", "/boot/atserinas")
.replace("#GRUB_CMD_INITRAMFS#", "module2 --nounzip"),
BootProtocol::Linux => buffer
.replace("#GRUB_CMD_KERNEL#", "linux")
- .replace("#KERNEL#", "/boot/jinuz")
+ .replace("#KERNEL#", "/boot/asterinaz")
.replace("#GRUB_CMD_INITRAMFS#", "initrd"),
};
diff --git a/runner/src/machine/qemu_grub_efi/mod.rs b/runner/src/machine/qemu_grub_efi/mod.rs
--- a/runner/src/machine/qemu_grub_efi/mod.rs
+++ b/runner/src/machine/qemu_grub_efi/mod.rs
@@ -164,15 +164,15 @@ pub fn generate_grub_cfg(
let buffer = match protocol {
BootProtocol::Multiboot => buffer
.replace("#GRUB_CMD_KERNEL#", "multiboot")
- .replace("#KERNEL#", "/boot/jinux")
+ .replace("#KERNEL#", "/boot/atserinas")
.replace("#GRUB_CMD_INITRAMFS#", "module --nounzip"),
BootProtocol::Multiboot2 => buffer
.replace("#GRUB_CMD_KERNEL#", "multiboot2")
- .replace("#KERNEL#", "/boot/jinux")
+ .replace("#KERNEL#", "/boot/atserinas")
.replace("#GRUB_CMD_INITRAMFS#", "module2 --nounzip"),
BootProtocol::Linux => buffer
.replace("#GRUB_CMD_KERNEL#", "linux")
- .replace("#KERNEL#", "/boot/jinuz")
+ .replace("#KERNEL#", "/boot/asterinaz")
.replace("#GRUB_CMD_INITRAMFS#", "initrd"),
};
diff --git a/runner/src/main.rs b/runner/src/main.rs
--- a/runner/src/main.rs
+++ b/runner/src/main.rs
@@ -1,8 +1,8 @@
-//! jinux-runner is the Jinux runner script to ease the pain of running
-//! and testing Jinux inside a QEMU VM. It should be built and run as the
+//! aster-runner is the Asterinas runner script to ease the pain of running
+//! and testing Asterinas inside a QEMU VM. It should be built and run as the
//! cargo runner: https://doc.rust-lang.org/cargo/reference/config.html
//!
-//! The runner will generate the filesystem image for starting Jinux. If
+//! The runner will generate the filesystem image for starting Asterinas. If
//! we should use the runner in the default mode, which invokes QEMU with
//! a GRUB boot device image, the runner would be responsible for generating
//! the appropriate kernel image and the boot device image. It also supports
diff --git a/runner/src/main.rs b/runner/src/main.rs
--- a/runner/src/main.rs
+++ b/runner/src/main.rs
@@ -40,7 +40,7 @@ pub enum BootProtocol {
#[command(author, version, about, long_about = None)]
struct Args {
// Positional arguments.
- /// The Jinux binary path.
+ /// The Asterinas binary path.
path: PathBuf,
/// Provide the kernel commandline, which specifies
diff --git a/runner/src/main.rs b/runner/src/main.rs
--- a/runner/src/main.rs
+++ b/runner/src/main.rs
@@ -40,7 +40,7 @@ pub enum BootProtocol {
#[command(author, version, about, long_about = None)]
struct Args {
// Positional arguments.
- /// The Jinux binary path.
+ /// The Asterinas binary path.
path: PathBuf,
/// Provide the kernel commandline, which specifies
diff --git a/runner/src/main.rs b/runner/src/main.rs
--- a/runner/src/main.rs
+++ b/runner/src/main.rs
@@ -117,7 +117,7 @@ pub fn random_hostfwd_ports() -> (u16, u16) {
pub const GDB_ARGS: &[&str] = &[
"-chardev",
- "socket,path=/tmp/jinux-gdb-socket,server=on,wait=off,id=gdb0",
+ "socket,path=/tmp/aster-gdb-socket,server=on,wait=off,id=gdb0",
"-gdb",
"chardev:gdb0",
"-S",
diff --git a/runner/src/main.rs b/runner/src/main.rs
--- a/runner/src/main.rs
+++ b/runner/src/main.rs
@@ -117,7 +117,7 @@ pub fn random_hostfwd_ports() -> (u16, u16) {
pub const GDB_ARGS: &[&str] = &[
"-chardev",
- "socket,path=/tmp/jinux-gdb-socket,server=on,wait=off,id=gdb0",
+ "socket,path=/tmp/aster-gdb-socket,server=on,wait=off,id=gdb0",
"-gdb",
"chardev:gdb0",
"-S",
diff --git a/runner/src/main.rs b/runner/src/main.rs
--- a/runner/src/main.rs
+++ b/runner/src/main.rs
@@ -145,13 +145,13 @@ fn main() {
port1, port2
));
println!(
- "[jinux-runner] Binding host ports to guest ports: ({} -> {}); ({} -> {}).",
+ "[aster-runner] Binding host ports to guest ports: ({} -> {}); ({} -> {}).",
port1, 22, port2, 8080
);
if args.halt_for_gdb {
if args.enable_kvm {
- println!("[jinux-runner] Can't enable KVM when running QEMU as a GDB server. Abort.");
+ println!("[aster-runner] Can't enable KVM when running QEMU as a GDB server. Abort.");
return;
}
qemu_cmd.args(GDB_ARGS);
diff --git a/runner/src/main.rs b/runner/src/main.rs
--- a/runner/src/main.rs
+++ b/runner/src/main.rs
@@ -145,13 +145,13 @@ fn main() {
port1, port2
));
println!(
- "[jinux-runner] Binding host ports to guest ports: ({} -> {}); ({} -> {}).",
+ "[aster-runner] Binding host ports to guest ports: ({} -> {}); ({} -> {}).",
port1, 22, port2, 8080
);
if args.halt_for_gdb {
if args.enable_kvm {
- println!("[jinux-runner] Can't enable KVM when running QEMU as a GDB server. Abort.");
+ println!("[aster-runner] Can't enable KVM when running QEMU as a GDB server. Abort.");
return;
}
qemu_cmd.args(GDB_ARGS);
diff --git a/runner/src/main.rs b/runner/src/main.rs
--- a/runner/src/main.rs
+++ b/runner/src/main.rs
@@ -206,17 +206,18 @@ fn main() {
qemu_cmd.arg(bootdev_image.as_os_str());
}
- println!("[jinux-runner] Running: {:#?}", qemu_cmd);
+ println!("[aster-runner] Running: {:#?}", qemu_cmd);
let exit_status = qemu_cmd.status().unwrap();
-
- // FIXME: Exit code manipulation is not needed when using non-x86 QEMU
- let qemu_exit_code = exit_status.code().unwrap();
- let kernel_exit_code = qemu_exit_code >> 1;
- match kernel_exit_code {
- 0x10 /* jinux_frame::QemuExitCode::Success */ => { std::process::exit(0); },
- 0x20 /* jinux_frame::QemuExitCode::Failed */ => { std::process::exit(1); },
- _ /* unknown, e.g., a triple fault */ => { std::process::exit(2) },
+ if !exit_status.success() {
+ // FIXME: Exit code manipulation is not needed when using non-x86 QEMU
+ let qemu_exit_code = exit_status.code().unwrap();
+ let kernel_exit_code = qemu_exit_code >> 1;
+ match kernel_exit_code {
+ 0x10 /*aster_frame::QemuExitCode::Success*/ => { std::process::exit(0); },
+ 0x20 /*aster_frame::QemuExitCode::Failed*/ => { std::process::exit(1); },
+ _ /* unknown, e.g., a triple fault */ => { std::process::exit(2) },
+ }
}
}
diff --git a/runner/src/main.rs b/runner/src/main.rs
--- a/runner/src/main.rs
+++ b/runner/src/main.rs
@@ -206,17 +206,18 @@ fn main() {
qemu_cmd.arg(bootdev_image.as_os_str());
}
- println!("[jinux-runner] Running: {:#?}", qemu_cmd);
+ println!("[aster-runner] Running: {:#?}", qemu_cmd);
let exit_status = qemu_cmd.status().unwrap();
-
- // FIXME: Exit code manipulation is not needed when using non-x86 QEMU
- let qemu_exit_code = exit_status.code().unwrap();
- let kernel_exit_code = qemu_exit_code >> 1;
- match kernel_exit_code {
- 0x10 /* jinux_frame::QemuExitCode::Success */ => { std::process::exit(0); },
- 0x20 /* jinux_frame::QemuExitCode::Failed */ => { std::process::exit(1); },
- _ /* unknown, e.g., a triple fault */ => { std::process::exit(2) },
+ if !exit_status.success() {
+ // FIXME: Exit code manipulation is not needed when using non-x86 QEMU
+ let qemu_exit_code = exit_status.code().unwrap();
+ let kernel_exit_code = qemu_exit_code >> 1;
+ match kernel_exit_code {
+ 0x10 /*aster_frame::QemuExitCode::Success*/ => { std::process::exit(0); },
+ 0x20 /*aster_frame::QemuExitCode::Failed*/ => { std::process::exit(1); },
+ _ /* unknown, e.g., a triple fault */ => { std::process::exit(2) },
+ }
}
}
diff --git a/services/comps/block/Cargo.toml b/services/comps/block/Cargo.toml
--- a/services/comps/block/Cargo.toml
+++ b/services/comps/block/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "jinux-block"
+name = "aster-block"
version = "0.1.0"
edition = "2021"
diff --git a/services/comps/block/Cargo.toml b/services/comps/block/Cargo.toml
--- a/services/comps/block/Cargo.toml
+++ b/services/comps/block/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "jinux-block"
+name = "aster-block"
version = "0.1.0"
edition = "2021"
diff --git a/services/comps/block/Cargo.toml b/services/comps/block/Cargo.toml
--- a/services/comps/block/Cargo.toml
+++ b/services/comps/block/Cargo.toml
@@ -8,8 +8,8 @@ edition = "2021"
[dependencies]
bitflags = "1.3"
spin = "0.9.4"
-jinux-frame = { path = "../../../framework/jinux-frame" }
-jinux-util = { path = "../../libs/jinux-util" }
+aster-frame = { path = "../../../framework/aster-frame" }
+aster-util = { path = "../../libs/aster-util" }
component = { path = "../../libs/comp-sys/component" }
log = "0.4"
diff --git a/services/comps/block/Cargo.toml b/services/comps/block/Cargo.toml
--- a/services/comps/block/Cargo.toml
+++ b/services/comps/block/Cargo.toml
@@ -8,8 +8,8 @@ edition = "2021"
[dependencies]
bitflags = "1.3"
spin = "0.9.4"
-jinux-frame = { path = "../../../framework/jinux-frame" }
-jinux-util = { path = "../../libs/jinux-util" }
+aster-frame = { path = "../../../framework/aster-frame" }
+aster-util = { path = "../../libs/aster-util" }
component = { path = "../../libs/comp-sys/component" }
log = "0.4"
diff --git a/services/comps/block/src/lib.rs b/services/comps/block/src/lib.rs
--- a/services/comps/block/src/lib.rs
+++ b/services/comps/block/src/lib.rs
@@ -1,4 +1,4 @@
-//! The block devices of jinux
+//! The block devices of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
#![feature(fn_traits)]
diff --git a/services/comps/block/src/lib.rs b/services/comps/block/src/lib.rs
--- a/services/comps/block/src/lib.rs
+++ b/services/comps/block/src/lib.rs
@@ -1,4 +1,4 @@
-//! The block devices of jinux
+//! The block devices of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
#![feature(fn_traits)]
diff --git a/services/comps/block/src/lib.rs b/services/comps/block/src/lib.rs
--- a/services/comps/block/src/lib.rs
+++ b/services/comps/block/src/lib.rs
@@ -12,9 +12,9 @@ use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
+use aster_frame::sync::SpinLock;
use component::init_component;
use component::ComponentInitError;
-use jinux_frame::sync::SpinLock;
use spin::Once;
pub const BLK_SIZE: usize = 512;
diff --git a/services/comps/block/src/lib.rs b/services/comps/block/src/lib.rs
--- a/services/comps/block/src/lib.rs
+++ b/services/comps/block/src/lib.rs
@@ -12,9 +12,9 @@ use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
+use aster_frame::sync::SpinLock;
use component::init_component;
use component::ComponentInitError;
-use jinux_frame::sync::SpinLock;
use spin::Once;
pub const BLK_SIZE: usize = 512;
diff --git a/services/comps/console/Cargo.toml b/services/comps/console/Cargo.toml
--- a/services/comps/console/Cargo.toml
+++ b/services/comps/console/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "jinux-console"
+name = "aster-console"
version = "0.1.0"
edition = "2021"
diff --git a/services/comps/console/Cargo.toml b/services/comps/console/Cargo.toml
--- a/services/comps/console/Cargo.toml
+++ b/services/comps/console/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "jinux-console"
+name = "aster-console"
version = "0.1.0"
edition = "2021"
diff --git a/services/comps/console/Cargo.toml b/services/comps/console/Cargo.toml
--- a/services/comps/console/Cargo.toml
+++ b/services/comps/console/Cargo.toml
@@ -8,8 +8,8 @@ edition = "2021"
[dependencies]
bitflags = "1.3"
spin = "0.9.4"
-jinux-frame = { path = "../../../framework/jinux-frame" }
-jinux-util = { path = "../../libs/jinux-util" }
+aster-frame = { path = "../../../framework/aster-frame" }
+aster-util = { path = "../../libs/aster-util" }
component = { path = "../../libs/comp-sys/component" }
log = "0.4"
diff --git a/services/comps/console/Cargo.toml b/services/comps/console/Cargo.toml
--- a/services/comps/console/Cargo.toml
+++ b/services/comps/console/Cargo.toml
@@ -8,8 +8,8 @@ edition = "2021"
[dependencies]
bitflags = "1.3"
spin = "0.9.4"
-jinux-frame = { path = "../../../framework/jinux-frame" }
-jinux-util = { path = "../../libs/jinux-util" }
+aster-frame = { path = "../../../framework/aster-frame" }
+aster-util = { path = "../../libs/aster-util" }
component = { path = "../../libs/comp-sys/component" }
log = "0.4"
diff --git a/services/comps/console/src/lib.rs b/services/comps/console/src/lib.rs
--- a/services/comps/console/src/lib.rs
+++ b/services/comps/console/src/lib.rs
@@ -1,4 +1,4 @@
-//! The console device of jinux
+//! The console device of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
#![feature(fn_traits)]
diff --git a/services/comps/console/src/lib.rs b/services/comps/console/src/lib.rs
--- a/services/comps/console/src/lib.rs
+++ b/services/comps/console/src/lib.rs
@@ -1,4 +1,4 @@
-//! The console device of jinux
+//! The console device of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
#![feature(fn_traits)]
diff --git a/services/comps/console/src/lib.rs b/services/comps/console/src/lib.rs
--- a/services/comps/console/src/lib.rs
+++ b/services/comps/console/src/lib.rs
@@ -8,8 +8,8 @@ extern crate alloc;
use alloc::{collections::BTreeMap, fmt::Debug, string::String, sync::Arc, vec::Vec};
use core::any::Any;
+use aster_frame::sync::SpinLock;
use component::{init_component, ComponentInitError};
-use jinux_frame::sync::SpinLock;
use spin::Once;
pub type ConsoleCallback = dyn Fn(&[u8]) + Send + Sync;
diff --git a/services/comps/console/src/lib.rs b/services/comps/console/src/lib.rs
--- a/services/comps/console/src/lib.rs
+++ b/services/comps/console/src/lib.rs
@@ -8,8 +8,8 @@ extern crate alloc;
use alloc::{collections::BTreeMap, fmt::Debug, string::String, sync::Arc, vec::Vec};
use core::any::Any;
+use aster_frame::sync::SpinLock;
use component::{init_component, ComponentInitError};
-use jinux_frame::sync::SpinLock;
use spin::Once;
pub type ConsoleCallback = dyn Fn(&[u8]) + Send + Sync;
diff --git a/services/comps/framebuffer/Cargo.toml b/services/comps/framebuffer/Cargo.toml
--- a/services/comps/framebuffer/Cargo.toml
+++ b/services/comps/framebuffer/Cargo.toml
@@ -1,12 +1,12 @@
[package]
-name = "jinux-framebuffer"
+name = "aster-framebuffer"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
-jinux-frame = { path = "../../../framework/jinux-frame" }
+aster-frame = { path = "../../../framework/aster-frame" }
component = { path = "../../libs/comp-sys/component" }
log = "0.4"
spin = "0.9.4"
diff --git a/services/comps/framebuffer/Cargo.toml b/services/comps/framebuffer/Cargo.toml
--- a/services/comps/framebuffer/Cargo.toml
+++ b/services/comps/framebuffer/Cargo.toml
@@ -1,12 +1,12 @@
[package]
-name = "jinux-framebuffer"
+name = "aster-framebuffer"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
-jinux-frame = { path = "../../../framework/jinux-frame" }
+aster-frame = { path = "../../../framework/aster-frame" }
component = { path = "../../libs/comp-sys/component" }
log = "0.4"
spin = "0.9.4"
diff --git a/services/comps/framebuffer/src/lib.rs b/services/comps/framebuffer/src/lib.rs
--- a/services/comps/framebuffer/src/lib.rs
+++ b/services/comps/framebuffer/src/lib.rs
@@ -1,4 +1,4 @@
-//! The framebuffer of jinux
+//! The framebuffer of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
#![feature(strict_provenance)]
diff --git a/services/comps/framebuffer/src/lib.rs b/services/comps/framebuffer/src/lib.rs
--- a/services/comps/framebuffer/src/lib.rs
+++ b/services/comps/framebuffer/src/lib.rs
@@ -1,4 +1,4 @@
-//! The framebuffer of jinux
+//! The framebuffer of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
#![feature(strict_provenance)]
diff --git a/services/comps/framebuffer/src/lib.rs b/services/comps/framebuffer/src/lib.rs
--- a/services/comps/framebuffer/src/lib.rs
+++ b/services/comps/framebuffer/src/lib.rs
@@ -6,13 +6,13 @@
extern crate alloc;
use alloc::vec::Vec;
+use aster_frame::{boot, config::PAGE_SIZE, io_mem::IoMem, sync::SpinLock, vm::VmIo};
use component::{init_component, ComponentInitError};
use core::{
fmt,
ops::{Index, IndexMut},
};
use font8x8::UnicodeFonts;
-use jinux_frame::{boot, config::PAGE_SIZE, io_mem::IoMem, sync::SpinLock, vm::VmIo};
use spin::Once;
#[init_component]
diff --git a/services/comps/framebuffer/src/lib.rs b/services/comps/framebuffer/src/lib.rs
--- a/services/comps/framebuffer/src/lib.rs
+++ b/services/comps/framebuffer/src/lib.rs
@@ -6,13 +6,13 @@
extern crate alloc;
use alloc::vec::Vec;
+use aster_frame::{boot, config::PAGE_SIZE, io_mem::IoMem, sync::SpinLock, vm::VmIo};
use component::{init_component, ComponentInitError};
use core::{
fmt,
ops::{Index, IndexMut},
};
use font8x8::UnicodeFonts;
-use jinux_frame::{boot, config::PAGE_SIZE, io_mem::IoMem, sync::SpinLock, vm::VmIo};
use spin::Once;
#[init_component]
diff --git a/services/comps/framebuffer/src/lib.rs b/services/comps/framebuffer/src/lib.rs
--- a/services/comps/framebuffer/src/lib.rs
+++ b/services/comps/framebuffer/src/lib.rs
@@ -28,7 +28,7 @@ pub(crate) fn init() {
let framebuffer = boot::framebuffer_arg();
let mut writer = None;
let mut size = 0;
- for i in jinux_frame::vm::FRAMEBUFFER_REGIONS.get().unwrap().iter() {
+ for i in aster_frame::vm::FRAMEBUFFER_REGIONS.get().unwrap().iter() {
size = i.len() as usize;
}
diff --git a/services/comps/framebuffer/src/lib.rs b/services/comps/framebuffer/src/lib.rs
--- a/services/comps/framebuffer/src/lib.rs
+++ b/services/comps/framebuffer/src/lib.rs
@@ -28,7 +28,7 @@ pub(crate) fn init() {
let framebuffer = boot::framebuffer_arg();
let mut writer = None;
let mut size = 0;
- for i in jinux_frame::vm::FRAMEBUFFER_REGIONS.get().unwrap().iter() {
+ for i in aster_frame::vm::FRAMEBUFFER_REGIONS.get().unwrap().iter() {
size = i.len() as usize;
}
diff --git a/services/comps/input/Cargo.toml b/services/comps/input/Cargo.toml
--- a/services/comps/input/Cargo.toml
+++ b/services/comps/input/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "jinux-input"
+name = "aster-input"
version = "0.1.0"
edition = "2021"
diff --git a/services/comps/input/Cargo.toml b/services/comps/input/Cargo.toml
--- a/services/comps/input/Cargo.toml
+++ b/services/comps/input/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "jinux-input"
+name = "aster-input"
version = "0.1.0"
edition = "2021"
diff --git a/services/comps/input/Cargo.toml b/services/comps/input/Cargo.toml
--- a/services/comps/input/Cargo.toml
+++ b/services/comps/input/Cargo.toml
@@ -8,9 +8,9 @@ edition = "2021"
[dependencies]
bitflags = "1.3"
spin = "0.9.4"
-jinux-frame = { path = "../../../framework/jinux-frame" }
-jinux-util = { path = "../../libs/jinux-util" }
-jinux-rights = { path = "../../libs/jinux-rights" }
+aster-frame = { path = "../../../framework/aster-frame" }
+aster-util = { path = "../../libs/aster-util" }
+aster-rights = { path = "../../libs/aster-rights" }
component = { path = "../../libs/comp-sys/component" }
virtio-input-decoder = "0.1.4"
log = "0.4"
diff --git a/services/comps/input/Cargo.toml b/services/comps/input/Cargo.toml
--- a/services/comps/input/Cargo.toml
+++ b/services/comps/input/Cargo.toml
@@ -8,9 +8,9 @@ edition = "2021"
[dependencies]
bitflags = "1.3"
spin = "0.9.4"
-jinux-frame = { path = "../../../framework/jinux-frame" }
-jinux-util = { path = "../../libs/jinux-util" }
-jinux-rights = { path = "../../libs/jinux-rights" }
+aster-frame = { path = "../../../framework/aster-frame" }
+aster-util = { path = "../../libs/aster-util" }
+aster-rights = { path = "../../libs/aster-rights" }
component = { path = "../../libs/comp-sys/component" }
virtio-input-decoder = "0.1.4"
log = "0.4"
diff --git a/services/comps/input/src/lib.rs b/services/comps/input/src/lib.rs
--- a/services/comps/input/src/lib.rs
+++ b/services/comps/input/src/lib.rs
@@ -1,4 +1,4 @@
-//! The input devices of jinux
+//! The input devices of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
#![feature(fn_traits)]
diff --git a/services/comps/input/src/lib.rs b/services/comps/input/src/lib.rs
--- a/services/comps/input/src/lib.rs
+++ b/services/comps/input/src/lib.rs
@@ -1,4 +1,4 @@
-//! The input devices of jinux
+//! The input devices of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
#![feature(fn_traits)]
diff --git a/services/comps/input/src/lib.rs b/services/comps/input/src/lib.rs
--- a/services/comps/input/src/lib.rs
+++ b/services/comps/input/src/lib.rs
@@ -14,7 +14,7 @@ use alloc::vec::Vec;
use component::init_component;
use component::ComponentInitError;
-use jinux_frame::sync::SpinLock;
+use aster_frame::sync::SpinLock;
use spin::Once;
use virtio_input_decoder::DecodeType;
diff --git a/services/comps/input/src/lib.rs b/services/comps/input/src/lib.rs
--- a/services/comps/input/src/lib.rs
+++ b/services/comps/input/src/lib.rs
@@ -14,7 +14,7 @@ use alloc::vec::Vec;
use component::init_component;
use component::ComponentInitError;
-use jinux_frame::sync::SpinLock;
+use aster_frame::sync::SpinLock;
use spin::Once;
use virtio_input_decoder::DecodeType;
diff --git a/services/comps/network/Cargo.toml b/services/comps/network/Cargo.toml
--- a/services/comps/network/Cargo.toml
+++ b/services/comps/network/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "jinux-network"
+name = "aster-network"
version = "0.1.0"
edition = "2021"
diff --git a/services/comps/network/Cargo.toml b/services/comps/network/Cargo.toml
--- a/services/comps/network/Cargo.toml
+++ b/services/comps/network/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "jinux-network"
+name = "aster-network"
version = "0.1.0"
edition = "2021"
diff --git a/services/comps/network/Cargo.toml b/services/comps/network/Cargo.toml
--- a/services/comps/network/Cargo.toml
+++ b/services/comps/network/Cargo.toml
@@ -7,13 +7,13 @@ edition = "2021"
[dependencies]
component = { path = "../../libs/comp-sys/component" }
-jinux-frame = { path = "../../../framework/jinux-frame" }
-jinux-util = { path = "../../libs/jinux-util" }
-jinux-rights = { path = "../../libs/jinux-rights" }
+aster-frame = { path = "../../../framework/aster-frame" }
+aster-util = { path = "../../libs/aster-util" }
+aster-rights = { path = "../../libs/aster-rights" }
align_ext = { path = "../../../framework/libs/align_ext" }
int-to-c-enum = { path = "../../libs/int-to-c-enum" }
bytes = { version = "1.4.0", default-features = false }
-pod = { git = "https://github.com/jinzhao-dev/pod", rev = "d7dba56" }
+pod = { git = "https://github.com/asterinas/pod", rev = "d7dba56" }
bitflags = "1.3"
spin = "0.9.4"
ringbuf = { version = "0.3.2", default-features = false, features = ["alloc"] }
diff --git a/services/comps/network/Cargo.toml b/services/comps/network/Cargo.toml
--- a/services/comps/network/Cargo.toml
+++ b/services/comps/network/Cargo.toml
@@ -7,13 +7,13 @@ edition = "2021"
[dependencies]
component = { path = "../../libs/comp-sys/component" }
-jinux-frame = { path = "../../../framework/jinux-frame" }
-jinux-util = { path = "../../libs/jinux-util" }
-jinux-rights = { path = "../../libs/jinux-rights" }
+aster-frame = { path = "../../../framework/aster-frame" }
+aster-util = { path = "../../libs/aster-util" }
+aster-rights = { path = "../../libs/aster-rights" }
align_ext = { path = "../../../framework/libs/align_ext" }
int-to-c-enum = { path = "../../libs/int-to-c-enum" }
bytes = { version = "1.4.0", default-features = false }
-pod = { git = "https://github.com/jinzhao-dev/pod", rev = "d7dba56" }
+pod = { git = "https://github.com/asterinas/pod", rev = "d7dba56" }
bitflags = "1.3"
spin = "0.9.4"
ringbuf = { version = "0.3.2", default-features = false, features = ["alloc"] }
diff --git a/services/comps/network/src/lib.rs b/services/comps/network/src/lib.rs
--- a/services/comps/network/src/lib.rs
+++ b/services/comps/network/src/lib.rs
@@ -13,14 +13,14 @@ use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
+use aster_frame::sync::SpinLock;
+use aster_util::safe_ptr::Pod;
use buffer::RxBuffer;
use buffer::TxBuffer;
use component::init_component;
use component::ComponentInitError;
use core::any::Any;
use core::fmt::Debug;
-use jinux_frame::sync::SpinLock;
-use jinux_util::safe_ptr::Pod;
use smoltcp::phy;
use spin::Once;
diff --git a/services/comps/network/src/lib.rs b/services/comps/network/src/lib.rs
--- a/services/comps/network/src/lib.rs
+++ b/services/comps/network/src/lib.rs
@@ -13,14 +13,14 @@ use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
+use aster_frame::sync::SpinLock;
+use aster_util::safe_ptr::Pod;
use buffer::RxBuffer;
use buffer::TxBuffer;
use component::init_component;
use component::ComponentInitError;
use core::any::Any;
use core::fmt::Debug;
-use jinux_frame::sync::SpinLock;
-use jinux_util::safe_ptr::Pod;
use smoltcp::phy;
use spin::Once;
diff --git a/services/comps/time/Cargo.toml b/services/comps/time/Cargo.toml
--- a/services/comps/time/Cargo.toml
+++ b/services/comps/time/Cargo.toml
@@ -1,13 +1,13 @@
[package]
-name = "jinux-time"
+name = "aster-time"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
-jinux-frame = { path = "../../../framework/jinux-frame" }
-jinux-util = { path = "../../libs/jinux-util" }
+aster-frame = { path = "../../../framework/aster-frame" }
+aster-util = { path = "../../libs/aster-util" }
component = { path = "../../libs/comp-sys/component" }
log = "0.4"
spin = "0.9.4"
diff --git a/services/comps/time/Cargo.toml b/services/comps/time/Cargo.toml
--- a/services/comps/time/Cargo.toml
+++ b/services/comps/time/Cargo.toml
@@ -1,13 +1,13 @@
[package]
-name = "jinux-time"
+name = "aster-time"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
-jinux-frame = { path = "../../../framework/jinux-frame" }
-jinux-util = { path = "../../libs/jinux-util" }
+aster-frame = { path = "../../../framework/aster-frame" }
+aster-util = { path = "../../libs/aster-util" }
component = { path = "../../libs/comp-sys/component" }
log = "0.4"
spin = "0.9.4"
diff --git a/services/comps/time/src/clocksource.rs b/services/comps/time/src/clocksource.rs
--- a/services/comps/time/src/clocksource.rs
+++ b/services/comps/time/src/clocksource.rs
@@ -6,9 +6,9 @@
//! It can be integrated into larger systems to provide timing capabilities, or used standalone for time tracking and elapsed time measurements.
use alloc::sync::Arc;
+use aster_frame::sync::SpinLock;
+use aster_util::coeff::Coeff;
use core::{cmp::max, ops::Add, time::Duration};
-use jinux_frame::sync::SpinLock;
-use jinux_util::coeff::Coeff;
use crate::NANOS_PER_SECOND;
diff --git a/services/comps/time/src/clocksource.rs b/services/comps/time/src/clocksource.rs
--- a/services/comps/time/src/clocksource.rs
+++ b/services/comps/time/src/clocksource.rs
@@ -6,9 +6,9 @@
//! It can be integrated into larger systems to provide timing capabilities, or used standalone for time tracking and elapsed time measurements.
use alloc::sync::Arc;
+use aster_frame::sync::SpinLock;
+use aster_util::coeff::Coeff;
use core::{cmp::max, ops::Add, time::Duration};
-use jinux_frame::sync::SpinLock;
-use jinux_util::coeff::Coeff;
use crate::NANOS_PER_SECOND;
diff --git a/services/comps/time/src/lib.rs b/services/comps/time/src/lib.rs
--- a/services/comps/time/src/lib.rs
+++ b/services/comps/time/src/lib.rs
@@ -1,13 +1,13 @@
-//! The system time of jinux
+//! The system time of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
extern crate alloc;
use alloc::sync::Arc;
+use aster_frame::sync::Mutex;
use component::{init_component, ComponentInitError};
use core::{sync::atomic::Ordering::Relaxed, time::Duration};
-use jinux_frame::sync::Mutex;
use spin::Once;
use clocksource::ClockSource;
diff --git a/services/comps/time/src/lib.rs b/services/comps/time/src/lib.rs
--- a/services/comps/time/src/lib.rs
+++ b/services/comps/time/src/lib.rs
@@ -1,13 +1,13 @@
-//! The system time of jinux
+//! The system time of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
extern crate alloc;
use alloc::sync::Arc;
+use aster_frame::sync::Mutex;
use component::{init_component, ComponentInitError};
use core::{sync::atomic::Ordering::Relaxed, time::Duration};
-use jinux_frame::sync::Mutex;
use spin::Once;
use clocksource::ClockSource;
diff --git a/services/comps/time/src/rtc.rs b/services/comps/time/src/rtc.rs
--- a/services/comps/time/src/rtc.rs
+++ b/services/comps/time/src/rtc.rs
@@ -1,6 +1,6 @@
+use aster_frame::arch::x86::device::cmos::{get_century_register, CMOS_ADDRESS, CMOS_DATA};
use core::sync::atomic::AtomicU8;
use core::sync::atomic::Ordering::Relaxed;
-use jinux_frame::arch::x86::device::cmos::{get_century_register, CMOS_ADDRESS, CMOS_DATA};
pub(crate) static CENTURY_REGISTER: AtomicU8 = AtomicU8::new(0);
diff --git a/services/comps/time/src/rtc.rs b/services/comps/time/src/rtc.rs
--- a/services/comps/time/src/rtc.rs
+++ b/services/comps/time/src/rtc.rs
@@ -1,6 +1,6 @@
+use aster_frame::arch::x86::device::cmos::{get_century_register, CMOS_ADDRESS, CMOS_DATA};
use core::sync::atomic::AtomicU8;
use core::sync::atomic::Ordering::Relaxed;
-use jinux_frame::arch::x86::device::cmos::{get_century_register, CMOS_ADDRESS, CMOS_DATA};
pub(crate) static CENTURY_REGISTER: AtomicU8 = AtomicU8::new(0);
diff --git a/services/comps/time/src/tsc.rs b/services/comps/time/src/tsc.rs
--- a/services/comps/time/src/tsc.rs
+++ b/services/comps/time/src/tsc.rs
@@ -2,9 +2,9 @@
//!
//! Use `init` to initialize this module.
use alloc::sync::Arc;
+use aster_frame::arch::{read_tsc, x86::tsc_freq};
+use aster_frame::timer::Timer;
use core::time::Duration;
-use jinux_frame::arch::{read_tsc, x86::tsc_freq};
-use jinux_frame::timer::Timer;
use spin::Once;
use crate::clocksource::{ClockSource, Instant};
diff --git a/services/comps/time/src/tsc.rs b/services/comps/time/src/tsc.rs
--- a/services/comps/time/src/tsc.rs
+++ b/services/comps/time/src/tsc.rs
@@ -2,9 +2,9 @@
//!
//! Use `init` to initialize this module.
use alloc::sync::Arc;
+use aster_frame::arch::{read_tsc, x86::tsc_freq};
+use aster_frame::timer::Timer;
use core::time::Duration;
-use jinux_frame::arch::{read_tsc, x86::tsc_freq};
-use jinux_frame::timer::Timer;
use spin::Once;
use crate::clocksource::{ClockSource, Instant};
diff --git a/services/comps/virtio/Cargo.toml b/services/comps/virtio/Cargo.toml
--- a/services/comps/virtio/Cargo.toml
+++ b/services/comps/virtio/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "jinux-virtio"
+name = "aster-virtio"
version = "0.1.0"
edition = "2021"
diff --git a/services/comps/virtio/Cargo.toml b/services/comps/virtio/Cargo.toml
--- a/services/comps/virtio/Cargo.toml
+++ b/services/comps/virtio/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "jinux-virtio"
+name = "aster-virtio"
version = "0.1.0"
edition = "2021"
diff --git a/services/comps/virtio/Cargo.toml b/services/comps/virtio/Cargo.toml
--- a/services/comps/virtio/Cargo.toml
+++ b/services/comps/virtio/Cargo.toml
@@ -11,15 +11,15 @@ spin = "0.9.4"
virtio-input-decoder = "0.1.4"
bytes = { version = "1.4.0", default-features = false }
align_ext = { path = "../../../framework/libs/align_ext" }
-jinux-input = { path = "../input" }
-jinux-block = { path = "../block" }
-jinux-network = { path = "../network" }
-jinux-console = { path = "../console" }
-jinux-frame = { path = "../../../framework/jinux-frame" }
-jinux-util = { path = "../../libs/jinux-util" }
-jinux-rights = { path = "../../libs/jinux-rights" }
+aster-input = { path = "../input" }
+aster-block = { path = "../block" }
+aster-network = { path = "../network" }
+aster-console = { path = "../console" }
+aster-frame = { path = "../../../framework/aster-frame" }
+aster-util = { path = "../../libs/aster-util" }
+aster-rights = { path = "../../libs/aster-rights" }
typeflags-util = { path = "../../libs/typeflags-util" }
-pod = { git = "https://github.com/jinzhao-dev/pod", rev = "d7dba56" }
+pod = { git = "https://github.com/asterinas/pod", rev = "d7dba56" }
component = { path = "../../libs/comp-sys/component" }
log = "0.4"
bit_field = "0.10.1"
diff --git a/services/comps/virtio/Cargo.toml b/services/comps/virtio/Cargo.toml
--- a/services/comps/virtio/Cargo.toml
+++ b/services/comps/virtio/Cargo.toml
@@ -11,15 +11,15 @@ spin = "0.9.4"
virtio-input-decoder = "0.1.4"
bytes = { version = "1.4.0", default-features = false }
align_ext = { path = "../../../framework/libs/align_ext" }
-jinux-input = { path = "../input" }
-jinux-block = { path = "../block" }
-jinux-network = { path = "../network" }
-jinux-console = { path = "../console" }
-jinux-frame = { path = "../../../framework/jinux-frame" }
-jinux-util = { path = "../../libs/jinux-util" }
-jinux-rights = { path = "../../libs/jinux-rights" }
+aster-input = { path = "../input" }
+aster-block = { path = "../block" }
+aster-network = { path = "../network" }
+aster-console = { path = "../console" }
+aster-frame = { path = "../../../framework/aster-frame" }
+aster-util = { path = "../../libs/aster-util" }
+aster-rights = { path = "../../libs/aster-rights" }
typeflags-util = { path = "../../libs/typeflags-util" }
-pod = { git = "https://github.com/jinzhao-dev/pod", rev = "d7dba56" }
+pod = { git = "https://github.com/asterinas/pod", rev = "d7dba56" }
component = { path = "../../libs/comp-sys/component" }
log = "0.4"
bit_field = "0.10.1"
diff --git a/services/comps/virtio/src/device/block/device.rs b/services/comps/virtio/src/device/block/device.rs
--- a/services/comps/virtio/src/device/block/device.rs
+++ b/services/comps/virtio/src/device/block/device.rs
@@ -1,8 +1,8 @@
use core::hint::spin_loop;
use alloc::{boxed::Box, string::ToString, sync::Arc};
-use jinux_frame::{io_mem::IoMem, sync::SpinLock, trap::TrapFrame};
-use jinux_util::safe_ptr::SafePtr;
+use aster_frame::{io_mem::IoMem, sync::SpinLock, trap::TrapFrame};
+use aster_util::safe_ptr::SafePtr;
use log::info;
use pod::Pod;
diff --git a/services/comps/virtio/src/device/block/device.rs b/services/comps/virtio/src/device/block/device.rs
--- a/services/comps/virtio/src/device/block/device.rs
+++ b/services/comps/virtio/src/device/block/device.rs
@@ -1,8 +1,8 @@
use core::hint::spin_loop;
use alloc::{boxed::Box, string::ToString, sync::Arc};
-use jinux_frame::{io_mem::IoMem, sync::SpinLock, trap::TrapFrame};
-use jinux_util::safe_ptr::SafePtr;
+use aster_frame::{io_mem::IoMem, sync::SpinLock, trap::TrapFrame};
+use aster_util::safe_ptr::SafePtr;
use log::info;
use pod::Pod;
diff --git a/services/comps/virtio/src/device/block/device.rs b/services/comps/virtio/src/device/block/device.rs
--- a/services/comps/virtio/src/device/block/device.rs
+++ b/services/comps/virtio/src/device/block/device.rs
@@ -97,7 +97,7 @@ impl BlockDevice {
.unwrap();
fn handle_block_device(_: &TrapFrame) {
- jinux_block::get_device(super::DEVICE_NAME)
+ aster_block::get_device(super::DEVICE_NAME)
.unwrap()
.handle_irq();
}
diff --git a/services/comps/virtio/src/device/block/device.rs b/services/comps/virtio/src/device/block/device.rs
--- a/services/comps/virtio/src/device/block/device.rs
+++ b/services/comps/virtio/src/device/block/device.rs
@@ -97,7 +97,7 @@ impl BlockDevice {
.unwrap();
fn handle_block_device(_: &TrapFrame) {
- jinux_block::get_device(super::DEVICE_NAME)
+ aster_block::get_device(super::DEVICE_NAME)
.unwrap()
.handle_irq();
}
diff --git a/services/comps/virtio/src/device/block/device.rs b/services/comps/virtio/src/device/block/device.rs
--- a/services/comps/virtio/src/device/block/device.rs
+++ b/services/comps/virtio/src/device/block/device.rs
@@ -107,7 +107,7 @@ impl BlockDevice {
}
device.transport.finish_init();
- jinux_block::register_device(super::DEVICE_NAME.to_string(), Arc::new(device));
+ aster_block::register_device(super::DEVICE_NAME.to_string(), Arc::new(device));
Ok(())
}
diff --git a/services/comps/virtio/src/device/block/device.rs b/services/comps/virtio/src/device/block/device.rs
--- a/services/comps/virtio/src/device/block/device.rs
+++ b/services/comps/virtio/src/device/block/device.rs
@@ -107,7 +107,7 @@ impl BlockDevice {
}
device.transport.finish_init();
- jinux_block::register_device(super::DEVICE_NAME.to_string(), Arc::new(device));
+ aster_block::register_device(super::DEVICE_NAME.to_string(), Arc::new(device));
Ok(())
}
diff --git a/services/comps/virtio/src/device/block/device.rs b/services/comps/virtio/src/device/block/device.rs
--- a/services/comps/virtio/src/device/block/device.rs
+++ b/services/comps/virtio/src/device/block/device.rs
@@ -120,7 +120,7 @@ impl BlockDevice {
}
}
-impl jinux_block::BlockDevice for BlockDevice {
+impl aster_block::BlockDevice for BlockDevice {
fn read_block(&self, block_id: usize, buf: &mut [u8]) {
self.read(block_id, buf);
}
diff --git a/services/comps/virtio/src/device/block/device.rs b/services/comps/virtio/src/device/block/device.rs
--- a/services/comps/virtio/src/device/block/device.rs
+++ b/services/comps/virtio/src/device/block/device.rs
@@ -120,7 +120,7 @@ impl BlockDevice {
}
}
-impl jinux_block::BlockDevice for BlockDevice {
+impl aster_block::BlockDevice for BlockDevice {
fn read_block(&self, block_id: usize, buf: &mut [u8]) {
self.read(block_id, buf);
}
diff --git a/services/comps/virtio/src/device/block/mod.rs b/services/comps/virtio/src/device/block/mod.rs
--- a/services/comps/virtio/src/device/block/mod.rs
+++ b/services/comps/virtio/src/device/block/mod.rs
@@ -1,9 +1,9 @@
pub mod device;
+use aster_frame::io_mem::IoMem;
+use aster_util::safe_ptr::SafePtr;
use bitflags::bitflags;
use int_to_c_enum::TryFromInt;
-use jinux_frame::io_mem::IoMem;
-use jinux_util::safe_ptr::SafePtr;
use pod::Pod;
use crate::transport::VirtioTransport;
diff --git a/services/comps/virtio/src/device/block/mod.rs b/services/comps/virtio/src/device/block/mod.rs
--- a/services/comps/virtio/src/device/block/mod.rs
+++ b/services/comps/virtio/src/device/block/mod.rs
@@ -1,9 +1,9 @@
pub mod device;
+use aster_frame::io_mem::IoMem;
+use aster_util::safe_ptr::SafePtr;
use bitflags::bitflags;
use int_to_c_enum::TryFromInt;
-use jinux_frame::io_mem::IoMem;
-use jinux_util::safe_ptr::SafePtr;
use pod::Pod;
use crate::transport::VirtioTransport;
diff --git a/services/comps/virtio/src/device/console/config.rs b/services/comps/virtio/src/device/console/config.rs
--- a/services/comps/virtio/src/device/console/config.rs
+++ b/services/comps/virtio/src/device/console/config.rs
@@ -1,5 +1,5 @@
-use jinux_frame::io_mem::IoMem;
-use jinux_util::safe_ptr::SafePtr;
+use aster_frame::io_mem::IoMem;
+use aster_util::safe_ptr::SafePtr;
use pod::Pod;
use crate::transport::VirtioTransport;
diff --git a/services/comps/virtio/src/device/console/config.rs b/services/comps/virtio/src/device/console/config.rs
--- a/services/comps/virtio/src/device/console/config.rs
+++ b/services/comps/virtio/src/device/console/config.rs
@@ -1,5 +1,5 @@
-use jinux_frame::io_mem::IoMem;
-use jinux_util::safe_ptr::SafePtr;
+use aster_frame::io_mem::IoMem;
+use aster_util::safe_ptr::SafePtr;
use pod::Pod;
use crate::transport::VirtioTransport;
diff --git a/services/comps/virtio/src/device/console/device.rs b/services/comps/virtio/src/device/console/device.rs
--- a/services/comps/virtio/src/device/console/device.rs
+++ b/services/comps/virtio/src/device/console/device.rs
@@ -1,9 +1,9 @@
use core::hint::spin_loop;
use alloc::{boxed::Box, fmt::Debug, string::ToString, sync::Arc, vec::Vec};
-use jinux_console::{AnyConsoleDevice, ConsoleCallback};
-use jinux_frame::{config::PAGE_SIZE, io_mem::IoMem, sync::SpinLock, trap::TrapFrame};
-use jinux_util::safe_ptr::SafePtr;
+use aster_console::{AnyConsoleDevice, ConsoleCallback};
+use aster_frame::{config::PAGE_SIZE, io_mem::IoMem, sync::SpinLock, trap::TrapFrame};
+use aster_util::safe_ptr::SafePtr;
use log::debug;
use crate::{
diff --git a/services/comps/virtio/src/device/console/device.rs b/services/comps/virtio/src/device/console/device.rs
--- a/services/comps/virtio/src/device/console/device.rs
+++ b/services/comps/virtio/src/device/console/device.rs
@@ -1,9 +1,9 @@
use core::hint::spin_loop;
use alloc::{boxed::Box, fmt::Debug, string::ToString, sync::Arc, vec::Vec};
-use jinux_console::{AnyConsoleDevice, ConsoleCallback};
-use jinux_frame::{config::PAGE_SIZE, io_mem::IoMem, sync::SpinLock, trap::TrapFrame};
-use jinux_util::safe_ptr::SafePtr;
+use aster_console::{AnyConsoleDevice, ConsoleCallback};
+use aster_frame::{config::PAGE_SIZE, io_mem::IoMem, sync::SpinLock, trap::TrapFrame};
+use aster_util::safe_ptr::SafePtr;
use log::debug;
use crate::{
diff --git a/services/comps/virtio/src/device/console/device.rs b/services/comps/virtio/src/device/console/device.rs
--- a/services/comps/virtio/src/device/console/device.rs
+++ b/services/comps/virtio/src/device/console/device.rs
@@ -130,14 +130,14 @@ impl ConsoleDevice {
.unwrap();
device.transport.finish_init();
- jinux_console::register_device(DEVICE_NAME.to_string(), Arc::new(device));
+ aster_console::register_device(DEVICE_NAME.to_string(), Arc::new(device));
Ok(())
}
}
fn handle_console_input(_: &TrapFrame) {
- jinux_console::get_device(DEVICE_NAME).unwrap().handle_irq();
+ aster_console::get_device(DEVICE_NAME).unwrap().handle_irq();
}
fn config_space_change(_: &TrapFrame) {
diff --git a/services/comps/virtio/src/device/console/device.rs b/services/comps/virtio/src/device/console/device.rs
--- a/services/comps/virtio/src/device/console/device.rs
+++ b/services/comps/virtio/src/device/console/device.rs
@@ -130,14 +130,14 @@ impl ConsoleDevice {
.unwrap();
device.transport.finish_init();
- jinux_console::register_device(DEVICE_NAME.to_string(), Arc::new(device));
+ aster_console::register_device(DEVICE_NAME.to_string(), Arc::new(device));
Ok(())
}
}
fn handle_console_input(_: &TrapFrame) {
- jinux_console::get_device(DEVICE_NAME).unwrap().handle_irq();
+ aster_console::get_device(DEVICE_NAME).unwrap().handle_irq();
}
fn config_space_change(_: &TrapFrame) {
diff --git a/services/comps/virtio/src/device/input/device.rs b/services/comps/virtio/src/device/input/device.rs
--- a/services/comps/virtio/src/device/input/device.rs
+++ b/services/comps/virtio/src/device/input/device.rs
@@ -7,9 +7,9 @@ use alloc::{
sync::Arc,
vec::Vec,
};
+use aster_frame::{io_mem::IoMem, offset_of, sync::SpinLock, trap::TrapFrame};
+use aster_util::{field_ptr, safe_ptr::SafePtr};
use bitflags::bitflags;
-use jinux_frame::{io_mem::IoMem, offset_of, sync::SpinLock, trap::TrapFrame};
-use jinux_util::{field_ptr, safe_ptr::SafePtr};
use log::{debug, info};
use pod::Pod;
use virtio_input_decoder::{DecodeType, Decoder};
diff --git a/services/comps/virtio/src/device/input/device.rs b/services/comps/virtio/src/device/input/device.rs
--- a/services/comps/virtio/src/device/input/device.rs
+++ b/services/comps/virtio/src/device/input/device.rs
@@ -7,9 +7,9 @@ use alloc::{
sync::Arc,
vec::Vec,
};
+use aster_frame::{io_mem::IoMem, offset_of, sync::SpinLock, trap::TrapFrame};
+use aster_util::{field_ptr, safe_ptr::SafePtr};
use bitflags::bitflags;
-use jinux_frame::{io_mem::IoMem, offset_of, sync::SpinLock, trap::TrapFrame};
-use jinux_util::{field_ptr, safe_ptr::SafePtr};
use log::{debug, info};
use pod::Pod;
use virtio_input_decoder::{DecodeType, Decoder};
diff --git a/services/comps/virtio/src/device/input/device.rs b/services/comps/virtio/src/device/input/device.rs
--- a/services/comps/virtio/src/device/input/device.rs
+++ b/services/comps/virtio/src/device/input/device.rs
@@ -112,7 +112,7 @@ impl InputDevice {
fn handle_input(_: &TrapFrame) {
debug!("Handle Virtio input interrupt");
- let device = jinux_input::get_device(super::DEVICE_NAME).unwrap();
+ let device = aster_input::get_device(super::DEVICE_NAME).unwrap();
device.handle_irq().unwrap();
}
diff --git a/services/comps/virtio/src/device/input/device.rs b/services/comps/virtio/src/device/input/device.rs
--- a/services/comps/virtio/src/device/input/device.rs
+++ b/services/comps/virtio/src/device/input/device.rs
@@ -112,7 +112,7 @@ impl InputDevice {
fn handle_input(_: &TrapFrame) {
debug!("Handle Virtio input interrupt");
- let device = jinux_input::get_device(super::DEVICE_NAME).unwrap();
+ let device = aster_input::get_device(super::DEVICE_NAME).unwrap();
device.handle_irq().unwrap();
}
diff --git a/services/comps/virtio/src/device/input/device.rs b/services/comps/virtio/src/device/input/device.rs
--- a/services/comps/virtio/src/device/input/device.rs
+++ b/services/comps/virtio/src/device/input/device.rs
@@ -131,7 +131,7 @@ impl InputDevice {
device.transport.finish_init();
- jinux_input::register_device(super::DEVICE_NAME.to_string(), Arc::new(device));
+ aster_input::register_device(super::DEVICE_NAME.to_string(), Arc::new(device));
Ok(())
}
diff --git a/services/comps/virtio/src/device/input/device.rs b/services/comps/virtio/src/device/input/device.rs
--- a/services/comps/virtio/src/device/input/device.rs
+++ b/services/comps/virtio/src/device/input/device.rs
@@ -131,7 +131,7 @@ impl InputDevice {
device.transport.finish_init();
- jinux_input::register_device(super::DEVICE_NAME.to_string(), Arc::new(device));
+ aster_input::register_device(super::DEVICE_NAME.to_string(), Arc::new(device));
Ok(())
}
diff --git a/services/comps/virtio/src/device/input/device.rs b/services/comps/virtio/src/device/input/device.rs
--- a/services/comps/virtio/src/device/input/device.rs
+++ b/services/comps/virtio/src/device/input/device.rs
@@ -183,7 +183,7 @@ impl InputDevice {
}
}
-impl jinux_input::InputDevice for InputDevice {
+impl aster_input::InputDevice for InputDevice {
fn handle_irq(&self) -> Option<()> {
// one interrupt may contains serval input, so it should loop
loop {
diff --git a/services/comps/virtio/src/device/input/device.rs b/services/comps/virtio/src/device/input/device.rs
--- a/services/comps/virtio/src/device/input/device.rs
+++ b/services/comps/virtio/src/device/input/device.rs
@@ -183,7 +183,7 @@ impl InputDevice {
}
}
-impl jinux_input::InputDevice for InputDevice {
+impl aster_input::InputDevice for InputDevice {
fn handle_irq(&self) -> Option<()> {
// one interrupt may contains serval input, so it should loop
loop {
diff --git a/services/comps/virtio/src/device/input/mod.rs b/services/comps/virtio/src/device/input/mod.rs
--- a/services/comps/virtio/src/device/input/mod.rs
+++ b/services/comps/virtio/src/device/input/mod.rs
@@ -26,8 +26,8 @@
pub mod device;
use crate::transport::VirtioTransport;
-use jinux_frame::io_mem::IoMem;
-use jinux_util::safe_ptr::SafePtr;
+use aster_frame::io_mem::IoMem;
+use aster_util::safe_ptr::SafePtr;
use pod::Pod;
pub static DEVICE_NAME: &str = "Virtio-Input";
diff --git a/services/comps/virtio/src/device/input/mod.rs b/services/comps/virtio/src/device/input/mod.rs
--- a/services/comps/virtio/src/device/input/mod.rs
+++ b/services/comps/virtio/src/device/input/mod.rs
@@ -26,8 +26,8 @@
pub mod device;
use crate::transport::VirtioTransport;
-use jinux_frame::io_mem::IoMem;
-use jinux_util::safe_ptr::SafePtr;
+use aster_frame::io_mem::IoMem;
+use aster_util::safe_ptr::SafePtr;
use pod::Pod;
pub static DEVICE_NAME: &str = "Virtio-Input";
diff --git a/services/comps/virtio/src/device/network/config.rs b/services/comps/virtio/src/device/network/config.rs
--- a/services/comps/virtio/src/device/network/config.rs
+++ b/services/comps/virtio/src/device/network/config.rs
@@ -1,7 +1,7 @@
+use aster_frame::io_mem::IoMem;
+use aster_network::EthernetAddr;
+use aster_util::safe_ptr::SafePtr;
use bitflags::bitflags;
-use jinux_frame::io_mem::IoMem;
-use jinux_network::EthernetAddr;
-use jinux_util::safe_ptr::SafePtr;
use pod::Pod;
use crate::transport::VirtioTransport;
diff --git a/services/comps/virtio/src/device/network/config.rs b/services/comps/virtio/src/device/network/config.rs
--- a/services/comps/virtio/src/device/network/config.rs
+++ b/services/comps/virtio/src/device/network/config.rs
@@ -1,7 +1,7 @@
+use aster_frame::io_mem::IoMem;
+use aster_network::EthernetAddr;
+use aster_util::safe_ptr::SafePtr;
use bitflags::bitflags;
-use jinux_frame::io_mem::IoMem;
-use jinux_network::EthernetAddr;
-use jinux_util::safe_ptr::SafePtr;
use pod::Pod;
use crate::transport::VirtioTransport;
diff --git a/services/comps/virtio/src/device/network/device.rs b/services/comps/virtio/src/device/network/device.rs
--- a/services/comps/virtio/src/device/network/device.rs
+++ b/services/comps/virtio/src/device/network/device.rs
@@ -1,12 +1,12 @@
use core::{fmt::Debug, hint::spin_loop, mem::size_of};
use alloc::{boxed::Box, string::ToString, sync::Arc, vec::Vec};
-use jinux_frame::{offset_of, sync::SpinLock, trap::TrapFrame};
-use jinux_network::{
+use aster_frame::{offset_of, sync::SpinLock, trap::TrapFrame};
+use aster_network::{
buffer::{RxBuffer, TxBuffer},
AnyNetworkDevice, EthernetAddr, NetDeviceIrqHandler, VirtioNetError,
};
-use jinux_util::{field_ptr, slot_vec::SlotVec};
+use aster_util::{field_ptr, slot_vec::SlotVec};
use log::debug;
use pod::Pod;
use smoltcp::phy::{DeviceCapabilities, Medium};
diff --git a/services/comps/virtio/src/device/network/device.rs b/services/comps/virtio/src/device/network/device.rs
--- a/services/comps/virtio/src/device/network/device.rs
+++ b/services/comps/virtio/src/device/network/device.rs
@@ -1,12 +1,12 @@
use core::{fmt::Debug, hint::spin_loop, mem::size_of};
use alloc::{boxed::Box, string::ToString, sync::Arc, vec::Vec};
-use jinux_frame::{offset_of, sync::SpinLock, trap::TrapFrame};
-use jinux_network::{
+use aster_frame::{offset_of, sync::SpinLock, trap::TrapFrame};
+use aster_network::{
buffer::{RxBuffer, TxBuffer},
AnyNetworkDevice, EthernetAddr, NetDeviceIrqHandler, VirtioNetError,
};
-use jinux_util::{field_ptr, slot_vec::SlotVec};
+use aster_util::{field_ptr, slot_vec::SlotVec};
use log::debug;
use pod::Pod;
use smoltcp::phy::{DeviceCapabilities, Medium};
diff --git a/services/comps/virtio/src/device/network/device.rs b/services/comps/virtio/src/device/network/device.rs
--- a/services/comps/virtio/src/device/network/device.rs
+++ b/services/comps/virtio/src/device/network/device.rs
@@ -87,7 +87,7 @@ impl NetworkDevice {
/// Interrupt handler if network device receives some packet
fn handle_network_event(_: &TrapFrame) {
- jinux_network::handle_recv_irq(super::DEVICE_NAME);
+ aster_network::handle_recv_irq(super::DEVICE_NAME);
}
device
diff --git a/services/comps/virtio/src/device/network/device.rs b/services/comps/virtio/src/device/network/device.rs
--- a/services/comps/virtio/src/device/network/device.rs
+++ b/services/comps/virtio/src/device/network/device.rs
@@ -87,7 +87,7 @@ impl NetworkDevice {
/// Interrupt handler if network device receives some packet
fn handle_network_event(_: &TrapFrame) {
- jinux_network::handle_recv_irq(super::DEVICE_NAME);
+ aster_network::handle_recv_irq(super::DEVICE_NAME);
}
device
diff --git a/services/comps/virtio/src/device/network/device.rs b/services/comps/virtio/src/device/network/device.rs
--- a/services/comps/virtio/src/device/network/device.rs
+++ b/services/comps/virtio/src/device/network/device.rs
@@ -99,7 +99,7 @@ impl NetworkDevice {
.register_queue_callback(QUEUE_RECV, Box::new(handle_network_event), false)
.unwrap();
- jinux_network::register_device(
+ aster_network::register_device(
super::DEVICE_NAME.to_string(),
Arc::new(SpinLock::new(Box::new(device))),
);
diff --git a/services/comps/virtio/src/device/network/device.rs b/services/comps/virtio/src/device/network/device.rs
--- a/services/comps/virtio/src/device/network/device.rs
+++ b/services/comps/virtio/src/device/network/device.rs
@@ -99,7 +99,7 @@ impl NetworkDevice {
.register_queue_callback(QUEUE_RECV, Box::new(handle_network_event), false)
.unwrap();
- jinux_network::register_device(
+ aster_network::register_device(
super::DEVICE_NAME.to_string(),
Arc::new(SpinLock::new(Box::new(device))),
);
diff --git a/services/comps/virtio/src/lib.rs b/services/comps/virtio/src/lib.rs
--- a/services/comps/virtio/src/lib.rs
+++ b/services/comps/virtio/src/lib.rs
@@ -1,4 +1,4 @@
-//! The virtio of jinux
+//! The virtio of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
#![allow(dead_code)]
diff --git a/services/comps/virtio/src/lib.rs b/services/comps/virtio/src/lib.rs
--- a/services/comps/virtio/src/lib.rs
+++ b/services/comps/virtio/src/lib.rs
@@ -1,4 +1,4 @@
-//! The virtio of jinux
+//! The virtio of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
#![allow(dead_code)]
diff --git a/services/comps/virtio/src/queue.rs b/services/comps/virtio/src/queue.rs
--- a/services/comps/virtio/src/queue.rs
+++ b/services/comps/virtio/src/queue.rs
@@ -3,18 +3,18 @@
use crate::transport::VirtioTransport;
use alloc::vec::Vec;
+use aster_frame::{
+ io_mem::IoMem,
+ offset_of,
+ vm::{DmaCoherent, VmAllocOptions},
+};
+use aster_rights::{Dup, TRightSet, TRights, Write};
+use aster_util::{field_ptr, safe_ptr::SafePtr};
use bitflags::bitflags;
use core::{
mem::size_of,
sync::atomic::{fence, Ordering},
};
-use jinux_frame::{
- io_mem::IoMem,
- offset_of,
- vm::{DmaCoherent, VmAllocOptions},
-};
-use jinux_rights::{Dup, TRightSet, TRights, Write};
-use jinux_util::{field_ptr, safe_ptr::SafePtr};
use log::debug;
use pod::Pod;
diff --git a/services/comps/virtio/src/queue.rs b/services/comps/virtio/src/queue.rs
--- a/services/comps/virtio/src/queue.rs
+++ b/services/comps/virtio/src/queue.rs
@@ -3,18 +3,18 @@
use crate::transport::VirtioTransport;
use alloc::vec::Vec;
+use aster_frame::{
+ io_mem::IoMem,
+ offset_of,
+ vm::{DmaCoherent, VmAllocOptions},
+};
+use aster_rights::{Dup, TRightSet, TRights, Write};
+use aster_util::{field_ptr, safe_ptr::SafePtr};
use bitflags::bitflags;
use core::{
mem::size_of,
sync::atomic::{fence, Ordering},
};
-use jinux_frame::{
- io_mem::IoMem,
- offset_of,
- vm::{DmaCoherent, VmAllocOptions},
-};
-use jinux_rights::{Dup, TRightSet, TRights, Write};
-use jinux_util::{field_ptr, safe_ptr::SafePtr};
use log::debug;
use pod::Pod;
diff --git a/services/comps/virtio/src/queue.rs b/services/comps/virtio/src/queue.rs
--- a/services/comps/virtio/src/queue.rs
+++ b/services/comps/virtio/src/queue.rs
@@ -372,7 +372,7 @@ fn set_buf(ptr: &SafePtr<Descriptor, &DmaCoherent, TRightSet<TRights![Dup, Write
// FIXME: use `DmaSteam` for buf. Now because the upper device driver lacks the
// ability to safely construct DmaStream from slice, slice is still used here.
let va = buf.as_ptr() as usize;
- let pa = jinux_frame::vm::vaddr_to_paddr(va).unwrap();
+ let pa = aster_frame::vm::vaddr_to_paddr(va).unwrap();
field_ptr!(ptr, Descriptor, addr)
.write(&(pa as u64))
.unwrap();
diff --git a/services/comps/virtio/src/queue.rs b/services/comps/virtio/src/queue.rs
--- a/services/comps/virtio/src/queue.rs
+++ b/services/comps/virtio/src/queue.rs
@@ -372,7 +372,7 @@ fn set_buf(ptr: &SafePtr<Descriptor, &DmaCoherent, TRightSet<TRights![Dup, Write
// FIXME: use `DmaSteam` for buf. Now because the upper device driver lacks the
// ability to safely construct DmaStream from slice, slice is still used here.
let va = buf.as_ptr() as usize;
- let pa = jinux_frame::vm::vaddr_to_paddr(va).unwrap();
+ let pa = aster_frame::vm::vaddr_to_paddr(va).unwrap();
field_ptr!(ptr, Descriptor, addr)
.write(&(pa as u64))
.unwrap();
diff --git a/services/comps/virtio/src/transport/mmio/device.rs b/services/comps/virtio/src/transport/mmio/device.rs
--- a/services/comps/virtio/src/transport/mmio/device.rs
+++ b/services/comps/virtio/src/transport/mmio/device.rs
@@ -1,6 +1,5 @@
use alloc::{boxed::Box, sync::Arc};
-use core::mem::size_of;
-use jinux_frame::{
+use aster_frame::{
bus::mmio::{
bus::MmioDevice,
device::{MmioCommonDevice, VirtioMmioVersion},
diff --git a/services/comps/virtio/src/transport/mmio/device.rs b/services/comps/virtio/src/transport/mmio/device.rs
--- a/services/comps/virtio/src/transport/mmio/device.rs
+++ b/services/comps/virtio/src/transport/mmio/device.rs
@@ -1,6 +1,5 @@
use alloc::{boxed::Box, sync::Arc};
-use core::mem::size_of;
-use jinux_frame::{
+use aster_frame::{
bus::mmio::{
bus::MmioDevice,
device::{MmioCommonDevice, VirtioMmioVersion},
diff --git a/services/comps/virtio/src/transport/mmio/device.rs b/services/comps/virtio/src/transport/mmio/device.rs
--- a/services/comps/virtio/src/transport/mmio/device.rs
+++ b/services/comps/virtio/src/transport/mmio/device.rs
@@ -12,8 +11,9 @@ use jinux_frame::{
trap::IrqCallbackFunction,
vm::DmaCoherent,
};
-use jinux_rights::{ReadOp, WriteOp};
-use jinux_util::{field_ptr, safe_ptr::SafePtr};
+use aster_rights::{ReadOp, WriteOp};
+use aster_util::{field_ptr, safe_ptr::SafePtr};
+use core::mem::size_of;
use log::warn;
use crate::{
diff --git a/services/comps/virtio/src/transport/mmio/device.rs b/services/comps/virtio/src/transport/mmio/device.rs
--- a/services/comps/virtio/src/transport/mmio/device.rs
+++ b/services/comps/virtio/src/transport/mmio/device.rs
@@ -12,8 +11,9 @@ use jinux_frame::{
trap::IrqCallbackFunction,
vm::DmaCoherent,
};
-use jinux_rights::{ReadOp, WriteOp};
-use jinux_util::{field_ptr, safe_ptr::SafePtr};
+use aster_rights::{ReadOp, WriteOp};
+use aster_util::{field_ptr, safe_ptr::SafePtr};
+use core::mem::size_of;
use log::warn;
use crate::{
diff --git a/services/comps/virtio/src/transport/mmio/device.rs b/services/comps/virtio/src/transport/mmio/device.rs
--- a/services/comps/virtio/src/transport/mmio/device.rs
+++ b/services/comps/virtio/src/transport/mmio/device.rs
@@ -33,7 +33,7 @@ pub struct VirtioMmioDevice {
pub struct VirtioMmioTransport {
layout: SafePtr<VirtioMmioLayout, IoMem>,
device: Arc<VirtioMmioDevice>,
- common_device: jinux_frame::bus::mmio::device::MmioCommonDevice,
+ common_device: aster_frame::bus::mmio::device::MmioCommonDevice,
multiplex: Arc<RwLock<MultiplexIrq>>,
}
diff --git a/services/comps/virtio/src/transport/mmio/device.rs b/services/comps/virtio/src/transport/mmio/device.rs
--- a/services/comps/virtio/src/transport/mmio/device.rs
+++ b/services/comps/virtio/src/transport/mmio/device.rs
@@ -33,7 +33,7 @@ pub struct VirtioMmioDevice {
pub struct VirtioMmioTransport {
layout: SafePtr<VirtioMmioLayout, IoMem>,
device: Arc<VirtioMmioDevice>,
- common_device: jinux_frame::bus::mmio::device::MmioCommonDevice,
+ common_device: aster_frame::bus::mmio::device::MmioCommonDevice,
multiplex: Arc<RwLock<MultiplexIrq>>,
}
diff --git a/services/comps/virtio/src/transport/mmio/driver.rs b/services/comps/virtio/src/transport/mmio/driver.rs
--- a/services/comps/virtio/src/transport/mmio/driver.rs
+++ b/services/comps/virtio/src/transport/mmio/driver.rs
@@ -1,5 +1,5 @@
use alloc::{sync::Arc, vec::Vec};
-use jinux_frame::{
+use aster_frame::{
bus::{
mmio::{
bus::{MmioDevice, MmioDriver},
diff --git a/services/comps/virtio/src/transport/mmio/driver.rs b/services/comps/virtio/src/transport/mmio/driver.rs
--- a/services/comps/virtio/src/transport/mmio/driver.rs
+++ b/services/comps/virtio/src/transport/mmio/driver.rs
@@ -1,5 +1,5 @@
use alloc::{sync::Arc, vec::Vec};
-use jinux_frame::{
+use aster_frame::{
bus::{
mmio::{
bus::{MmioDevice, MmioDriver},
diff --git a/services/comps/virtio/src/transport/mmio/mod.rs b/services/comps/virtio/src/transport/mmio/mod.rs
--- a/services/comps/virtio/src/transport/mmio/mod.rs
+++ b/services/comps/virtio/src/transport/mmio/mod.rs
@@ -1,5 +1,5 @@
use alloc::sync::Arc;
-use jinux_frame::bus::mmio::MMIO_BUS;
+use aster_frame::bus::mmio::MMIO_BUS;
use spin::Once;
use self::driver::VirtioMmioDriver;
diff --git a/services/comps/virtio/src/transport/mmio/mod.rs b/services/comps/virtio/src/transport/mmio/mod.rs
--- a/services/comps/virtio/src/transport/mmio/mod.rs
+++ b/services/comps/virtio/src/transport/mmio/mod.rs
@@ -1,5 +1,5 @@
use alloc::sync::Arc;
-use jinux_frame::bus::mmio::MMIO_BUS;
+use aster_frame::bus::mmio::MMIO_BUS;
use spin::Once;
use self::driver::VirtioMmioDriver;
diff --git a/services/comps/virtio/src/transport/mmio/multiplex.rs b/services/comps/virtio/src/transport/mmio/multiplex.rs
--- a/services/comps/virtio/src/transport/mmio/multiplex.rs
+++ b/services/comps/virtio/src/transport/mmio/multiplex.rs
@@ -1,13 +1,13 @@
use core::fmt::Debug;
use alloc::{boxed::Box, sync::Arc, vec::Vec};
-use jinux_frame::{
+use aster_frame::{
io_mem::IoMem,
sync::RwLock,
trap::{IrqCallbackFunction, IrqLine, TrapFrame},
};
-use jinux_rights::{ReadOp, TRightSet, WriteOp};
-use jinux_util::safe_ptr::SafePtr;
+use aster_rights::{ReadOp, TRightSet, WriteOp};
+use aster_util::safe_ptr::SafePtr;
/// Multiplexing Irqs. The two interrupt types (configuration space change and queue interrupt)
/// of the virtio-mmio device share the same IRQ, so `MultiplexIrq` are used to distinguish them.
diff --git a/services/comps/virtio/src/transport/mmio/multiplex.rs b/services/comps/virtio/src/transport/mmio/multiplex.rs
--- a/services/comps/virtio/src/transport/mmio/multiplex.rs
+++ b/services/comps/virtio/src/transport/mmio/multiplex.rs
@@ -1,13 +1,13 @@
use core::fmt::Debug;
use alloc::{boxed::Box, sync::Arc, vec::Vec};
-use jinux_frame::{
+use aster_frame::{
io_mem::IoMem,
sync::RwLock,
trap::{IrqCallbackFunction, IrqLine, TrapFrame},
};
-use jinux_rights::{ReadOp, TRightSet, WriteOp};
-use jinux_util::safe_ptr::SafePtr;
+use aster_rights::{ReadOp, TRightSet, WriteOp};
+use aster_util::safe_ptr::SafePtr;
/// Multiplexing Irqs. The two interrupt types (configuration space change and queue interrupt)
/// of the virtio-mmio device share the same IRQ, so `MultiplexIrq` are used to distinguish them.
diff --git a/services/comps/virtio/src/transport/mod.rs b/services/comps/virtio/src/transport/mod.rs
--- a/services/comps/virtio/src/transport/mod.rs
+++ b/services/comps/virtio/src/transport/mod.rs
@@ -1,8 +1,8 @@
use core::fmt::Debug;
use alloc::boxed::Box;
-use jinux_frame::{io_mem::IoMem, trap::IrqCallbackFunction, vm::DmaCoherent};
-use jinux_util::safe_ptr::SafePtr;
+use aster_frame::{io_mem::IoMem, trap::IrqCallbackFunction, vm::DmaCoherent};
+use aster_util::safe_ptr::SafePtr;
use crate::{
queue::{AvailRing, Descriptor, UsedRing},
diff --git a/services/comps/virtio/src/transport/mod.rs b/services/comps/virtio/src/transport/mod.rs
--- a/services/comps/virtio/src/transport/mod.rs
+++ b/services/comps/virtio/src/transport/mod.rs
@@ -1,8 +1,8 @@
use core::fmt::Debug;
use alloc::boxed::Box;
-use jinux_frame::{io_mem::IoMem, trap::IrqCallbackFunction, vm::DmaCoherent};
-use jinux_util::safe_ptr::SafePtr;
+use aster_frame::{io_mem::IoMem, trap::IrqCallbackFunction, vm::DmaCoherent};
+use aster_util::safe_ptr::SafePtr;
use crate::{
queue::{AvailRing, Descriptor, UsedRing},
diff --git a/services/comps/virtio/src/transport/pci/capability.rs b/services/comps/virtio/src/transport/pci/capability.rs
--- a/services/comps/virtio/src/transport/pci/capability.rs
+++ b/services/comps/virtio/src/transport/pci/capability.rs
@@ -1,5 +1,5 @@
use alloc::sync::Arc;
-use jinux_frame::bus::pci::{
+use aster_frame::bus::pci::{
capability::vendor::CapabilityVndrData,
cfg_space::{Bar, IoBar, MemoryBar},
common_device::BarManager,
diff --git a/services/comps/virtio/src/transport/pci/capability.rs b/services/comps/virtio/src/transport/pci/capability.rs
--- a/services/comps/virtio/src/transport/pci/capability.rs
+++ b/services/comps/virtio/src/transport/pci/capability.rs
@@ -1,5 +1,5 @@
use alloc::sync::Arc;
-use jinux_frame::bus::pci::{
+use aster_frame::bus::pci::{
capability::vendor::CapabilityVndrData,
cfg_space::{Bar, IoBar, MemoryBar},
common_device::BarManager,
diff --git a/services/comps/virtio/src/transport/pci/common_cfg.rs b/services/comps/virtio/src/transport/pci/common_cfg.rs
--- a/services/comps/virtio/src/transport/pci/common_cfg.rs
+++ b/services/comps/virtio/src/transport/pci/common_cfg.rs
@@ -1,5 +1,5 @@
-use jinux_frame::io_mem::IoMem;
-use jinux_util::safe_ptr::SafePtr;
+use aster_frame::io_mem::IoMem;
+use aster_util::safe_ptr::SafePtr;
use pod::Pod;
use crate::transport::pci::capability::VirtioPciCpabilityType;
diff --git a/services/comps/virtio/src/transport/pci/common_cfg.rs b/services/comps/virtio/src/transport/pci/common_cfg.rs
--- a/services/comps/virtio/src/transport/pci/common_cfg.rs
+++ b/services/comps/virtio/src/transport/pci/common_cfg.rs
@@ -1,5 +1,5 @@
-use jinux_frame::io_mem::IoMem;
-use jinux_util::safe_ptr::SafePtr;
+use aster_frame::io_mem::IoMem;
+use aster_util::safe_ptr::SafePtr;
use pod::Pod;
use crate::transport::pci::capability::VirtioPciCpabilityType;
diff --git a/services/comps/virtio/src/transport/pci/device.rs b/services/comps/virtio/src/transport/pci/device.rs
--- a/services/comps/virtio/src/transport/pci/device.rs
+++ b/services/comps/virtio/src/transport/pci/device.rs
@@ -1,4 +1,4 @@
-use jinux_frame::{
+use aster_frame::{
bus::{
pci::{
bus::PciDevice, capability::CapabilityData, common_device::PciCommonDevice, PciDeviceId,
diff --git a/services/comps/virtio/src/transport/pci/device.rs b/services/comps/virtio/src/transport/pci/device.rs
--- a/services/comps/virtio/src/transport/pci/device.rs
+++ b/services/comps/virtio/src/transport/pci/device.rs
@@ -1,4 +1,4 @@
-use jinux_frame::{
+use aster_frame::{
bus::{
pci::{
bus::PciDevice, capability::CapabilityData, common_device::PciCommonDevice, PciDeviceId,
diff --git a/services/comps/virtio/src/transport/pci/device.rs b/services/comps/virtio/src/transport/pci/device.rs
--- a/services/comps/virtio/src/transport/pci/device.rs
+++ b/services/comps/virtio/src/transport/pci/device.rs
@@ -12,8 +12,8 @@ use jinux_frame::{
};
use alloc::{boxed::Box, sync::Arc};
+use aster_util::{field_ptr, safe_ptr::SafePtr};
use core::fmt::Debug;
-use jinux_util::{field_ptr, safe_ptr::SafePtr};
use log::{info, warn};
use super::{common_cfg::VirtioPciCommonCfg, msix::VirtioMsixManager};
diff --git a/services/comps/virtio/src/transport/pci/device.rs b/services/comps/virtio/src/transport/pci/device.rs
--- a/services/comps/virtio/src/transport/pci/device.rs
+++ b/services/comps/virtio/src/transport/pci/device.rs
@@ -12,8 +12,8 @@ use jinux_frame::{
};
use alloc::{boxed::Box, sync::Arc};
+use aster_util::{field_ptr, safe_ptr::SafePtr};
use core::fmt::Debug;
-use jinux_util::{field_ptr, safe_ptr::SafePtr};
use log::{info, warn};
use super::{common_cfg::VirtioPciCommonCfg, msix::VirtioMsixManager};
diff --git a/services/comps/virtio/src/transport/pci/driver.rs b/services/comps/virtio/src/transport/pci/driver.rs
--- a/services/comps/virtio/src/transport/pci/driver.rs
+++ b/services/comps/virtio/src/transport/pci/driver.rs
@@ -1,5 +1,5 @@
use alloc::{sync::Arc, vec::Vec};
-use jinux_frame::{
+use aster_frame::{
bus::{
pci::{
bus::{PciDevice, PciDriver},
diff --git a/services/comps/virtio/src/transport/pci/driver.rs b/services/comps/virtio/src/transport/pci/driver.rs
--- a/services/comps/virtio/src/transport/pci/driver.rs
+++ b/services/comps/virtio/src/transport/pci/driver.rs
@@ -1,5 +1,5 @@
use alloc::{sync::Arc, vec::Vec};
-use jinux_frame::{
+use aster_frame::{
bus::{
pci::{
bus::{PciDevice, PciDriver},
diff --git a/services/comps/virtio/src/transport/pci/mod.rs b/services/comps/virtio/src/transport/pci/mod.rs
--- a/services/comps/virtio/src/transport/pci/mod.rs
+++ b/services/comps/virtio/src/transport/pci/mod.rs
@@ -5,7 +5,7 @@ pub mod driver;
pub(super) mod msix;
use alloc::sync::Arc;
-use jinux_frame::bus::pci::PCI_BUS;
+use aster_frame::bus::pci::PCI_BUS;
use spin::Once;
use self::driver::VirtioPciDriver;
diff --git a/services/comps/virtio/src/transport/pci/mod.rs b/services/comps/virtio/src/transport/pci/mod.rs
--- a/services/comps/virtio/src/transport/pci/mod.rs
+++ b/services/comps/virtio/src/transport/pci/mod.rs
@@ -5,7 +5,7 @@ pub mod driver;
pub(super) mod msix;
use alloc::sync::Arc;
-use jinux_frame::bus::pci::PCI_BUS;
+use aster_frame::bus::pci::PCI_BUS;
use spin::Once;
use self::driver::VirtioPciDriver;
diff --git a/services/comps/virtio/src/transport/pci/msix.rs b/services/comps/virtio/src/transport/pci/msix.rs
--- a/services/comps/virtio/src/transport/pci/msix.rs
+++ b/services/comps/virtio/src/transport/pci/msix.rs
@@ -1,5 +1,5 @@
use alloc::vec::Vec;
-use jinux_frame::{bus::pci::capability::msix::CapabilityMsixData, trap::IrqLine};
+use aster_frame::{bus::pci::capability::msix::CapabilityMsixData, trap::IrqLine};
pub struct VirtioMsixManager {
config_msix_vector: u16,
diff --git a/services/comps/virtio/src/transport/pci/msix.rs b/services/comps/virtio/src/transport/pci/msix.rs
--- a/services/comps/virtio/src/transport/pci/msix.rs
+++ b/services/comps/virtio/src/transport/pci/msix.rs
@@ -1,5 +1,5 @@
use alloc::vec::Vec;
-use jinux_frame::{bus::pci::capability::msix::CapabilityMsixData, trap::IrqLine};
+use aster_frame::{bus::pci::capability::msix::CapabilityMsixData, trap::IrqLine};
pub struct VirtioMsixManager {
config_msix_vector: u16,
diff --git a/services/comps/virtio/src/transport/pci/msix.rs b/services/comps/virtio/src/transport/pci/msix.rs
--- a/services/comps/virtio/src/transport/pci/msix.rs
+++ b/services/comps/virtio/src/transport/pci/msix.rs
@@ -17,7 +17,7 @@ impl VirtioMsixManager {
pub fn new(mut msix: CapabilityMsixData) -> Self {
let mut msix_vector_list: Vec<u16> = (0..msix.table_size()).collect();
for i in msix_vector_list.iter() {
- let irq = jinux_frame::trap::IrqLine::alloc().unwrap();
+ let irq = aster_frame::trap::IrqLine::alloc().unwrap();
msix.set_interrupt_vector(irq, *i);
}
let config_msix_vector = msix_vector_list.pop().unwrap();
diff --git a/services/comps/virtio/src/transport/pci/msix.rs b/services/comps/virtio/src/transport/pci/msix.rs
--- a/services/comps/virtio/src/transport/pci/msix.rs
+++ b/services/comps/virtio/src/transport/pci/msix.rs
@@ -17,7 +17,7 @@ impl VirtioMsixManager {
pub fn new(mut msix: CapabilityMsixData) -> Self {
let mut msix_vector_list: Vec<u16> = (0..msix.table_size()).collect();
for i in msix_vector_list.iter() {
- let irq = jinux_frame::trap::IrqLine::alloc().unwrap();
+ let irq = aster_frame::trap::IrqLine::alloc().unwrap();
msix.set_interrupt_vector(irq, *i);
}
let config_msix_vector = msix_vector_list.pop().unwrap();
diff --git a/services/libs/jinux-rights-proc/Cargo.toml b/services/libs/aster-rights-proc/Cargo.toml
--- a/services/libs/jinux-rights-proc/Cargo.toml
+++ b/services/libs/aster-rights-proc/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "jinux-rights-proc"
+name = "aster-rights-proc"
version = "0.1.0"
edition = "2021"
diff --git a/services/libs/jinux-rights-proc/Cargo.toml b/services/libs/aster-rights-proc/Cargo.toml
--- a/services/libs/jinux-rights-proc/Cargo.toml
+++ b/services/libs/aster-rights-proc/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "jinux-rights-proc"
+name = "aster-rights-proc"
version = "0.1.0"
edition = "2021"
diff --git a/services/libs/jinux-rights-proc/src/lib.rs b/services/libs/aster-rights-proc/src/lib.rs
--- a/services/libs/jinux-rights-proc/src/lib.rs
+++ b/services/libs/aster-rights-proc/src/lib.rs
@@ -1,4 +1,4 @@
-//!This crate defines the require procedural macros to implement capability for jinux.
+//!This crate defines the require procedural macros to implement capability for Asterinas.
//! When use this crate, typeflags and typeflags-util should also be added as dependency.
//!
//! The require macro are used to ensure that an object has the enough capability to call the function.
diff --git a/services/libs/jinux-rights-proc/src/lib.rs b/services/libs/aster-rights-proc/src/lib.rs
--- a/services/libs/jinux-rights-proc/src/lib.rs
+++ b/services/libs/aster-rights-proc/src/lib.rs
@@ -1,4 +1,4 @@
-//!This crate defines the require procedural macros to implement capability for jinux.
+//!This crate defines the require procedural macros to implement capability for Asterinas.
//! When use this crate, typeflags and typeflags-util should also be added as dependency.
//!
//! The require macro are used to ensure that an object has the enough capability to call the function.
diff --git a/services/libs/jinux-rights/Cargo.toml b/services/libs/aster-rights/Cargo.toml
--- a/services/libs/jinux-rights/Cargo.toml
+++ b/services/libs/aster-rights/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "jinux-rights"
+name = "aster-rights"
version = "0.1.0"
edition = "2021"
diff --git a/services/libs/jinux-rights/Cargo.toml b/services/libs/aster-rights/Cargo.toml
--- a/services/libs/jinux-rights/Cargo.toml
+++ b/services/libs/aster-rights/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "jinux-rights"
+name = "aster-rights"
version = "0.1.0"
edition = "2021"
diff --git a/services/libs/jinux-rights/Cargo.toml b/services/libs/aster-rights/Cargo.toml
--- a/services/libs/jinux-rights/Cargo.toml
+++ b/services/libs/aster-rights/Cargo.toml
@@ -9,6 +9,6 @@ edition = "2021"
typeflags = { path = "../typeflags" }
typeflags-util = { path = "../typeflags-util" }
bitflags = "1.3"
-jinux-rights-proc = { path = "../jinux-rights-proc" }
+aster-rights-proc = { path = "../aster-rights-proc" }
[features]
diff --git a/services/libs/jinux-rights/Cargo.toml b/services/libs/aster-rights/Cargo.toml
--- a/services/libs/jinux-rights/Cargo.toml
+++ b/services/libs/aster-rights/Cargo.toml
@@ -9,6 +9,6 @@ edition = "2021"
typeflags = { path = "../typeflags" }
typeflags-util = { path = "../typeflags-util" }
bitflags = "1.3"
-jinux-rights-proc = { path = "../jinux-rights-proc" }
+aster-rights-proc = { path = "../aster-rights-proc" }
[features]
diff --git a/services/libs/jinux-rights/src/lib.rs b/services/libs/aster-rights/src/lib.rs
--- a/services/libs/jinux-rights/src/lib.rs
+++ b/services/libs/aster-rights/src/lib.rs
@@ -58,7 +58,7 @@ pub type FullOp = TRights![Read, Write, Dup];
/// Example:
///
/// ```rust
-/// use jinux_rights::{Rights, TRights, TRightSet};
+/// use aster_rights::{Rights, TRights, TRightSet};
///
/// pub struct Vmo<R=Rights>(R);
///
diff --git a/services/libs/jinux-rights/src/lib.rs b/services/libs/aster-rights/src/lib.rs
--- a/services/libs/jinux-rights/src/lib.rs
+++ b/services/libs/aster-rights/src/lib.rs
@@ -58,7 +58,7 @@ pub type FullOp = TRights![Read, Write, Dup];
/// Example:
///
/// ```rust
-/// use jinux_rights::{Rights, TRights, TRightSet};
+/// use aster_rights::{Rights, TRights, TRightSet};
///
/// pub struct Vmo<R=Rights>(R);
///
diff --git a/services/libs/jinux-std/Cargo.toml b/services/libs/aster-std/Cargo.toml
--- a/services/libs/jinux-std/Cargo.toml
+++ b/services/libs/aster-std/Cargo.toml
@@ -1,26 +1,26 @@
[package]
-name = "jinux-std"
+name = "aster-std"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
-jinux-frame = { path = "../../../framework/jinux-frame" }
+aster-frame = { path = "../../../framework/aster-frame" }
align_ext = { path = "../../../framework/libs/align_ext" }
-pod = { git = "https://github.com/jinzhao-dev/pod", rev = "d7dba56" }
-jinux-input = { path = "../../comps/input" }
-jinux-block = { path = "../../comps/block" }
-jinux-network = { path = "../../comps/network" }
-jinux-console = { path = "../../comps/console" }
-jinux-time = { path = "../../comps/time" }
-jinux-virtio = { path = "../../comps/virtio" }
-jinux-rights = { path = "../jinux-rights" }
+pod = { git = "https://github.com/asterinas/pod", rev = "d7dba56" }
+aster-input = { path = "../../comps/input" }
+aster-block = { path = "../../comps/block" }
+aster-network = { path = "../../comps/network" }
+aster-console = { path = "../../comps/console" }
+aster-time = { path = "../../comps/time" }
+aster-virtio = { path = "../../comps/virtio" }
+aster-rights = { path = "../aster-rights" }
controlled = { path = "../../libs/comp-sys/controlled" }
typeflags = { path = "../typeflags" }
typeflags-util = { path = "../typeflags-util" }
-jinux-rights-proc = { path = "../jinux-rights-proc" }
-jinux-util = { path = "../jinux-util" }
+aster-rights-proc = { path = "../aster-rights-proc" }
+aster-util = { path = "../aster-util" }
int-to-c-enum = { path = "../../libs/int-to-c-enum" }
cpio-decoder = { path = "../cpio-decoder" }
virtio-input-decoder = "0.1.4"
diff --git a/services/libs/jinux-std/Cargo.toml b/services/libs/aster-std/Cargo.toml
--- a/services/libs/jinux-std/Cargo.toml
+++ b/services/libs/aster-std/Cargo.toml
@@ -1,26 +1,26 @@
[package]
-name = "jinux-std"
+name = "aster-std"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
-jinux-frame = { path = "../../../framework/jinux-frame" }
+aster-frame = { path = "../../../framework/aster-frame" }
align_ext = { path = "../../../framework/libs/align_ext" }
-pod = { git = "https://github.com/jinzhao-dev/pod", rev = "d7dba56" }
-jinux-input = { path = "../../comps/input" }
-jinux-block = { path = "../../comps/block" }
-jinux-network = { path = "../../comps/network" }
-jinux-console = { path = "../../comps/console" }
-jinux-time = { path = "../../comps/time" }
-jinux-virtio = { path = "../../comps/virtio" }
-jinux-rights = { path = "../jinux-rights" }
+pod = { git = "https://github.com/asterinas/pod", rev = "d7dba56" }
+aster-input = { path = "../../comps/input" }
+aster-block = { path = "../../comps/block" }
+aster-network = { path = "../../comps/network" }
+aster-console = { path = "../../comps/console" }
+aster-time = { path = "../../comps/time" }
+aster-virtio = { path = "../../comps/virtio" }
+aster-rights = { path = "../aster-rights" }
controlled = { path = "../../libs/comp-sys/controlled" }
typeflags = { path = "../typeflags" }
typeflags-util = { path = "../typeflags-util" }
-jinux-rights-proc = { path = "../jinux-rights-proc" }
-jinux-util = { path = "../jinux-util" }
+aster-rights-proc = { path = "../aster-rights-proc" }
+aster-util = { path = "../aster-util" }
int-to-c-enum = { path = "../../libs/int-to-c-enum" }
cpio-decoder = { path = "../cpio-decoder" }
virtio-input-decoder = "0.1.4"
diff --git a/services/libs/jinux-std/Cargo.toml b/services/libs/aster-std/Cargo.toml
--- a/services/libs/jinux-std/Cargo.toml
+++ b/services/libs/aster-std/Cargo.toml
@@ -52,7 +52,7 @@ bitflags = "1.3"
ringbuf = { version = "0.3.2", default-features = false, features = ["alloc"] }
keyable-arc = { path = "../keyable-arc" }
# unzip initramfs
-libflate = { git = "https://github.com/jinzhao-dev/libflate", rev = "b781da6", features = [
+libflate = { git = "https://github.com/asterinas/libflate", rev = "b781da6", features = [
"no_std",
] }
core2 = { version = "0.4", default_features = false, features = ["alloc"] }
diff --git a/services/libs/jinux-std/Cargo.toml b/services/libs/aster-std/Cargo.toml
--- a/services/libs/jinux-std/Cargo.toml
+++ b/services/libs/aster-std/Cargo.toml
@@ -52,7 +52,7 @@ bitflags = "1.3"
ringbuf = { version = "0.3.2", default-features = false, features = ["alloc"] }
keyable-arc = { path = "../keyable-arc" }
# unzip initramfs
-libflate = { git = "https://github.com/jinzhao-dev/libflate", rev = "b781da6", features = [
+libflate = { git = "https://github.com/asterinas/libflate", rev = "b781da6", features = [
"no_std",
] }
core2 = { version = "0.4", default_features = false, features = ["alloc"] }
diff --git a/services/libs/jinux-std/src/console.rs b/services/libs/aster-std/src/console.rs
--- a/services/libs/jinux-std/src/console.rs
+++ b/services/libs/aster-std/src/console.rs
@@ -9,7 +9,7 @@ struct VirtioConsolesPrinter;
impl Write for VirtioConsolesPrinter {
fn write_str(&mut self, s: &str) -> core::fmt::Result {
- for (_, device) in jinux_console::all_devices() {
+ for (_, device) in aster_console::all_devices() {
device.send(s.as_bytes());
}
Ok(())
diff --git a/services/libs/jinux-std/src/console.rs b/services/libs/aster-std/src/console.rs
--- a/services/libs/jinux-std/src/console.rs
+++ b/services/libs/aster-std/src/console.rs
@@ -9,7 +9,7 @@ struct VirtioConsolesPrinter;
impl Write for VirtioConsolesPrinter {
fn write_str(&mut self, s: &str) -> core::fmt::Result {
- for (_, device) in jinux_console::all_devices() {
+ for (_, device) in aster_console::all_devices() {
device.send(s.as_bytes());
}
Ok(())
diff --git a/services/libs/jinux-std/src/device/tty/driver.rs b/services/libs/aster-std/src/device/tty/driver.rs
--- a/services/libs/jinux-std/src/device/tty/driver.rs
+++ b/services/libs/aster-std/src/device/tty/driver.rs
@@ -1,4 +1,4 @@
-pub use jinux_frame::arch::console::register_console_input_callback;
+pub use aster_frame::arch::console::register_console_input_callback;
use spin::Once;
use crate::{
diff --git a/services/libs/jinux-std/src/device/tty/driver.rs b/services/libs/aster-std/src/device/tty/driver.rs
--- a/services/libs/jinux-std/src/device/tty/driver.rs
+++ b/services/libs/aster-std/src/device/tty/driver.rs
@@ -1,4 +1,4 @@
-pub use jinux_frame::arch::console::register_console_input_callback;
+pub use aster_frame::arch::console::register_console_input_callback;
use spin::Once;
use crate::{
diff --git a/services/libs/jinux-std/src/device/tty/driver.rs b/services/libs/aster-std/src/device/tty/driver.rs
--- a/services/libs/jinux-std/src/device/tty/driver.rs
+++ b/services/libs/aster-std/src/device/tty/driver.rs
@@ -9,7 +9,7 @@ use crate::{
pub static TTY_DRIVER: Once<Arc<TtyDriver>> = Once::new();
pub(super) fn init() {
- for (_, device) in jinux_console::all_devices() {
+ for (_, device) in aster_console::all_devices() {
device.register_callback(&console_input_callback)
}
let tty_driver = Arc::new(TtyDriver::new());
diff --git a/services/libs/jinux-std/src/device/tty/driver.rs b/services/libs/aster-std/src/device/tty/driver.rs
--- a/services/libs/jinux-std/src/device/tty/driver.rs
+++ b/services/libs/aster-std/src/device/tty/driver.rs
@@ -9,7 +9,7 @@ use crate::{
pub static TTY_DRIVER: Once<Arc<TtyDriver>> = Once::new();
pub(super) fn init() {
- for (_, device) in jinux_console::all_devices() {
+ for (_, device) in aster_console::all_devices() {
device.register_callback(&console_input_callback)
}
let tty_driver = Arc::new(TtyDriver::new());
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/aster-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/aster-std/src/device/tty/line_discipline.rs
@@ -6,7 +6,7 @@ use crate::process::signal::{Pollee, Poller};
use crate::thread::work_queue::work_item::WorkItem;
use crate::thread::work_queue::{submit_work_item, WorkPriority};
use alloc::format;
-use jinux_frame::trap::disable_local;
+use aster_frame::trap::disable_local;
use ringbuf::{ring_buffer::RbBase, Rb, StaticRb};
use super::termio::{KernelTermios, WinSize, CC_C_CHAR};
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/aster-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/aster-std/src/device/tty/line_discipline.rs
@@ -6,7 +6,7 @@ use crate::process::signal::{Pollee, Poller};
use crate::thread::work_queue::work_item::WorkItem;
use crate::thread::work_queue::{submit_work_item, WorkPriority};
use alloc::format;
-use jinux_frame::trap::disable_local;
+use aster_frame::trap::disable_local;
use ringbuf::{ring_buffer::RbBase, Rb, StaticRb};
use super::termio::{KernelTermios, WinSize, CC_C_CHAR};
diff --git a/services/libs/jinux-std/src/driver/mod.rs b/services/libs/aster-std/src/driver/mod.rs
--- a/services/libs/jinux-std/src/driver/mod.rs
+++ b/services/libs/aster-std/src/driver/mod.rs
@@ -2,14 +2,14 @@ use log::info;
pub fn init() {
// print all the input device to make sure input crate will compile
- for (name, _) in jinux_input::all_devices() {
+ for (name, _) in aster_input::all_devices() {
info!("Found Input device, name:{}", name);
}
}
#[allow(unused)]
fn block_device_test() {
- for (_, device) in jinux_block::all_devices() {
+ for (_, device) in aster_block::all_devices() {
let mut write_buffer = [0u8; 512];
let mut read_buffer = [0u8; 512];
info!("write_buffer address:{:x}", write_buffer.as_ptr() as usize);
diff --git a/services/libs/jinux-std/src/error.rs b/services/libs/aster-std/src/error.rs
--- a/services/libs/jinux-std/src/error.rs
+++ b/services/libs/aster-std/src/error.rs
@@ -178,15 +178,15 @@ impl From<Errno> for Error {
}
}
-impl From<jinux_frame::Error> for Error {
- fn from(frame_error: jinux_frame::Error) -> Self {
+impl From<aster_frame::Error> for Error {
+ fn from(frame_error: aster_frame::Error) -> Self {
match frame_error {
- jinux_frame::Error::AccessDenied => Error::new(Errno::EFAULT),
- jinux_frame::Error::NoMemory => Error::new(Errno::ENOMEM),
- jinux_frame::Error::InvalidArgs => Error::new(Errno::EINVAL),
- jinux_frame::Error::IoError => Error::new(Errno::EIO),
- jinux_frame::Error::NotEnoughResources => Error::new(Errno::EBUSY),
- jinux_frame::Error::PageFault => Error::new(Errno::EFAULT),
+ aster_frame::Error::AccessDenied => Error::new(Errno::EFAULT),
+ aster_frame::Error::NoMemory => Error::new(Errno::ENOMEM),
+ aster_frame::Error::InvalidArgs => Error::new(Errno::EINVAL),
+ aster_frame::Error::IoError => Error::new(Errno::EIO),
+ aster_frame::Error::NotEnoughResources => Error::new(Errno::EBUSY),
+ aster_frame::Error::PageFault => Error::new(Errno::EFAULT),
}
}
}
diff --git a/services/libs/jinux-std/src/error.rs b/services/libs/aster-std/src/error.rs
--- a/services/libs/jinux-std/src/error.rs
+++ b/services/libs/aster-std/src/error.rs
@@ -178,15 +178,15 @@ impl From<Errno> for Error {
}
}
-impl From<jinux_frame::Error> for Error {
- fn from(frame_error: jinux_frame::Error) -> Self {
+impl From<aster_frame::Error> for Error {
+ fn from(frame_error: aster_frame::Error) -> Self {
match frame_error {
- jinux_frame::Error::AccessDenied => Error::new(Errno::EFAULT),
- jinux_frame::Error::NoMemory => Error::new(Errno::ENOMEM),
- jinux_frame::Error::InvalidArgs => Error::new(Errno::EINVAL),
- jinux_frame::Error::IoError => Error::new(Errno::EIO),
- jinux_frame::Error::NotEnoughResources => Error::new(Errno::EBUSY),
- jinux_frame::Error::PageFault => Error::new(Errno::EFAULT),
+ aster_frame::Error::AccessDenied => Error::new(Errno::EFAULT),
+ aster_frame::Error::NoMemory => Error::new(Errno::ENOMEM),
+ aster_frame::Error::InvalidArgs => Error::new(Errno::EINVAL),
+ aster_frame::Error::IoError => Error::new(Errno::EIO),
+ aster_frame::Error::NotEnoughResources => Error::new(Errno::EBUSY),
+ aster_frame::Error::PageFault => Error::new(Errno::EFAULT),
}
}
}
diff --git a/services/libs/jinux-std/src/error.rs b/services/libs/aster-std/src/error.rs
--- a/services/libs/jinux-std/src/error.rs
+++ b/services/libs/aster-std/src/error.rs
@@ -237,16 +237,16 @@ impl From<cpio_decoder::error::Error> for Error {
}
}
-impl From<Error> for jinux_frame::Error {
+impl From<Error> for aster_frame::Error {
fn from(error: Error) -> Self {
match error.errno {
- Errno::EACCES => jinux_frame::Error::AccessDenied,
- Errno::EIO => jinux_frame::Error::IoError,
- Errno::ENOMEM => jinux_frame::Error::NoMemory,
- Errno::EFAULT => jinux_frame::Error::PageFault,
- Errno::EINVAL => jinux_frame::Error::InvalidArgs,
- Errno::EBUSY => jinux_frame::Error::NotEnoughResources,
- _ => jinux_frame::Error::InvalidArgs,
+ Errno::EACCES => aster_frame::Error::AccessDenied,
+ Errno::EIO => aster_frame::Error::IoError,
+ Errno::ENOMEM => aster_frame::Error::NoMemory,
+ Errno::EFAULT => aster_frame::Error::PageFault,
+ Errno::EINVAL => aster_frame::Error::InvalidArgs,
+ Errno::EBUSY => aster_frame::Error::NotEnoughResources,
+ _ => aster_frame::Error::InvalidArgs,
}
}
}
diff --git a/services/libs/jinux-std/src/error.rs b/services/libs/aster-std/src/error.rs
--- a/services/libs/jinux-std/src/error.rs
+++ b/services/libs/aster-std/src/error.rs
@@ -237,16 +237,16 @@ impl From<cpio_decoder::error::Error> for Error {
}
}
-impl From<Error> for jinux_frame::Error {
+impl From<Error> for aster_frame::Error {
fn from(error: Error) -> Self {
match error.errno {
- Errno::EACCES => jinux_frame::Error::AccessDenied,
- Errno::EIO => jinux_frame::Error::IoError,
- Errno::ENOMEM => jinux_frame::Error::NoMemory,
- Errno::EFAULT => jinux_frame::Error::PageFault,
- Errno::EINVAL => jinux_frame::Error::InvalidArgs,
- Errno::EBUSY => jinux_frame::Error::NotEnoughResources,
- _ => jinux_frame::Error::InvalidArgs,
+ Errno::EACCES => aster_frame::Error::AccessDenied,
+ Errno::EIO => aster_frame::Error::IoError,
+ Errno::ENOMEM => aster_frame::Error::NoMemory,
+ Errno::EFAULT => aster_frame::Error::PageFault,
+ Errno::EINVAL => aster_frame::Error::InvalidArgs,
+ Errno::EBUSY => aster_frame::Error::NotEnoughResources,
+ _ => aster_frame::Error::InvalidArgs,
}
}
}
diff --git a/services/libs/jinux-std/src/fs/devpts/mod.rs b/services/libs/aster-std/src/fs/devpts/mod.rs
--- a/services/libs/jinux-std/src/fs/devpts/mod.rs
+++ b/services/libs/aster-std/src/fs/devpts/mod.rs
@@ -6,9 +6,9 @@ use crate::fs::utils::{
};
use crate::prelude::*;
+use aster_frame::vm::VmFrame;
+use aster_util::{id_allocator::IdAlloc, slot_vec::SlotVec};
use core::time::Duration;
-use jinux_frame::vm::VmFrame;
-use jinux_util::{id_allocator::IdAlloc, slot_vec::SlotVec};
use self::ptmx::Ptmx;
use self::slave::PtySlaveInode;
diff --git a/services/libs/jinux-std/src/fs/devpts/mod.rs b/services/libs/aster-std/src/fs/devpts/mod.rs
--- a/services/libs/jinux-std/src/fs/devpts/mod.rs
+++ b/services/libs/aster-std/src/fs/devpts/mod.rs
@@ -6,9 +6,9 @@ use crate::fs::utils::{
};
use crate::prelude::*;
+use aster_frame::vm::VmFrame;
+use aster_util::{id_allocator::IdAlloc, slot_vec::SlotVec};
use core::time::Duration;
-use jinux_frame::vm::VmFrame;
-use jinux_util::{id_allocator::IdAlloc, slot_vec::SlotVec};
use self::ptmx::Ptmx;
use self::slave::PtySlaveInode;
diff --git a/services/libs/jinux-std/src/fs/file_table.rs b/services/libs/aster-std/src/fs/file_table.rs
--- a/services/libs/jinux-std/src/fs/file_table.rs
+++ b/services/libs/aster-std/src/fs/file_table.rs
@@ -2,8 +2,8 @@ use crate::events::{Events, Observer, Subject};
use crate::net::socket::Socket;
use crate::prelude::*;
+use aster_util::slot_vec::SlotVec;
use core::cell::Cell;
-use jinux_util::slot_vec::SlotVec;
use super::file_handle::FileLike;
use super::fs_resolver::{FsPath, FsResolver, AT_FDCWD};
diff --git a/services/libs/jinux-std/src/fs/file_table.rs b/services/libs/aster-std/src/fs/file_table.rs
--- a/services/libs/jinux-std/src/fs/file_table.rs
+++ b/services/libs/aster-std/src/fs/file_table.rs
@@ -2,8 +2,8 @@ use crate::events::{Events, Observer, Subject};
use crate::net::socket::Socket;
use crate::prelude::*;
+use aster_util::slot_vec::SlotVec;
use core::cell::Cell;
-use jinux_util::slot_vec::SlotVec;
use super::file_handle::FileLike;
use super::fs_resolver::{FsPath, FsResolver, AT_FDCWD};
diff --git a/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs b/services/libs/aster-std/src/fs/inode_handle/dyn_cap.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
+++ b/services/libs/aster-std/src/fs/inode_handle/dyn_cap.rs
@@ -1,7 +1,7 @@
use crate::events::IoEvents;
use crate::prelude::*;
use crate::process::signal::Poller;
-use jinux_rights::{Rights, TRights};
+use aster_rights::{Rights, TRights};
use super::*;
diff --git a/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs b/services/libs/aster-std/src/fs/inode_handle/dyn_cap.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
+++ b/services/libs/aster-std/src/fs/inode_handle/dyn_cap.rs
@@ -1,7 +1,7 @@
use crate::events::IoEvents;
use crate::prelude::*;
use crate::process::signal::Poller;
-use jinux_rights::{Rights, TRights};
+use aster_rights::{Rights, TRights};
use super::*;
diff --git a/services/libs/jinux-std/src/fs/inode_handle/mod.rs b/services/libs/aster-std/src/fs/inode_handle/mod.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/mod.rs
+++ b/services/libs/aster-std/src/fs/inode_handle/mod.rs
@@ -13,7 +13,7 @@ use crate::fs::utils::{
};
use crate::prelude::*;
use crate::process::signal::Poller;
-use jinux_rights::Rights;
+use aster_rights::Rights;
#[derive(Debug)]
pub struct InodeHandle<R = Rights>(Arc<InodeHandle_>, R);
diff --git a/services/libs/jinux-std/src/fs/inode_handle/mod.rs b/services/libs/aster-std/src/fs/inode_handle/mod.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/mod.rs
+++ b/services/libs/aster-std/src/fs/inode_handle/mod.rs
@@ -13,7 +13,7 @@ use crate::fs::utils::{
};
use crate::prelude::*;
use crate::process::signal::Poller;
-use jinux_rights::Rights;
+use aster_rights::Rights;
#[derive(Debug)]
pub struct InodeHandle<R = Rights>(Arc<InodeHandle_>, R);
diff --git a/services/libs/jinux-std/src/fs/inode_handle/static_cap.rs b/services/libs/aster-std/src/fs/inode_handle/static_cap.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/static_cap.rs
+++ b/services/libs/aster-std/src/fs/inode_handle/static_cap.rs
@@ -1,6 +1,6 @@
use crate::prelude::*;
-use jinux_rights::{Read, TRightSet, TRights, Write};
-use jinux_rights_proc::require;
+use aster_rights::{Read, TRightSet, TRights, Write};
+use aster_rights_proc::require;
use super::*;
diff --git a/services/libs/jinux-std/src/fs/inode_handle/static_cap.rs b/services/libs/aster-std/src/fs/inode_handle/static_cap.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/static_cap.rs
+++ b/services/libs/aster-std/src/fs/inode_handle/static_cap.rs
@@ -1,6 +1,6 @@
use crate::prelude::*;
-use jinux_rights::{Read, TRightSet, TRights, Write};
-use jinux_rights_proc::require;
+use aster_rights::{Read, TRightSet, TRights, Write};
+use aster_rights_proc::require;
use super::*;
diff --git a/services/libs/jinux-std/src/fs/procfs/template/dir.rs b/services/libs/aster-std/src/fs/procfs/template/dir.rs
--- a/services/libs/jinux-std/src/fs/procfs/template/dir.rs
+++ b/services/libs/aster-std/src/fs/procfs/template/dir.rs
@@ -1,5 +1,5 @@
+use aster_util::slot_vec::SlotVec;
use core::time::Duration;
-use jinux_util::slot_vec::SlotVec;
use crate::fs::device::Device;
use crate::fs::utils::{DirentVisitor, FileSystem, Inode, InodeMode, InodeType, Metadata};
diff --git a/services/libs/jinux-std/src/fs/procfs/template/dir.rs b/services/libs/aster-std/src/fs/procfs/template/dir.rs
--- a/services/libs/jinux-std/src/fs/procfs/template/dir.rs
+++ b/services/libs/aster-std/src/fs/procfs/template/dir.rs
@@ -1,5 +1,5 @@
+use aster_util::slot_vec::SlotVec;
use core::time::Duration;
-use jinux_util::slot_vec::SlotVec;
use crate::fs::device::Device;
use crate::fs::utils::{DirentVisitor, FileSystem, Inode, InodeMode, InodeType, Metadata};
diff --git a/services/libs/jinux-std/src/fs/procfs/template/file.rs b/services/libs/aster-std/src/fs/procfs/template/file.rs
--- a/services/libs/jinux-std/src/fs/procfs/template/file.rs
+++ b/services/libs/aster-std/src/fs/procfs/template/file.rs
@@ -1,5 +1,5 @@
+use aster_frame::vm::VmFrame;
use core::time::Duration;
-use jinux_frame::vm::VmFrame;
use crate::fs::utils::{FileSystem, Inode, InodeMode, InodeType, IoctlCmd, Metadata};
use crate::prelude::*;
diff --git a/services/libs/jinux-std/src/fs/procfs/template/file.rs b/services/libs/aster-std/src/fs/procfs/template/file.rs
--- a/services/libs/jinux-std/src/fs/procfs/template/file.rs
+++ b/services/libs/aster-std/src/fs/procfs/template/file.rs
@@ -1,5 +1,5 @@
+use aster_frame::vm::VmFrame;
use core::time::Duration;
-use jinux_frame::vm::VmFrame;
use crate::fs::utils::{FileSystem, Inode, InodeMode, InodeType, IoctlCmd, Metadata};
use crate::prelude::*;
diff --git a/services/libs/jinux-std/src/fs/procfs/template/sym.rs b/services/libs/aster-std/src/fs/procfs/template/sym.rs
--- a/services/libs/jinux-std/src/fs/procfs/template/sym.rs
+++ b/services/libs/aster-std/src/fs/procfs/template/sym.rs
@@ -1,5 +1,5 @@
+use aster_frame::vm::VmFrame;
use core::time::Duration;
-use jinux_frame::vm::VmFrame;
use crate::fs::utils::{FileSystem, Inode, InodeMode, InodeType, IoctlCmd, Metadata};
use crate::prelude::*;
diff --git a/services/libs/jinux-std/src/fs/procfs/template/sym.rs b/services/libs/aster-std/src/fs/procfs/template/sym.rs
--- a/services/libs/jinux-std/src/fs/procfs/template/sym.rs
+++ b/services/libs/aster-std/src/fs/procfs/template/sym.rs
@@ -1,5 +1,5 @@
+use aster_frame::vm::VmFrame;
use core::time::Duration;
-use jinux_frame::vm::VmFrame;
use crate::fs::utils::{FileSystem, Inode, InodeMode, InodeType, IoctlCmd, Metadata};
use crate::prelude::*;
diff --git a/services/libs/jinux-std/src/fs/ramfs/fs.rs b/services/libs/aster-std/src/fs/ramfs/fs.rs
--- a/services/libs/jinux-std/src/fs/ramfs/fs.rs
+++ b/services/libs/aster-std/src/fs/ramfs/fs.rs
@@ -1,10 +1,10 @@
use alloc::str;
+use aster_frame::sync::{RwLock, RwLockWriteGuard};
+use aster_frame::vm::{VmFrame, VmIo};
+use aster_rights::Full;
+use aster_util::slot_vec::SlotVec;
use core::sync::atomic::{AtomicUsize, Ordering};
use core::time::Duration;
-use jinux_frame::sync::{RwLock, RwLockWriteGuard};
-use jinux_frame::vm::{VmFrame, VmIo};
-use jinux_rights::Full;
-use jinux_util::slot_vec::SlotVec;
use super::*;
use crate::events::IoEvents;
diff --git a/services/libs/jinux-std/src/fs/ramfs/fs.rs b/services/libs/aster-std/src/fs/ramfs/fs.rs
--- a/services/libs/jinux-std/src/fs/ramfs/fs.rs
+++ b/services/libs/aster-std/src/fs/ramfs/fs.rs
@@ -1,10 +1,10 @@
use alloc::str;
+use aster_frame::sync::{RwLock, RwLockWriteGuard};
+use aster_frame::vm::{VmFrame, VmIo};
+use aster_rights::Full;
+use aster_util::slot_vec::SlotVec;
use core::sync::atomic::{AtomicUsize, Ordering};
use core::time::Duration;
-use jinux_frame::sync::{RwLock, RwLockWriteGuard};
-use jinux_frame::vm::{VmFrame, VmIo};
-use jinux_rights::Full;
-use jinux_util::slot_vec::SlotVec;
use super::*;
use crate::events::IoEvents;
diff --git a/services/libs/jinux-std/src/fs/utils/access_mode.rs b/services/libs/aster-std/src/fs/utils/access_mode.rs
--- a/services/libs/jinux-std/src/fs/utils/access_mode.rs
+++ b/services/libs/aster-std/src/fs/utils/access_mode.rs
@@ -1,5 +1,5 @@
use crate::prelude::*;
-use jinux_rights::Rights;
+use aster_rights::Rights;
#[allow(non_camel_case_types)]
#[derive(Clone, Copy, Debug)]
diff --git a/services/libs/jinux-std/src/fs/utils/access_mode.rs b/services/libs/aster-std/src/fs/utils/access_mode.rs
--- a/services/libs/jinux-std/src/fs/utils/access_mode.rs
+++ b/services/libs/aster-std/src/fs/utils/access_mode.rs
@@ -1,5 +1,5 @@
use crate::prelude::*;
-use jinux_rights::Rights;
+use aster_rights::Rights;
#[allow(non_camel_case_types)]
#[derive(Clone, Copy, Debug)]
diff --git a/services/libs/jinux-std/src/fs/utils/channel.rs b/services/libs/aster-std/src/fs/utils/channel.rs
--- a/services/libs/jinux-std/src/fs/utils/channel.rs
+++ b/services/libs/aster-std/src/fs/utils/channel.rs
@@ -1,12 +1,12 @@
+use aster_rights_proc::require;
use core::sync::atomic::{AtomicBool, AtomicU32, Ordering};
-use jinux_rights_proc::require;
use ringbuf::{HeapConsumer as HeapRbConsumer, HeapProducer as HeapRbProducer, HeapRb};
use crate::events::IoEvents;
use crate::events::Observer;
use crate::prelude::*;
use crate::process::signal::{Pollee, Poller};
-use jinux_rights::{Read, ReadOp, TRights, Write, WriteOp};
+use aster_rights::{Read, ReadOp, TRights, Write, WriteOp};
use super::StatusFlags;
diff --git a/services/libs/jinux-std/src/fs/utils/channel.rs b/services/libs/aster-std/src/fs/utils/channel.rs
--- a/services/libs/jinux-std/src/fs/utils/channel.rs
+++ b/services/libs/aster-std/src/fs/utils/channel.rs
@@ -1,12 +1,12 @@
+use aster_rights_proc::require;
use core::sync::atomic::{AtomicBool, AtomicU32, Ordering};
-use jinux_rights_proc::require;
use ringbuf::{HeapConsumer as HeapRbConsumer, HeapProducer as HeapRbProducer, HeapRb};
use crate::events::IoEvents;
use crate::events::Observer;
use crate::prelude::*;
use crate::process::signal::{Pollee, Poller};
-use jinux_rights::{Read, ReadOp, TRights, Write, WriteOp};
+use aster_rights::{Read, ReadOp, TRights, Write, WriteOp};
use super::StatusFlags;
diff --git a/services/libs/jinux-std/src/fs/utils/direntry_vec.rs b/services/libs/aster-std/src/fs/utils/direntry_vec.rs
--- a/services/libs/jinux-std/src/fs/utils/direntry_vec.rs
+++ b/services/libs/aster-std/src/fs/utils/direntry_vec.rs
@@ -1,7 +1,7 @@
use super::Inode;
use crate::prelude::*;
-use jinux_util::slot_vec::SlotVec;
+use aster_util::slot_vec::SlotVec;
pub trait DirEntryVecExt {
/// If the entry is not found by `name`, use `f` to get the inode, then put the entry into vec.
diff --git a/services/libs/jinux-std/src/fs/utils/direntry_vec.rs b/services/libs/aster-std/src/fs/utils/direntry_vec.rs
--- a/services/libs/jinux-std/src/fs/utils/direntry_vec.rs
+++ b/services/libs/aster-std/src/fs/utils/direntry_vec.rs
@@ -1,7 +1,7 @@
use super::Inode;
use crate::prelude::*;
-use jinux_util::slot_vec::SlotVec;
+use aster_util::slot_vec::SlotVec;
pub trait DirEntryVecExt {
/// If the entry is not found by `name`, use `f` to get the inode, then put the entry into vec.
diff --git a/services/libs/jinux-std/src/fs/utils/inode.rs b/services/libs/aster-std/src/fs/utils/inode.rs
--- a/services/libs/jinux-std/src/fs/utils/inode.rs
+++ b/services/libs/aster-std/src/fs/utils/inode.rs
@@ -1,7 +1,7 @@
+use aster_frame::vm::VmFrame;
+use aster_rights::Full;
use core::time::Duration;
use core2::io::{Error as IoError, ErrorKind as IoErrorKind, Result as IoResult, Write};
-use jinux_frame::vm::VmFrame;
-use jinux_rights::Full;
use super::{DirentVisitor, FileSystem, IoctlCmd, SuperBlock};
use crate::events::IoEvents;
diff --git a/services/libs/jinux-std/src/fs/utils/inode.rs b/services/libs/aster-std/src/fs/utils/inode.rs
--- a/services/libs/jinux-std/src/fs/utils/inode.rs
+++ b/services/libs/aster-std/src/fs/utils/inode.rs
@@ -1,7 +1,7 @@
+use aster_frame::vm::VmFrame;
+use aster_rights::Full;
use core::time::Duration;
use core2::io::{Error as IoError, ErrorKind as IoErrorKind, Result as IoResult, Write};
-use jinux_frame::vm::VmFrame;
-use jinux_rights::Full;
use super::{DirentVisitor, FileSystem, IoctlCmd, SuperBlock};
use crate::events::IoEvents;
diff --git a/services/libs/jinux-std/src/fs/utils/page_cache.rs b/services/libs/aster-std/src/fs/utils/page_cache.rs
--- a/services/libs/jinux-std/src/fs/utils/page_cache.rs
+++ b/services/libs/aster-std/src/fs/utils/page_cache.rs
@@ -1,10 +1,10 @@
use super::Inode;
use crate::prelude::*;
use crate::vm::vmo::{get_page_idx_range, Pager, Vmo, VmoFlags, VmoOptions};
-use jinux_rights::Full;
+use aster_rights::Full;
+use aster_frame::vm::{VmAllocOptions, VmFrame};
use core::ops::Range;
-use jinux_frame::vm::{VmAllocOptions, VmFrame};
use lru::LruCache;
pub struct PageCache {
diff --git a/services/libs/jinux-std/src/fs/utils/page_cache.rs b/services/libs/aster-std/src/fs/utils/page_cache.rs
--- a/services/libs/jinux-std/src/fs/utils/page_cache.rs
+++ b/services/libs/aster-std/src/fs/utils/page_cache.rs
@@ -1,10 +1,10 @@
use super::Inode;
use crate::prelude::*;
use crate::vm::vmo::{get_page_idx_range, Pager, Vmo, VmoFlags, VmoOptions};
-use jinux_rights::Full;
+use aster_rights::Full;
+use aster_frame::vm::{VmAllocOptions, VmFrame};
use core::ops::Range;
-use jinux_frame::vm::{VmAllocOptions, VmFrame};
use lru::LruCache;
pub struct PageCache {
diff --git a/services/libs/jinux-std/src/lib.rs b/services/libs/aster-std/src/lib.rs
--- a/services/libs/jinux-std/src/lib.rs
+++ b/services/libs/aster-std/src/lib.rs
@@ -1,4 +1,4 @@
-//! The std library of jinux
+//! The std library of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
#![allow(dead_code)]
diff --git a/services/libs/jinux-std/src/lib.rs b/services/libs/aster-std/src/lib.rs
--- a/services/libs/jinux-std/src/lib.rs
+++ b/services/libs/aster-std/src/lib.rs
@@ -1,4 +1,4 @@
-//! The std library of jinux
+//! The std library of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
#![allow(dead_code)]
diff --git a/services/libs/jinux-std/src/lib.rs b/services/libs/aster-std/src/lib.rs
--- a/services/libs/jinux-std/src/lib.rs
+++ b/services/libs/aster-std/src/lib.rs
@@ -28,7 +28,7 @@ use crate::{
Thread,
},
};
-use jinux_frame::{
+use aster_frame::{
arch::qemu::{exit_qemu, QemuExitCode},
boot,
};
diff --git a/services/libs/jinux-std/src/lib.rs b/services/libs/aster-std/src/lib.rs
--- a/services/libs/jinux-std/src/lib.rs
+++ b/services/libs/aster-std/src/lib.rs
@@ -28,7 +28,7 @@ use crate::{
Thread,
},
};
-use jinux_frame::{
+use aster_frame::{
arch::qemu::{exit_qemu, QemuExitCode},
boot,
};
diff --git a/services/libs/jinux-std/src/lib.rs b/services/libs/aster-std/src/lib.rs
--- a/services/libs/jinux-std/src/lib.rs
+++ b/services/libs/aster-std/src/lib.rs
@@ -82,7 +82,7 @@ fn init_thread() {
}));
thread.join();
info!(
- "[jinux-std/lib.rs] spawn kernel thread, tid = {}",
+ "[aster-std/lib.rs] spawn kernel thread, tid = {}",
thread.tid()
);
thread::work_queue::init();
diff --git a/services/libs/jinux-std/src/lib.rs b/services/libs/aster-std/src/lib.rs
--- a/services/libs/jinux-std/src/lib.rs
+++ b/services/libs/aster-std/src/lib.rs
@@ -82,7 +82,7 @@ fn init_thread() {
}));
thread.join();
info!(
- "[jinux-std/lib.rs] spawn kernel thread, tid = {}",
+ "[aster-std/lib.rs] spawn kernel thread, tid = {}",
thread.tid()
);
thread::work_queue::init();
diff --git a/services/libs/jinux-std/src/lib.rs b/services/libs/aster-std/src/lib.rs
--- a/services/libs/jinux-std/src/lib.rs
+++ b/services/libs/aster-std/src/lib.rs
@@ -125,12 +125,10 @@ fn print_banner() {
println!("\x1B[36m");
println!(
r"
- __ __ .__ __. __ __ ___ ___
- | | | | | \ | | | | | | \ \ / /
- | | | | | \| | | | | | \ V /
-.--. | | | | | . ` | | | | | > <
-| `--' | | | | |\ | | `--' | / . \
- \______/ |__| |__| \__| \______/ /__/ \__\
+ _ ___ _____ ___ ___ ___ _ _ _ ___
+ /_\ / __|_ _| __| _ \_ _| \| | /_\ / __|
+ / _ \\__ \ | | | _|| /| || .` |/ _ \\__ \
+/_/ \_\___/ |_| |___|_|_\___|_|\_/_/ \_\___/
"
);
println!("\x1B[0m");
diff --git a/services/libs/jinux-std/src/lib.rs b/services/libs/aster-std/src/lib.rs
--- a/services/libs/jinux-std/src/lib.rs
+++ b/services/libs/aster-std/src/lib.rs
@@ -125,12 +125,10 @@ fn print_banner() {
println!("\x1B[36m");
println!(
r"
- __ __ .__ __. __ __ ___ ___
- | | | | | \ | | | | | | \ \ / /
- | | | | | \| | | | | | \ V /
-.--. | | | | | . ` | | | | | > <
-| `--' | | | | |\ | | `--' | / . \
- \______/ |__| |__| \__| \______/ /__/ \__\
+ _ ___ _____ ___ ___ ___ _ _ _ ___
+ /_\ / __|_ _| __| _ \_ _| \| | /_\ / __|
+ / _ \\__ \ | | | _|| /| || .` |/ _ \\__ \
+/_/ \_\___/ |_| |___|_|_\___|_|\_/_/ \_\___/
"
);
println!("\x1B[0m");
diff --git a/services/libs/jinux-std/src/net/iface/time.rs b/services/libs/aster-std/src/net/iface/time.rs
--- a/services/libs/jinux-std/src/net/iface/time.rs
+++ b/services/libs/aster-std/src/net/iface/time.rs
@@ -1,4 +1,4 @@
-use jinux_frame::timer::read_monotonic_milli_seconds;
+use aster_frame::timer::read_monotonic_milli_seconds;
pub(super) fn get_network_timestamp() -> smoltcp::time::Instant {
let millis = read_monotonic_milli_seconds();
diff --git a/services/libs/jinux-std/src/net/iface/time.rs b/services/libs/aster-std/src/net/iface/time.rs
--- a/services/libs/jinux-std/src/net/iface/time.rs
+++ b/services/libs/aster-std/src/net/iface/time.rs
@@ -1,4 +1,4 @@
-use jinux_frame::timer::read_monotonic_milli_seconds;
+use aster_frame::timer::read_monotonic_milli_seconds;
pub(super) fn get_network_timestamp() -> smoltcp::time::Instant {
let millis = read_monotonic_milli_seconds();
diff --git a/services/libs/jinux-std/src/net/iface/util.rs b/services/libs/aster-std/src/net/iface/util.rs
--- a/services/libs/jinux-std/src/net/iface/util.rs
+++ b/services/libs/aster-std/src/net/iface/util.rs
@@ -1,4 +1,4 @@
-use jinux_frame::timer::read_monotonic_milli_seconds;
+use aster_frame::timer::read_monotonic_milli_seconds;
use crate::{
prelude::*,
diff --git a/services/libs/jinux-std/src/net/iface/util.rs b/services/libs/aster-std/src/net/iface/util.rs
--- a/services/libs/jinux-std/src/net/iface/util.rs
+++ b/services/libs/aster-std/src/net/iface/util.rs
@@ -1,4 +1,4 @@
-use jinux_frame::timer::read_monotonic_milli_seconds;
+use aster_frame::timer::read_monotonic_milli_seconds;
use crate::{
prelude::*,
diff --git a/services/libs/jinux-std/src/net/iface/virtio.rs b/services/libs/aster-std/src/net/iface/virtio.rs
--- a/services/libs/jinux-std/src/net/iface/virtio.rs
+++ b/services/libs/aster-std/src/net/iface/virtio.rs
@@ -1,7 +1,7 @@
use crate::prelude::*;
-use jinux_frame::sync::SpinLock;
-use jinux_network::AnyNetworkDevice;
-use jinux_virtio::device::network::DEVICE_NAME;
+use aster_frame::sync::SpinLock;
+use aster_network::AnyNetworkDevice;
+use aster_virtio::device::network::DEVICE_NAME;
use smoltcp::{
iface::{Config, Routes, SocketHandle, SocketSet},
socket::dhcpv4,
diff --git a/services/libs/jinux-std/src/net/iface/virtio.rs b/services/libs/aster-std/src/net/iface/virtio.rs
--- a/services/libs/jinux-std/src/net/iface/virtio.rs
+++ b/services/libs/aster-std/src/net/iface/virtio.rs
@@ -1,7 +1,7 @@
use crate::prelude::*;
-use jinux_frame::sync::SpinLock;
-use jinux_network::AnyNetworkDevice;
-use jinux_virtio::device::network::DEVICE_NAME;
+use aster_frame::sync::SpinLock;
+use aster_network::AnyNetworkDevice;
+use aster_virtio::device::network::DEVICE_NAME;
use smoltcp::{
iface::{Config, Routes, SocketHandle, SocketSet},
socket::dhcpv4,
diff --git a/services/libs/jinux-std/src/net/iface/virtio.rs b/services/libs/aster-std/src/net/iface/virtio.rs
--- a/services/libs/jinux-std/src/net/iface/virtio.rs
+++ b/services/libs/aster-std/src/net/iface/virtio.rs
@@ -19,7 +19,7 @@ pub struct IfaceVirtio {
impl IfaceVirtio {
pub fn new() -> Arc<Self> {
- let virtio_net = jinux_network::get_device(DEVICE_NAME).unwrap();
+ let virtio_net = aster_network::get_device(DEVICE_NAME).unwrap();
let interface = {
let mac_addr = virtio_net.lock().mac_addr();
let ip_addr = IpCidr::new(wire::IpAddress::Ipv4(wire::Ipv4Address::UNSPECIFIED), 0);
diff --git a/services/libs/jinux-std/src/net/iface/virtio.rs b/services/libs/aster-std/src/net/iface/virtio.rs
--- a/services/libs/jinux-std/src/net/iface/virtio.rs
+++ b/services/libs/aster-std/src/net/iface/virtio.rs
@@ -19,7 +19,7 @@ pub struct IfaceVirtio {
impl IfaceVirtio {
pub fn new() -> Arc<Self> {
- let virtio_net = jinux_network::get_device(DEVICE_NAME).unwrap();
+ let virtio_net = aster_network::get_device(DEVICE_NAME).unwrap();
let interface = {
let mac_addr = virtio_net.lock().mac_addr();
let ip_addr = IpCidr::new(wire::IpAddress::Ipv4(wire::Ipv4Address::UNSPECIFIED), 0);
diff --git a/services/libs/jinux-std/src/net/mod.rs b/services/libs/aster-std/src/net/mod.rs
--- a/services/libs/jinux-std/src/net/mod.rs
+++ b/services/libs/aster-std/src/net/mod.rs
@@ -18,8 +18,8 @@ pub fn init() {
vec![iface_virtio, iface_loopback]
});
- for (name, _) in jinux_network::all_devices() {
- jinux_network::register_recv_callback(&name, || {
+ for (name, _) in aster_network::all_devices() {
+ aster_network::register_recv_callback(&name, || {
// TODO: further check that the irq num is the same as iface's irq num
let iface_virtio = &IFACES.get().unwrap()[0];
iface_virtio.poll();
diff --git a/services/libs/jinux-std/src/net/mod.rs b/services/libs/aster-std/src/net/mod.rs
--- a/services/libs/jinux-std/src/net/mod.rs
+++ b/services/libs/aster-std/src/net/mod.rs
@@ -18,8 +18,8 @@ pub fn init() {
vec![iface_virtio, iface_loopback]
});
- for (name, _) in jinux_network::all_devices() {
- jinux_network::register_recv_callback(&name, || {
+ for (name, _) in aster_network::all_devices() {
+ aster_network::register_recv_callback(&name, || {
// TODO: further check that the irq num is the same as iface's irq num
let iface_virtio = &IFACES.get().unwrap()[0];
iface_virtio.poll();
diff --git a/services/libs/jinux-std/src/prelude.rs b/services/libs/aster-std/src/prelude.rs
--- a/services/libs/jinux-std/src/prelude.rs
+++ b/services/libs/aster-std/src/prelude.rs
@@ -12,14 +12,14 @@ pub(crate) use alloc::sync::Arc;
pub(crate) use alloc::sync::Weak;
pub(crate) use alloc::vec;
pub(crate) use alloc::vec::Vec;
+pub(crate) use aster_frame::config::PAGE_SIZE;
+pub(crate) use aster_frame::sync::{Mutex, MutexGuard, RwLock, SpinLock, SpinLockGuard};
+pub(crate) use aster_frame::vm::Vaddr;
pub(crate) use bitflags::bitflags;
pub(crate) use core::any::Any;
pub(crate) use core::ffi::CStr;
pub(crate) use core::fmt::Debug;
pub(crate) use int_to_c_enum::TryFromInt;
-pub(crate) use jinux_frame::config::PAGE_SIZE;
-pub(crate) use jinux_frame::sync::{Mutex, MutexGuard, RwLock, SpinLock, SpinLockGuard};
-pub(crate) use jinux_frame::vm::Vaddr;
pub(crate) use log::{debug, error, info, trace, warn};
pub(crate) use pod::Pod;
diff --git a/services/libs/jinux-std/src/prelude.rs b/services/libs/aster-std/src/prelude.rs
--- a/services/libs/jinux-std/src/prelude.rs
+++ b/services/libs/aster-std/src/prelude.rs
@@ -12,14 +12,14 @@ pub(crate) use alloc::sync::Arc;
pub(crate) use alloc::sync::Weak;
pub(crate) use alloc::vec;
pub(crate) use alloc::vec::Vec;
+pub(crate) use aster_frame::config::PAGE_SIZE;
+pub(crate) use aster_frame::sync::{Mutex, MutexGuard, RwLock, SpinLock, SpinLockGuard};
+pub(crate) use aster_frame::vm::Vaddr;
pub(crate) use bitflags::bitflags;
pub(crate) use core::any::Any;
pub(crate) use core::ffi::CStr;
pub(crate) use core::fmt::Debug;
pub(crate) use int_to_c_enum::TryFromInt;
-pub(crate) use jinux_frame::config::PAGE_SIZE;
-pub(crate) use jinux_frame::sync::{Mutex, MutexGuard, RwLock, SpinLock, SpinLockGuard};
-pub(crate) use jinux_frame::vm::Vaddr;
pub(crate) use log::{debug, error, info, trace, warn};
pub(crate) use pod::Pod;
diff --git a/services/libs/jinux-std/src/process/clone.rs b/services/libs/aster-std/src/process/clone.rs
--- a/services/libs/jinux-std/src/process/clone.rs
+++ b/services/libs/aster-std/src/process/clone.rs
@@ -10,10 +10,10 @@ use crate::prelude::*;
use crate::thread::{allocate_tid, thread_table, Thread, Tid};
use crate::util::write_val_to_user;
use crate::vm::vmar::Vmar;
-use jinux_frame::cpu::UserContext;
-use jinux_frame::user::UserSpace;
-use jinux_frame::vm::VmIo;
-use jinux_rights::Full;
+use aster_frame::cpu::UserContext;
+use aster_frame::user::UserSpace;
+use aster_frame::vm::VmIo;
+use aster_rights::Full;
bitflags! {
pub struct CloneFlags: u32 {
diff --git a/services/libs/jinux-std/src/process/clone.rs b/services/libs/aster-std/src/process/clone.rs
--- a/services/libs/jinux-std/src/process/clone.rs
+++ b/services/libs/aster-std/src/process/clone.rs
@@ -10,10 +10,10 @@ use crate::prelude::*;
use crate::thread::{allocate_tid, thread_table, Thread, Tid};
use crate::util::write_val_to_user;
use crate::vm::vmar::Vmar;
-use jinux_frame::cpu::UserContext;
-use jinux_frame::user::UserSpace;
-use jinux_frame::vm::VmIo;
-use jinux_rights::Full;
+use aster_frame::cpu::UserContext;
+use aster_frame::user::UserSpace;
+use aster_frame::vm::VmIo;
+use aster_rights::Full;
bitflags! {
pub struct CloneFlags: u32 {
diff --git a/services/libs/jinux-std/src/process/credentials/credentials_.rs b/services/libs/aster-std/src/process/credentials/credentials_.rs
--- a/services/libs/jinux-std/src/process/credentials/credentials_.rs
+++ b/services/libs/aster-std/src/process/credentials/credentials_.rs
@@ -2,7 +2,7 @@ use super::group::AtomicGid;
use super::user::AtomicUid;
use super::{Gid, Uid};
use crate::prelude::*;
-use jinux_frame::sync::{RwLockReadGuard, RwLockWriteGuard};
+use aster_frame::sync::{RwLockReadGuard, RwLockWriteGuard};
#[derive(Debug)]
pub(super) struct Credentials_ {
diff --git a/services/libs/jinux-std/src/process/credentials/credentials_.rs b/services/libs/aster-std/src/process/credentials/credentials_.rs
--- a/services/libs/jinux-std/src/process/credentials/credentials_.rs
+++ b/services/libs/aster-std/src/process/credentials/credentials_.rs
@@ -2,7 +2,7 @@ use super::group::AtomicGid;
use super::user::AtomicUid;
use super::{Gid, Uid};
use crate::prelude::*;
-use jinux_frame::sync::{RwLockReadGuard, RwLockWriteGuard};
+use aster_frame::sync::{RwLockReadGuard, RwLockWriteGuard};
#[derive(Debug)]
pub(super) struct Credentials_ {
diff --git a/services/libs/jinux-std/src/process/credentials/mod.rs b/services/libs/aster-std/src/process/credentials/mod.rs
--- a/services/libs/jinux-std/src/process/credentials/mod.rs
+++ b/services/libs/aster-std/src/process/credentials/mod.rs
@@ -4,8 +4,8 @@ mod static_cap;
mod user;
use crate::prelude::*;
+use aster_rights::{FullOp, ReadOp, WriteOp};
use credentials_::Credentials_;
-use jinux_rights::{FullOp, ReadOp, WriteOp};
pub use group::Gid;
pub use user::Uid;
diff --git a/services/libs/jinux-std/src/process/credentials/mod.rs b/services/libs/aster-std/src/process/credentials/mod.rs
--- a/services/libs/jinux-std/src/process/credentials/mod.rs
+++ b/services/libs/aster-std/src/process/credentials/mod.rs
@@ -4,8 +4,8 @@ mod static_cap;
mod user;
use crate::prelude::*;
+use aster_rights::{FullOp, ReadOp, WriteOp};
use credentials_::Credentials_;
-use jinux_rights::{FullOp, ReadOp, WriteOp};
pub use group::Gid;
pub use user::Uid;
diff --git a/services/libs/jinux-std/src/process/credentials/static_cap.rs b/services/libs/aster-std/src/process/credentials/static_cap.rs
--- a/services/libs/jinux-std/src/process/credentials/static_cap.rs
+++ b/services/libs/aster-std/src/process/credentials/static_cap.rs
@@ -1,9 +1,9 @@
use super::credentials_::Credentials_;
use super::{Credentials, Gid, Uid};
use crate::prelude::*;
-use jinux_frame::sync::{RwLockReadGuard, RwLockWriteGuard};
-use jinux_rights::{Dup, Read, TRights, Write};
-use jinux_rights_proc::require;
+use aster_frame::sync::{RwLockReadGuard, RwLockWriteGuard};
+use aster_rights::{Dup, Read, TRights, Write};
+use aster_rights_proc::require;
impl<R: TRights> Credentials<R> {
/// Creates a root `Credentials`. This method can only be used when creating the first process
diff --git a/services/libs/jinux-std/src/process/credentials/static_cap.rs b/services/libs/aster-std/src/process/credentials/static_cap.rs
--- a/services/libs/jinux-std/src/process/credentials/static_cap.rs
+++ b/services/libs/aster-std/src/process/credentials/static_cap.rs
@@ -1,9 +1,9 @@
use super::credentials_::Credentials_;
use super::{Credentials, Gid, Uid};
use crate::prelude::*;
-use jinux_frame::sync::{RwLockReadGuard, RwLockWriteGuard};
-use jinux_rights::{Dup, Read, TRights, Write};
-use jinux_rights_proc::require;
+use aster_frame::sync::{RwLockReadGuard, RwLockWriteGuard};
+use aster_rights::{Dup, Read, TRights, Write};
+use aster_rights_proc::require;
impl<R: TRights> Credentials<R> {
/// Creates a root `Credentials`. This method can only be used when creating the first process
diff --git a/services/libs/jinux-std/src/process/posix_thread/builder.rs b/services/libs/aster-std/src/process/posix_thread/builder.rs
--- a/services/libs/jinux-std/src/process/posix_thread/builder.rs
+++ b/services/libs/aster-std/src/process/posix_thread/builder.rs
@@ -1,4 +1,4 @@
-use jinux_frame::user::UserSpace;
+use aster_frame::user::UserSpace;
use crate::{
prelude::*,
diff --git a/services/libs/jinux-std/src/process/posix_thread/builder.rs b/services/libs/aster-std/src/process/posix_thread/builder.rs
--- a/services/libs/jinux-std/src/process/posix_thread/builder.rs
+++ b/services/libs/aster-std/src/process/posix_thread/builder.rs
@@ -1,4 +1,4 @@
-use jinux_frame::user::UserSpace;
+use aster_frame::user::UserSpace;
use crate::{
prelude::*,
diff --git a/services/libs/jinux-std/src/process/posix_thread/futex.rs b/services/libs/aster-std/src/process/posix_thread/futex.rs
--- a/services/libs/jinux-std/src/process/posix_thread/futex.rs
+++ b/services/libs/aster-std/src/process/posix_thread/futex.rs
@@ -1,6 +1,6 @@
use core::sync::atomic::{AtomicBool, Ordering};
-use jinux_frame::cpu::num_cpus;
+use aster_frame::cpu::num_cpus;
use crate::{
prelude::*,
diff --git a/services/libs/jinux-std/src/process/posix_thread/futex.rs b/services/libs/aster-std/src/process/posix_thread/futex.rs
--- a/services/libs/jinux-std/src/process/posix_thread/futex.rs
+++ b/services/libs/aster-std/src/process/posix_thread/futex.rs
@@ -1,6 +1,6 @@
use core::sync::atomic::{AtomicBool, Ordering};
-use jinux_frame::cpu::num_cpus;
+use aster_frame::cpu::num_cpus;
use crate::{
prelude::*,
diff --git a/services/libs/jinux-std/src/process/posix_thread/mod.rs b/services/libs/aster-std/src/process/posix_thread/mod.rs
--- a/services/libs/jinux-std/src/process/posix_thread/mod.rs
+++ b/services/libs/aster-std/src/process/posix_thread/mod.rs
@@ -10,8 +10,8 @@ use crate::prelude::*;
use crate::process::signal::constants::SIGCONT;
use crate::thread::{thread_table, Tid};
use crate::util::write_val_to_user;
+use aster_rights::{ReadOp, WriteOp};
use futex::futex_wake;
-use jinux_rights::{ReadOp, WriteOp};
use robust_list::wake_robust_futex;
mod builder;
diff --git a/services/libs/jinux-std/src/process/posix_thread/mod.rs b/services/libs/aster-std/src/process/posix_thread/mod.rs
--- a/services/libs/jinux-std/src/process/posix_thread/mod.rs
+++ b/services/libs/aster-std/src/process/posix_thread/mod.rs
@@ -10,8 +10,8 @@ use crate::prelude::*;
use crate::process::signal::constants::SIGCONT;
use crate::thread::{thread_table, Tid};
use crate::util::write_val_to_user;
+use aster_rights::{ReadOp, WriteOp};
use futex::futex_wake;
-use jinux_rights::{ReadOp, WriteOp};
use robust_list::wake_robust_futex;
mod builder;
diff --git a/services/libs/jinux-std/src/process/posix_thread/posix_thread_ext.rs b/services/libs/aster-std/src/process/posix_thread/posix_thread_ext.rs
--- a/services/libs/jinux-std/src/process/posix_thread/posix_thread_ext.rs
+++ b/services/libs/aster-std/src/process/posix_thread/posix_thread_ext.rs
@@ -1,4 +1,4 @@
-use jinux_frame::{cpu::UserContext, user::UserSpace};
+use aster_frame::{cpu::UserContext, user::UserSpace};
use crate::{
fs::fs_resolver::{FsPath, FsResolver, AT_FDCWD},
diff --git a/services/libs/jinux-std/src/process/posix_thread/posix_thread_ext.rs b/services/libs/aster-std/src/process/posix_thread/posix_thread_ext.rs
--- a/services/libs/jinux-std/src/process/posix_thread/posix_thread_ext.rs
+++ b/services/libs/aster-std/src/process/posix_thread/posix_thread_ext.rs
@@ -1,4 +1,4 @@
-use jinux_frame::{cpu::UserContext, user::UserSpace};
+use aster_frame::{cpu::UserContext, user::UserSpace};
use crate::{
fs::fs_resolver::{FsPath, FsResolver, AT_FDCWD},
diff --git a/services/libs/jinux-std/src/process/process/mod.rs b/services/libs/aster-std/src/process/process/mod.rs
--- a/services/libs/jinux-std/src/process/process/mod.rs
+++ b/services/libs/aster-std/src/process/process/mod.rs
@@ -23,8 +23,8 @@ mod process_group;
mod session;
mod terminal;
+use aster_rights::Full;
pub use builder::ProcessBuilder;
-use jinux_rights::Full;
pub use job_control::JobControl;
pub use process_group::ProcessGroup;
pub use session::Session;
diff --git a/services/libs/jinux-std/src/process/process/mod.rs b/services/libs/aster-std/src/process/process/mod.rs
--- a/services/libs/jinux-std/src/process/process/mod.rs
+++ b/services/libs/aster-std/src/process/process/mod.rs
@@ -23,8 +23,8 @@ mod process_group;
mod session;
mod terminal;
+use aster_rights::Full;
pub use builder::ProcessBuilder;
-use jinux_rights::Full;
pub use job_control::JobControl;
pub use process_group::ProcessGroup;
pub use session::Session;
diff --git a/services/libs/jinux-std/src/process/process_vm/mod.rs b/services/libs/aster-std/src/process/process_vm/mod.rs
--- a/services/libs/jinux-std/src/process/process_vm/mod.rs
+++ b/services/libs/aster-std/src/process/process_vm/mod.rs
@@ -6,7 +6,7 @@
pub mod user_heap;
-use jinux_rights::Full;
+use aster_rights::Full;
use user_heap::UserHeap;
use crate::vm::vmar::Vmar;
diff --git a/services/libs/jinux-std/src/process/process_vm/mod.rs b/services/libs/aster-std/src/process/process_vm/mod.rs
--- a/services/libs/jinux-std/src/process/process_vm/mod.rs
+++ b/services/libs/aster-std/src/process/process_vm/mod.rs
@@ -6,7 +6,7 @@
pub mod user_heap;
-use jinux_rights::Full;
+use aster_rights::Full;
use user_heap::UserHeap;
use crate::vm::vmar::Vmar;
diff --git a/services/libs/jinux-std/src/process/process_vm/user_heap.rs b/services/libs/aster-std/src/process/process_vm/user_heap.rs
--- a/services/libs/jinux-std/src/process/process_vm/user_heap.rs
+++ b/services/libs/aster-std/src/process/process_vm/user_heap.rs
@@ -7,7 +7,7 @@ use crate::{
vm::vmo::{VmoFlags, VmoOptions},
};
use align_ext::AlignExt;
-use jinux_rights::{Full, Rights};
+use aster_rights::{Full, Rights};
pub const USER_HEAP_BASE: Vaddr = 0x0000_0000_1000_0000;
pub const USER_HEAP_SIZE_LIMIT: usize = PAGE_SIZE * 1000;
diff --git a/services/libs/jinux-std/src/process/process_vm/user_heap.rs b/services/libs/aster-std/src/process/process_vm/user_heap.rs
--- a/services/libs/jinux-std/src/process/process_vm/user_heap.rs
+++ b/services/libs/aster-std/src/process/process_vm/user_heap.rs
@@ -7,7 +7,7 @@ use crate::{
vm::vmo::{VmoFlags, VmoOptions},
};
use align_ext::AlignExt;
-use jinux_rights::{Full, Rights};
+use aster_rights::{Full, Rights};
pub const USER_HEAP_BASE: Vaddr = 0x0000_0000_1000_0000;
pub const USER_HEAP_SIZE_LIMIT: usize = PAGE_SIZE * 1000;
diff --git a/services/libs/jinux-std/src/process/program_loader/elf/init_stack.rs b/services/libs/aster-std/src/process/program_loader/elf/init_stack.rs
--- a/services/libs/jinux-std/src/process/program_loader/elf/init_stack.rs
+++ b/services/libs/aster-std/src/process/program_loader/elf/init_stack.rs
@@ -8,9 +8,9 @@ use crate::{
vm::{vmar::Vmar, vmo::VmoOptions},
};
use align_ext::AlignExt;
+use aster_frame::vm::{VmIo, VmPerm};
+use aster_rights::{Full, Rights};
use core::mem;
-use jinux_frame::vm::{VmIo, VmPerm};
-use jinux_rights::{Full, Rights};
use super::aux_vec::{AuxKey, AuxVec};
use super::elf_file::Elf;
diff --git a/services/libs/jinux-std/src/process/program_loader/elf/init_stack.rs b/services/libs/aster-std/src/process/program_loader/elf/init_stack.rs
--- a/services/libs/jinux-std/src/process/program_loader/elf/init_stack.rs
+++ b/services/libs/aster-std/src/process/program_loader/elf/init_stack.rs
@@ -8,9 +8,9 @@ use crate::{
vm::{vmar::Vmar, vmo::VmoOptions},
};
use align_ext::AlignExt;
+use aster_frame::vm::{VmIo, VmPerm};
+use aster_rights::{Full, Rights};
use core::mem;
-use jinux_frame::vm::{VmIo, VmPerm};
-use jinux_rights::{Full, Rights};
use super::aux_vec::{AuxKey, AuxVec};
use super::elf_file::Elf;
diff --git a/services/libs/jinux-std/src/process/program_loader/elf/load_elf.rs b/services/libs/aster-std/src/process/program_loader/elf/load_elf.rs
--- a/services/libs/jinux-std/src/process/program_loader/elf/load_elf.rs
+++ b/services/libs/aster-std/src/process/program_loader/elf/load_elf.rs
@@ -13,9 +13,9 @@ use crate::{
vm::{vmar::Vmar, vmo::Vmo},
};
use align_ext::AlignExt;
-use jinux_frame::task::Task;
-use jinux_frame::vm::{VmIo, VmPerm};
-use jinux_rights::{Full, Rights};
+use aster_frame::task::Task;
+use aster_frame::vm::{VmIo, VmPerm};
+use aster_rights::{Full, Rights};
use xmas_elf::program::{self, ProgramHeader64};
use super::elf_file::Elf;
diff --git a/services/libs/jinux-std/src/process/program_loader/elf/load_elf.rs b/services/libs/aster-std/src/process/program_loader/elf/load_elf.rs
--- a/services/libs/jinux-std/src/process/program_loader/elf/load_elf.rs
+++ b/services/libs/aster-std/src/process/program_loader/elf/load_elf.rs
@@ -13,9 +13,9 @@ use crate::{
vm::{vmar::Vmar, vmo::Vmo},
};
use align_ext::AlignExt;
-use jinux_frame::task::Task;
-use jinux_frame::vm::{VmIo, VmPerm};
-use jinux_rights::{Full, Rights};
+use aster_frame::task::Task;
+use aster_frame::vm::{VmIo, VmPerm};
+use aster_rights::{Full, Rights};
use xmas_elf::program::{self, ProgramHeader64};
use super::elf_file::Elf;
diff --git a/services/libs/jinux-std/src/process/signal/c_types.rs b/services/libs/aster-std/src/process/signal/c_types.rs
--- a/services/libs/jinux-std/src/process/signal/c_types.rs
+++ b/services/libs/aster-std/src/process/signal/c_types.rs
@@ -1,8 +1,8 @@
#![allow(non_camel_case_types)]
use core::mem;
-use jinux_frame::cpu::GeneralRegs;
-use jinux_util::{read_union_fields, union_read_ptr::UnionReadPtr};
+use aster_frame::cpu::GeneralRegs;
+use aster_util::{read_union_fields, union_read_ptr::UnionReadPtr};
use crate::{
prelude::*,
diff --git a/services/libs/jinux-std/src/process/signal/c_types.rs b/services/libs/aster-std/src/process/signal/c_types.rs
--- a/services/libs/jinux-std/src/process/signal/c_types.rs
+++ b/services/libs/aster-std/src/process/signal/c_types.rs
@@ -1,8 +1,8 @@
#![allow(non_camel_case_types)]
use core::mem;
-use jinux_frame::cpu::GeneralRegs;
-use jinux_util::{read_union_fields, union_read_ptr::UnionReadPtr};
+use aster_frame::cpu::GeneralRegs;
+use aster_util::{read_union_fields, union_read_ptr::UnionReadPtr};
use crate::{
prelude::*,
diff --git a/services/libs/jinux-std/src/process/signal/mod.rs b/services/libs/aster-std/src/process/signal/mod.rs
--- a/services/libs/jinux-std/src/process/signal/mod.rs
+++ b/services/libs/aster-std/src/process/signal/mod.rs
@@ -17,9 +17,9 @@ pub use poll::{Pollee, Poller};
pub use sig_stack::{SigStack, SigStackFlags, SigStackStatus};
use align_ext::AlignExt;
+use aster_frame::cpu::UserContext;
+use aster_frame::task::Task;
use core::mem;
-use jinux_frame::cpu::UserContext;
-use jinux_frame::task::Task;
use super::posix_thread::{PosixThread, PosixThreadExt};
use crate::prelude::*;
diff --git a/services/libs/jinux-std/src/process/signal/mod.rs b/services/libs/aster-std/src/process/signal/mod.rs
--- a/services/libs/jinux-std/src/process/signal/mod.rs
+++ b/services/libs/aster-std/src/process/signal/mod.rs
@@ -17,9 +17,9 @@ pub use poll::{Pollee, Poller};
pub use sig_stack::{SigStack, SigStackFlags, SigStackStatus};
use align_ext::AlignExt;
+use aster_frame::cpu::UserContext;
+use aster_frame::task::Task;
use core::mem;
-use jinux_frame::cpu::UserContext;
-use jinux_frame::task::Task;
use super::posix_thread::{PosixThread, PosixThreadExt};
use crate::prelude::*;
diff --git a/services/libs/jinux-std/src/process/signal/pauser.rs b/services/libs/aster-std/src/process/signal/pauser.rs
--- a/services/libs/jinux-std/src/process/signal/pauser.rs
+++ b/services/libs/aster-std/src/process/signal/pauser.rs
@@ -1,7 +1,7 @@
use core::sync::atomic::{AtomicBool, Ordering};
use core::time::Duration;
-use jinux_frame::sync::WaitQueue;
+use aster_frame::sync::WaitQueue;
use crate::events::Observer;
use crate::prelude::*;
diff --git a/services/libs/jinux-std/src/process/signal/pauser.rs b/services/libs/aster-std/src/process/signal/pauser.rs
--- a/services/libs/jinux-std/src/process/signal/pauser.rs
+++ b/services/libs/aster-std/src/process/signal/pauser.rs
@@ -1,7 +1,7 @@
use core::sync::atomic::{AtomicBool, Ordering};
use core::time::Duration;
-use jinux_frame::sync::WaitQueue;
+use aster_frame::sync::WaitQueue;
use crate::events::Observer;
use crate::prelude::*;
diff --git a/services/libs/jinux-std/src/process/signal/signals/fault.rs b/services/libs/aster-std/src/process/signal/signals/fault.rs
--- a/services/libs/jinux-std/src/process/signal/signals/fault.rs
+++ b/services/libs/aster-std/src/process/signal/signals/fault.rs
@@ -1,5 +1,5 @@
-use jinux_frame::cpu::{CpuException, CpuExceptionInfo};
-use jinux_frame::cpu::{
+use aster_frame::cpu::{CpuException, CpuExceptionInfo};
+use aster_frame::cpu::{
ALIGNMENT_CHECK, BOUND_RANGE_EXCEEDED, DIVIDE_BY_ZERO, GENERAL_PROTECTION_FAULT,
INVALID_OPCODE, PAGE_FAULT, SIMD_FLOATING_POINT_EXCEPTION, X87_FLOATING_POINT_EXCEPTION,
};
diff --git a/services/libs/jinux-std/src/process/signal/signals/fault.rs b/services/libs/aster-std/src/process/signal/signals/fault.rs
--- a/services/libs/jinux-std/src/process/signal/signals/fault.rs
+++ b/services/libs/aster-std/src/process/signal/signals/fault.rs
@@ -1,5 +1,5 @@
-use jinux_frame::cpu::{CpuException, CpuExceptionInfo};
-use jinux_frame::cpu::{
+use aster_frame::cpu::{CpuException, CpuExceptionInfo};
+use aster_frame::cpu::{
ALIGNMENT_CHECK, BOUND_RANGE_EXCEEDED, DIVIDE_BY_ZERO, GENERAL_PROTECTION_FAULT,
INVALID_OPCODE, PAGE_FAULT, SIMD_FLOATING_POINT_EXCEPTION, X87_FLOATING_POINT_EXCEPTION,
};
diff --git a/services/libs/jinux-std/src/sched/priority_scheduler.rs b/services/libs/aster-std/src/sched/priority_scheduler.rs
--- a/services/libs/jinux-std/src/sched/priority_scheduler.rs
+++ b/services/libs/aster-std/src/sched/priority_scheduler.rs
@@ -1,6 +1,6 @@
use crate::prelude::*;
+use aster_frame::task::{set_scheduler, Scheduler, Task, TaskAdapter};
use intrusive_collections::LinkedList;
-use jinux_frame::task::{set_scheduler, Scheduler, Task, TaskAdapter};
pub fn init() {
let preempt_scheduler = Box::new(PreemptScheduler::new());
diff --git a/services/libs/jinux-std/src/sched/priority_scheduler.rs b/services/libs/aster-std/src/sched/priority_scheduler.rs
--- a/services/libs/jinux-std/src/sched/priority_scheduler.rs
+++ b/services/libs/aster-std/src/sched/priority_scheduler.rs
@@ -1,6 +1,6 @@
use crate::prelude::*;
+use aster_frame::task::{set_scheduler, Scheduler, Task, TaskAdapter};
use intrusive_collections::LinkedList;
-use jinux_frame::task::{set_scheduler, Scheduler, Task, TaskAdapter};
pub fn init() {
let preempt_scheduler = Box::new(PreemptScheduler::new());
diff --git a/services/libs/jinux-std/src/syscall/arch_prctl.rs b/services/libs/aster-std/src/syscall/arch_prctl.rs
--- a/services/libs/jinux-std/src/syscall/arch_prctl.rs
+++ b/services/libs/aster-std/src/syscall/arch_prctl.rs
@@ -1,4 +1,4 @@
-use jinux_frame::cpu::UserContext;
+use aster_frame::cpu::UserContext;
use crate::syscall::SYS_ARCH_PRCTL;
use crate::{log_syscall_entry, prelude::*};
diff --git a/services/libs/jinux-std/src/syscall/arch_prctl.rs b/services/libs/aster-std/src/syscall/arch_prctl.rs
--- a/services/libs/jinux-std/src/syscall/arch_prctl.rs
+++ b/services/libs/aster-std/src/syscall/arch_prctl.rs
@@ -1,4 +1,4 @@
-use jinux_frame::cpu::UserContext;
+use aster_frame::cpu::UserContext;
use crate::syscall::SYS_ARCH_PRCTL;
use crate::{log_syscall_entry, prelude::*};
diff --git a/services/libs/jinux-std/src/syscall/clone.rs b/services/libs/aster-std/src/syscall/clone.rs
--- a/services/libs/jinux-std/src/syscall/clone.rs
+++ b/services/libs/aster-std/src/syscall/clone.rs
@@ -1,4 +1,4 @@
-use jinux_frame::cpu::UserContext;
+use aster_frame::cpu::UserContext;
use crate::log_syscall_entry;
use crate::process::{clone_child, CloneArgs, CloneFlags};
diff --git a/services/libs/jinux-std/src/syscall/clone.rs b/services/libs/aster-std/src/syscall/clone.rs
--- a/services/libs/jinux-std/src/syscall/clone.rs
+++ b/services/libs/aster-std/src/syscall/clone.rs
@@ -1,4 +1,4 @@
-use jinux_frame::cpu::UserContext;
+use aster_frame::cpu::UserContext;
use crate::log_syscall_entry;
use crate::process::{clone_child, CloneArgs, CloneFlags};
diff --git a/services/libs/jinux-std/src/syscall/execve.rs b/services/libs/aster-std/src/syscall/execve.rs
--- a/services/libs/jinux-std/src/syscall/execve.rs
+++ b/services/libs/aster-std/src/syscall/execve.rs
@@ -1,5 +1,5 @@
-use jinux_frame::cpu::UserContext;
-use jinux_rights::WriteOp;
+use aster_frame::cpu::UserContext;
+use aster_rights::WriteOp;
use super::{constants::*, SyscallReturn};
use crate::fs::file_table::FileDescripter;
diff --git a/services/libs/jinux-std/src/syscall/execve.rs b/services/libs/aster-std/src/syscall/execve.rs
--- a/services/libs/jinux-std/src/syscall/execve.rs
+++ b/services/libs/aster-std/src/syscall/execve.rs
@@ -1,5 +1,5 @@
-use jinux_frame::cpu::UserContext;
-use jinux_rights::WriteOp;
+use aster_frame::cpu::UserContext;
+use aster_rights::WriteOp;
use super::{constants::*, SyscallReturn};
use crate::fs::file_table::FileDescripter;
diff --git a/services/libs/jinux-std/src/syscall/fork.rs b/services/libs/aster-std/src/syscall/fork.rs
--- a/services/libs/jinux-std/src/syscall/fork.rs
+++ b/services/libs/aster-std/src/syscall/fork.rs
@@ -3,7 +3,7 @@ use crate::{
prelude::*,
process::{clone_child, CloneArgs},
};
-use jinux_frame::cpu::UserContext;
+use aster_frame::cpu::UserContext;
use crate::syscall::SYS_FORK;
diff --git a/services/libs/jinux-std/src/syscall/fork.rs b/services/libs/aster-std/src/syscall/fork.rs
--- a/services/libs/jinux-std/src/syscall/fork.rs
+++ b/services/libs/aster-std/src/syscall/fork.rs
@@ -3,7 +3,7 @@ use crate::{
prelude::*,
process::{clone_child, CloneArgs},
};
-use jinux_frame::cpu::UserContext;
+use aster_frame::cpu::UserContext;
use crate::syscall::SYS_FORK;
diff --git a/services/libs/jinux-std/src/syscall/mmap.rs b/services/libs/aster-std/src/syscall/mmap.rs
--- a/services/libs/jinux-std/src/syscall/mmap.rs
+++ b/services/libs/aster-std/src/syscall/mmap.rs
@@ -5,8 +5,8 @@ use crate::vm::perms::VmPerms;
use crate::vm::vmo::{VmoChildOptions, VmoOptions, VmoRightsOp};
use crate::{log_syscall_entry, prelude::*};
use align_ext::AlignExt;
-use jinux_frame::vm::VmPerm;
-use jinux_rights::Rights;
+use aster_frame::vm::VmPerm;
+use aster_rights::Rights;
use crate::syscall::SYS_MMAP;
diff --git a/services/libs/jinux-std/src/syscall/mmap.rs b/services/libs/aster-std/src/syscall/mmap.rs
--- a/services/libs/jinux-std/src/syscall/mmap.rs
+++ b/services/libs/aster-std/src/syscall/mmap.rs
@@ -5,8 +5,8 @@ use crate::vm::perms::VmPerms;
use crate::vm::vmo::{VmoChildOptions, VmoOptions, VmoRightsOp};
use crate::{log_syscall_entry, prelude::*};
use align_ext::AlignExt;
-use jinux_frame::vm::VmPerm;
-use jinux_rights::Rights;
+use aster_frame::vm::VmPerm;
+use aster_rights::Rights;
use crate::syscall::SYS_MMAP;
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/aster-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/aster-std/src/syscall/mod.rs
@@ -69,7 +69,7 @@ use crate::syscall::wait4::sys_wait4;
use crate::syscall::waitid::sys_waitid;
use crate::syscall::write::sys_write;
use crate::syscall::writev::sys_writev;
-use jinux_frame::cpu::UserContext;
+use aster_frame::cpu::UserContext;
use self::accept::sys_accept;
use self::bind::sys_bind;
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/aster-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/aster-std/src/syscall/mod.rs
@@ -69,7 +69,7 @@ use crate::syscall::wait4::sys_wait4;
use crate::syscall::waitid::sys_waitid;
use crate::syscall::write::sys_write;
use crate::syscall::writev::sys_writev;
-use jinux_frame::cpu::UserContext;
+use aster_frame::cpu::UserContext;
use self::accept::sys_accept;
use self::bind::sys_bind;
diff --git a/services/libs/jinux-std/src/syscall/rt_sigprocmask.rs b/services/libs/aster-std/src/syscall/rt_sigprocmask.rs
--- a/services/libs/jinux-std/src/syscall/rt_sigprocmask.rs
+++ b/services/libs/aster-std/src/syscall/rt_sigprocmask.rs
@@ -4,7 +4,7 @@ use crate::prelude::*;
use crate::process::posix_thread::PosixThreadExt;
use crate::process::signal::constants::{SIGKILL, SIGSTOP};
use crate::process::signal::sig_mask::SigMask;
-use jinux_frame::vm::VmIo;
+use aster_frame::vm::VmIo;
pub fn sys_rt_sigprocmask(
how: u32,
diff --git a/services/libs/jinux-std/src/syscall/rt_sigprocmask.rs b/services/libs/aster-std/src/syscall/rt_sigprocmask.rs
--- a/services/libs/jinux-std/src/syscall/rt_sigprocmask.rs
+++ b/services/libs/aster-std/src/syscall/rt_sigprocmask.rs
@@ -4,7 +4,7 @@ use crate::prelude::*;
use crate::process::posix_thread::PosixThreadExt;
use crate::process::signal::constants::{SIGKILL, SIGSTOP};
use crate::process::signal::sig_mask::SigMask;
-use jinux_frame::vm::VmIo;
+use aster_frame::vm::VmIo;
pub fn sys_rt_sigprocmask(
how: u32,
diff --git a/services/libs/jinux-std/src/syscall/rt_sigreturn.rs b/services/libs/aster-std/src/syscall/rt_sigreturn.rs
--- a/services/libs/jinux-std/src/syscall/rt_sigreturn.rs
+++ b/services/libs/aster-std/src/syscall/rt_sigreturn.rs
@@ -4,7 +4,7 @@ use crate::{
process::{posix_thread::PosixThreadExt, signal::c_types::ucontext_t},
util::read_val_from_user,
};
-use jinux_frame::cpu::UserContext;
+use aster_frame::cpu::UserContext;
use super::{SyscallReturn, SYS_RT_SIGRETRUN};
diff --git a/services/libs/jinux-std/src/syscall/rt_sigreturn.rs b/services/libs/aster-std/src/syscall/rt_sigreturn.rs
--- a/services/libs/jinux-std/src/syscall/rt_sigreturn.rs
+++ b/services/libs/aster-std/src/syscall/rt_sigreturn.rs
@@ -4,7 +4,7 @@ use crate::{
process::{posix_thread::PosixThreadExt, signal::c_types::ucontext_t},
util::read_val_from_user,
};
-use jinux_frame::cpu::UserContext;
+use aster_frame::cpu::UserContext;
use super::{SyscallReturn, SYS_RT_SIGRETRUN};
diff --git a/services/libs/jinux-std/src/thread/exception.rs b/services/libs/aster-std/src/thread/exception.rs
--- a/services/libs/jinux-std/src/thread/exception.rs
+++ b/services/libs/aster-std/src/thread/exception.rs
@@ -1,8 +1,8 @@
use crate::prelude::*;
use crate::process::signal::signals::fault::FaultSignal;
use crate::vm::page_fault_handler::PageFaultHandler;
-use jinux_frame::cpu::*;
-use jinux_frame::vm::VmIo;
+use aster_frame::cpu::*;
+use aster_frame::vm::VmIo;
/// We can't handle most exceptions, just send self a fault signal before return to user space.
pub fn handle_exception(context: &UserContext) {
diff --git a/services/libs/jinux-std/src/thread/exception.rs b/services/libs/aster-std/src/thread/exception.rs
--- a/services/libs/jinux-std/src/thread/exception.rs
+++ b/services/libs/aster-std/src/thread/exception.rs
@@ -1,8 +1,8 @@
use crate::prelude::*;
use crate::process::signal::signals::fault::FaultSignal;
use crate::vm::page_fault_handler::PageFaultHandler;
-use jinux_frame::cpu::*;
-use jinux_frame::vm::VmIo;
+use aster_frame::cpu::*;
+use aster_frame::vm::VmIo;
/// We can't handle most exceptions, just send self a fault signal before return to user space.
pub fn handle_exception(context: &UserContext) {
diff --git a/services/libs/jinux-std/src/thread/kernel_thread.rs b/services/libs/aster-std/src/thread/kernel_thread.rs
--- a/services/libs/jinux-std/src/thread/kernel_thread.rs
+++ b/services/libs/aster-std/src/thread/kernel_thread.rs
@@ -1,5 +1,5 @@
-use jinux_frame::cpu::CpuSet;
-use jinux_frame::task::{Priority, TaskOptions};
+use aster_frame::cpu::CpuSet;
+use aster_frame::task::{Priority, TaskOptions};
use crate::prelude::*;
diff --git a/services/libs/jinux-std/src/thread/kernel_thread.rs b/services/libs/aster-std/src/thread/kernel_thread.rs
--- a/services/libs/jinux-std/src/thread/kernel_thread.rs
+++ b/services/libs/aster-std/src/thread/kernel_thread.rs
@@ -1,5 +1,5 @@
-use jinux_frame::cpu::CpuSet;
-use jinux_frame::task::{Priority, TaskOptions};
+use aster_frame::cpu::CpuSet;
+use aster_frame::task::{Priority, TaskOptions};
use crate::prelude::*;
diff --git a/services/libs/jinux-std/src/thread/mod.rs b/services/libs/aster-std/src/thread/mod.rs
--- a/services/libs/jinux-std/src/thread/mod.rs
+++ b/services/libs/aster-std/src/thread/mod.rs
@@ -5,7 +5,7 @@ use core::{
sync::atomic::{AtomicU32, Ordering},
};
-use jinux_frame::task::Task;
+use aster_frame::task::Task;
use crate::prelude::*;
diff --git a/services/libs/jinux-std/src/thread/mod.rs b/services/libs/aster-std/src/thread/mod.rs
--- a/services/libs/jinux-std/src/thread/mod.rs
+++ b/services/libs/aster-std/src/thread/mod.rs
@@ -5,7 +5,7 @@ use core::{
sync::atomic::{AtomicU32, Ordering},
};
-use jinux_frame::task::Task;
+use aster_frame::task::Task;
use crate::prelude::*;
diff --git a/services/libs/jinux-std/src/thread/task.rs b/services/libs/aster-std/src/thread/task.rs
--- a/services/libs/jinux-std/src/thread/task.rs
+++ b/services/libs/aster-std/src/thread/task.rs
@@ -1,4 +1,4 @@
-use jinux_frame::{
+use aster_frame::{
cpu::UserContext,
task::{preempt, Task, TaskOptions},
user::{UserContextApi, UserEvent, UserMode, UserSpace},
diff --git a/services/libs/jinux-std/src/thread/task.rs b/services/libs/aster-std/src/thread/task.rs
--- a/services/libs/jinux-std/src/thread/task.rs
+++ b/services/libs/aster-std/src/thread/task.rs
@@ -1,4 +1,4 @@
-use jinux_frame::{
+use aster_frame::{
cpu::UserContext,
task::{preempt, Task, TaskOptions},
user::{UserContextApi, UserEvent, UserMode, UserSpace},
diff --git a/services/libs/jinux-std/src/thread/work_queue/mod.rs b/services/libs/aster-std/src/thread/work_queue/mod.rs
--- a/services/libs/jinux-std/src/thread/work_queue/mod.rs
+++ b/services/libs/aster-std/src/thread/work_queue/mod.rs
@@ -1,5 +1,5 @@
use crate::prelude::*;
-use jinux_frame::cpu::CpuSet;
+use aster_frame::cpu::CpuSet;
use spin::Once;
use work_item::WorkItem;
use worker_pool::WorkerPool;
diff --git a/services/libs/jinux-std/src/thread/work_queue/mod.rs b/services/libs/aster-std/src/thread/work_queue/mod.rs
--- a/services/libs/jinux-std/src/thread/work_queue/mod.rs
+++ b/services/libs/aster-std/src/thread/work_queue/mod.rs
@@ -1,5 +1,5 @@
use crate::prelude::*;
-use jinux_frame::cpu::CpuSet;
+use aster_frame::cpu::CpuSet;
use spin::Once;
use work_item::WorkItem;
use worker_pool::WorkerPool;
diff --git a/services/libs/jinux-std/src/thread/work_queue/mod.rs b/services/libs/aster-std/src/thread/work_queue/mod.rs
--- a/services/libs/jinux-std/src/thread/work_queue/mod.rs
+++ b/services/libs/aster-std/src/thread/work_queue/mod.rs
@@ -60,7 +60,7 @@ static WORKQUEUE_GLOBAL_HIGH_PRI: Once<Arc<WorkQueue>> = Once::new();
/// Certainly, users can also create a dedicated WorkQueue and WorkerPool.
///
/// ```rust
-/// use jinux_frame::cpu::CpuSet;
+/// use aster_frame::cpu::CpuSet;
/// use crate::thread::work_queue::{WorkQueue, WorkerPool, WorkItem};
///
/// fn deferred_task(){
diff --git a/services/libs/jinux-std/src/thread/work_queue/mod.rs b/services/libs/aster-std/src/thread/work_queue/mod.rs
--- a/services/libs/jinux-std/src/thread/work_queue/mod.rs
+++ b/services/libs/aster-std/src/thread/work_queue/mod.rs
@@ -60,7 +60,7 @@ static WORKQUEUE_GLOBAL_HIGH_PRI: Once<Arc<WorkQueue>> = Once::new();
/// Certainly, users can also create a dedicated WorkQueue and WorkerPool.
///
/// ```rust
-/// use jinux_frame::cpu::CpuSet;
+/// use aster_frame::cpu::CpuSet;
/// use crate::thread::work_queue::{WorkQueue, WorkerPool, WorkItem};
///
/// fn deferred_task(){
diff --git a/services/libs/jinux-std/src/thread/work_queue/work_item.rs b/services/libs/aster-std/src/thread/work_queue/work_item.rs
--- a/services/libs/jinux-std/src/thread/work_queue/work_item.rs
+++ b/services/libs/aster-std/src/thread/work_queue/work_item.rs
@@ -1,7 +1,7 @@
use crate::prelude::*;
+use aster_frame::cpu::CpuSet;
use core::sync::atomic::AtomicBool;
use core::sync::atomic::Ordering;
-use jinux_frame::cpu::CpuSet;
/// A task to be executed by a worker thread.
pub struct WorkItem {
diff --git a/services/libs/jinux-std/src/thread/work_queue/work_item.rs b/services/libs/aster-std/src/thread/work_queue/work_item.rs
--- a/services/libs/jinux-std/src/thread/work_queue/work_item.rs
+++ b/services/libs/aster-std/src/thread/work_queue/work_item.rs
@@ -1,7 +1,7 @@
use crate::prelude::*;
+use aster_frame::cpu::CpuSet;
use core::sync::atomic::AtomicBool;
use core::sync::atomic::Ordering;
-use jinux_frame::cpu::CpuSet;
/// A task to be executed by a worker thread.
pub struct WorkItem {
diff --git a/services/libs/jinux-std/src/thread/work_queue/worker.rs b/services/libs/aster-std/src/thread/work_queue/worker.rs
--- a/services/libs/jinux-std/src/thread/work_queue/worker.rs
+++ b/services/libs/aster-std/src/thread/work_queue/worker.rs
@@ -2,8 +2,8 @@ use super::worker_pool::WorkerPool;
use crate::prelude::*;
use crate::thread::kernel_thread::{KernelThreadExt, ThreadOptions};
use crate::Thread;
-use jinux_frame::cpu::CpuSet;
-use jinux_frame::task::Priority;
+use aster_frame::cpu::CpuSet;
+use aster_frame::task::Priority;
/// A worker thread. A `Worker` will attempt to retrieve unfinished
/// work items from its corresponding `WorkerPool`. If there are none,
diff --git a/services/libs/jinux-std/src/thread/work_queue/worker.rs b/services/libs/aster-std/src/thread/work_queue/worker.rs
--- a/services/libs/jinux-std/src/thread/work_queue/worker.rs
+++ b/services/libs/aster-std/src/thread/work_queue/worker.rs
@@ -2,8 +2,8 @@ use super::worker_pool::WorkerPool;
use crate::prelude::*;
use crate::thread::kernel_thread::{KernelThreadExt, ThreadOptions};
use crate::Thread;
-use jinux_frame::cpu::CpuSet;
-use jinux_frame::task::Priority;
+use aster_frame::cpu::CpuSet;
+use aster_frame::task::Priority;
/// A worker thread. A `Worker` will attempt to retrieve unfinished
/// work items from its corresponding `WorkerPool`. If there are none,
diff --git a/services/libs/jinux-std/src/thread/work_queue/worker_pool.rs b/services/libs/aster-std/src/thread/work_queue/worker_pool.rs
--- a/services/libs/jinux-std/src/thread/work_queue/worker_pool.rs
+++ b/services/libs/aster-std/src/thread/work_queue/worker_pool.rs
@@ -4,9 +4,9 @@ use super::{simple_scheduler::SimpleScheduler, worker::Worker, WorkItem, WorkPri
use crate::prelude::*;
use crate::thread::kernel_thread::{KernelThreadExt, ThreadOptions};
use crate::Thread;
-use jinux_frame::cpu::CpuSet;
-use jinux_frame::sync::WaitQueue;
-use jinux_frame::task::Priority;
+use aster_frame::cpu::CpuSet;
+use aster_frame::sync::WaitQueue;
+use aster_frame::task::Priority;
/// A pool of workers.
///
diff --git a/services/libs/jinux-std/src/thread/work_queue/worker_pool.rs b/services/libs/aster-std/src/thread/work_queue/worker_pool.rs
--- a/services/libs/jinux-std/src/thread/work_queue/worker_pool.rs
+++ b/services/libs/aster-std/src/thread/work_queue/worker_pool.rs
@@ -4,9 +4,9 @@ use super::{simple_scheduler::SimpleScheduler, worker::Worker, WorkItem, WorkPri
use crate::prelude::*;
use crate::thread::kernel_thread::{KernelThreadExt, ThreadOptions};
use crate::Thread;
-use jinux_frame::cpu::CpuSet;
-use jinux_frame::sync::WaitQueue;
-use jinux_frame::task::Priority;
+use aster_frame::cpu::CpuSet;
+use aster_frame::sync::WaitQueue;
+use aster_frame::task::Priority;
/// A pool of workers.
///
diff --git a/services/libs/jinux-std/src/time/mod.rs b/services/libs/aster-std/src/time/mod.rs
--- a/services/libs/jinux-std/src/time/mod.rs
+++ b/services/libs/aster-std/src/time/mod.rs
@@ -3,7 +3,7 @@ use core::time::Duration;
use crate::prelude::*;
-use jinux_time::read_monotonic_time;
+use aster_time::read_monotonic_time;
mod system_time;
diff --git a/services/libs/jinux-std/src/time/mod.rs b/services/libs/aster-std/src/time/mod.rs
--- a/services/libs/jinux-std/src/time/mod.rs
+++ b/services/libs/aster-std/src/time/mod.rs
@@ -3,7 +3,7 @@ use core::time::Duration;
use crate::prelude::*;
-use jinux_time::read_monotonic_time;
+use aster_time::read_monotonic_time;
mod system_time;
diff --git a/services/libs/jinux-std/src/time/system_time.rs b/services/libs/aster-std/src/time/system_time.rs
--- a/services/libs/jinux-std/src/time/system_time.rs
+++ b/services/libs/aster-std/src/time/system_time.rs
@@ -1,5 +1,5 @@
+use aster_time::{read_monotonic_time, read_start_time};
use core::time::Duration;
-use jinux_time::{read_monotonic_time, read_start_time};
use time::{Date, Month, PrimitiveDateTime, Time};
use crate::prelude::*;
diff --git a/services/libs/jinux-std/src/time/system_time.rs b/services/libs/aster-std/src/time/system_time.rs
--- a/services/libs/jinux-std/src/time/system_time.rs
+++ b/services/libs/aster-std/src/time/system_time.rs
@@ -1,5 +1,5 @@
+use aster_time::{read_monotonic_time, read_start_time};
use core::time::Duration;
-use jinux_time::{read_monotonic_time, read_start_time};
use time::{Date, Month, PrimitiveDateTime, Time};
use crate::prelude::*;
diff --git a/services/libs/jinux-std/src/time/system_time.rs b/services/libs/aster-std/src/time/system_time.rs
--- a/services/libs/jinux-std/src/time/system_time.rs
+++ b/services/libs/aster-std/src/time/system_time.rs
@@ -68,8 +68,8 @@ impl SystemTime {
}
}
-/// convert jinux_frame::time::Time to System time
-fn convert_system_time(system_time: jinux_time::SystemTime) -> Result<SystemTime> {
+/// convert aster_frame::time::Time to System time
+fn convert_system_time(system_time: aster_time::SystemTime) -> Result<SystemTime> {
let month = match Month::try_from(system_time.month) {
Ok(month) => month,
Err(_) => return_errno_with_message!(Errno::EINVAL, "unknown month in system time"),
diff --git a/services/libs/jinux-std/src/time/system_time.rs b/services/libs/aster-std/src/time/system_time.rs
--- a/services/libs/jinux-std/src/time/system_time.rs
+++ b/services/libs/aster-std/src/time/system_time.rs
@@ -68,8 +68,8 @@ impl SystemTime {
}
}
-/// convert jinux_frame::time::Time to System time
-fn convert_system_time(system_time: jinux_time::SystemTime) -> Result<SystemTime> {
+/// convert aster_frame::time::Time to System time
+fn convert_system_time(system_time: aster_time::SystemTime) -> Result<SystemTime> {
let month = match Month::try_from(system_time.month) {
Ok(month) => month,
Err(_) => return_errno_with_message!(Errno::EINVAL, "unknown month in system time"),
diff --git a/services/libs/jinux-std/src/util/mod.rs b/services/libs/aster-std/src/util/mod.rs
--- a/services/libs/jinux-std/src/util/mod.rs
+++ b/services/libs/aster-std/src/util/mod.rs
@@ -1,5 +1,5 @@
use crate::prelude::*;
-use jinux_frame::vm::VmIo;
+use aster_frame::vm::VmIo;
pub mod net;
/// copy bytes from user space of current process. The bytes len is the len of dest.
diff --git a/services/libs/jinux-std/src/util/mod.rs b/services/libs/aster-std/src/util/mod.rs
--- a/services/libs/jinux-std/src/util/mod.rs
+++ b/services/libs/aster-std/src/util/mod.rs
@@ -1,5 +1,5 @@
use crate::prelude::*;
-use jinux_frame::vm::VmIo;
+use aster_frame::vm::VmIo;
pub mod net;
/// copy bytes from user space of current process. The bytes len is the len of dest.
diff --git a/services/libs/jinux-std/src/vdso.rs b/services/libs/aster-std/src/vdso.rs
--- a/services/libs/jinux-std/src/vdso.rs
+++ b/services/libs/aster-std/src/vdso.rs
@@ -11,10 +11,10 @@
use alloc::boxed::Box;
use alloc::sync::Arc;
-use jinux_frame::{config::PAGE_SIZE, sync::Mutex, vm::VmIo};
-use jinux_rights::Rights;
-use jinux_time::Instant;
-use jinux_util::coeff::Coeff;
+use aster_frame::{config::PAGE_SIZE, sync::Mutex, vm::VmIo};
+use aster_rights::Rights;
+use aster_time::Instant;
+use aster_util::coeff::Coeff;
use pod::Pod;
use spin::Once;
diff --git a/services/libs/jinux-std/src/vdso.rs b/services/libs/aster-std/src/vdso.rs
--- a/services/libs/jinux-std/src/vdso.rs
+++ b/services/libs/aster-std/src/vdso.rs
@@ -11,10 +11,10 @@
use alloc::boxed::Box;
use alloc::sync::Arc;
-use jinux_frame::{config::PAGE_SIZE, sync::Mutex, vm::VmIo};
-use jinux_rights::Rights;
-use jinux_time::Instant;
-use jinux_util::coeff::Coeff;
+use aster_frame::{config::PAGE_SIZE, sync::Mutex, vm::VmIo};
+use aster_rights::Rights;
+use aster_time::Instant;
+use aster_util::coeff::Coeff;
use pod::Pod;
use spin::Once;
diff --git a/services/libs/jinux-std/src/vdso.rs b/services/libs/aster-std/src/vdso.rs
--- a/services/libs/jinux-std/src/vdso.rs
+++ b/services/libs/aster-std/src/vdso.rs
@@ -108,7 +108,7 @@ impl VdsoData {
/// Init vdso data based on the default clocksource.
fn init(&mut self) {
- let clocksource = jinux_time::default_clocksource();
+ let clocksource = aster_time::default_clocksource();
let coeff = clocksource.coeff();
self.set_clock_mode(DEFAULT_CLOCK_MODE);
self.set_coeff(coeff);
diff --git a/services/libs/jinux-std/src/vdso.rs b/services/libs/aster-std/src/vdso.rs
--- a/services/libs/jinux-std/src/vdso.rs
+++ b/services/libs/aster-std/src/vdso.rs
@@ -108,7 +108,7 @@ impl VdsoData {
/// Init vdso data based on the default clocksource.
fn init(&mut self) {
- let clocksource = jinux_time::default_clocksource();
+ let clocksource = aster_time::default_clocksource();
let coeff = clocksource.coeff();
self.set_clock_mode(DEFAULT_CLOCK_MODE);
self.set_coeff(coeff);
diff --git a/services/libs/jinux-std/src/vdso.rs b/services/libs/aster-std/src/vdso.rs
--- a/services/libs/jinux-std/src/vdso.rs
+++ b/services/libs/aster-std/src/vdso.rs
@@ -249,7 +249,7 @@ fn init_vdso() {
pub(super) fn init() {
init_start_secs_count();
init_vdso();
- jinux_time::VDSO_DATA_UPDATE.call_once(|| Arc::new(update_vdso_instant));
+ aster_time::VDSO_DATA_UPDATE.call_once(|| Arc::new(update_vdso_instant));
}
/// Return the vdso vmo.
diff --git a/services/libs/jinux-std/src/vdso.rs b/services/libs/aster-std/src/vdso.rs
--- a/services/libs/jinux-std/src/vdso.rs
+++ b/services/libs/aster-std/src/vdso.rs
@@ -249,7 +249,7 @@ fn init_vdso() {
pub(super) fn init() {
init_start_secs_count();
init_vdso();
- jinux_time::VDSO_DATA_UPDATE.call_once(|| Arc::new(update_vdso_instant));
+ aster_time::VDSO_DATA_UPDATE.call_once(|| Arc::new(update_vdso_instant));
}
/// Return the vdso vmo.
diff --git a/services/libs/jinux-std/src/vm/mod.rs b/services/libs/aster-std/src/vm/mod.rs
--- a/services/libs/jinux-std/src/vm/mod.rs
+++ b/services/libs/aster-std/src/vm/mod.rs
@@ -10,8 +10,8 @@
//! [Zircon](https://fuchsia.dev/fuchsia-src/reference/kernel_objects/vm_object).
//! As capabilities, the two abstractions are aligned with our goal
//! of everything-is-a-capability, although their specifications and
-//! implementations in C/C++ cannot apply directly to Jinux.
-//! In Jinux, VMARs and VMOs, as well as other capabilities, are implemented
+//! implementations in C/C++ cannot apply directly to Asterinas.
+//! In Asterinas, VMARs and VMOs, as well as other capabilities, are implemented
//! as zero-cost capabilities.
pub mod page_fault_handler;
diff --git a/services/libs/jinux-std/src/vm/mod.rs b/services/libs/aster-std/src/vm/mod.rs
--- a/services/libs/jinux-std/src/vm/mod.rs
+++ b/services/libs/aster-std/src/vm/mod.rs
@@ -10,8 +10,8 @@
//! [Zircon](https://fuchsia.dev/fuchsia-src/reference/kernel_objects/vm_object).
//! As capabilities, the two abstractions are aligned with our goal
//! of everything-is-a-capability, although their specifications and
-//! implementations in C/C++ cannot apply directly to Jinux.
-//! In Jinux, VMARs and VMOs, as well as other capabilities, are implemented
+//! implementations in C/C++ cannot apply directly to Asterinas.
+//! In Asterinas, VMARs and VMOs, as well as other capabilities, are implemented
//! as zero-cost capabilities.
pub mod page_fault_handler;
diff --git a/services/libs/jinux-std/src/vm/perms.rs b/services/libs/aster-std/src/vm/perms.rs
--- a/services/libs/jinux-std/src/vm/perms.rs
+++ b/services/libs/aster-std/src/vm/perms.rs
@@ -1,6 +1,6 @@
+use aster_frame::vm::VmPerm;
+use aster_rights::Rights;
use bitflags::bitflags;
-use jinux_frame::vm::VmPerm;
-use jinux_rights::Rights;
bitflags! {
/// The memory access permissions of memory mappings.
diff --git a/services/libs/jinux-std/src/vm/perms.rs b/services/libs/aster-std/src/vm/perms.rs
--- a/services/libs/jinux-std/src/vm/perms.rs
+++ b/services/libs/aster-std/src/vm/perms.rs
@@ -1,6 +1,6 @@
+use aster_frame::vm::VmPerm;
+use aster_rights::Rights;
use bitflags::bitflags;
-use jinux_frame::vm::VmPerm;
-use jinux_rights::Rights;
bitflags! {
/// The memory access permissions of memory mappings.
diff --git a/services/libs/jinux-std/src/vm/vmar/dyn_cap.rs b/services/libs/aster-std/src/vm/vmar/dyn_cap.rs
--- a/services/libs/jinux-std/src/vm/vmar/dyn_cap.rs
+++ b/services/libs/aster-std/src/vm/vmar/dyn_cap.rs
@@ -1,6 +1,6 @@
+use aster_frame::vm::{Vaddr, VmIo};
+use aster_rights::Rights;
use core::ops::Range;
-use jinux_frame::vm::{Vaddr, VmIo};
-use jinux_rights::Rights;
use crate::prelude::*;
diff --git a/services/libs/jinux-std/src/vm/vmar/dyn_cap.rs b/services/libs/aster-std/src/vm/vmar/dyn_cap.rs
--- a/services/libs/jinux-std/src/vm/vmar/dyn_cap.rs
+++ b/services/libs/aster-std/src/vm/vmar/dyn_cap.rs
@@ -1,6 +1,6 @@
+use aster_frame::vm::{Vaddr, VmIo};
+use aster_rights::Rights;
use core::ops::Range;
-use jinux_frame::vm::{Vaddr, VmIo};
-use jinux_rights::Rights;
use crate::prelude::*;
diff --git a/services/libs/jinux-std/src/vm/vmar/dyn_cap.rs b/services/libs/aster-std/src/vm/vmar/dyn_cap.rs
--- a/services/libs/jinux-std/src/vm/vmar/dyn_cap.rs
+++ b/services/libs/aster-std/src/vm/vmar/dyn_cap.rs
@@ -23,8 +23,8 @@ impl Vmar<Rights> {
/// # Example
///
/// ```
- /// use jinux_std::prelude::*;
- /// use jinux_std::vm::{PAGE_SIZE, Vmar, VmoOptions};
+ /// use aster_std::prelude::*;
+ /// use aster_std::vm::{PAGE_SIZE, Vmar, VmoOptions};
///
/// let vmar = Vmar::new().unwrap();
/// let vmo = VmoOptions::new(PAGE_SIZE).alloc().unwrap();
diff --git a/services/libs/jinux-std/src/vm/vmar/dyn_cap.rs b/services/libs/aster-std/src/vm/vmar/dyn_cap.rs
--- a/services/libs/jinux-std/src/vm/vmar/dyn_cap.rs
+++ b/services/libs/aster-std/src/vm/vmar/dyn_cap.rs
@@ -23,8 +23,8 @@ impl Vmar<Rights> {
/// # Example
///
/// ```
- /// use jinux_std::prelude::*;
- /// use jinux_std::vm::{PAGE_SIZE, Vmar, VmoOptions};
+ /// use aster_std::prelude::*;
+ /// use aster_std::vm::{PAGE_SIZE, Vmar, VmoOptions};
///
/// let vmar = Vmar::new().unwrap();
/// let vmo = VmoOptions::new(PAGE_SIZE).alloc().unwrap();
diff --git a/services/libs/jinux-std/src/vm/vmar/dyn_cap.rs b/services/libs/aster-std/src/vm/vmar/dyn_cap.rs
--- a/services/libs/jinux-std/src/vm/vmar/dyn_cap.rs
+++ b/services/libs/aster-std/src/vm/vmar/dyn_cap.rs
@@ -156,13 +156,13 @@ impl Vmar<Rights> {
}
impl VmIo for Vmar<Rights> {
- fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> jinux_frame::Result<()> {
+ fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> aster_frame::Result<()> {
self.check_rights(Rights::READ)?;
self.0.read(offset, buf)?;
Ok(())
}
- fn write_bytes(&self, offset: usize, buf: &[u8]) -> jinux_frame::Result<()> {
+ fn write_bytes(&self, offset: usize, buf: &[u8]) -> aster_frame::Result<()> {
self.check_rights(Rights::WRITE)?;
self.0.write(offset, buf)?;
Ok(())
diff --git a/services/libs/jinux-std/src/vm/vmar/dyn_cap.rs b/services/libs/aster-std/src/vm/vmar/dyn_cap.rs
--- a/services/libs/jinux-std/src/vm/vmar/dyn_cap.rs
+++ b/services/libs/aster-std/src/vm/vmar/dyn_cap.rs
@@ -156,13 +156,13 @@ impl Vmar<Rights> {
}
impl VmIo for Vmar<Rights> {
- fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> jinux_frame::Result<()> {
+ fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> aster_frame::Result<()> {
self.check_rights(Rights::READ)?;
self.0.read(offset, buf)?;
Ok(())
}
- fn write_bytes(&self, offset: usize, buf: &[u8]) -> jinux_frame::Result<()> {
+ fn write_bytes(&self, offset: usize, buf: &[u8]) -> aster_frame::Result<()> {
self.check_rights(Rights::WRITE)?;
self.0.write(offset, buf)?;
Ok(())
diff --git a/services/libs/jinux-std/src/vm/vmar/mod.rs b/services/libs/aster-std/src/vm/vmar/mod.rs
--- a/services/libs/jinux-std/src/vm/vmar/mod.rs
+++ b/services/libs/aster-std/src/vm/vmar/mod.rs
@@ -12,9 +12,9 @@ use alloc::collections::BTreeMap;
use alloc::sync::Arc;
use alloc::sync::Weak;
use alloc::vec::Vec;
+use aster_frame::vm::VmSpace;
+use aster_rights::Rights;
use core::ops::Range;
-use jinux_frame::vm::VmSpace;
-use jinux_rights::Rights;
use self::vm_mapping::VmMapping;
diff --git a/services/libs/jinux-std/src/vm/vmar/mod.rs b/services/libs/aster-std/src/vm/vmar/mod.rs
--- a/services/libs/jinux-std/src/vm/vmar/mod.rs
+++ b/services/libs/aster-std/src/vm/vmar/mod.rs
@@ -12,9 +12,9 @@ use alloc::collections::BTreeMap;
use alloc::sync::Arc;
use alloc::sync::Weak;
use alloc::vec::Vec;
+use aster_frame::vm::VmSpace;
+use aster_rights::Rights;
use core::ops::Range;
-use jinux_frame::vm::VmSpace;
-use jinux_rights::Rights;
use self::vm_mapping::VmMapping;
diff --git a/services/libs/jinux-std/src/vm/vmar/options.rs b/services/libs/aster-std/src/vm/vmar/options.rs
--- a/services/libs/jinux-std/src/vm/vmar/options.rs
+++ b/services/libs/aster-std/src/vm/vmar/options.rs
@@ -1,7 +1,7 @@
//! Options for allocating child VMARs.
-use jinux_frame::config::PAGE_SIZE;
-use jinux_frame::{Error, Result};
+use aster_frame::config::PAGE_SIZE;
+use aster_frame::{Error, Result};
use super::Vmar;
diff --git a/services/libs/jinux-std/src/vm/vmar/options.rs b/services/libs/aster-std/src/vm/vmar/options.rs
--- a/services/libs/jinux-std/src/vm/vmar/options.rs
+++ b/services/libs/aster-std/src/vm/vmar/options.rs
@@ -1,7 +1,7 @@
//! Options for allocating child VMARs.
-use jinux_frame::config::PAGE_SIZE;
-use jinux_frame::{Error, Result};
+use aster_frame::config::PAGE_SIZE;
+use aster_frame::{Error, Result};
use super::Vmar;
diff --git a/services/libs/jinux-std/src/vm/vmar/options.rs b/services/libs/aster-std/src/vm/vmar/options.rs
--- a/services/libs/jinux-std/src/vm/vmar/options.rs
+++ b/services/libs/aster-std/src/vm/vmar/options.rs
@@ -13,7 +13,7 @@ use super::Vmar;
/// A child VMAR created from a parent VMAR of _dynamic_ capability is also a
/// _dynamic_ capability.
/// ```
-/// use jinux_std::vm::{PAGE_SIZE, Vmar};
+/// use aster_std::vm::{PAGE_SIZE, Vmar};
///
/// let parent_vmar = Vmar::new();
/// let child_size = 10 * PAGE_SIZE;
diff --git a/services/libs/jinux-std/src/vm/vmar/options.rs b/services/libs/aster-std/src/vm/vmar/options.rs
--- a/services/libs/jinux-std/src/vm/vmar/options.rs
+++ b/services/libs/aster-std/src/vm/vmar/options.rs
@@ -13,7 +13,7 @@ use super::Vmar;
/// A child VMAR created from a parent VMAR of _dynamic_ capability is also a
/// _dynamic_ capability.
/// ```
-/// use jinux_std::vm::{PAGE_SIZE, Vmar};
+/// use aster_std::vm::{PAGE_SIZE, Vmar};
///
/// let parent_vmar = Vmar::new();
/// let child_size = 10 * PAGE_SIZE;
diff --git a/services/libs/jinux-std/src/vm/vmar/options.rs b/services/libs/aster-std/src/vm/vmar/options.rs
--- a/services/libs/jinux-std/src/vm/vmar/options.rs
+++ b/services/libs/aster-std/src/vm/vmar/options.rs
@@ -28,8 +28,8 @@ use super::Vmar;
/// A child VMAR created from a parent VMAR of _static_ capability is also a
/// _static_ capability.
/// ```
-/// use jinux_std::prelude::*;
-/// use jinux_std::vm::{PAGE_SIZE, Vmar};
+/// use aster_std::prelude::*;
+/// use aster_std::vm::{PAGE_SIZE, Vmar};
///
/// let parent_vmar: Vmar<Full> = Vmar::new();
/// let child_size = 10 * PAGE_SIZE;
diff --git a/services/libs/jinux-std/src/vm/vmar/options.rs b/services/libs/aster-std/src/vm/vmar/options.rs
--- a/services/libs/jinux-std/src/vm/vmar/options.rs
+++ b/services/libs/aster-std/src/vm/vmar/options.rs
@@ -28,8 +28,8 @@ use super::Vmar;
/// A child VMAR created from a parent VMAR of _static_ capability is also a
/// _static_ capability.
/// ```
-/// use jinux_std::prelude::*;
-/// use jinux_std::vm::{PAGE_SIZE, Vmar};
+/// use aster_std::prelude::*;
+/// use aster_std::vm::{PAGE_SIZE, Vmar};
///
/// let parent_vmar: Vmar<Full> = Vmar::new();
/// let child_size = 10 * PAGE_SIZE;
diff --git a/services/libs/jinux-std/src/vm/vmar/options.rs b/services/libs/aster-std/src/vm/vmar/options.rs
--- a/services/libs/jinux-std/src/vm/vmar/options.rs
+++ b/services/libs/aster-std/src/vm/vmar/options.rs
@@ -139,8 +139,8 @@ mod test {
use crate::vm::perms::VmPerms;
use crate::vm::vmo::VmoRightsOp;
use crate::vm::{vmar::ROOT_VMAR_HIGHEST_ADDR, vmo::VmoOptions};
- use jinux_frame::vm::VmIo;
- use jinux_rights::Full;
+ use aster_frame::vm::VmIo;
+ use aster_rights::Full;
#[ktest]
fn root_vmar() {
diff --git a/services/libs/jinux-std/src/vm/vmar/static_cap.rs b/services/libs/aster-std/src/vm/vmar/static_cap.rs
--- a/services/libs/jinux-std/src/vm/vmar/static_cap.rs
+++ b/services/libs/aster-std/src/vm/vmar/static_cap.rs
@@ -1,9 +1,9 @@
use core::ops::Range;
use crate::prelude::*;
-use jinux_frame::vm::VmIo;
-use jinux_rights::{Dup, Rights, TRightSet, TRights};
-use jinux_rights_proc::require;
+use aster_frame::vm::VmIo;
+use aster_rights::{Dup, Rights, TRightSet, TRights};
+use aster_rights_proc::require;
use crate::vm::{page_fault_handler::PageFaultHandler, vmo::Vmo};
diff --git a/services/libs/jinux-std/src/vm/vmar/static_cap.rs b/services/libs/aster-std/src/vm/vmar/static_cap.rs
--- a/services/libs/jinux-std/src/vm/vmar/static_cap.rs
+++ b/services/libs/aster-std/src/vm/vmar/static_cap.rs
@@ -1,9 +1,9 @@
use core::ops::Range;
use crate::prelude::*;
-use jinux_frame::vm::VmIo;
-use jinux_rights::{Dup, Rights, TRightSet, TRights};
-use jinux_rights_proc::require;
+use aster_frame::vm::VmIo;
+use aster_rights::{Dup, Rights, TRightSet, TRights};
+use aster_rights_proc::require;
use crate::vm::{page_fault_handler::PageFaultHandler, vmo::Vmo};
diff --git a/services/libs/jinux-std/src/vm/vmar/static_cap.rs b/services/libs/aster-std/src/vm/vmar/static_cap.rs
--- a/services/libs/jinux-std/src/vm/vmar/static_cap.rs
+++ b/services/libs/aster-std/src/vm/vmar/static_cap.rs
@@ -28,8 +28,8 @@ impl<R: TRights> Vmar<TRightSet<R>> {
/// # Example
///
/// ```
- /// use jinux_std::prelude::*;
- /// use jinux_std::vm::{PAGE_SIZE, Vmar, VmoOptions};
+ /// use aster_std::prelude::*;
+ /// use aster_std::vm::{PAGE_SIZE, Vmar, VmoOptions};
///
/// let vmar = Vmar::<RightsWrapper<Full>>::new().unwrap();
/// let vmo = VmoOptions::new(PAGE_SIZE).alloc().unwrap();
diff --git a/services/libs/jinux-std/src/vm/vmar/static_cap.rs b/services/libs/aster-std/src/vm/vmar/static_cap.rs
--- a/services/libs/jinux-std/src/vm/vmar/static_cap.rs
+++ b/services/libs/aster-std/src/vm/vmar/static_cap.rs
@@ -28,8 +28,8 @@ impl<R: TRights> Vmar<TRightSet<R>> {
/// # Example
///
/// ```
- /// use jinux_std::prelude::*;
- /// use jinux_std::vm::{PAGE_SIZE, Vmar, VmoOptions};
+ /// use aster_std::prelude::*;
+ /// use aster_std::vm::{PAGE_SIZE, Vmar, VmoOptions};
///
/// let vmar = Vmar::<RightsWrapper<Full>>::new().unwrap();
/// let vmo = VmoOptions::new(PAGE_SIZE).alloc().unwrap();
diff --git a/services/libs/jinux-std/src/vm/vmar/static_cap.rs b/services/libs/aster-std/src/vm/vmar/static_cap.rs
--- a/services/libs/jinux-std/src/vm/vmar/static_cap.rs
+++ b/services/libs/aster-std/src/vm/vmar/static_cap.rs
@@ -177,13 +177,13 @@ impl<R: TRights> Vmar<TRightSet<R>> {
}
impl<R: TRights> VmIo for Vmar<TRightSet<R>> {
- fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> jinux_frame::Result<()> {
+ fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> aster_frame::Result<()> {
self.check_rights(Rights::READ)?;
self.0.read(offset, buf)?;
Ok(())
}
- fn write_bytes(&self, offset: usize, buf: &[u8]) -> jinux_frame::Result<()> {
+ fn write_bytes(&self, offset: usize, buf: &[u8]) -> aster_frame::Result<()> {
self.check_rights(Rights::WRITE)?;
self.0.write(offset, buf)?;
Ok(())
diff --git a/services/libs/jinux-std/src/vm/vmar/static_cap.rs b/services/libs/aster-std/src/vm/vmar/static_cap.rs
--- a/services/libs/jinux-std/src/vm/vmar/static_cap.rs
+++ b/services/libs/aster-std/src/vm/vmar/static_cap.rs
@@ -177,13 +177,13 @@ impl<R: TRights> Vmar<TRightSet<R>> {
}
impl<R: TRights> VmIo for Vmar<TRightSet<R>> {
- fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> jinux_frame::Result<()> {
+ fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> aster_frame::Result<()> {
self.check_rights(Rights::READ)?;
self.0.read(offset, buf)?;
Ok(())
}
- fn write_bytes(&self, offset: usize, buf: &[u8]) -> jinux_frame::Result<()> {
+ fn write_bytes(&self, offset: usize, buf: &[u8]) -> aster_frame::Result<()> {
self.check_rights(Rights::WRITE)?;
self.0.write(offset, buf)?;
Ok(())
diff --git a/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs b/services/libs/aster-std/src/vm/vmar/vm_mapping.rs
--- a/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
+++ b/services/libs/aster-std/src/vm/vmar/vm_mapping.rs
@@ -1,7 +1,7 @@
use crate::prelude::*;
+use aster_frame::sync::Mutex;
+use aster_frame::vm::{VmFrame, VmFrameVec, VmIo, VmMapOptions, VmPerm, VmSpace};
use core::ops::Range;
-use jinux_frame::sync::Mutex;
-use jinux_frame::vm::{VmFrame, VmFrameVec, VmIo, VmMapOptions, VmPerm, VmSpace};
use crate::vm::{
vmo::get_page_idx_range,
diff --git a/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs b/services/libs/aster-std/src/vm/vmar/vm_mapping.rs
--- a/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
+++ b/services/libs/aster-std/src/vm/vmar/vm_mapping.rs
@@ -1,7 +1,7 @@
use crate::prelude::*;
+use aster_frame::sync::Mutex;
+use aster_frame::vm::{VmFrame, VmFrameVec, VmIo, VmMapOptions, VmPerm, VmSpace};
use core::ops::Range;
-use jinux_frame::sync::Mutex;
-use jinux_frame::vm::{VmFrame, VmFrameVec, VmIo, VmMapOptions, VmPerm, VmSpace};
use crate::vm::{
vmo::get_page_idx_range,
diff --git a/services/libs/jinux-std/src/vm/vmo/dyn_cap.rs b/services/libs/aster-std/src/vm/vmo/dyn_cap.rs
--- a/services/libs/jinux-std/src/vm/vmo/dyn_cap.rs
+++ b/services/libs/aster-std/src/vm/vmo/dyn_cap.rs
@@ -2,9 +2,9 @@ use core::ops::Range;
use crate::prelude::*;
-use jinux_frame::vm::VmIo;
+use aster_frame::vm::VmIo;
-use jinux_rights::{Rights, TRights};
+use aster_rights::{Rights, TRights};
use super::VmoRightsOp;
use super::{
diff --git a/services/libs/jinux-std/src/vm/vmo/dyn_cap.rs b/services/libs/aster-std/src/vm/vmo/dyn_cap.rs
--- a/services/libs/jinux-std/src/vm/vmo/dyn_cap.rs
+++ b/services/libs/aster-std/src/vm/vmo/dyn_cap.rs
@@ -2,9 +2,9 @@ use core::ops::Range;
use crate::prelude::*;
-use jinux_frame::vm::VmIo;
+use aster_frame::vm::VmIo;
-use jinux_rights::{Rights, TRights};
+use aster_rights::{Rights, TRights};
use super::VmoRightsOp;
use super::{
diff --git a/services/libs/jinux-std/src/vm/vmo/dyn_cap.rs b/services/libs/aster-std/src/vm/vmo/dyn_cap.rs
--- a/services/libs/jinux-std/src/vm/vmo/dyn_cap.rs
+++ b/services/libs/aster-std/src/vm/vmo/dyn_cap.rs
@@ -150,13 +150,13 @@ impl Vmo<Rights> {
}
impl VmIo for Vmo<Rights> {
- fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> jinux_frame::Result<()> {
+ fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> aster_frame::Result<()> {
self.check_rights(Rights::READ)?;
self.0.read_bytes(offset, buf)?;
Ok(())
}
- fn write_bytes(&self, offset: usize, buf: &[u8]) -> jinux_frame::Result<()> {
+ fn write_bytes(&self, offset: usize, buf: &[u8]) -> aster_frame::Result<()> {
self.check_rights(Rights::WRITE)?;
self.0.write_bytes(offset, buf)?;
Ok(())
diff --git a/services/libs/jinux-std/src/vm/vmo/dyn_cap.rs b/services/libs/aster-std/src/vm/vmo/dyn_cap.rs
--- a/services/libs/jinux-std/src/vm/vmo/dyn_cap.rs
+++ b/services/libs/aster-std/src/vm/vmo/dyn_cap.rs
@@ -150,13 +150,13 @@ impl Vmo<Rights> {
}
impl VmIo for Vmo<Rights> {
- fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> jinux_frame::Result<()> {
+ fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> aster_frame::Result<()> {
self.check_rights(Rights::READ)?;
self.0.read_bytes(offset, buf)?;
Ok(())
}
- fn write_bytes(&self, offset: usize, buf: &[u8]) -> jinux_frame::Result<()> {
+ fn write_bytes(&self, offset: usize, buf: &[u8]) -> aster_frame::Result<()> {
self.check_rights(Rights::WRITE)?;
self.0.write_bytes(offset, buf)?;
Ok(())
diff --git a/services/libs/jinux-std/src/vm/vmo/mod.rs b/services/libs/aster-std/src/vm/vmo/mod.rs
--- a/services/libs/jinux-std/src/vm/vmo/mod.rs
+++ b/services/libs/aster-std/src/vm/vmo/mod.rs
@@ -3,8 +3,8 @@
use core::ops::Range;
use align_ext::AlignExt;
-use jinux_frame::vm::{VmAllocOptions, VmFrame, VmFrameVec, VmIo};
-use jinux_rights::Rights;
+use aster_frame::vm::{VmAllocOptions, VmFrame, VmFrameVec, VmIo};
+use aster_rights::Rights;
use crate::prelude::*;
diff --git a/services/libs/jinux-std/src/vm/vmo/mod.rs b/services/libs/aster-std/src/vm/vmo/mod.rs
--- a/services/libs/jinux-std/src/vm/vmo/mod.rs
+++ b/services/libs/aster-std/src/vm/vmo/mod.rs
@@ -3,8 +3,8 @@
use core::ops::Range;
use align_ext::AlignExt;
-use jinux_frame::vm::{VmAllocOptions, VmFrame, VmFrameVec, VmIo};
-use jinux_rights::Rights;
+use aster_frame::vm::{VmAllocOptions, VmFrame, VmFrameVec, VmIo};
+use aster_rights::Rights;
use crate::prelude::*;
diff --git a/services/libs/jinux-std/src/vm/vmo/mod.rs b/services/libs/aster-std/src/vm/vmo/mod.rs
--- a/services/libs/jinux-std/src/vm/vmo/mod.rs
+++ b/services/libs/aster-std/src/vm/vmo/mod.rs
@@ -66,7 +66,7 @@ pub use pager::Pager;
/// # Implementation
///
/// `Vmo` provides high-level APIs for address space management by wrapping
-/// around its low-level counterpart `jinux_frame::vm::VmFrames`.
+/// around its low-level counterpart `aster_frame::vm::VmFrames`.
/// Compared with `VmFrames`,
/// `Vmo` is easier to use (by offering more powerful APIs) and
/// harder to misuse (thanks to its nature of being capability).
diff --git a/services/libs/jinux-std/src/vm/vmo/mod.rs b/services/libs/aster-std/src/vm/vmo/mod.rs
--- a/services/libs/jinux-std/src/vm/vmo/mod.rs
+++ b/services/libs/aster-std/src/vm/vmo/mod.rs
@@ -66,7 +66,7 @@ pub use pager::Pager;
/// # Implementation
///
/// `Vmo` provides high-level APIs for address space management by wrapping
-/// around its low-level counterpart `jinux_frame::vm::VmFrames`.
+/// around its low-level counterpart `aster_frame::vm::VmFrames`.
/// Compared with `VmFrames`,
/// `Vmo` is easier to use (by offering more powerful APIs) and
/// harder to misuse (thanks to its nature of being capability).
diff --git a/services/libs/jinux-std/src/vm/vmo/options.rs b/services/libs/aster-std/src/vm/vmo/options.rs
--- a/services/libs/jinux-std/src/vm/vmo/options.rs
+++ b/services/libs/aster-std/src/vm/vmo/options.rs
@@ -4,15 +4,15 @@ use core::marker::PhantomData;
use core::ops::Range;
use align_ext::AlignExt;
-use jinux_frame::vm::{VmAllocOptions, VmFrame};
-use jinux_rights_proc::require;
+use aster_frame::vm::{VmAllocOptions, VmFrame};
+use aster_rights_proc::require;
use typeflags_util::{SetExtend, SetExtendOp};
use crate::prelude::*;
use crate::vm::vmo::get_inherited_frames_from_parent;
use crate::vm::vmo::{VmoInner, Vmo_};
-use jinux_rights::{Dup, Rights, TRightSet, TRights, Write};
+use aster_rights::{Dup, Rights, TRightSet, TRights, Write};
use super::VmoRightsOp;
use super::{Pager, Vmo, VmoFlags};
diff --git a/services/libs/jinux-std/src/vm/vmo/options.rs b/services/libs/aster-std/src/vm/vmo/options.rs
--- a/services/libs/jinux-std/src/vm/vmo/options.rs
+++ b/services/libs/aster-std/src/vm/vmo/options.rs
@@ -4,15 +4,15 @@ use core::marker::PhantomData;
use core::ops::Range;
use align_ext::AlignExt;
-use jinux_frame::vm::{VmAllocOptions, VmFrame};
-use jinux_rights_proc::require;
+use aster_frame::vm::{VmAllocOptions, VmFrame};
+use aster_rights_proc::require;
use typeflags_util::{SetExtend, SetExtendOp};
use crate::prelude::*;
use crate::vm::vmo::get_inherited_frames_from_parent;
use crate::vm::vmo::{VmoInner, Vmo_};
-use jinux_rights::{Dup, Rights, TRightSet, TRights, Write};
+use aster_rights::{Dup, Rights, TRightSet, TRights, Write};
use super::VmoRightsOp;
use super::{Pager, Vmo, VmoFlags};
diff --git a/services/libs/jinux-std/src/vm/vmo/options.rs b/services/libs/aster-std/src/vm/vmo/options.rs
--- a/services/libs/jinux-std/src/vm/vmo/options.rs
+++ b/services/libs/aster-std/src/vm/vmo/options.rs
@@ -23,7 +23,7 @@ use super::{Pager, Vmo, VmoFlags};
///
/// Creating a VMO as a _dynamic_ capability with full access rights:
/// ```
-/// use jinux_std::vm::{PAGE_SIZE, VmoOptions};
+/// use aster_std::vm::{PAGE_SIZE, VmoOptions};
///
/// let vmo = VmoOptions::new(PAGE_SIZE)
/// .alloc()
diff --git a/services/libs/jinux-std/src/vm/vmo/options.rs b/services/libs/aster-std/src/vm/vmo/options.rs
--- a/services/libs/jinux-std/src/vm/vmo/options.rs
+++ b/services/libs/aster-std/src/vm/vmo/options.rs
@@ -23,7 +23,7 @@ use super::{Pager, Vmo, VmoFlags};
///
/// Creating a VMO as a _dynamic_ capability with full access rights:
/// ```
-/// use jinux_std::vm::{PAGE_SIZE, VmoOptions};
+/// use aster_std::vm::{PAGE_SIZE, VmoOptions};
///
/// let vmo = VmoOptions::new(PAGE_SIZE)
/// .alloc()
diff --git a/services/libs/jinux-std/src/vm/vmo/options.rs b/services/libs/aster-std/src/vm/vmo/options.rs
--- a/services/libs/jinux-std/src/vm/vmo/options.rs
+++ b/services/libs/aster-std/src/vm/vmo/options.rs
@@ -32,8 +32,8 @@ use super::{Pager, Vmo, VmoFlags};
///
/// Creating a VMO as a _static_ capability with all access rights:
/// ```
-/// use jinux_std::prelude::*;
-/// use jinux_std::vm::{PAGE_SIZE, VmoOptions};
+/// use aster_std::prelude::*;
+/// use aster_std::vm::{PAGE_SIZE, VmoOptions};
///
/// let vmo = VmoOptions::<Full>::new(PAGE_SIZE)
/// .alloc()
diff --git a/services/libs/jinux-std/src/vm/vmo/options.rs b/services/libs/aster-std/src/vm/vmo/options.rs
--- a/services/libs/jinux-std/src/vm/vmo/options.rs
+++ b/services/libs/aster-std/src/vm/vmo/options.rs
@@ -32,8 +32,8 @@ use super::{Pager, Vmo, VmoFlags};
///
/// Creating a VMO as a _static_ capability with all access rights:
/// ```
-/// use jinux_std::prelude::*;
-/// use jinux_std::vm::{PAGE_SIZE, VmoOptions};
+/// use aster_std::prelude::*;
+/// use aster_std::vm::{PAGE_SIZE, VmoOptions};
///
/// let vmo = VmoOptions::<Full>::new(PAGE_SIZE)
/// .alloc()
diff --git a/services/libs/jinux-std/src/vm/vmo/options.rs b/services/libs/aster-std/src/vm/vmo/options.rs
--- a/services/libs/jinux-std/src/vm/vmo/options.rs
+++ b/services/libs/aster-std/src/vm/vmo/options.rs
@@ -44,7 +44,7 @@ use super::{Pager, Vmo, VmoFlags};
/// physically contiguous:
///
/// ```
-/// use jinux_std::vm::{PAGE_SIZE, VmoOptions, VmoFlags};
+/// use aster_std::vm::{PAGE_SIZE, VmoOptions, VmoFlags};
///
/// let vmo = VmoOptions::new(10 * PAGE_SIZE)
/// .flags(VmoFlags::RESIZABLE)
diff --git a/services/libs/jinux-std/src/vm/vmo/options.rs b/services/libs/aster-std/src/vm/vmo/options.rs
--- a/services/libs/jinux-std/src/vm/vmo/options.rs
+++ b/services/libs/aster-std/src/vm/vmo/options.rs
@@ -44,7 +44,7 @@ use super::{Pager, Vmo, VmoFlags};
/// physically contiguous:
///
/// ```
-/// use jinux_std::vm::{PAGE_SIZE, VmoOptions, VmoFlags};
+/// use aster_std::vm::{PAGE_SIZE, VmoOptions, VmoFlags};
///
/// let vmo = VmoOptions::new(10 * PAGE_SIZE)
/// .flags(VmoFlags::RESIZABLE)
diff --git a/services/libs/jinux-std/src/vm/vmo/options.rs b/services/libs/aster-std/src/vm/vmo/options.rs
--- a/services/libs/jinux-std/src/vm/vmo/options.rs
+++ b/services/libs/aster-std/src/vm/vmo/options.rs
@@ -164,7 +164,7 @@ fn committed_pages_if_continuous(flags: VmoFlags, size: usize) -> Result<BTreeMa
/// A child VMO created from a parent VMO of _dynamic_ capability is also a
/// _dynamic_ capability.
/// ```
-/// use jinux_std::vm::{PAGE_SIZE, VmoOptions};
+/// use aster_std::vm::{PAGE_SIZE, VmoOptions};
///
/// let parent_vmo = VmoOptions::new(PAGE_SIZE)
/// .alloc()
diff --git a/services/libs/jinux-std/src/vm/vmo/options.rs b/services/libs/aster-std/src/vm/vmo/options.rs
--- a/services/libs/jinux-std/src/vm/vmo/options.rs
+++ b/services/libs/aster-std/src/vm/vmo/options.rs
@@ -164,7 +164,7 @@ fn committed_pages_if_continuous(flags: VmoFlags, size: usize) -> Result<BTreeMa
/// A child VMO created from a parent VMO of _dynamic_ capability is also a
/// _dynamic_ capability.
/// ```
-/// use jinux_std::vm::{PAGE_SIZE, VmoOptions};
+/// use aster_std::vm::{PAGE_SIZE, VmoOptions};
///
/// let parent_vmo = VmoOptions::new(PAGE_SIZE)
/// .alloc()
diff --git a/services/libs/jinux-std/src/vm/vmo/options.rs b/services/libs/aster-std/src/vm/vmo/options.rs
--- a/services/libs/jinux-std/src/vm/vmo/options.rs
+++ b/services/libs/aster-std/src/vm/vmo/options.rs
@@ -178,8 +178,8 @@ fn committed_pages_if_continuous(flags: VmoFlags, size: usize) -> Result<BTreeMa
/// A child VMO created from a parent VMO of _static_ capability is also a
/// _static_ capability.
/// ```
-/// use jinux_std::prelude::*;
-/// use jinux_std::vm::{PAGE_SIZE, VmoOptions, VmoChildOptions};
+/// use aster_std::prelude::*;
+/// use aster_std::vm::{PAGE_SIZE, VmoOptions, VmoChildOptions};
///
/// let parent_vmo: Vmo<Full> = VmoOptions::new(PAGE_SIZE)
/// .alloc()
diff --git a/services/libs/jinux-std/src/vm/vmo/options.rs b/services/libs/aster-std/src/vm/vmo/options.rs
--- a/services/libs/jinux-std/src/vm/vmo/options.rs
+++ b/services/libs/aster-std/src/vm/vmo/options.rs
@@ -178,8 +178,8 @@ fn committed_pages_if_continuous(flags: VmoFlags, size: usize) -> Result<BTreeMa
/// A child VMO created from a parent VMO of _static_ capability is also a
/// _static_ capability.
/// ```
-/// use jinux_std::prelude::*;
-/// use jinux_std::vm::{PAGE_SIZE, VmoOptions, VmoChildOptions};
+/// use aster_std::prelude::*;
+/// use aster_std::vm::{PAGE_SIZE, VmoOptions, VmoChildOptions};
///
/// let parent_vmo: Vmo<Full> = VmoOptions::new(PAGE_SIZE)
/// .alloc()
diff --git a/services/libs/jinux-std/src/vm/vmo/options.rs b/services/libs/aster-std/src/vm/vmo/options.rs
--- a/services/libs/jinux-std/src/vm/vmo/options.rs
+++ b/services/libs/aster-std/src/vm/vmo/options.rs
@@ -196,7 +196,7 @@ fn committed_pages_if_continuous(flags: VmoFlags, size: usize) -> Result<BTreeMa
/// right regardless of whether the parent is writable or not.
///
/// ```
-/// use jinux_std::vm::{PAGE_SIZE, VmoOptions, VmoChildOptions};
+/// use aster_std::vm::{PAGE_SIZE, VmoOptions, VmoChildOptions};
///
/// let parent_vmo = VmoOptions::new(PAGE_SIZE)
/// .alloc()
diff --git a/services/libs/jinux-std/src/vm/vmo/options.rs b/services/libs/aster-std/src/vm/vmo/options.rs
--- a/services/libs/jinux-std/src/vm/vmo/options.rs
+++ b/services/libs/aster-std/src/vm/vmo/options.rs
@@ -196,7 +196,7 @@ fn committed_pages_if_continuous(flags: VmoFlags, size: usize) -> Result<BTreeMa
/// right regardless of whether the parent is writable or not.
///
/// ```
-/// use jinux_std::vm::{PAGE_SIZE, VmoOptions, VmoChildOptions};
+/// use aster_std::vm::{PAGE_SIZE, VmoOptions, VmoChildOptions};
///
/// let parent_vmo = VmoOptions::new(PAGE_SIZE)
/// .alloc()
diff --git a/services/libs/jinux-std/src/vm/vmo/options.rs b/services/libs/aster-std/src/vm/vmo/options.rs
--- a/services/libs/jinux-std/src/vm/vmo/options.rs
+++ b/services/libs/aster-std/src/vm/vmo/options.rs
@@ -211,7 +211,7 @@ fn committed_pages_if_continuous(flags: VmoFlags, size: usize) -> Result<BTreeMa
/// The above rule for COW VMO children also applies to static capabilities.
///
/// ```
-/// use jinux_std::vm::{PAGE_SIZE, VmoOptions, VmoChildOptions};
+/// use aster_std::vm::{PAGE_SIZE, VmoOptions, VmoChildOptions};
///
/// let parent_vmo = VmoOptions::<TRights![Read, Dup]>::new(PAGE_SIZE)
/// .alloc()
diff --git a/services/libs/jinux-std/src/vm/vmo/options.rs b/services/libs/aster-std/src/vm/vmo/options.rs
--- a/services/libs/jinux-std/src/vm/vmo/options.rs
+++ b/services/libs/aster-std/src/vm/vmo/options.rs
@@ -211,7 +211,7 @@ fn committed_pages_if_continuous(flags: VmoFlags, size: usize) -> Result<BTreeMa
/// The above rule for COW VMO children also applies to static capabilities.
///
/// ```
-/// use jinux_std::vm::{PAGE_SIZE, VmoOptions, VmoChildOptions};
+/// use aster_std::vm::{PAGE_SIZE, VmoOptions, VmoChildOptions};
///
/// let parent_vmo = VmoOptions::<TRights![Read, Dup]>::new(PAGE_SIZE)
/// .alloc()
diff --git a/services/libs/jinux-std/src/vm/vmo/options.rs b/services/libs/aster-std/src/vm/vmo/options.rs
--- a/services/libs/jinux-std/src/vm/vmo/options.rs
+++ b/services/libs/aster-std/src/vm/vmo/options.rs
@@ -227,7 +227,7 @@ fn committed_pages_if_continuous(flags: VmoFlags, size: usize) -> Result<BTreeMa
/// Note that a slice VMO child and its parent cannot not be resizable.
///
/// ```rust
-/// use jinux_std::vm::{PAGE_SIZE, VmoOptions};
+/// use aster_std::vm::{PAGE_SIZE, VmoOptions};
///
/// let parent_vmo = VmoOptions::new(PAGE_SIZE)
/// .alloc()
diff --git a/services/libs/jinux-std/src/vm/vmo/options.rs b/services/libs/aster-std/src/vm/vmo/options.rs
--- a/services/libs/jinux-std/src/vm/vmo/options.rs
+++ b/services/libs/aster-std/src/vm/vmo/options.rs
@@ -227,7 +227,7 @@ fn committed_pages_if_continuous(flags: VmoFlags, size: usize) -> Result<BTreeMa
/// Note that a slice VMO child and its parent cannot not be resizable.
///
/// ```rust
-/// use jinux_std::vm::{PAGE_SIZE, VmoOptions};
+/// use aster_std::vm::{PAGE_SIZE, VmoOptions};
///
/// let parent_vmo = VmoOptions::new(PAGE_SIZE)
/// .alloc()
diff --git a/services/libs/jinux-std/src/vm/vmo/options.rs b/services/libs/aster-std/src/vm/vmo/options.rs
--- a/services/libs/jinux-std/src/vm/vmo/options.rs
+++ b/services/libs/aster-std/src/vm/vmo/options.rs
@@ -519,8 +519,8 @@ impl VmoChildType for VmoCowChild {}
#[if_cfg_ktest]
mod test {
use super::*;
- use jinux_frame::vm::VmIo;
- use jinux_rights::Full;
+ use aster_frame::vm::VmIo;
+ use aster_rights::Full;
#[ktest]
fn alloc_vmo() {
diff --git a/services/libs/jinux-std/src/vm/vmo/pager.rs b/services/libs/aster-std/src/vm/vmo/pager.rs
--- a/services/libs/jinux-std/src/vm/vmo/pager.rs
+++ b/services/libs/aster-std/src/vm/vmo/pager.rs
@@ -1,5 +1,5 @@
use crate::prelude::*;
-use jinux_frame::vm::VmFrame;
+use aster_frame::vm::VmFrame;
/// Pagers provide frame to a VMO.
///
diff --git a/services/libs/jinux-std/src/vm/vmo/pager.rs b/services/libs/aster-std/src/vm/vmo/pager.rs
--- a/services/libs/jinux-std/src/vm/vmo/pager.rs
+++ b/services/libs/aster-std/src/vm/vmo/pager.rs
@@ -1,5 +1,5 @@
use crate::prelude::*;
-use jinux_frame::vm::VmFrame;
+use aster_frame::vm::VmFrame;
/// Pagers provide frame to a VMO.
///
diff --git a/services/libs/jinux-std/src/vm/vmo/static_cap.rs b/services/libs/aster-std/src/vm/vmo/static_cap.rs
--- a/services/libs/jinux-std/src/vm/vmo/static_cap.rs
+++ b/services/libs/aster-std/src/vm/vmo/static_cap.rs
@@ -1,9 +1,9 @@
use crate::prelude::*;
+use aster_frame::vm::VmIo;
+use aster_rights_proc::require;
use core::ops::Range;
-use jinux_frame::vm::VmIo;
-use jinux_rights_proc::require;
-use jinux_rights::{Dup, Rights, TRightSet, TRights, Write};
+use aster_rights::{Dup, Rights, TRightSet, TRights, Write};
use super::VmoRightsOp;
use super::{
diff --git a/services/libs/jinux-std/src/vm/vmo/static_cap.rs b/services/libs/aster-std/src/vm/vmo/static_cap.rs
--- a/services/libs/jinux-std/src/vm/vmo/static_cap.rs
+++ b/services/libs/aster-std/src/vm/vmo/static_cap.rs
@@ -1,9 +1,9 @@
use crate::prelude::*;
+use aster_frame::vm::VmIo;
+use aster_rights_proc::require;
use core::ops::Range;
-use jinux_frame::vm::VmIo;
-use jinux_rights_proc::require;
-use jinux_rights::{Dup, Rights, TRightSet, TRights, Write};
+use aster_rights::{Dup, Rights, TRightSet, TRights, Write};
use super::VmoRightsOp;
use super::{
diff --git a/services/libs/jinux-std/src/vm/vmo/static_cap.rs b/services/libs/aster-std/src/vm/vmo/static_cap.rs
--- a/services/libs/jinux-std/src/vm/vmo/static_cap.rs
+++ b/services/libs/aster-std/src/vm/vmo/static_cap.rs
@@ -145,13 +145,13 @@ impl<R: TRights> Vmo<TRightSet<R>> {
}
impl<R: TRights> VmIo for Vmo<TRightSet<R>> {
- fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> jinux_frame::Result<()> {
+ fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> aster_frame::Result<()> {
self.check_rights(Rights::READ)?;
self.0.read_bytes(offset, buf)?;
Ok(())
}
- fn write_bytes(&self, offset: usize, buf: &[u8]) -> jinux_frame::Result<()> {
+ fn write_bytes(&self, offset: usize, buf: &[u8]) -> aster_frame::Result<()> {
self.check_rights(Rights::WRITE)?;
self.0.write_bytes(offset, buf)?;
Ok(())
diff --git a/services/libs/jinux-std/src/vm/vmo/static_cap.rs b/services/libs/aster-std/src/vm/vmo/static_cap.rs
--- a/services/libs/jinux-std/src/vm/vmo/static_cap.rs
+++ b/services/libs/aster-std/src/vm/vmo/static_cap.rs
@@ -145,13 +145,13 @@ impl<R: TRights> Vmo<TRightSet<R>> {
}
impl<R: TRights> VmIo for Vmo<TRightSet<R>> {
- fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> jinux_frame::Result<()> {
+ fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> aster_frame::Result<()> {
self.check_rights(Rights::READ)?;
self.0.read_bytes(offset, buf)?;
Ok(())
}
- fn write_bytes(&self, offset: usize, buf: &[u8]) -> jinux_frame::Result<()> {
+ fn write_bytes(&self, offset: usize, buf: &[u8]) -> aster_frame::Result<()> {
self.check_rights(Rights::WRITE)?;
self.0.write_bytes(offset, buf)?;
Ok(())
diff --git a/services/libs/jinux-util/Cargo.toml b/services/libs/aster-util/Cargo.toml
--- a/services/libs/jinux-util/Cargo.toml
+++ b/services/libs/aster-util/Cargo.toml
@@ -1,16 +1,16 @@
[package]
-name = "jinux-util"
+name = "aster-util"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
-jinux-frame = { path = "../../../framework/jinux-frame" }
-pod = { git = "https://github.com/jinzhao-dev/pod", rev = "d7dba56" }
+aster-frame = { path = "../../../framework/aster-frame" }
+pod = { git = "https://github.com/asterinas/pod", rev = "d7dba56" }
typeflags-util = { path = "../typeflags-util" }
-jinux-rights-proc = { path = "../jinux-rights-proc" }
-jinux-rights = { path = "../jinux-rights" }
+aster-rights-proc = { path = "../aster-rights-proc" }
+aster-rights = { path = "../aster-rights" }
bitvec = { version = "1.0", default-features = false, features = ["alloc"] }
ktest = { path = "../../../framework/libs/ktest" }
[features]
diff --git a/services/libs/jinux-util/src/dup.rs b/services/libs/aster-util/src/dup.rs
--- a/services/libs/jinux-util/src/dup.rs
+++ b/services/libs/aster-util/src/dup.rs
@@ -9,5 +9,5 @@
/// _exclusively_ to one another. In other words, a type should not implement
/// both traits.
pub trait Dup: Sized {
- fn dup(&self) -> jinux_frame::Result<Self>;
+ fn dup(&self) -> aster_frame::Result<Self>;
}
diff --git a/services/libs/jinux-util/src/dup.rs b/services/libs/aster-util/src/dup.rs
--- a/services/libs/jinux-util/src/dup.rs
+++ b/services/libs/aster-util/src/dup.rs
@@ -9,5 +9,5 @@
/// _exclusively_ to one another. In other words, a type should not implement
/// both traits.
pub trait Dup: Sized {
- fn dup(&self) -> jinux_frame::Result<Self>;
+ fn dup(&self) -> aster_frame::Result<Self>;
}
diff --git a/services/libs/jinux-util/src/lib.rs b/services/libs/aster-util/src/lib.rs
--- a/services/libs/jinux-util/src/lib.rs
+++ b/services/libs/aster-util/src/lib.rs
@@ -1,4 +1,4 @@
-//! The util of jinux
+//! The util of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
diff --git a/services/libs/jinux-util/src/lib.rs b/services/libs/aster-util/src/lib.rs
--- a/services/libs/jinux-util/src/lib.rs
+++ b/services/libs/aster-util/src/lib.rs
@@ -1,4 +1,4 @@
-//! The util of jinux
+//! The util of Asterinas.
#![no_std]
#![forbid(unsafe_code)]
diff --git a/services/libs/jinux-util/src/safe_ptr.rs b/services/libs/aster-util/src/safe_ptr.rs
--- a/services/libs/jinux-util/src/safe_ptr.rs
+++ b/services/libs/aster-util/src/safe_ptr.rs
@@ -1,10 +1,10 @@
+use aster_frame::vm::Paddr;
+use aster_frame::vm::{HasPaddr, VmIo};
+use aster_frame::Result;
+use aster_rights::{Dup, Exec, Full, Read, Signal, TRightSet, TRights, Write};
+use aster_rights_proc::require;
use core::fmt::Debug;
use core::marker::PhantomData;
-use jinux_frame::vm::Paddr;
-use jinux_frame::vm::{HasPaddr, VmIo};
-use jinux_frame::Result;
-use jinux_rights::{Dup, Exec, Full, Read, Signal, TRightSet, TRights, Write};
-use jinux_rights_proc::require;
pub use pod::Pod;
pub use typeflags_util::SetContain;
diff --git a/services/libs/jinux-util/src/safe_ptr.rs b/services/libs/aster-util/src/safe_ptr.rs
--- a/services/libs/jinux-util/src/safe_ptr.rs
+++ b/services/libs/aster-util/src/safe_ptr.rs
@@ -1,10 +1,10 @@
+use aster_frame::vm::Paddr;
+use aster_frame::vm::{HasPaddr, VmIo};
+use aster_frame::Result;
+use aster_rights::{Dup, Exec, Full, Read, Signal, TRightSet, TRights, Write};
+use aster_rights_proc::require;
use core::fmt::Debug;
use core::marker::PhantomData;
-use jinux_frame::vm::Paddr;
-use jinux_frame::vm::{HasPaddr, VmIo};
-use jinux_frame::Result;
-use jinux_rights::{Dup, Exec, Full, Read, Signal, TRightSet, TRights, Write};
-use jinux_rights_proc::require;
pub use pod::Pod;
pub use typeflags_util::SetContain;
diff --git a/services/libs/jinux-util/src/safe_ptr.rs b/services/libs/aster-util/src/safe_ptr.rs
--- a/services/libs/jinux-util/src/safe_ptr.rs
+++ b/services/libs/aster-util/src/safe_ptr.rs
@@ -358,14 +358,14 @@ impl<T, M: Debug, R> Debug for SafePtr<T, M, R> {
#[macro_export]
macro_rules! field_ptr {
($ptr:expr, $type:ty, $($field:tt)+) => {{
- use jinux_frame::offset_of;
- use jinux_frame::vm::VmIo;
- use jinux_rights::Dup;
- use jinux_rights::TRightSet;
- use jinux_rights::TRights;
- use jinux_util::safe_ptr::Pod;
- use jinux_util::safe_ptr::SetContain;
- use jinux_util::safe_ptr::SafePtr;
+ use aster_frame::offset_of;
+ use aster_frame::vm::VmIo;
+ use aster_rights::Dup;
+ use aster_rights::TRightSet;
+ use aster_rights::TRights;
+ use aster_util::safe_ptr::Pod;
+ use aster_util::safe_ptr::SetContain;
+ use aster_util::safe_ptr::SafePtr;
#[inline]
fn new_field_ptr<T, M, R, U>(
diff --git a/services/libs/jinux-util/src/safe_ptr.rs b/services/libs/aster-util/src/safe_ptr.rs
--- a/services/libs/jinux-util/src/safe_ptr.rs
+++ b/services/libs/aster-util/src/safe_ptr.rs
@@ -358,14 +358,14 @@ impl<T, M: Debug, R> Debug for SafePtr<T, M, R> {
#[macro_export]
macro_rules! field_ptr {
($ptr:expr, $type:ty, $($field:tt)+) => {{
- use jinux_frame::offset_of;
- use jinux_frame::vm::VmIo;
- use jinux_rights::Dup;
- use jinux_rights::TRightSet;
- use jinux_rights::TRights;
- use jinux_util::safe_ptr::Pod;
- use jinux_util::safe_ptr::SetContain;
- use jinux_util::safe_ptr::SafePtr;
+ use aster_frame::offset_of;
+ use aster_frame::vm::VmIo;
+ use aster_rights::Dup;
+ use aster_rights::TRightSet;
+ use aster_rights::TRights;
+ use aster_util::safe_ptr::Pod;
+ use aster_util::safe_ptr::SetContain;
+ use aster_util::safe_ptr::SafePtr;
#[inline]
fn new_field_ptr<T, M, R, U>(
diff --git a/services/libs/jinux-util/src/union_read_ptr.rs b/services/libs/aster-util/src/union_read_ptr.rs
--- a/services/libs/jinux-util/src/union_read_ptr.rs
+++ b/services/libs/aster-util/src/union_read_ptr.rs
@@ -35,7 +35,7 @@ macro_rules! read_union_fields {
union_read_ptr.read_at(offset)
});
($container:ident.$($field:ident).*) => ({
- let field_offset = jinux_frame::value_offset!($container.$($field).*);
+ let field_offset = aster_frame::value_offset!($container.$($field).*);
let union_read_ptr = UnionReadPtr::new(&*$container);
union_read_ptr.read_at(field_offset)
});
diff --git a/services/libs/jinux-util/src/union_read_ptr.rs b/services/libs/aster-util/src/union_read_ptr.rs
--- a/services/libs/jinux-util/src/union_read_ptr.rs
+++ b/services/libs/aster-util/src/union_read_ptr.rs
@@ -35,7 +35,7 @@ macro_rules! read_union_fields {
union_read_ptr.read_at(offset)
});
($container:ident.$($field:ident).*) => ({
- let field_offset = jinux_frame::value_offset!($container.$($field).*);
+ let field_offset = aster_frame::value_offset!($container.$($field).*);
let union_read_ptr = UnionReadPtr::new(&*$container);
union_read_ptr.read_at(field_offset)
});
diff --git a/services/libs/comp-sys/cargo-component/README.md b/services/libs/comp-sys/cargo-component/README.md
--- a/services/libs/comp-sys/cargo-component/README.md
+++ b/services/libs/comp-sys/cargo-component/README.md
@@ -1,15 +1,15 @@
## Overview
-The crate contains cargo-component, a cargo subcommand to enable component-level access control in Jinux. For more info about Jinux component system, see the [RFC](https://github.com/jinzhao-dev/jinux/issues/58). The implementation mainly follows [rust clippy](https://github.com/rust-lang/rust-clippy). Internally, this tool will call `cargo check` to compile the whole project and bases the analysis on MIR.
+The crate contains cargo-component, a cargo subcommand to enable component-level access control in Asterinas. For more info about Asterinas component system, see the [RFC](https://github.com/asterinas/Asterinas/issues/58). The implementation mainly follows [rust clippy](https://github.com/rust-lang/rust-clippy). Internally, this tool will call `cargo check` to compile the whole project and bases the analysis on MIR.
## install
-After running `make setup` for jinux, this crate can be created with cargo.
+After running `make setup` for Asterinas, this crate can be created with cargo.
```shell
cargo install --path .
```
This will install two binaries `cargo-component` and `component-driver` at `$HOME/.cargo/bin`(by default, it depends on the cargo config).
## Usage
-Use `cargo component` or `cargo component check` or `cargo component audit`. The three commands are the same now. For jinux, we shoud use another alias command `cargo component-check`, which was defined in `src/.cargo/config.toml`.
+Use `cargo component` or `cargo component check` or `cargo component audit`. The three commands are the same now. For Asterinas, we shoud use another alias command `cargo component-check`, which was defined in `src/.cargo/config.toml`.
### Two notes:
- The directory **where you run the command** should contains a `Components.toml` config file, where defines all components and whitelist.
diff --git a/services/libs/comp-sys/cargo-component/README.md b/services/libs/comp-sys/cargo-component/README.md
--- a/services/libs/comp-sys/cargo-component/README.md
+++ b/services/libs/comp-sys/cargo-component/README.md
@@ -1,15 +1,15 @@
## Overview
-The crate contains cargo-component, a cargo subcommand to enable component-level access control in Jinux. For more info about Jinux component system, see the [RFC](https://github.com/jinzhao-dev/jinux/issues/58). The implementation mainly follows [rust clippy](https://github.com/rust-lang/rust-clippy). Internally, this tool will call `cargo check` to compile the whole project and bases the analysis on MIR.
+The crate contains cargo-component, a cargo subcommand to enable component-level access control in Asterinas. For more info about Asterinas component system, see the [RFC](https://github.com/asterinas/Asterinas/issues/58). The implementation mainly follows [rust clippy](https://github.com/rust-lang/rust-clippy). Internally, this tool will call `cargo check` to compile the whole project and bases the analysis on MIR.
## install
-After running `make setup` for jinux, this crate can be created with cargo.
+After running `make setup` for Asterinas, this crate can be created with cargo.
```shell
cargo install --path .
```
This will install two binaries `cargo-component` and `component-driver` at `$HOME/.cargo/bin`(by default, it depends on the cargo config).
## Usage
-Use `cargo component` or `cargo component check` or `cargo component audit`. The three commands are the same now. For jinux, we shoud use another alias command `cargo component-check`, which was defined in `src/.cargo/config.toml`.
+Use `cargo component` or `cargo component check` or `cargo component audit`. The three commands are the same now. For Asterinas, we shoud use another alias command `cargo component-check`, which was defined in `src/.cargo/config.toml`.
### Two notes:
- The directory **where you run the command** should contains a `Components.toml` config file, where defines all components and whitelist.
diff --git a/services/libs/typeflags-util/src/lib.rs b/services/libs/typeflags-util/src/lib.rs
--- a/services/libs/typeflags-util/src/lib.rs
+++ b/services/libs/typeflags-util/src/lib.rs
@@ -1,7 +1,7 @@
//! The content of this crate is from another project CapComp.
//! This crate defines common type level operations, like SameAsOp, and Bool type operations.
//! Besides, this crate defines operations to deal with type sets, like SetContain and SetInclude.
-//! When use jinux-typeflags or jinux-rights-poc, this crate should also be added as a dependency.
+//! When use typeflags or aster-rights-poc, this crate should also be added as a dependency.
#![no_std]
pub mod assert;
pub mod bool;
diff --git a/services/libs/typeflags-util/src/lib.rs b/services/libs/typeflags-util/src/lib.rs
--- a/services/libs/typeflags-util/src/lib.rs
+++ b/services/libs/typeflags-util/src/lib.rs
@@ -1,7 +1,7 @@
//! The content of this crate is from another project CapComp.
//! This crate defines common type level operations, like SameAsOp, and Bool type operations.
//! Besides, this crate defines operations to deal with type sets, like SetContain and SetInclude.
-//! When use jinux-typeflags or jinux-rights-poc, this crate should also be added as a dependency.
+//! When use typeflags or aster-rights-poc, this crate should also be added as a dependency.
#![no_std]
pub mod assert;
pub mod bool;
diff --git a/services/libs/typeflags/src/lib.rs b/services/libs/typeflags/src/lib.rs
--- a/services/libs/typeflags/src/lib.rs
+++ b/services/libs/typeflags/src/lib.rs
@@ -1,4 +1,4 @@
-//!This crate defines the procedural macro typeflags to implement capability for jinux.
+//!This crate defines the procedural macro typeflags to implement capability for Asterinas.
//! When using this crate, typeflags-util should also be added as dependency.
//! This is due to typeflgas is a proc-macro crate, which is only allowed to export proc-macro interfaces.
//! So we leave the common type-level operations and structures defined in typeflags-util.
diff --git a/services/libs/typeflags/src/lib.rs b/services/libs/typeflags/src/lib.rs
--- a/services/libs/typeflags/src/lib.rs
+++ b/services/libs/typeflags/src/lib.rs
@@ -1,4 +1,4 @@
-//!This crate defines the procedural macro typeflags to implement capability for jinux.
+//!This crate defines the procedural macro typeflags to implement capability for Asterinas.
//! When using this crate, typeflags-util should also be added as dependency.
//! This is due to typeflgas is a proc-macro crate, which is only allowed to export proc-macro interfaces.
//! So we leave the common type-level operations and structures defined in typeflags-util.
diff --git a/tools/bump_version.sh b/tools/bump_version.sh
--- a/tools/bump_version.sh
+++ b/tools/bump_version.sh
@@ -1,6 +1,6 @@
#!/bin/bash
-# This script is used to update Jinux version numbers in all relevant files in the repository.
+# This script is used to update Asterinas version numbers in all relevant files in the repository.
# Usage: ./tools/bump_version.sh <new_version>
# Update Cargo style versions (`version = "{version}"`) in file $1
diff --git a/tools/bump_version.sh b/tools/bump_version.sh
--- a/tools/bump_version.sh
+++ b/tools/bump_version.sh
@@ -1,6 +1,6 @@
#!/bin/bash
-# This script is used to update Jinux version numbers in all relevant files in the repository.
+# This script is used to update Asterinas version numbers in all relevant files in the repository.
# Usage: ./tools/bump_version.sh <new_version>
# Update Cargo style versions (`version = "{version}"`) in file $1
diff --git a/tools/bump_version.sh b/tools/bump_version.sh
--- a/tools/bump_version.sh
+++ b/tools/bump_version.sh
@@ -9,16 +9,16 @@ update_cargo_versions() {
sed -i "s/^version = \"[[:digit:]]\+\.[[:digit:]]\+\.[[:digit:]]\+\"$/version = \"${new_version}\"/g" $1
}
-# Update Docker image versions (`jinuxdev/jinux:{version}`) in file $1
+# Update Docker image versions (`asterinas/asterinas:{version}`) in file $1
update_image_versions() {
echo "Updating file $1"
- sed -i "s/jinuxdev\/jinux:[[:digit:]]\+\.[[:digit:]]\+\.[[:digit:]]\+/jinuxdev\/jinux:${new_version}/g" $1
+ sed -i "s/asterinas\/asterinas:[[:digit:]]\+\.[[:digit:]]\+\.[[:digit:]]\+/asterinas\/asterinas:${new_version}/g" $1
}
SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
-JINUX_SRC_DIR=${SCRIPT_DIR}/..
-CARGO_TOML_PATH=${JINUX_SRC_DIR}/Cargo.toml
-VERSION_PATH=${JINUX_SRC_DIR}/VERSION
+ASTER_SRC_DIR=${SCRIPT_DIR}/..
+CARGO_TOML_PATH=${ASTER_SRC_DIR}/Cargo.toml
+VERSION_PATH=${ASTER_SRC_DIR}/VERSION
# Get and check the new version number
if [[ $1 =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
diff --git a/tools/bump_version.sh b/tools/bump_version.sh
--- a/tools/bump_version.sh
+++ b/tools/bump_version.sh
@@ -9,16 +9,16 @@ update_cargo_versions() {
sed -i "s/^version = \"[[:digit:]]\+\.[[:digit:]]\+\.[[:digit:]]\+\"$/version = \"${new_version}\"/g" $1
}
-# Update Docker image versions (`jinuxdev/jinux:{version}`) in file $1
+# Update Docker image versions (`asterinas/asterinas:{version}`) in file $1
update_image_versions() {
echo "Updating file $1"
- sed -i "s/jinuxdev\/jinux:[[:digit:]]\+\.[[:digit:]]\+\.[[:digit:]]\+/jinuxdev\/jinux:${new_version}/g" $1
+ sed -i "s/asterinas\/asterinas:[[:digit:]]\+\.[[:digit:]]\+\.[[:digit:]]\+/asterinas\/asterinas:${new_version}/g" $1
}
SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
-JINUX_SRC_DIR=${SCRIPT_DIR}/..
-CARGO_TOML_PATH=${JINUX_SRC_DIR}/Cargo.toml
-VERSION_PATH=${JINUX_SRC_DIR}/VERSION
+ASTER_SRC_DIR=${SCRIPT_DIR}/..
+CARGO_TOML_PATH=${ASTER_SRC_DIR}/Cargo.toml
+VERSION_PATH=${ASTER_SRC_DIR}/VERSION
# Get and check the new version number
if [[ $1 =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
diff --git a/tools/bump_version.sh b/tools/bump_version.sh
--- a/tools/bump_version.sh
+++ b/tools/bump_version.sh
@@ -32,14 +32,14 @@ fi
update_cargo_versions ${CARGO_TOML_PATH}
# Automatically bump Cargo.lock file
-cargo update -p jinux --precise $new_version
+cargo update -p asterinas --precise $new_version
# Update Docker image versions in README files
-update_image_versions ${JINUX_SRC_DIR}/README.md
+update_image_versions ${ASTER_SRC_DIR}/README.md
update_image_versions ${SCRIPT_DIR}/docker/README.md
# Update Docker image versions in workflows
-WORKFLOWS=$(find "${JINUX_SRC_DIR}/.github/workflows/" -type f -name "*.yml")
+WORKFLOWS=$(find "${ASTER_SRC_DIR}/.github/workflows/" -type f -name "*.yml")
for workflow in $WORKFLOWS; do
update_image_versions $workflow
done
diff --git a/tools/bump_version.sh b/tools/bump_version.sh
--- a/tools/bump_version.sh
+++ b/tools/bump_version.sh
@@ -32,14 +32,14 @@ fi
update_cargo_versions ${CARGO_TOML_PATH}
# Automatically bump Cargo.lock file
-cargo update -p jinux --precise $new_version
+cargo update -p asterinas --precise $new_version
# Update Docker image versions in README files
-update_image_versions ${JINUX_SRC_DIR}/README.md
+update_image_versions ${ASTER_SRC_DIR}/README.md
update_image_versions ${SCRIPT_DIR}/docker/README.md
# Update Docker image versions in workflows
-WORKFLOWS=$(find "${JINUX_SRC_DIR}/.github/workflows/" -type f -name "*.yml")
+WORKFLOWS=$(find "${ASTER_SRC_DIR}/.github/workflows/" -type f -name "*.yml")
for workflow in $WORKFLOWS; do
update_image_versions $workflow
done
diff --git a/tools/bump_version.sh b/tools/bump_version.sh
--- a/tools/bump_version.sh
+++ b/tools/bump_version.sh
@@ -47,4 +47,4 @@ done
# Create or update VERSION
echo "${new_version}" > ${VERSION_PATH}
-echo "Bumped Jinux version to $new_version"
+echo "Bumped Asterinas version to $new_version"
diff --git a/tools/bump_version.sh b/tools/bump_version.sh
--- a/tools/bump_version.sh
+++ b/tools/bump_version.sh
@@ -47,4 +47,4 @@ done
# Create or update VERSION
echo "${new_version}" > ${VERSION_PATH}
-echo "Bumped Jinux version to $new_version"
+echo "Bumped Asterinas version to $new_version"
diff --git a/tools/docker/Dockerfile.ubuntu22.04 b/tools/docker/Dockerfile.ubuntu22.04
--- a/tools/docker/Dockerfile.ubuntu22.04
+++ b/tools/docker/Dockerfile.ubuntu22.04
@@ -182,15 +182,15 @@ RUN make defconfig \
&& sed -i "s/# CONFIG_FEATURE_SH_STANDALONE is not set/CONFIG_FEATURE_SH_STANDALONE=y/g" .config \
&& make -j
-#= The final stages to produce the Jinux development image ====================
+#= The final stages to produce the Asterinas development image ====================
FROM build-base as rust
# Install Rust
ENV PATH="/root/.cargo/bin:${PATH}"
-ARG JINUX_RUST_VERSION
+ARG ASTER_RUST_VERSION
RUN curl https://sh.rustup.rs -sSf | \
- sh -s -- --default-toolchain ${JINUX_RUST_VERSION} -y \
+ sh -s -- --default-toolchain ${ASTER_RUST_VERSION} -y \
&& rm -rf /root/.cargo/registry && rm -rf /root/.cargo/git \
&& cargo -V \
&& rustup component add rust-src rustc-dev llvm-tools-preview
diff --git a/tools/docker/Dockerfile.ubuntu22.04 b/tools/docker/Dockerfile.ubuntu22.04
--- a/tools/docker/Dockerfile.ubuntu22.04
+++ b/tools/docker/Dockerfile.ubuntu22.04
@@ -182,15 +182,15 @@ RUN make defconfig \
&& sed -i "s/# CONFIG_FEATURE_SH_STANDALONE is not set/CONFIG_FEATURE_SH_STANDALONE=y/g" .config \
&& make -j
-#= The final stages to produce the Jinux development image ====================
+#= The final stages to produce the Asterinas development image ====================
FROM build-base as rust
# Install Rust
ENV PATH="/root/.cargo/bin:${PATH}"
-ARG JINUX_RUST_VERSION
+ARG ASTER_RUST_VERSION
RUN curl https://sh.rustup.rs -sSf | \
- sh -s -- --default-toolchain ${JINUX_RUST_VERSION} -y \
+ sh -s -- --default-toolchain ${ASTER_RUST_VERSION} -y \
&& rm -rf /root/.cargo/registry && rm -rf /root/.cargo/git \
&& cargo -V \
&& rustup component add rust-src rustc-dev llvm-tools-preview
diff --git a/tools/docker/Dockerfile.ubuntu22.04 b/tools/docker/Dockerfile.ubuntu22.04
--- a/tools/docker/Dockerfile.ubuntu22.04
+++ b/tools/docker/Dockerfile.ubuntu22.04
@@ -202,7 +202,7 @@ RUN cargo install \
FROM rust
-# Install all Jinux dependent packages
+# Install all Asterinas dependent packages
RUN apt update && apt-get install -y --no-install-recommends \
cpio \
cpuid \
diff --git a/tools/docker/Dockerfile.ubuntu22.04 b/tools/docker/Dockerfile.ubuntu22.04
--- a/tools/docker/Dockerfile.ubuntu22.04
+++ b/tools/docker/Dockerfile.ubuntu22.04
@@ -202,7 +202,7 @@ RUN cargo install \
FROM rust
-# Install all Jinux dependent packages
+# Install all Asterinas dependent packages
RUN apt update && apt-get install -y --no-install-recommends \
cpio \
cpuid \
diff --git a/tools/docker/Dockerfile.ubuntu22.04 b/tools/docker/Dockerfile.ubuntu22.04
--- a/tools/docker/Dockerfile.ubuntu22.04
+++ b/tools/docker/Dockerfile.ubuntu22.04
@@ -226,7 +226,7 @@ RUN apt clean && rm -rf /var/lib/apt/lists/*
# Prepare the system call test suite
COPY --from=syscall_test /root/syscall_test/build/syscall_test_bins /root/syscall_test_bins
-ENV JINUX_PREBUILT_SYSCALL_TEST=/root/syscall_test_bins
+ENV ASTER_PREBUILT_SYSCALL_TEST=/root/syscall_test_bins
# Install QEMU built from the previous stages
COPY --from=qemu /usr/local/qemu /usr/local/qemu
diff --git a/tools/docker/Dockerfile.ubuntu22.04 b/tools/docker/Dockerfile.ubuntu22.04
--- a/tools/docker/Dockerfile.ubuntu22.04
+++ b/tools/docker/Dockerfile.ubuntu22.04
@@ -249,9 +249,9 @@ COPY --from=busybox /root/busybox/busybox /bin/busybox
# Install benchmarks built from the previous stages
COPY --from=build-benchmarks /usr/local/benchmark /usr/local/benchmark
-# Add the path of jinux tools
-ENV PATH="/root/jinux/target/bin:${PATH}"
+# Add the path of Asterinas tools
+ENV PATH="/root/asterinas/target/bin:${PATH}"
-VOLUME [ "/root/jinux" ]
+VOLUME [ "/root/asterinas" ]
-WORKDIR /root/jinux
+WORKDIR /root/asterinas
diff --git a/tools/docker/Dockerfile.ubuntu22.04 b/tools/docker/Dockerfile.ubuntu22.04
--- a/tools/docker/Dockerfile.ubuntu22.04
+++ b/tools/docker/Dockerfile.ubuntu22.04
@@ -249,9 +249,9 @@ COPY --from=busybox /root/busybox/busybox /bin/busybox
# Install benchmarks built from the previous stages
COPY --from=build-benchmarks /usr/local/benchmark /usr/local/benchmark
-# Add the path of jinux tools
-ENV PATH="/root/jinux/target/bin:${PATH}"
+# Add the path of Asterinas tools
+ENV PATH="/root/asterinas/target/bin:${PATH}"
-VOLUME [ "/root/jinux" ]
+VOLUME [ "/root/asterinas" ]
-WORKDIR /root/jinux
+WORKDIR /root/asterinas
diff --git a/tools/docker/README.md b/tools/docker/README.md
--- a/tools/docker/README.md
+++ b/tools/docker/README.md
@@ -1,35 +1,35 @@
-# Jinux Development Docker Images
+# Asterinas Development Docker Images
-Jinux development Docker images are provided to facilitate developing and testing Jinux project. These images can be found in the [jinuxdev/jinux](https://hub.docker.com/r/jinuxdev/jinux/) repository on DockerHub.
+Asterinas development Docker images are provided to facilitate developing and testing Asterinas project. These images can be found in the [asterinas/asterinas](https://hub.docker.com/r/asterinas/asterinas/) repository on DockerHub.
## Building Docker Images
-To build a Docker image for Jinux and test it on your local machine, navigate to the root directory of the Jinux source code tree and execute the following command:
+To build a Docker image for Asterinas and test it on your local machine, navigate to the root directory of the Asterinas source code tree and execute the following command:
```bash
docker buildx build \
-f tools/docker/Dockerfile.ubuntu22.04 \
- --build-arg JINUX_RUST_VERSION=$RUST_VERSION \
- -t jinuxdev/jinux:$JINUX_VERSION \
+ --build-arg ASTER_RUST_VERSION=$RUST_VERSION \
+ -t asterinas/asterinas:$ASTER_VERSION \
.
```
The meanings of the two environment variables in the command are as follows:
-- `$JINUX_VERSION`: Represents the version number of Jinux. You can find this in the `VERSION` file.
+- `$ASTER_VERSION`: Represents the version number of Asterinas. You can find this in the `VERSION` file.
- `$RUST_VERSION`: Denotes the required Rust toolchain version, as specified in the `rust-toolchain` file.
## Tagging Docker Images
-It's essential for each Jinux Docker image to have a distinct tag. By convention, the tag is assigned with the version number of the Jinux project itself. This methodology ensures clear correspondence between a commit of the source code and its respective Docker image.
+It's essential for each Asterinas Docker image to have a distinct tag. By convention, the tag is assigned with the version number of the Asterinas project itself. This methodology ensures clear correspondence between a commit of the source code and its respective Docker image.
If a commit needs to create a new Docker image, it should
1. Update the Dockerfile as well as other materials relevant to the Docker image, and
-2. Run [`tools/bump_version.sh`](../bump_version.sh) tool to update the Jinux project's version number.
+2. Run [`tools/bump_version.sh`](../bump_version.sh) tool to update the Asterinas project's version number.
For bug fixes or small changes, increment the last number of a [SemVer](https://semver.org/) by one. For major features or releases, increment the second number. All changes made in the two steps should be included in the commit.
## Uploading Docker Images
-New versions of Jinux's Docker images are automatically uploaded to DockerHub through Github Actions. Simply submit your PR that updates Jinux's Docker image for review. After getting the project maintainers' approval, the [Docker image building workflow](../../.github/workflows/docker_build.yml) will be started, building the new Docker image and pushing it to DockerHub.
\ No newline at end of file
+New versions of Asterinas's Docker images are automatically uploaded to DockerHub through Github Actions. Simply submit your PR that updates Asterinas's Docker image for review. After getting the project maintainers' approval, the [Docker image building workflow](../../.github/workflows/docker_build.yml) will be started, building the new Docker image and pushing it to DockerHub.
\ No newline at end of file
diff --git a/tools/docker/run_dev_container.sh b/tools/docker/run_dev_container.sh
--- a/tools/docker/run_dev_container.sh
+++ b/tools/docker/run_dev_container.sh
@@ -3,9 +3,9 @@
set -e
SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
-JINUX_SRC_DIR=${SCRIPT_DIR}/../..
+ASTER_SRC_DIR=${SCRIPT_DIR}/../..
CARGO_TOML_PATH=${SCRIPT_DIR}/../../Cargo.toml
-VERSION=$( cat ${JINUX_SRC_DIR}/VERSION )
-IMAGE_NAME=jinuxdev/jinux:${VERSION}
+VERSION=$( cat ${ASTER_SRC_DIR}/VERSION )
+IMAGE_NAME=asterinas/asterinas:${VERSION}
-docker run -it --privileged --network=host --device=/dev/kvm -v ${JINUX_SRC_DIR}:/root/jinux ${IMAGE_NAME}
+docker run -it --privileged --network=host --device=/dev/kvm -v ${ASTER_SRC_DIR}:/root/asterinas ${IMAGE_NAME}
diff --git a/tools/docker/run_dev_container.sh b/tools/docker/run_dev_container.sh
--- a/tools/docker/run_dev_container.sh
+++ b/tools/docker/run_dev_container.sh
@@ -3,9 +3,9 @@
set -e
SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
-JINUX_SRC_DIR=${SCRIPT_DIR}/../..
+ASTER_SRC_DIR=${SCRIPT_DIR}/../..
CARGO_TOML_PATH=${SCRIPT_DIR}/../../Cargo.toml
-VERSION=$( cat ${JINUX_SRC_DIR}/VERSION )
-IMAGE_NAME=jinuxdev/jinux:${VERSION}
+VERSION=$( cat ${ASTER_SRC_DIR}/VERSION )
+IMAGE_NAME=asterinas/asterinas:${VERSION}
-docker run -it --privileged --network=host --device=/dev/kvm -v ${JINUX_SRC_DIR}:/root/jinux ${IMAGE_NAME}
+docker run -it --privileged --network=host --device=/dev/kvm -v ${ASTER_SRC_DIR}:/root/asterinas ${IMAGE_NAME}
|
2023-12-25T03:34:33Z
|
6dbf5d560deafea0dcec228e4cb2d5e53c756174
|
|
asterinas/asterinas
|
diff --git a/regression/syscall_test/blocklists/pty_test b/regression/syscall_test/blocklists/pty_test
--- a/regression/syscall_test/blocklists/pty_test
+++ b/regression/syscall_test/blocklists/pty_test
@@ -21,22 +21,8 @@ PtyTest.SwitchNoncanonToCanonNoNewlineBig
PtyTest.NoncanonBigWrite
PtyTest.SwitchNoncanonToCanonMultiline
PtyTest.SwitchTwiceMultiline
-JobControlTest.SetTTYMaster
-JobControlTest.SetTTY
-JobControlTest.SetTTYNonLeader
JobControlTest.SetTTYBadArg
JobControlTest.SetTTYDifferentSession
-JobControlTest.ReleaseTTY
-JobControlTest.ReleaseUnsetTTY
-JobControlTest.ReleaseWrongTTY
-JobControlTest.ReleaseTTYNonLeader
-JobControlTest.ReleaseTTYDifferentSession
JobControlTest.ReleaseTTYSignals
-JobControlTest.GetForegroundProcessGroup
-JobControlTest.GetForegroundProcessGroupNonControlling
JobControlTest.SetForegroundProcessGroup
-JobControlTest.SetForegroundProcessGroupWrongTTY
-JobControlTest.SetForegroundProcessGroupNegPgid
-JobControlTest.SetForegroundProcessGroupEmptyProcessGroup
-JobControlTest.SetForegroundProcessGroupDifferentSession
-JobControlTest.OrphanRegression
\ No newline at end of file
+JobControlTest.SetForegroundProcessGroupEmptyProcessGroup
\ No newline at end of file
diff --git a/services/libs/jinux-std/src/process/process/mod.rs b/services/libs/jinux-std/src/process/process/mod.rs
--- a/services/libs/jinux-std/src/process/process/mod.rs
+++ b/services/libs/jinux-std/src/process/process/mod.rs
@@ -319,3 +561,100 @@ pub fn current() -> Arc<Process> {
panic!("[Internal error]The current thread does not belong to a process");
}
}
+
+#[if_cfg_ktest]
+mod test {
+ use super::*;
+
+ fn new_process(parent: Option<Arc<Process>>) -> Arc<Process> {
+ crate::fs::rootfs::init_root_mount();
+ let pid = allocate_tid();
+ let parent = if let Some(parent) = parent {
+ Arc::downgrade(&parent)
+ } else {
+ Weak::new()
+ };
+ Arc::new(Process::new(
+ pid,
+ parent,
+ vec![],
+ String::new(),
+ ProcessVm::alloc(),
+ Arc::new(Mutex::new(FileTable::new())),
+ Arc::new(RwLock::new(FsResolver::new())),
+ Arc::new(RwLock::new(FileCreationMask::default())),
+ Arc::new(Mutex::new(SigDispositions::default())),
+ ResourceLimits::default(),
+ ))
+ }
+
+ fn new_process_in_session(parent: Option<Arc<Process>>) -> Arc<Process> {
+ // Lock order: session table -> group table -> group of process -> group inner
+ // -> session inner
+ let mut session_table_mut = process_table::session_table_mut();
+ let mut group_table_mut = process_table::group_table_mut();
+
+ let process = new_process(parent);
+ // Creates new group
+ let group = ProcessGroup::new(process.clone());
+ *process.process_group.lock() = Arc::downgrade(&group);
+
+ // Creates new session
+ let sess = Session::new(group.clone());
+ group.inner.lock().session = Arc::downgrade(&sess);
+ sess.inner.lock().leader = Some(process.clone());
+
+ group_table_mut.insert(group.pgid(), group);
+ session_table_mut.insert(sess.sid(), sess);
+
+ process
+ }
+
+ fn remove_session_and_group(process: Arc<Process>) {
+ // Lock order: session table -> group table
+ let mut session_table_mut = process_table::session_table_mut();
+ let mut group_table_mut = process_table::group_table_mut();
+ if let Some(sess) = process.session() {
+ session_table_mut.remove(&sess.sid());
+ }
+
+ if let Some(group) = process.process_group() {
+ group_table_mut.remove(&group.pgid());
+ }
+ }
+
+ #[ktest]
+ fn init_process() {
+ let process = new_process(None);
+ assert!(process.process_group().is_none());
+ assert!(process.session().is_none());
+ }
+
+ #[ktest]
+ fn init_process_in_session() {
+ let process = new_process_in_session(None);
+ assert!(process.is_group_leader());
+ assert!(process.is_session_leader());
+ remove_session_and_group(process);
+ }
+
+ #[ktest]
+ fn to_new_session() {
+ let process = new_process_in_session(None);
+ let sess = process.session().unwrap();
+ sess.inner.lock().leader = None;
+
+ assert!(!process.is_session_leader());
+ assert!(process
+ .to_new_session()
+ .is_err_and(|e| e.error() == Errno::EPERM));
+
+ let group = process.process_group().unwrap();
+ group.inner.lock().leader = None;
+ assert!(!process.is_group_leader());
+
+ assert!(process
+ .to_new_session()
+ .is_err_and(|e| e.error() == Errno::EPERM));
+ }
+}
diff --git a/services/libs/jinux-std/src/process/signal/sig_queues.rs b/services/libs/jinux-std/src/process/signal/sig_queues.rs
--- a/services/libs/jinux-std/src/process/signal/sig_queues.rs
+++ b/services/libs/jinux-std/src/process/signal/sig_queues.rs
@@ -81,8 +81,11 @@ impl SigQueues {
// POSIX leaves unspecified which to deliver first if there are multiple
// pending standard signals. So we are free to define our own. The
// principle is to give more urgent signals higher priority (like SIGKILL).
+
+ // FIXME: the gvisor pty_test JobControlTest::ReleaseTTY requires that
+ // the SIGHUP signal should be handled before SIGCONT.
const ORDERED_STD_SIGS: [SigNum; COUNT_STD_SIGS] = [
- SIGKILL, SIGTERM, SIGSTOP, SIGCONT, SIGSEGV, SIGILL, SIGHUP, SIGINT, SIGQUIT, SIGTRAP,
+ SIGKILL, SIGTERM, SIGSTOP, SIGSEGV, SIGILL, SIGHUP, SIGCONT, SIGINT, SIGQUIT, SIGTRAP,
SIGABRT, SIGBUS, SIGFPE, SIGUSR1, SIGUSR2, SIGPIPE, SIGALRM, SIGSTKFLT, SIGCHLD,
SIGTSTP, SIGTTIN, SIGTTOU, SIGURG, SIGXCPU, SIGXFSZ, SIGVTALRM, SIGPROF, SIGWINCH,
SIGIO, SIGPWR, SIGSYS,
|
[
"254"
] |
0.2
|
576578baf4025686ae4c2893c2aafbc8d1e14722
|
Implement session for shell job control
Process groups and sessions form a two-level hierarchical relationship between processes. A session is a collection of process groups. A process’s session membership is determined by its session identifier (SID). All of the processes in a session share a single controlling terminal.
The related syscalls are getsid and setsid
|
asterinas__asterinas-395
| 395
|
diff --git a/regression/syscall_test/blocklists/pty_test b/regression/syscall_test/blocklists/pty_test
--- a/regression/syscall_test/blocklists/pty_test
+++ b/regression/syscall_test/blocklists/pty_test
@@ -21,22 +21,8 @@ PtyTest.SwitchNoncanonToCanonNoNewlineBig
PtyTest.NoncanonBigWrite
PtyTest.SwitchNoncanonToCanonMultiline
PtyTest.SwitchTwiceMultiline
-JobControlTest.SetTTYMaster
-JobControlTest.SetTTY
-JobControlTest.SetTTYNonLeader
JobControlTest.SetTTYBadArg
JobControlTest.SetTTYDifferentSession
-JobControlTest.ReleaseTTY
-JobControlTest.ReleaseUnsetTTY
-JobControlTest.ReleaseWrongTTY
-JobControlTest.ReleaseTTYNonLeader
-JobControlTest.ReleaseTTYDifferentSession
JobControlTest.ReleaseTTYSignals
-JobControlTest.GetForegroundProcessGroup
-JobControlTest.GetForegroundProcessGroupNonControlling
JobControlTest.SetForegroundProcessGroup
-JobControlTest.SetForegroundProcessGroupWrongTTY
-JobControlTest.SetForegroundProcessGroupNegPgid
-JobControlTest.SetForegroundProcessGroupEmptyProcessGroup
-JobControlTest.SetForegroundProcessGroupDifferentSession
-JobControlTest.OrphanRegression
\ No newline at end of file
+JobControlTest.SetForegroundProcessGroupEmptyProcessGroup
\ No newline at end of file
diff --git a/services/libs/jinux-std/src/device/mod.rs b/services/libs/jinux-std/src/device/mod.rs
--- a/services/libs/jinux-std/src/device/mod.rs
+++ b/services/libs/jinux-std/src/device/mod.rs
@@ -12,6 +12,8 @@ pub use pty::{PtyMaster, PtySlave};
pub use random::Random;
pub use urandom::Urandom;
+use self::tty::get_n_tty;
+
/// Init the device node in fs, must be called after mounting rootfs.
pub fn init() -> Result<()> {
let null = Arc::new(null::Null);
diff --git a/services/libs/jinux-std/src/device/mod.rs b/services/libs/jinux-std/src/device/mod.rs
--- a/services/libs/jinux-std/src/device/mod.rs
+++ b/services/libs/jinux-std/src/device/mod.rs
@@ -12,6 +12,8 @@ pub use pty::{PtyMaster, PtySlave};
pub use random::Random;
pub use urandom::Urandom;
+use self::tty::get_n_tty;
+
/// Init the device node in fs, must be called after mounting rootfs.
pub fn init() -> Result<()> {
let null = Arc::new(null::Null);
diff --git a/services/libs/jinux-std/src/device/mod.rs b/services/libs/jinux-std/src/device/mod.rs
--- a/services/libs/jinux-std/src/device/mod.rs
+++ b/services/libs/jinux-std/src/device/mod.rs
@@ -19,7 +21,9 @@ pub fn init() -> Result<()> {
let zero = Arc::new(zero::Zero);
add_node(zero, "zero")?;
tty::init();
- let tty = tty::get_n_tty().clone();
+ let console = get_n_tty().clone();
+ add_node(console, "console")?;
+ let tty = Arc::new(tty::TtyDevice);
add_node(tty, "tty")?;
let random = Arc::new(random::Random);
add_node(random, "random")?;
diff --git a/services/libs/jinux-std/src/device/mod.rs b/services/libs/jinux-std/src/device/mod.rs
--- a/services/libs/jinux-std/src/device/mod.rs
+++ b/services/libs/jinux-std/src/device/mod.rs
@@ -19,7 +21,9 @@ pub fn init() -> Result<()> {
let zero = Arc::new(zero::Zero);
add_node(zero, "zero")?;
tty::init();
- let tty = tty::get_n_tty().clone();
+ let console = get_n_tty().clone();
+ add_node(console, "console")?;
+ let tty = Arc::new(tty::TtyDevice);
add_node(tty, "tty")?;
let random = Arc::new(random::Random);
add_node(random, "random")?;
diff --git a/services/libs/jinux-std/src/device/null.rs b/services/libs/jinux-std/src/device/null.rs
--- a/services/libs/jinux-std/src/device/null.rs
+++ b/services/libs/jinux-std/src/device/null.rs
@@ -1,5 +1,8 @@
use super::*;
+use crate::events::IoEvents;
+use crate::fs::inode_handle::FileIo;
use crate::prelude::*;
+use crate::process::signal::Poller;
pub struct Null;
diff --git a/services/libs/jinux-std/src/device/null.rs b/services/libs/jinux-std/src/device/null.rs
--- a/services/libs/jinux-std/src/device/null.rs
+++ b/services/libs/jinux-std/src/device/null.rs
@@ -1,5 +1,8 @@
use super::*;
+use crate::events::IoEvents;
+use crate::fs::inode_handle::FileIo;
use crate::prelude::*;
+use crate::process::signal::Poller;
pub struct Null;
diff --git a/services/libs/jinux-std/src/device/null.rs b/services/libs/jinux-std/src/device/null.rs
--- a/services/libs/jinux-std/src/device/null.rs
+++ b/services/libs/jinux-std/src/device/null.rs
@@ -12,7 +15,9 @@ impl Device for Null {
// Same value with Linux
DeviceId::new(1, 3)
}
+}
+impl FileIo for Null {
fn read(&self, _buf: &mut [u8]) -> Result<usize> {
Ok(0)
}
diff --git a/services/libs/jinux-std/src/device/null.rs b/services/libs/jinux-std/src/device/null.rs
--- a/services/libs/jinux-std/src/device/null.rs
+++ b/services/libs/jinux-std/src/device/null.rs
@@ -12,7 +15,9 @@ impl Device for Null {
// Same value with Linux
DeviceId::new(1, 3)
}
+}
+impl FileIo for Null {
fn read(&self, _buf: &mut [u8]) -> Result<usize> {
Ok(0)
}
diff --git a/services/libs/jinux-std/src/device/null.rs b/services/libs/jinux-std/src/device/null.rs
--- a/services/libs/jinux-std/src/device/null.rs
+++ b/services/libs/jinux-std/src/device/null.rs
@@ -20,4 +25,9 @@ impl Device for Null {
fn write(&self, buf: &[u8]) -> Result<usize> {
Ok(buf.len())
}
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ let events = IoEvents::IN | IoEvents::OUT;
+ events & mask
+ }
}
diff --git a/services/libs/jinux-std/src/device/null.rs b/services/libs/jinux-std/src/device/null.rs
--- a/services/libs/jinux-std/src/device/null.rs
+++ b/services/libs/jinux-std/src/device/null.rs
@@ -20,4 +25,9 @@ impl Device for Null {
fn write(&self, buf: &[u8]) -> Result<usize> {
Ok(buf.len())
}
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ let events = IoEvents::IN | IoEvents::OUT;
+ events & mask
+ }
}
diff --git a/services/libs/jinux-std/src/device/pty/mod.rs b/services/libs/jinux-std/src/device/pty/mod.rs
--- a/services/libs/jinux-std/src/device/pty/mod.rs
+++ b/services/libs/jinux-std/src/device/pty/mod.rs
@@ -33,7 +33,7 @@ pub fn init() -> Result<()> {
pub fn new_pty_pair(index: u32, ptmx: Arc<dyn Inode>) -> Result<(Arc<PtyMaster>, Arc<PtySlave>)> {
debug!("pty index = {}", index);
- let master = Arc::new(PtyMaster::new(ptmx, index));
- let slave = Arc::new(PtySlave::new(master.clone()));
+ let master = PtyMaster::new(ptmx, index);
+ let slave = PtySlave::new(&master);
Ok((master, slave))
}
diff --git a/services/libs/jinux-std/src/device/pty/mod.rs b/services/libs/jinux-std/src/device/pty/mod.rs
--- a/services/libs/jinux-std/src/device/pty/mod.rs
+++ b/services/libs/jinux-std/src/device/pty/mod.rs
@@ -33,7 +33,7 @@ pub fn init() -> Result<()> {
pub fn new_pty_pair(index: u32, ptmx: Arc<dyn Inode>) -> Result<(Arc<PtyMaster>, Arc<PtySlave>)> {
debug!("pty index = {}", index);
- let master = Arc::new(PtyMaster::new(ptmx, index));
- let slave = Arc::new(PtySlave::new(master.clone()));
+ let master = PtyMaster::new(ptmx, index);
+ let slave = PtySlave::new(&master);
Ok((master, slave))
}
diff --git a/services/libs/jinux-std/src/device/pty/pty.rs b/services/libs/jinux-std/src/device/pty/pty.rs
--- a/services/libs/jinux-std/src/device/pty/pty.rs
+++ b/services/libs/jinux-std/src/device/pty/pty.rs
@@ -2,16 +2,18 @@ use alloc::format;
use ringbuf::{ring_buffer::RbBase, HeapRb, Rb};
use crate::device::tty::line_discipline::LineDiscipline;
+use crate::device::tty::new_job_control_and_ldisc;
use crate::events::IoEvents;
use crate::fs::device::{Device, DeviceId, DeviceType};
-use crate::fs::file_handle::FileLike;
+use crate::fs::devpts::DevPts;
use crate::fs::fs_resolver::FsPath;
+use crate::fs::inode_handle::FileIo;
use crate::fs::utils::{AccessMode, Inode, InodeMode, IoctlCmd};
use crate::prelude::*;
use crate::process::signal::{Pollee, Poller};
+use crate::process::{JobControl, Terminal};
use crate::util::{read_val_from_user, write_val_to_user};
-const PTS_DIR: &str = "/dev/pts";
const BUFFER_CAPACITY: usize = 4096;
/// Pesudo terminal master.
diff --git a/services/libs/jinux-std/src/device/pty/pty.rs b/services/libs/jinux-std/src/device/pty/pty.rs
--- a/services/libs/jinux-std/src/device/pty/pty.rs
+++ b/services/libs/jinux-std/src/device/pty/pty.rs
@@ -2,16 +2,18 @@ use alloc::format;
use ringbuf::{ring_buffer::RbBase, HeapRb, Rb};
use crate::device::tty::line_discipline::LineDiscipline;
+use crate::device::tty::new_job_control_and_ldisc;
use crate::events::IoEvents;
use crate::fs::device::{Device, DeviceId, DeviceType};
-use crate::fs::file_handle::FileLike;
+use crate::fs::devpts::DevPts;
use crate::fs::fs_resolver::FsPath;
+use crate::fs::inode_handle::FileIo;
use crate::fs::utils::{AccessMode, Inode, InodeMode, IoctlCmd};
use crate::prelude::*;
use crate::process::signal::{Pollee, Poller};
+use crate::process::{JobControl, Terminal};
use crate::util::{read_val_from_user, write_val_to_user};
-const PTS_DIR: &str = "/dev/pts";
const BUFFER_CAPACITY: usize = 4096;
/// Pesudo terminal master.
diff --git a/services/libs/jinux-std/src/device/pty/pty.rs b/services/libs/jinux-std/src/device/pty/pty.rs
--- a/services/libs/jinux-std/src/device/pty/pty.rs
+++ b/services/libs/jinux-std/src/device/pty/pty.rs
@@ -23,19 +25,24 @@ pub struct PtyMaster {
index: u32,
output: Arc<LineDiscipline>,
input: SpinLock<HeapRb<u8>>,
+ job_control: Arc<JobControl>,
/// The state of input buffer
pollee: Pollee,
+ weak_self: Weak<Self>,
}
impl PtyMaster {
- pub fn new(ptmx: Arc<dyn Inode>, index: u32) -> Self {
- Self {
+ pub fn new(ptmx: Arc<dyn Inode>, index: u32) -> Arc<Self> {
+ let (job_control, ldisc) = new_job_control_and_ldisc();
+ Arc::new_cyclic(move |weak_ref| PtyMaster {
ptmx,
index,
- output: LineDiscipline::new(),
+ output: ldisc,
input: SpinLock::new(HeapRb::new(BUFFER_CAPACITY)),
+ job_control,
pollee: Pollee::new(IoEvents::OUT),
- }
+ weak_self: weak_ref.clone(),
+ })
}
pub fn index(&self) -> u32 {
diff --git a/services/libs/jinux-std/src/device/pty/pty.rs b/services/libs/jinux-std/src/device/pty/pty.rs
--- a/services/libs/jinux-std/src/device/pty/pty.rs
+++ b/services/libs/jinux-std/src/device/pty/pty.rs
@@ -23,19 +25,24 @@ pub struct PtyMaster {
index: u32,
output: Arc<LineDiscipline>,
input: SpinLock<HeapRb<u8>>,
+ job_control: Arc<JobControl>,
/// The state of input buffer
pollee: Pollee,
+ weak_self: Weak<Self>,
}
impl PtyMaster {
- pub fn new(ptmx: Arc<dyn Inode>, index: u32) -> Self {
- Self {
+ pub fn new(ptmx: Arc<dyn Inode>, index: u32) -> Arc<Self> {
+ let (job_control, ldisc) = new_job_control_and_ldisc();
+ Arc::new_cyclic(move |weak_ref| PtyMaster {
ptmx,
index,
- output: LineDiscipline::new(),
+ output: ldisc,
input: SpinLock::new(HeapRb::new(BUFFER_CAPACITY)),
+ job_control,
pollee: Pollee::new(IoEvents::OUT),
- }
+ weak_self: weak_ref.clone(),
+ })
}
pub fn index(&self) -> u32 {
diff --git a/services/libs/jinux-std/src/device/pty/pty.rs b/services/libs/jinux-std/src/device/pty/pty.rs
--- a/services/libs/jinux-std/src/device/pty/pty.rs
+++ b/services/libs/jinux-std/src/device/pty/pty.rs
@@ -46,16 +53,12 @@ impl PtyMaster {
&self.ptmx
}
- pub(super) fn slave_push_byte(&self, byte: u8) {
+ pub(super) fn slave_push_char(&self, ch: u8) {
let mut input = self.input.lock_irq_disabled();
- input.push_overwrite(byte);
+ input.push_overwrite(ch);
self.update_state(&input);
}
- pub(super) fn slave_read(&self, buf: &mut [u8]) -> Result<usize> {
- self.output.read(buf)
- }
-
pub(super) fn slave_poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
let mut poll_status = IoEvents::empty();
diff --git a/services/libs/jinux-std/src/device/pty/pty.rs b/services/libs/jinux-std/src/device/pty/pty.rs
--- a/services/libs/jinux-std/src/device/pty/pty.rs
+++ b/services/libs/jinux-std/src/device/pty/pty.rs
@@ -46,16 +53,12 @@ impl PtyMaster {
&self.ptmx
}
- pub(super) fn slave_push_byte(&self, byte: u8) {
+ pub(super) fn slave_push_char(&self, ch: u8) {
let mut input = self.input.lock_irq_disabled();
- input.push_overwrite(byte);
+ input.push_overwrite(ch);
self.update_state(&input);
}
- pub(super) fn slave_read(&self, buf: &mut [u8]) -> Result<usize> {
- self.output.read(buf)
- }
-
pub(super) fn slave_poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
let mut poll_status = IoEvents::empty();
diff --git a/services/libs/jinux-std/src/device/pty/pty.rs b/services/libs/jinux-std/src/device/pty/pty.rs
--- a/services/libs/jinux-std/src/device/pty/pty.rs
+++ b/services/libs/jinux-std/src/device/pty/pty.rs
@@ -87,7 +90,7 @@ impl PtyMaster {
}
}
-impl FileLike for PtyMaster {
+impl FileIo for PtyMaster {
fn read(&self, buf: &mut [u8]) -> Result<usize> {
// TODO: deal with nonblocking read
if buf.is_empty() {
diff --git a/services/libs/jinux-std/src/device/pty/pty.rs b/services/libs/jinux-std/src/device/pty/pty.rs
--- a/services/libs/jinux-std/src/device/pty/pty.rs
+++ b/services/libs/jinux-std/src/device/pty/pty.rs
@@ -87,7 +90,7 @@ impl PtyMaster {
}
}
-impl FileLike for PtyMaster {
+impl FileIo for PtyMaster {
fn read(&self, buf: &mut [u8]) -> Result<usize> {
// TODO: deal with nonblocking read
if buf.is_empty() {
diff --git a/services/libs/jinux-std/src/device/pty/pty.rs b/services/libs/jinux-std/src/device/pty/pty.rs
--- a/services/libs/jinux-std/src/device/pty/pty.rs
+++ b/services/libs/jinux-std/src/device/pty/pty.rs
@@ -122,7 +125,6 @@ impl FileLike for PtyMaster {
fn write(&self, buf: &[u8]) -> Result<usize> {
let mut input = self.input.lock();
-
for character in buf {
self.output.push_char(*character, |content| {
for byte in content.as_bytes() {
diff --git a/services/libs/jinux-std/src/device/pty/pty.rs b/services/libs/jinux-std/src/device/pty/pty.rs
--- a/services/libs/jinux-std/src/device/pty/pty.rs
+++ b/services/libs/jinux-std/src/device/pty/pty.rs
@@ -122,7 +125,6 @@ impl FileLike for PtyMaster {
fn write(&self, buf: &[u8]) -> Result<usize> {
let mut input = self.input.lock();
-
for character in buf {
self.output.push_char(*character, |content| {
for byte in content.as_bytes() {
diff --git a/services/libs/jinux-std/src/device/pty/pty.rs b/services/libs/jinux-std/src/device/pty/pty.rs
--- a/services/libs/jinux-std/src/device/pty/pty.rs
+++ b/services/libs/jinux-std/src/device/pty/pty.rs
@@ -193,29 +195,35 @@ impl FileLike for PtyMaster {
self.output.set_window_size(winsize);
Ok(0)
}
- IoctlCmd::TIOCSCTTY => {
- // TODO: reimplement when adding session.
- let foreground = {
- let current = current!();
- let process_group = current.process_group().unwrap();
- Arc::downgrade(&process_group)
- };
- self.output.set_fg(foreground);
- Ok(0)
- }
IoctlCmd::TIOCGPGRP => {
- let Some(fg_pgid) = self.output.fg_pgid() else {
+ let Some(foreground) = self.foreground() else {
return_errno_with_message!(
Errno::ESRCH,
"the foreground process group does not exist"
);
};
+ let fg_pgid = foreground.pgid();
write_val_to_user(arg, &fg_pgid)?;
Ok(0)
}
+ IoctlCmd::TIOCSPGRP => {
+ let pgid = {
+ let pgid: i32 = read_val_from_user(arg)?;
+ if pgid < 0 {
+ return_errno_with_message!(Errno::EINVAL, "negative pgid");
+ }
+ pgid as u32
+ };
+
+ self.set_foreground(&pgid)?;
+ Ok(0)
+ }
+ IoctlCmd::TIOCSCTTY => {
+ self.set_current_session()?;
+ Ok(0)
+ }
IoctlCmd::TIOCNOTTY => {
- // TODO: reimplement when adding session.
- self.output.set_fg(Weak::new());
+ self.release_current_session()?;
Ok(0)
}
IoctlCmd::FIONREAD => {
diff --git a/services/libs/jinux-std/src/device/pty/pty.rs b/services/libs/jinux-std/src/device/pty/pty.rs
--- a/services/libs/jinux-std/src/device/pty/pty.rs
+++ b/services/libs/jinux-std/src/device/pty/pty.rs
@@ -193,29 +195,35 @@ impl FileLike for PtyMaster {
self.output.set_window_size(winsize);
Ok(0)
}
- IoctlCmd::TIOCSCTTY => {
- // TODO: reimplement when adding session.
- let foreground = {
- let current = current!();
- let process_group = current.process_group().unwrap();
- Arc::downgrade(&process_group)
- };
- self.output.set_fg(foreground);
- Ok(0)
- }
IoctlCmd::TIOCGPGRP => {
- let Some(fg_pgid) = self.output.fg_pgid() else {
+ let Some(foreground) = self.foreground() else {
return_errno_with_message!(
Errno::ESRCH,
"the foreground process group does not exist"
);
};
+ let fg_pgid = foreground.pgid();
write_val_to_user(arg, &fg_pgid)?;
Ok(0)
}
+ IoctlCmd::TIOCSPGRP => {
+ let pgid = {
+ let pgid: i32 = read_val_from_user(arg)?;
+ if pgid < 0 {
+ return_errno_with_message!(Errno::EINVAL, "negative pgid");
+ }
+ pgid as u32
+ };
+
+ self.set_foreground(&pgid)?;
+ Ok(0)
+ }
+ IoctlCmd::TIOCSCTTY => {
+ self.set_current_session()?;
+ Ok(0)
+ }
IoctlCmd::TIOCNOTTY => {
- // TODO: reimplement when adding session.
- self.output.set_fg(Weak::new());
+ self.release_current_session()?;
Ok(0)
}
IoctlCmd::FIONREAD => {
diff --git a/services/libs/jinux-std/src/device/pty/pty.rs b/services/libs/jinux-std/src/device/pty/pty.rs
--- a/services/libs/jinux-std/src/device/pty/pty.rs
+++ b/services/libs/jinux-std/src/device/pty/pty.rs
@@ -246,15 +254,47 @@ impl FileLike for PtyMaster {
}
}
-pub struct PtySlave(Arc<PtyMaster>);
+impl Terminal for PtyMaster {
+ fn arc_self(&self) -> Arc<dyn Terminal> {
+ self.weak_self.upgrade().unwrap() as _
+ }
+
+ fn job_control(&self) -> &JobControl {
+ &self.job_control
+ }
+}
+
+impl Drop for PtyMaster {
+ fn drop(&mut self) {
+ let fs = self.ptmx.fs();
+ let devpts = fs.downcast_ref::<DevPts>().unwrap();
+
+ let index = self.index;
+ devpts.remove_slave(index);
+ }
+}
+
+pub struct PtySlave {
+ master: Weak<PtyMaster>,
+ job_control: JobControl,
+ weak_self: Weak<Self>,
+}
impl PtySlave {
- pub fn new(master: Arc<PtyMaster>) -> Self {
- PtySlave(master)
+ pub fn new(master: &Arc<PtyMaster>) -> Arc<Self> {
+ Arc::new_cyclic(|weak_ref| PtySlave {
+ master: Arc::downgrade(master),
+ job_control: JobControl::new(),
+ weak_self: weak_ref.clone(),
+ })
}
pub fn index(&self) -> u32 {
- self.0.index()
+ self.master().index()
+ }
+
+ fn master(&self) -> Arc<PtyMaster> {
+ self.master.upgrade().unwrap()
}
}
diff --git a/services/libs/jinux-std/src/device/pty/pty.rs b/services/libs/jinux-std/src/device/pty/pty.rs
--- a/services/libs/jinux-std/src/device/pty/pty.rs
+++ b/services/libs/jinux-std/src/device/pty/pty.rs
@@ -246,15 +254,47 @@ impl FileLike for PtyMaster {
}
}
-pub struct PtySlave(Arc<PtyMaster>);
+impl Terminal for PtyMaster {
+ fn arc_self(&self) -> Arc<dyn Terminal> {
+ self.weak_self.upgrade().unwrap() as _
+ }
+
+ fn job_control(&self) -> &JobControl {
+ &self.job_control
+ }
+}
+
+impl Drop for PtyMaster {
+ fn drop(&mut self) {
+ let fs = self.ptmx.fs();
+ let devpts = fs.downcast_ref::<DevPts>().unwrap();
+
+ let index = self.index;
+ devpts.remove_slave(index);
+ }
+}
+
+pub struct PtySlave {
+ master: Weak<PtyMaster>,
+ job_control: JobControl,
+ weak_self: Weak<Self>,
+}
impl PtySlave {
- pub fn new(master: Arc<PtyMaster>) -> Self {
- PtySlave(master)
+ pub fn new(master: &Arc<PtyMaster>) -> Arc<Self> {
+ Arc::new_cyclic(|weak_ref| PtySlave {
+ master: Arc::downgrade(master),
+ job_control: JobControl::new(),
+ weak_self: weak_ref.clone(),
+ })
}
pub fn index(&self) -> u32 {
- self.0.index()
+ self.master().index()
+ }
+
+ fn master(&self) -> Arc<PtyMaster> {
+ self.master.upgrade().unwrap()
}
}
diff --git a/services/libs/jinux-std/src/device/pty/pty.rs b/services/libs/jinux-std/src/device/pty/pty.rs
--- a/services/libs/jinux-std/src/device/pty/pty.rs
+++ b/services/libs/jinux-std/src/device/pty/pty.rs
@@ -266,50 +306,91 @@ impl Device for PtySlave {
fn id(&self) -> crate::fs::device::DeviceId {
DeviceId::new(88, self.index())
}
+}
+impl Terminal for PtySlave {
+ fn arc_self(&self) -> Arc<dyn Terminal> {
+ self.weak_self.upgrade().unwrap() as _
+ }
+
+ fn job_control(&self) -> &JobControl {
+ &self.job_control
+ }
+}
+
+impl FileIo for PtySlave {
fn read(&self, buf: &mut [u8]) -> Result<usize> {
- self.0.slave_read(buf)
+ self.job_control.wait_until_in_foreground()?;
+ self.master().output.read(buf)
}
fn write(&self, buf: &[u8]) -> Result<usize> {
+ let master = self.master();
for ch in buf {
// do we need to add '\r' here?
if *ch == b'\n' {
- self.0.slave_push_byte(b'\r');
- self.0.slave_push_byte(b'\n');
+ master.slave_push_char(b'\r');
+ master.slave_push_char(b'\n');
} else {
- self.0.slave_push_byte(*ch);
+ master.slave_push_char(*ch);
}
}
Ok(buf.len())
}
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ self.master().slave_poll(mask, poller)
+ }
+
fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
match cmd {
IoctlCmd::TCGETS
| IoctlCmd::TCSETS
- | IoctlCmd::TIOCGPGRP
| IoctlCmd::TIOCGPTN
| IoctlCmd::TIOCGWINSZ
- | IoctlCmd::TIOCSWINSZ => self.0.ioctl(cmd, arg),
+ | IoctlCmd::TIOCSWINSZ => self.master().ioctl(cmd, arg),
+ IoctlCmd::TIOCGPGRP => {
+ if !self.is_controlling_terminal() {
+ return_errno_with_message!(Errno::ENOTTY, "slave is not controlling terminal");
+ }
+
+ let Some(foreground) = self.foreground() else {
+ return_errno_with_message!(
+ Errno::ESRCH,
+ "the foreground process group does not exist"
+ );
+ };
+
+ let fg_pgid = foreground.pgid();
+ write_val_to_user(arg, &fg_pgid)?;
+ Ok(0)
+ }
+ IoctlCmd::TIOCSPGRP => {
+ let pgid = {
+ let pgid: i32 = read_val_from_user(arg)?;
+ if pgid < 0 {
+ return_errno_with_message!(Errno::EINVAL, "negative pgid");
+ }
+ pgid as u32
+ };
+
+ self.set_foreground(&pgid)?;
+ Ok(0)
+ }
IoctlCmd::TIOCSCTTY => {
- // TODO:
+ self.set_current_session()?;
Ok(0)
}
IoctlCmd::TIOCNOTTY => {
- // TODO:
+ self.release_current_session()?;
Ok(0)
}
IoctlCmd::FIONREAD => {
- let buffer_len = self.0.slave_buf_len() as i32;
+ let buffer_len = self.master().slave_buf_len() as i32;
write_val_to_user(arg, &buffer_len)?;
Ok(0)
}
_ => Ok(0),
}
}
-
- fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
- self.0.slave_poll(mask, poller)
- }
}
diff --git a/services/libs/jinux-std/src/device/pty/pty.rs b/services/libs/jinux-std/src/device/pty/pty.rs
--- a/services/libs/jinux-std/src/device/pty/pty.rs
+++ b/services/libs/jinux-std/src/device/pty/pty.rs
@@ -266,50 +306,91 @@ impl Device for PtySlave {
fn id(&self) -> crate::fs::device::DeviceId {
DeviceId::new(88, self.index())
}
+}
+impl Terminal for PtySlave {
+ fn arc_self(&self) -> Arc<dyn Terminal> {
+ self.weak_self.upgrade().unwrap() as _
+ }
+
+ fn job_control(&self) -> &JobControl {
+ &self.job_control
+ }
+}
+
+impl FileIo for PtySlave {
fn read(&self, buf: &mut [u8]) -> Result<usize> {
- self.0.slave_read(buf)
+ self.job_control.wait_until_in_foreground()?;
+ self.master().output.read(buf)
}
fn write(&self, buf: &[u8]) -> Result<usize> {
+ let master = self.master();
for ch in buf {
// do we need to add '\r' here?
if *ch == b'\n' {
- self.0.slave_push_byte(b'\r');
- self.0.slave_push_byte(b'\n');
+ master.slave_push_char(b'\r');
+ master.slave_push_char(b'\n');
} else {
- self.0.slave_push_byte(*ch);
+ master.slave_push_char(*ch);
}
}
Ok(buf.len())
}
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ self.master().slave_poll(mask, poller)
+ }
+
fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
match cmd {
IoctlCmd::TCGETS
| IoctlCmd::TCSETS
- | IoctlCmd::TIOCGPGRP
| IoctlCmd::TIOCGPTN
| IoctlCmd::TIOCGWINSZ
- | IoctlCmd::TIOCSWINSZ => self.0.ioctl(cmd, arg),
+ | IoctlCmd::TIOCSWINSZ => self.master().ioctl(cmd, arg),
+ IoctlCmd::TIOCGPGRP => {
+ if !self.is_controlling_terminal() {
+ return_errno_with_message!(Errno::ENOTTY, "slave is not controlling terminal");
+ }
+
+ let Some(foreground) = self.foreground() else {
+ return_errno_with_message!(
+ Errno::ESRCH,
+ "the foreground process group does not exist"
+ );
+ };
+
+ let fg_pgid = foreground.pgid();
+ write_val_to_user(arg, &fg_pgid)?;
+ Ok(0)
+ }
+ IoctlCmd::TIOCSPGRP => {
+ let pgid = {
+ let pgid: i32 = read_val_from_user(arg)?;
+ if pgid < 0 {
+ return_errno_with_message!(Errno::EINVAL, "negative pgid");
+ }
+ pgid as u32
+ };
+
+ self.set_foreground(&pgid)?;
+ Ok(0)
+ }
IoctlCmd::TIOCSCTTY => {
- // TODO:
+ self.set_current_session()?;
Ok(0)
}
IoctlCmd::TIOCNOTTY => {
- // TODO:
+ self.release_current_session()?;
Ok(0)
}
IoctlCmd::FIONREAD => {
- let buffer_len = self.0.slave_buf_len() as i32;
+ let buffer_len = self.master().slave_buf_len() as i32;
write_val_to_user(arg, &buffer_len)?;
Ok(0)
}
_ => Ok(0),
}
}
-
- fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
- self.0.slave_poll(mask, poller)
- }
}
diff --git a/services/libs/jinux-std/src/device/random.rs b/services/libs/jinux-std/src/device/random.rs
--- a/services/libs/jinux-std/src/device/random.rs
+++ b/services/libs/jinux-std/src/device/random.rs
@@ -1,5 +1,8 @@
+use crate::events::IoEvents;
use crate::fs::device::{Device, DeviceId, DeviceType};
+use crate::fs::inode_handle::FileIo;
use crate::prelude::*;
+use crate::process::signal::Poller;
pub struct Random;
diff --git a/services/libs/jinux-std/src/device/random.rs b/services/libs/jinux-std/src/device/random.rs
--- a/services/libs/jinux-std/src/device/random.rs
+++ b/services/libs/jinux-std/src/device/random.rs
@@ -1,5 +1,8 @@
+use crate::events::IoEvents;
use crate::fs::device::{Device, DeviceId, DeviceType};
+use crate::fs::inode_handle::FileIo;
use crate::prelude::*;
+use crate::process::signal::Poller;
pub struct Random;
diff --git a/services/libs/jinux-std/src/device/random.rs b/services/libs/jinux-std/src/device/random.rs
--- a/services/libs/jinux-std/src/device/random.rs
+++ b/services/libs/jinux-std/src/device/random.rs
@@ -19,7 +22,9 @@ impl Device for Random {
// The same value as Linux
DeviceId::new(1, 8)
}
+}
+impl FileIo for Random {
fn read(&self, buf: &mut [u8]) -> Result<usize> {
Self::getrandom(buf)
}
diff --git a/services/libs/jinux-std/src/device/random.rs b/services/libs/jinux-std/src/device/random.rs
--- a/services/libs/jinux-std/src/device/random.rs
+++ b/services/libs/jinux-std/src/device/random.rs
@@ -19,7 +22,9 @@ impl Device for Random {
// The same value as Linux
DeviceId::new(1, 8)
}
+}
+impl FileIo for Random {
fn read(&self, buf: &mut [u8]) -> Result<usize> {
Self::getrandom(buf)
}
diff --git a/services/libs/jinux-std/src/device/random.rs b/services/libs/jinux-std/src/device/random.rs
--- a/services/libs/jinux-std/src/device/random.rs
+++ b/services/libs/jinux-std/src/device/random.rs
@@ -27,6 +32,11 @@ impl Device for Random {
fn write(&self, buf: &[u8]) -> Result<usize> {
Ok(buf.len())
}
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ let events = IoEvents::IN | IoEvents::OUT;
+ events & mask
+ }
}
impl From<getrandom::Error> for Error {
diff --git a/services/libs/jinux-std/src/device/random.rs b/services/libs/jinux-std/src/device/random.rs
--- a/services/libs/jinux-std/src/device/random.rs
+++ b/services/libs/jinux-std/src/device/random.rs
@@ -27,6 +32,11 @@ impl Device for Random {
fn write(&self, buf: &[u8]) -> Result<usize> {
Ok(buf.len())
}
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ let events = IoEvents::IN | IoEvents::OUT;
+ events & mask
+ }
}
impl From<getrandom::Error> for Error {
diff --git /dev/null b/services/libs/jinux-std/src/device/tty/device.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/device/tty/device.rs
@@ -0,0 +1,47 @@
+use crate::events::IoEvents;
+use crate::fs::device::{Device, DeviceId, DeviceType};
+use crate::fs::inode_handle::FileIo;
+use crate::prelude::*;
+use crate::process::signal::Poller;
+
+/// Corresponds to `/dev/tty` in the file system. This device represents the controlling terminal
+/// of the session of current process.
+pub struct TtyDevice;
+
+impl Device for TtyDevice {
+ fn open(&self) -> Result<Option<Arc<dyn FileIo>>> {
+ let current = current!();
+ let session = current.session().unwrap();
+
+ let Some(terminal) = session.terminal() else {
+ return_errno_with_message!(
+ Errno::ENOTTY,
+ "the session does not have controlling terminal"
+ );
+ };
+
+ Ok(Some(terminal as Arc<dyn FileIo>))
+ }
+
+ fn type_(&self) -> DeviceType {
+ DeviceType::CharDevice
+ }
+
+ fn id(&self) -> DeviceId {
+ DeviceId::new(5, 0)
+ }
+}
+
+impl FileIo for TtyDevice {
+ fn read(&self, buf: &mut [u8]) -> Result<usize> {
+ return_errno_with_message!(Errno::EINVAL, "cannot read tty device");
+ }
+
+ fn write(&self, buf: &[u8]) -> Result<usize> {
+ return_errno_with_message!(Errno::EINVAL, "cannot write tty device");
+ }
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ IoEvents::empty()
+ }
+}
diff --git /dev/null b/services/libs/jinux-std/src/device/tty/device.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/device/tty/device.rs
@@ -0,0 +1,47 @@
+use crate::events::IoEvents;
+use crate::fs::device::{Device, DeviceId, DeviceType};
+use crate::fs::inode_handle::FileIo;
+use crate::prelude::*;
+use crate::process::signal::Poller;
+
+/// Corresponds to `/dev/tty` in the file system. This device represents the controlling terminal
+/// of the session of current process.
+pub struct TtyDevice;
+
+impl Device for TtyDevice {
+ fn open(&self) -> Result<Option<Arc<dyn FileIo>>> {
+ let current = current!();
+ let session = current.session().unwrap();
+
+ let Some(terminal) = session.terminal() else {
+ return_errno_with_message!(
+ Errno::ENOTTY,
+ "the session does not have controlling terminal"
+ );
+ };
+
+ Ok(Some(terminal as Arc<dyn FileIo>))
+ }
+
+ fn type_(&self) -> DeviceType {
+ DeviceType::CharDevice
+ }
+
+ fn id(&self) -> DeviceId {
+ DeviceId::new(5, 0)
+ }
+}
+
+impl FileIo for TtyDevice {
+ fn read(&self, buf: &mut [u8]) -> Result<usize> {
+ return_errno_with_message!(Errno::EINVAL, "cannot read tty device");
+ }
+
+ fn write(&self, buf: &[u8]) -> Result<usize> {
+ return_errno_with_message!(Errno::EINVAL, "cannot write tty device");
+ }
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ IoEvents::empty()
+ }
+}
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -1,13 +1,10 @@
use crate::events::IoEvents;
+use crate::prelude::*;
use crate::process::signal::constants::{SIGINT, SIGQUIT};
+use crate::process::signal::signals::kernel::KernelSignal;
use crate::process::signal::{Pollee, Poller};
-use crate::process::ProcessGroup;
use crate::thread::work_queue::work_item::WorkItem;
use crate::thread::work_queue::{submit_work_item, WorkPriority};
-use crate::{
- prelude::*,
- process::{signal::signals::kernel::KernelSignal, Pgid},
-};
use alloc::format;
use jinux_frame::trap::disable_local;
use ringbuf::{ring_buffer::RbBase, Rb, StaticRb};
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -1,13 +1,10 @@
use crate::events::IoEvents;
+use crate::prelude::*;
use crate::process::signal::constants::{SIGINT, SIGQUIT};
+use crate::process::signal::signals::kernel::KernelSignal;
use crate::process::signal::{Pollee, Poller};
-use crate::process::ProcessGroup;
use crate::thread::work_queue::work_item::WorkItem;
use crate::thread::work_queue::{submit_work_item, WorkPriority};
-use crate::{
- prelude::*,
- process::{signal::signals::kernel::KernelSignal, Pgid},
-};
use alloc::format;
use jinux_frame::trap::disable_local;
use ringbuf::{ring_buffer::RbBase, Rb, StaticRb};
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -19,19 +16,21 @@ use super::termio::{KernelTermios, WinSize, CC_C_CHAR};
const BUFFER_CAPACITY: usize = 4096;
+pub type LdiscSignalSender = Arc<dyn Fn(KernelSignal) + Send + Sync + 'static>;
+
pub struct LineDiscipline {
/// current line
current_line: SpinLock<CurrentLine>,
/// The read buffer
read_buffer: SpinLock<StaticRb<u8, BUFFER_CAPACITY>>,
- /// The foreground process group
- foreground: SpinLock<Weak<ProcessGroup>>,
/// termios
termios: SpinLock<KernelTermios>,
/// Windows size,
winsize: SpinLock<WinSize>,
/// Pollee
pollee: Pollee,
+ /// Used to send signal for foreground processes, when some char comes.
+ send_signal: LdiscSignalSender,
/// work item
work_item: Arc<WorkItem>,
/// Parameters used by a work item.
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -19,19 +16,21 @@ use super::termio::{KernelTermios, WinSize, CC_C_CHAR};
const BUFFER_CAPACITY: usize = 4096;
+pub type LdiscSignalSender = Arc<dyn Fn(KernelSignal) + Send + Sync + 'static>;
+
pub struct LineDiscipline {
/// current line
current_line: SpinLock<CurrentLine>,
/// The read buffer
read_buffer: SpinLock<StaticRb<u8, BUFFER_CAPACITY>>,
- /// The foreground process group
- foreground: SpinLock<Weak<ProcessGroup>>,
/// termios
termios: SpinLock<KernelTermios>,
/// Windows size,
winsize: SpinLock<WinSize>,
/// Pollee
pollee: Pollee,
+ /// Used to send signal for foreground processes, when some char comes.
+ send_signal: LdiscSignalSender,
/// work item
work_item: Arc<WorkItem>,
/// Parameters used by a work item.
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -76,8 +75,8 @@ impl CurrentLine {
impl LineDiscipline {
/// Create a new line discipline
- pub fn new() -> Arc<Self> {
- Arc::new_cyclic(|line_ref: &Weak<LineDiscipline>| {
+ pub fn new(send_signal: LdiscSignalSender) -> Arc<Self> {
+ Arc::new_cyclic(move |line_ref: &Weak<LineDiscipline>| {
let line_discipline = line_ref.clone();
let work_item = Arc::new(WorkItem::new(Box::new(move || {
if let Some(line_discipline) = line_discipline.upgrade() {
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -76,8 +75,8 @@ impl CurrentLine {
impl LineDiscipline {
/// Create a new line discipline
- pub fn new() -> Arc<Self> {
- Arc::new_cyclic(|line_ref: &Weak<LineDiscipline>| {
+ pub fn new(send_signal: LdiscSignalSender) -> Arc<Self> {
+ Arc::new_cyclic(move |line_ref: &Weak<LineDiscipline>| {
let line_discipline = line_ref.clone();
let work_item = Arc::new(WorkItem::new(Box::new(move || {
if let Some(line_discipline) = line_discipline.upgrade() {
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -87,10 +86,10 @@ impl LineDiscipline {
Self {
current_line: SpinLock::new(CurrentLine::new()),
read_buffer: SpinLock::new(StaticRb::default()),
- foreground: SpinLock::new(Weak::new()),
termios: SpinLock::new(KernelTermios::default()),
winsize: SpinLock::new(WinSize::default()),
pollee: Pollee::new(IoEvents::empty()),
+ send_signal,
work_item,
work_item_para: Arc::new(SpinLock::new(LineDisciplineWorkPara::new())),
}
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -87,10 +86,10 @@ impl LineDiscipline {
Self {
current_line: SpinLock::new(CurrentLine::new()),
read_buffer: SpinLock::new(StaticRb::default()),
- foreground: SpinLock::new(Weak::new()),
termios: SpinLock::new(KernelTermios::default()),
winsize: SpinLock::new(WinSize::default()),
pollee: Pollee::new(IoEvents::empty()),
+ send_signal,
work_item,
work_item_para: Arc::new(SpinLock::new(LineDisciplineWorkPara::new())),
}
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -98,7 +97,7 @@ impl LineDiscipline {
}
/// Push char to line discipline.
- pub fn push_char<F: FnMut(&str)>(&self, ch: u8, echo_callback: F) {
+ pub fn push_char<F2: FnMut(&str)>(&self, ch: u8, echo_callback: F2) {
let termios = self.termios.lock_irq_disabled();
let ch = if termios.contains_icrnl() && ch == b'\r' {
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -98,7 +97,7 @@ impl LineDiscipline {
}
/// Push char to line discipline.
- pub fn push_char<F: FnMut(&str)>(&self, ch: u8, echo_callback: F) {
+ pub fn push_char<F2: FnMut(&str)>(&self, ch: u8, echo_callback: F2) {
let termios = self.termios.lock_irq_disabled();
let ch = if termios.contains_icrnl() && ch == b'\r' {
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -107,7 +106,7 @@ impl LineDiscipline {
ch
};
- if self.may_send_signal_to_foreground(&termios, ch) {
+ if self.may_send_signal(&termios, ch) {
// The char is already dealt with, so just return
return;
}
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -107,7 +106,7 @@ impl LineDiscipline {
ch
};
- if self.may_send_signal_to_foreground(&termios, ch) {
+ if self.may_send_signal(&termios, ch) {
// The char is already dealt with, so just return
return;
}
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -158,22 +157,14 @@ impl LineDiscipline {
self.update_readable_state_deferred();
}
- fn may_send_signal_to_foreground(&self, termios: &KernelTermios, ch: u8) -> bool {
- if !termios.contains_isig() {
+ fn may_send_signal(&self, termios: &KernelTermios, ch: u8) -> bool {
+ if !termios.is_canonical_mode() || !termios.contains_isig() {
return false;
}
- let Some(foreground) = self.foreground.lock().upgrade() else {
- return false;
- };
-
let signal = match ch {
- item if item == *termios.get_special_char(CC_C_CHAR::VINTR) => {
- KernelSignal::new(SIGINT)
- }
- item if item == *termios.get_special_char(CC_C_CHAR::VQUIT) => {
- KernelSignal::new(SIGQUIT)
- }
+ ch if ch == *termios.get_special_char(CC_C_CHAR::VINTR) => KernelSignal::new(SIGINT),
+ ch if ch == *termios.get_special_char(CC_C_CHAR::VQUIT) => KernelSignal::new(SIGQUIT),
_ => return false,
};
// `kernel_signal()` may cause sleep, so only construct parameters here.
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -158,22 +157,14 @@ impl LineDiscipline {
self.update_readable_state_deferred();
}
- fn may_send_signal_to_foreground(&self, termios: &KernelTermios, ch: u8) -> bool {
- if !termios.contains_isig() {
+ fn may_send_signal(&self, termios: &KernelTermios, ch: u8) -> bool {
+ if !termios.is_canonical_mode() || !termios.contains_isig() {
return false;
}
- let Some(foreground) = self.foreground.lock().upgrade() else {
- return false;
- };
-
let signal = match ch {
- item if item == *termios.get_special_char(CC_C_CHAR::VINTR) => {
- KernelSignal::new(SIGINT)
- }
- item if item == *termios.get_special_char(CC_C_CHAR::VQUIT) => {
- KernelSignal::new(SIGQUIT)
- }
+ ch if ch == *termios.get_special_char(CC_C_CHAR::VINTR) => KernelSignal::new(SIGINT),
+ ch if ch == *termios.get_special_char(CC_C_CHAR::VQUIT) => KernelSignal::new(SIGQUIT),
_ => return false,
};
// `kernel_signal()` may cause sleep, so only construct parameters here.
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -182,7 +173,7 @@ impl LineDiscipline {
true
}
- fn update_readable_state(&self) {
+ pub fn update_readable_state(&self) {
let buffer = self.read_buffer.lock_irq_disabled();
if !buffer.is_empty() {
self.pollee.add_events(IoEvents::IN);
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -182,7 +173,7 @@ impl LineDiscipline {
true
}
- fn update_readable_state(&self) {
+ pub fn update_readable_state(&self) {
let buffer = self.read_buffer.lock_irq_disabled();
if !buffer.is_empty() {
self.pollee.add_events(IoEvents::IN);
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -193,7 +184,6 @@ impl LineDiscipline {
fn update_readable_state_deferred(&self) {
let buffer = self.read_buffer.lock_irq_disabled();
- let pollee = self.pollee.clone();
// add/del events may sleep, so only construct parameters here.
if !buffer.is_empty() {
self.work_item_para.lock_irq_disabled().pollee_type = Some(PolleeType::Add);
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -193,7 +184,6 @@ impl LineDiscipline {
fn update_readable_state_deferred(&self) {
let buffer = self.read_buffer.lock_irq_disabled();
- let pollee = self.pollee.clone();
// add/del events may sleep, so only construct parameters here.
if !buffer.is_empty() {
self.work_item_para.lock_irq_disabled().pollee_type = Some(PolleeType::Add);
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -206,11 +196,7 @@ impl LineDiscipline {
/// include all operations that may cause sleep, and processes by a work queue.
fn update_readable_state_after(&self) {
if let Some(signal) = self.work_item_para.lock_irq_disabled().kernel_signal.take() {
- self.foreground
- .lock()
- .upgrade()
- .unwrap()
- .kernel_signal(signal)
+ (self.send_signal)(signal);
};
if let Some(pollee_type) = self.work_item_para.lock_irq_disabled().pollee_type.take() {
match pollee_type {
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -206,11 +196,7 @@ impl LineDiscipline {
/// include all operations that may cause sleep, and processes by a work queue.
fn update_readable_state_after(&self) {
if let Some(signal) = self.work_item_para.lock_irq_disabled().kernel_signal.take() {
- self.foreground
- .lock()
- .upgrade()
- .unwrap()
- .kernel_signal(signal)
+ (self.send_signal)(signal);
};
if let Some(pollee_type) = self.work_item_para.lock_irq_disabled().pollee_type.take() {
match pollee_type {
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -243,42 +229,24 @@ impl LineDiscipline {
}
}
- /// read all bytes buffered to dst, return the actual read length.
- pub fn read(&self, dst: &mut [u8]) -> Result<usize> {
- let mut poller = None;
+ pub fn read(&self, buf: &mut [u8]) -> Result<usize> {
loop {
- let res = self.try_read(dst);
+ let res = self.try_read(buf);
match res {
- Ok(read_len) => {
- return Ok(read_len);
- }
- Err(e) => {
- if e.error() != Errno::EAGAIN {
- return Err(e);
+ Ok(len) => return Ok(len),
+ Err(e) if e.error() != Errno::EAGAIN => return Err(e),
+ Err(_) => {
+ let poller = Some(Poller::new());
+ if self.poll(IoEvents::IN, poller.as_ref()).is_empty() {
+ poller.as_ref().unwrap().wait()?
}
}
}
-
- // Wait for read event
- let need_poller = if poller.is_none() {
- poller = Some(Poller::new());
- poller.as_ref()
- } else {
- None
- };
- let revents = self.pollee.poll(IoEvents::IN, need_poller);
- if revents.is_empty() {
- // FIXME: deal with ldisc read timeout
- poller.as_ref().unwrap().wait()?;
- }
}
}
- pub fn try_read(&self, dst: &mut [u8]) -> Result<usize> {
- if !self.current_can_read() {
- return_errno!(Errno::EAGAIN);
- }
-
+ /// read all bytes buffered to dst, return the actual read length.
+ fn try_read(&self, dst: &mut [u8]) -> Result<usize> {
let (vmin, vtime) = {
let termios = self.termios.lock_irq_disabled();
let vmin = *termios.get_special_char(CC_C_CHAR::VMIN);
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -243,42 +229,24 @@ impl LineDiscipline {
}
}
- /// read all bytes buffered to dst, return the actual read length.
- pub fn read(&self, dst: &mut [u8]) -> Result<usize> {
- let mut poller = None;
+ pub fn read(&self, buf: &mut [u8]) -> Result<usize> {
loop {
- let res = self.try_read(dst);
+ let res = self.try_read(buf);
match res {
- Ok(read_len) => {
- return Ok(read_len);
- }
- Err(e) => {
- if e.error() != Errno::EAGAIN {
- return Err(e);
+ Ok(len) => return Ok(len),
+ Err(e) if e.error() != Errno::EAGAIN => return Err(e),
+ Err(_) => {
+ let poller = Some(Poller::new());
+ if self.poll(IoEvents::IN, poller.as_ref()).is_empty() {
+ poller.as_ref().unwrap().wait()?
}
}
}
-
- // Wait for read event
- let need_poller = if poller.is_none() {
- poller = Some(Poller::new());
- poller.as_ref()
- } else {
- None
- };
- let revents = self.pollee.poll(IoEvents::IN, need_poller);
- if revents.is_empty() {
- // FIXME: deal with ldisc read timeout
- poller.as_ref().unwrap().wait()?;
- }
}
}
- pub fn try_read(&self, dst: &mut [u8]) -> Result<usize> {
- if !self.current_can_read() {
- return_errno!(Errno::EAGAIN);
- }
-
+ /// read all bytes buffered to dst, return the actual read length.
+ fn try_read(&self, dst: &mut [u8]) -> Result<usize> {
let (vmin, vtime) = {
let termios = self.termios.lock_irq_disabled();
let vmin = *termios.get_special_char(CC_C_CHAR::VMIN);
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -326,7 +294,8 @@ impl LineDiscipline {
if termios.is_canonical_mode() {
// canonical mode, read until meet new line
if is_line_terminator(next_char, &termios) {
- if !should_not_be_read(next_char, &termios) {
+ // The eof should not be read
+ if !is_eof(next_char, &termios) {
*dst_i = next_char;
read_len += 1;
}
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -326,7 +294,8 @@ impl LineDiscipline {
if termios.is_canonical_mode() {
// canonical mode, read until meet new line
if is_line_terminator(next_char, &termios) {
- if !should_not_be_read(next_char, &termios) {
+ // The eof should not be read
+ if !is_eof(next_char, &termios) {
*dst_i = next_char;
read_len += 1;
}
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -368,31 +337,6 @@ impl LineDiscipline {
todo!()
}
- /// Determine whether current process can read the line discipline. If current belongs to the foreground process group.
- /// or the foreground process group is None, returns true.
- fn current_can_read(&self) -> bool {
- let current = current!();
- let Some(foreground) = self.foreground.lock_irq_disabled().upgrade() else {
- return true;
- };
- foreground.contains_process(current.pid())
- }
-
- /// set foreground process group
- pub fn set_fg(&self, foreground: Weak<ProcessGroup>) {
- *self.foreground.lock_irq_disabled() = foreground;
- // Some background processes may be waiting on the wait queue, when set_fg, the background processes may be able to read.
- self.update_readable_state();
- }
-
- /// get foreground process group id
- pub fn fg_pgid(&self) -> Option<Pgid> {
- self.foreground
- .lock_irq_disabled()
- .upgrade()
- .map(|foreground| foreground.pgid())
- }
-
/// whether there is buffered data
pub fn is_empty(&self) -> bool {
self.read_buffer.lock_irq_disabled().len() == 0
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -368,31 +337,6 @@ impl LineDiscipline {
todo!()
}
- /// Determine whether current process can read the line discipline. If current belongs to the foreground process group.
- /// or the foreground process group is None, returns true.
- fn current_can_read(&self) -> bool {
- let current = current!();
- let Some(foreground) = self.foreground.lock_irq_disabled().upgrade() else {
- return true;
- };
- foreground.contains_process(current.pid())
- }
-
- /// set foreground process group
- pub fn set_fg(&self, foreground: Weak<ProcessGroup>) {
- *self.foreground.lock_irq_disabled() = foreground;
- // Some background processes may be waiting on the wait queue, when set_fg, the background processes may be able to read.
- self.update_readable_state();
- }
-
- /// get foreground process group id
- pub fn fg_pgid(&self) -> Option<Pgid> {
- self.foreground
- .lock_irq_disabled()
- .upgrade()
- .map(|foreground| foreground.pgid())
- }
-
/// whether there is buffered data
pub fn is_empty(&self) -> bool {
self.read_buffer.lock_irq_disabled().len() == 0
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -439,8 +383,7 @@ fn is_line_terminator(item: u8, termios: &KernelTermios) -> bool {
false
}
-/// The special char should not be read by reading process
-fn should_not_be_read(ch: u8, termios: &KernelTermios) -> bool {
+fn is_eof(ch: u8, termios: &KernelTermios) -> bool {
ch == *termios.get_special_char(CC_C_CHAR::VEOF)
}
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -439,8 +383,7 @@ fn is_line_terminator(item: u8, termios: &KernelTermios) -> bool {
false
}
-/// The special char should not be read by reading process
-fn should_not_be_read(ch: u8, termios: &KernelTermios) -> bool {
+fn is_eof(ch: u8, termios: &KernelTermios) -> bool {
ch == *termios.get_special_char(CC_C_CHAR::VEOF)
}
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -467,6 +410,7 @@ enum PolleeType {
}
struct LineDisciplineWorkPara {
+ #[allow(clippy::type_complexity)]
kernel_signal: Option<KernelSignal>,
pollee_type: Option<PolleeType>,
}
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -467,6 +410,7 @@ enum PolleeType {
}
struct LineDisciplineWorkPara {
+ #[allow(clippy::type_complexity)]
kernel_signal: Option<KernelSignal>,
pollee_type: Option<PolleeType>,
}
diff --git a/services/libs/jinux-std/src/device/tty/mod.rs b/services/libs/jinux-std/src/device/tty/mod.rs
--- a/services/libs/jinux-std/src/device/tty/mod.rs
+++ b/services/libs/jinux-std/src/device/tty/mod.rs
@@ -2,23 +2,28 @@ use spin::Once;
use self::driver::TtyDriver;
use self::line_discipline::LineDiscipline;
-use super::*;
use crate::events::IoEvents;
+use crate::fs::device::{Device, DeviceId, DeviceType};
+use crate::fs::inode_handle::FileIo;
use crate::fs::utils::IoctlCmd;
use crate::prelude::*;
+use crate::process::signal::signals::kernel::KernelSignal;
use crate::process::signal::Poller;
-use crate::process::{process_table, ProcessGroup};
+use crate::process::{JobControl, Process, Terminal};
use crate::util::{read_val_from_user, write_val_to_user};
+mod device;
pub mod driver;
pub mod line_discipline;
pub mod termio;
+pub use device::TtyDevice;
+
static N_TTY: Once<Arc<Tty>> = Once::new();
pub(super) fn init() {
let name = CString::new("console").unwrap();
- let tty = Arc::new(Tty::new(name));
+ let tty = Tty::new(name);
N_TTY.call_once(|| tty);
driver::init();
}
diff --git a/services/libs/jinux-std/src/device/tty/mod.rs b/services/libs/jinux-std/src/device/tty/mod.rs
--- a/services/libs/jinux-std/src/device/tty/mod.rs
+++ b/services/libs/jinux-std/src/device/tty/mod.rs
@@ -2,23 +2,28 @@ use spin::Once;
use self::driver::TtyDriver;
use self::line_discipline::LineDiscipline;
-use super::*;
use crate::events::IoEvents;
+use crate::fs::device::{Device, DeviceId, DeviceType};
+use crate::fs::inode_handle::FileIo;
use crate::fs::utils::IoctlCmd;
use crate::prelude::*;
+use crate::process::signal::signals::kernel::KernelSignal;
use crate::process::signal::Poller;
-use crate::process::{process_table, ProcessGroup};
+use crate::process::{JobControl, Process, Terminal};
use crate::util::{read_val_from_user, write_val_to_user};
+mod device;
pub mod driver;
pub mod line_discipline;
pub mod termio;
+pub use device::TtyDevice;
+
static N_TTY: Once<Arc<Tty>> = Once::new();
pub(super) fn init() {
let name = CString::new("console").unwrap();
- let tty = Arc::new(Tty::new(name));
+ let tty = Tty::new(name);
N_TTY.call_once(|| tty);
driver::init();
}
diff --git a/services/libs/jinux-std/src/device/tty/mod.rs b/services/libs/jinux-std/src/device/tty/mod.rs
--- a/services/libs/jinux-std/src/device/tty/mod.rs
+++ b/services/libs/jinux-std/src/device/tty/mod.rs
@@ -28,44 +33,36 @@ pub struct Tty {
name: CString,
/// line discipline
ldisc: Arc<LineDiscipline>,
+ job_control: Arc<JobControl>,
/// driver
driver: SpinLock<Weak<TtyDriver>>,
+ weak_self: Weak<Self>,
}
impl Tty {
- pub fn new(name: CString) -> Self {
- Tty {
+ pub fn new(name: CString) -> Arc<Self> {
+ let (job_control, ldisc) = new_job_control_and_ldisc();
+ Arc::new_cyclic(move |weak_ref| Tty {
name,
- ldisc: LineDiscipline::new(),
+ ldisc,
+ job_control,
driver: SpinLock::new(Weak::new()),
- }
- }
-
- /// Set foreground process group
- pub fn set_fg(&self, process_group: Weak<ProcessGroup>) {
- self.ldisc.set_fg(process_group);
+ weak_self: weak_ref.clone(),
+ })
}
pub fn set_driver(&self, driver: Weak<TtyDriver>) {
*self.driver.lock_irq_disabled() = driver;
}
- pub fn receive_char(&self, item: u8) {
- self.ldisc.push_char(item, |content| print!("{}", content));
+ pub fn receive_char(&self, ch: u8) {
+ self.ldisc.push_char(ch, |content| print!("{}", content));
}
}
-impl Device for Tty {
- fn type_(&self) -> DeviceType {
- DeviceType::CharDevice
- }
-
- fn id(&self) -> DeviceId {
- // Same value with Linux
- DeviceId::new(5, 0)
- }
-
+impl FileIo for Tty {
fn read(&self, buf: &mut [u8]) -> Result<usize> {
+ self.job_control.wait_until_in_foreground()?;
self.ldisc.read(buf)
}
diff --git a/services/libs/jinux-std/src/device/tty/mod.rs b/services/libs/jinux-std/src/device/tty/mod.rs
--- a/services/libs/jinux-std/src/device/tty/mod.rs
+++ b/services/libs/jinux-std/src/device/tty/mod.rs
@@ -28,44 +33,36 @@ pub struct Tty {
name: CString,
/// line discipline
ldisc: Arc<LineDiscipline>,
+ job_control: Arc<JobControl>,
/// driver
driver: SpinLock<Weak<TtyDriver>>,
+ weak_self: Weak<Self>,
}
impl Tty {
- pub fn new(name: CString) -> Self {
- Tty {
+ pub fn new(name: CString) -> Arc<Self> {
+ let (job_control, ldisc) = new_job_control_and_ldisc();
+ Arc::new_cyclic(move |weak_ref| Tty {
name,
- ldisc: LineDiscipline::new(),
+ ldisc,
+ job_control,
driver: SpinLock::new(Weak::new()),
- }
- }
-
- /// Set foreground process group
- pub fn set_fg(&self, process_group: Weak<ProcessGroup>) {
- self.ldisc.set_fg(process_group);
+ weak_self: weak_ref.clone(),
+ })
}
pub fn set_driver(&self, driver: Weak<TtyDriver>) {
*self.driver.lock_irq_disabled() = driver;
}
- pub fn receive_char(&self, item: u8) {
- self.ldisc.push_char(item, |content| print!("{}", content));
+ pub fn receive_char(&self, ch: u8) {
+ self.ldisc.push_char(ch, |content| print!("{}", content));
}
}
-impl Device for Tty {
- fn type_(&self) -> DeviceType {
- DeviceType::CharDevice
- }
-
- fn id(&self) -> DeviceId {
- // Same value with Linux
- DeviceId::new(5, 0)
- }
-
+impl FileIo for Tty {
fn read(&self, buf: &mut [u8]) -> Result<usize> {
+ self.job_control.wait_until_in_foreground()?;
self.ldisc.read(buf)
}
diff --git a/services/libs/jinux-std/src/device/tty/mod.rs b/services/libs/jinux-std/src/device/tty/mod.rs
--- a/services/libs/jinux-std/src/device/tty/mod.rs
+++ b/services/libs/jinux-std/src/device/tty/mod.rs
@@ -92,23 +89,28 @@ impl Device for Tty {
Ok(0)
}
IoctlCmd::TIOCGPGRP => {
- let Some(fg_pgid) = self.ldisc.fg_pgid() else {
- return_errno_with_message!(Errno::ENOENT, "No fg process group")
+ let Some(foreground) = self.foreground() else {
+ return_errno_with_message!(Errno::ESRCH, "No fg process group")
};
+ let fg_pgid = foreground.pgid();
debug!("fg_pgid = {}", fg_pgid);
write_val_to_user(arg, &fg_pgid)?;
Ok(0)
}
IoctlCmd::TIOCSPGRP => {
// Set the process group id of fg progress group
- let pgid = read_val_from_user::<i32>(arg)?;
- if pgid < 0 {
- return_errno_with_message!(Errno::EINVAL, "invalid pgid");
- }
- match process_table::pgid_to_process_group(pgid as u32) {
- None => self.ldisc.set_fg(Weak::new()),
- Some(process_group) => self.ldisc.set_fg(Arc::downgrade(&process_group)),
- }
+ let pgid = {
+ let pgid: i32 = read_val_from_user(arg)?;
+ if pgid < 0 {
+ return_errno_with_message!(Errno::EINVAL, "negative pgid");
+ }
+ pgid as u32
+ };
+
+ self.set_foreground(&pgid)?;
+ // Some background processes may be waiting on the wait queue,
+ // when set_fg, the background processes may be able to read.
+ self.ldisc.update_readable_state();
Ok(0)
}
IoctlCmd::TCSETS => {
diff --git a/services/libs/jinux-std/src/device/tty/mod.rs b/services/libs/jinux-std/src/device/tty/mod.rs
--- a/services/libs/jinux-std/src/device/tty/mod.rs
+++ b/services/libs/jinux-std/src/device/tty/mod.rs
@@ -92,23 +89,28 @@ impl Device for Tty {
Ok(0)
}
IoctlCmd::TIOCGPGRP => {
- let Some(fg_pgid) = self.ldisc.fg_pgid() else {
- return_errno_with_message!(Errno::ENOENT, "No fg process group")
+ let Some(foreground) = self.foreground() else {
+ return_errno_with_message!(Errno::ESRCH, "No fg process group")
};
+ let fg_pgid = foreground.pgid();
debug!("fg_pgid = {}", fg_pgid);
write_val_to_user(arg, &fg_pgid)?;
Ok(0)
}
IoctlCmd::TIOCSPGRP => {
// Set the process group id of fg progress group
- let pgid = read_val_from_user::<i32>(arg)?;
- if pgid < 0 {
- return_errno_with_message!(Errno::EINVAL, "invalid pgid");
- }
- match process_table::pgid_to_process_group(pgid as u32) {
- None => self.ldisc.set_fg(Weak::new()),
- Some(process_group) => self.ldisc.set_fg(Arc::downgrade(&process_group)),
- }
+ let pgid = {
+ let pgid: i32 = read_val_from_user(arg)?;
+ if pgid < 0 {
+ return_errno_with_message!(Errno::EINVAL, "negative pgid");
+ }
+ pgid as u32
+ };
+
+ self.set_foreground(&pgid)?;
+ // Some background processes may be waiting on the wait queue,
+ // when set_fg, the background processes may be able to read.
+ self.ldisc.update_readable_state();
Ok(0)
}
IoctlCmd::TCSETS => {
diff --git a/services/libs/jinux-std/src/device/tty/mod.rs b/services/libs/jinux-std/src/device/tty/mod.rs
--- a/services/libs/jinux-std/src/device/tty/mod.rs
+++ b/services/libs/jinux-std/src/device/tty/mod.rs
@@ -143,12 +145,73 @@ impl Device for Tty {
self.ldisc.set_window_size(winsize);
Ok(0)
}
+ IoctlCmd::TIOCSCTTY => {
+ self.set_current_session()?;
+ Ok(0)
+ }
_ => todo!(),
}
}
}
-/// FIXME: should we maintain a static console?
+impl Terminal for Tty {
+ fn arc_self(&self) -> Arc<dyn Terminal> {
+ self.weak_self.upgrade().unwrap() as _
+ }
+
+ fn job_control(&self) -> &JobControl {
+ &self.job_control
+ }
+}
+
+impl Device for Tty {
+ fn type_(&self) -> DeviceType {
+ DeviceType::CharDevice
+ }
+
+ fn id(&self) -> DeviceId {
+ // The same value as /dev/console in linux.
+ DeviceId::new(88, 0)
+ }
+}
+
+pub fn new_job_control_and_ldisc() -> (Arc<JobControl>, Arc<LineDiscipline>) {
+ let job_control = Arc::new(JobControl::new());
+
+ let send_signal = {
+ let cloned_job_control = job_control.clone();
+ move |signal: KernelSignal| {
+ let Some(foreground) = cloned_job_control.foreground() else {
+ return;
+ };
+
+ foreground.broadcast_signal(signal);
+ }
+ };
+
+ let ldisc = LineDiscipline::new(Arc::new(send_signal));
+
+ (job_control, ldisc)
+}
+
pub fn get_n_tty() -> &'static Arc<Tty> {
N_TTY.get().unwrap()
}
+
+/// Open `N_TTY` as the controlling terminal for the process. This method should
+/// only be called when creating the init process.
+pub fn open_ntty_as_controlling_terminal(process: &Process) -> Result<()> {
+ let tty = get_n_tty();
+
+ let session = &process.session().unwrap();
+ let process_group = process.process_group().unwrap();
+
+ session.set_terminal(|| {
+ tty.job_control.set_session(session);
+ Ok(tty.clone())
+ })?;
+
+ tty.job_control.set_foreground(Some(&process_group))?;
+
+ Ok(())
+}
diff --git a/services/libs/jinux-std/src/device/tty/mod.rs b/services/libs/jinux-std/src/device/tty/mod.rs
--- a/services/libs/jinux-std/src/device/tty/mod.rs
+++ b/services/libs/jinux-std/src/device/tty/mod.rs
@@ -143,12 +145,73 @@ impl Device for Tty {
self.ldisc.set_window_size(winsize);
Ok(0)
}
+ IoctlCmd::TIOCSCTTY => {
+ self.set_current_session()?;
+ Ok(0)
+ }
_ => todo!(),
}
}
}
-/// FIXME: should we maintain a static console?
+impl Terminal for Tty {
+ fn arc_self(&self) -> Arc<dyn Terminal> {
+ self.weak_self.upgrade().unwrap() as _
+ }
+
+ fn job_control(&self) -> &JobControl {
+ &self.job_control
+ }
+}
+
+impl Device for Tty {
+ fn type_(&self) -> DeviceType {
+ DeviceType::CharDevice
+ }
+
+ fn id(&self) -> DeviceId {
+ // The same value as /dev/console in linux.
+ DeviceId::new(88, 0)
+ }
+}
+
+pub fn new_job_control_and_ldisc() -> (Arc<JobControl>, Arc<LineDiscipline>) {
+ let job_control = Arc::new(JobControl::new());
+
+ let send_signal = {
+ let cloned_job_control = job_control.clone();
+ move |signal: KernelSignal| {
+ let Some(foreground) = cloned_job_control.foreground() else {
+ return;
+ };
+
+ foreground.broadcast_signal(signal);
+ }
+ };
+
+ let ldisc = LineDiscipline::new(Arc::new(send_signal));
+
+ (job_control, ldisc)
+}
+
pub fn get_n_tty() -> &'static Arc<Tty> {
N_TTY.get().unwrap()
}
+
+/// Open `N_TTY` as the controlling terminal for the process. This method should
+/// only be called when creating the init process.
+pub fn open_ntty_as_controlling_terminal(process: &Process) -> Result<()> {
+ let tty = get_n_tty();
+
+ let session = &process.session().unwrap();
+ let process_group = process.process_group().unwrap();
+
+ session.set_terminal(|| {
+ tty.job_control.set_session(session);
+ Ok(tty.clone())
+ })?;
+
+ tty.job_control.set_foreground(Some(&process_group))?;
+
+ Ok(())
+}
diff --git a/services/libs/jinux-std/src/device/urandom.rs b/services/libs/jinux-std/src/device/urandom.rs
--- a/services/libs/jinux-std/src/device/urandom.rs
+++ b/services/libs/jinux-std/src/device/urandom.rs
@@ -1,5 +1,8 @@
+use crate::events::IoEvents;
use crate::fs::device::{Device, DeviceId, DeviceType};
+use crate::fs::inode_handle::FileIo;
use crate::prelude::*;
+use crate::process::signal::Poller;
pub struct Urandom;
diff --git a/services/libs/jinux-std/src/device/urandom.rs b/services/libs/jinux-std/src/device/urandom.rs
--- a/services/libs/jinux-std/src/device/urandom.rs
+++ b/services/libs/jinux-std/src/device/urandom.rs
@@ -1,5 +1,8 @@
+use crate::events::IoEvents;
use crate::fs::device::{Device, DeviceId, DeviceType};
+use crate::fs::inode_handle::FileIo;
use crate::prelude::*;
+use crate::process::signal::Poller;
pub struct Urandom;
diff --git a/services/libs/jinux-std/src/device/urandom.rs b/services/libs/jinux-std/src/device/urandom.rs
--- a/services/libs/jinux-std/src/device/urandom.rs
+++ b/services/libs/jinux-std/src/device/urandom.rs
@@ -19,7 +22,9 @@ impl Device for Urandom {
// The same value as Linux
DeviceId::new(1, 9)
}
+}
+impl FileIo for Urandom {
fn read(&self, buf: &mut [u8]) -> Result<usize> {
Self::getrandom(buf)
}
diff --git a/services/libs/jinux-std/src/device/urandom.rs b/services/libs/jinux-std/src/device/urandom.rs
--- a/services/libs/jinux-std/src/device/urandom.rs
+++ b/services/libs/jinux-std/src/device/urandom.rs
@@ -19,7 +22,9 @@ impl Device for Urandom {
// The same value as Linux
DeviceId::new(1, 9)
}
+}
+impl FileIo for Urandom {
fn read(&self, buf: &mut [u8]) -> Result<usize> {
Self::getrandom(buf)
}
diff --git a/services/libs/jinux-std/src/device/urandom.rs b/services/libs/jinux-std/src/device/urandom.rs
--- a/services/libs/jinux-std/src/device/urandom.rs
+++ b/services/libs/jinux-std/src/device/urandom.rs
@@ -27,4 +32,9 @@ impl Device for Urandom {
fn write(&self, buf: &[u8]) -> Result<usize> {
Ok(buf.len())
}
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ let events = IoEvents::IN | IoEvents::OUT;
+ events & mask
+ }
}
diff --git a/services/libs/jinux-std/src/device/urandom.rs b/services/libs/jinux-std/src/device/urandom.rs
--- a/services/libs/jinux-std/src/device/urandom.rs
+++ b/services/libs/jinux-std/src/device/urandom.rs
@@ -27,4 +32,9 @@ impl Device for Urandom {
fn write(&self, buf: &[u8]) -> Result<usize> {
Ok(buf.len())
}
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ let events = IoEvents::IN | IoEvents::OUT;
+ events & mask
+ }
}
diff --git a/services/libs/jinux-std/src/device/zero.rs b/services/libs/jinux-std/src/device/zero.rs
--- a/services/libs/jinux-std/src/device/zero.rs
+++ b/services/libs/jinux-std/src/device/zero.rs
@@ -1,5 +1,8 @@
use super::*;
+use crate::events::IoEvents;
+use crate::fs::inode_handle::FileIo;
use crate::prelude::*;
+use crate::process::signal::Poller;
pub struct Zero;
diff --git a/services/libs/jinux-std/src/device/zero.rs b/services/libs/jinux-std/src/device/zero.rs
--- a/services/libs/jinux-std/src/device/zero.rs
+++ b/services/libs/jinux-std/src/device/zero.rs
@@ -1,5 +1,8 @@
use super::*;
+use crate::events::IoEvents;
+use crate::fs::inode_handle::FileIo;
use crate::prelude::*;
+use crate::process::signal::Poller;
pub struct Zero;
diff --git a/services/libs/jinux-std/src/device/zero.rs b/services/libs/jinux-std/src/device/zero.rs
--- a/services/libs/jinux-std/src/device/zero.rs
+++ b/services/libs/jinux-std/src/device/zero.rs
@@ -12,7 +15,9 @@ impl Device for Zero {
// Same value with Linux
DeviceId::new(1, 5)
}
+}
+impl FileIo for Zero {
fn read(&self, buf: &mut [u8]) -> Result<usize> {
for byte in buf.iter_mut() {
*byte = 0;
diff --git a/services/libs/jinux-std/src/device/zero.rs b/services/libs/jinux-std/src/device/zero.rs
--- a/services/libs/jinux-std/src/device/zero.rs
+++ b/services/libs/jinux-std/src/device/zero.rs
@@ -12,7 +15,9 @@ impl Device for Zero {
// Same value with Linux
DeviceId::new(1, 5)
}
+}
+impl FileIo for Zero {
fn read(&self, buf: &mut [u8]) -> Result<usize> {
for byte in buf.iter_mut() {
*byte = 0;
diff --git a/services/libs/jinux-std/src/device/zero.rs b/services/libs/jinux-std/src/device/zero.rs
--- a/services/libs/jinux-std/src/device/zero.rs
+++ b/services/libs/jinux-std/src/device/zero.rs
@@ -23,4 +28,9 @@ impl Device for Zero {
fn write(&self, buf: &[u8]) -> Result<usize> {
Ok(buf.len())
}
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ let events = IoEvents::IN | IoEvents::OUT;
+ events & mask
+ }
}
diff --git a/services/libs/jinux-std/src/device/zero.rs b/services/libs/jinux-std/src/device/zero.rs
--- a/services/libs/jinux-std/src/device/zero.rs
+++ b/services/libs/jinux-std/src/device/zero.rs
@@ -23,4 +28,9 @@ impl Device for Zero {
fn write(&self, buf: &[u8]) -> Result<usize> {
Ok(buf.len())
}
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ let events = IoEvents::IN | IoEvents::OUT;
+ events & mask
+ }
}
diff --git a/services/libs/jinux-std/src/fs/device.rs b/services/libs/jinux-std/src/fs/device.rs
--- a/services/libs/jinux-std/src/fs/device.rs
+++ b/services/libs/jinux-std/src/fs/device.rs
@@ -1,33 +1,21 @@
-use crate::events::IoEvents;
use crate::fs::fs_resolver::{FsPath, FsResolver};
use crate::fs::utils::Dentry;
-use crate::fs::utils::{InodeMode, InodeType, IoctlCmd};
+use crate::fs::utils::{InodeMode, InodeType};
use crate::prelude::*;
-use crate::process::signal::Poller;
+
+use super::inode_handle::FileIo;
/// The abstract of device
-pub trait Device: Sync + Send {
+pub trait Device: Sync + Send + FileIo {
/// Return the device type.
fn type_(&self) -> DeviceType;
/// Return the device ID.
fn id(&self) -> DeviceId;
- /// Read from the device.
- fn read(&self, buf: &mut [u8]) -> Result<usize>;
-
- /// Write to the device.
- fn write(&self, buf: &[u8]) -> Result<usize>;
-
- /// Poll on the device.
- fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
- let events = IoEvents::IN | IoEvents::OUT;
- events & mask
- }
-
- /// Ioctl on the device.
- fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
- return_errno_with_message!(Errno::EINVAL, "ioctl is not supported");
+ /// Open a device.
+ fn open(&self) -> Result<Option<Arc<dyn FileIo>>> {
+ Ok(None)
}
}
diff --git a/services/libs/jinux-std/src/fs/device.rs b/services/libs/jinux-std/src/fs/device.rs
--- a/services/libs/jinux-std/src/fs/device.rs
+++ b/services/libs/jinux-std/src/fs/device.rs
@@ -1,33 +1,21 @@
-use crate::events::IoEvents;
use crate::fs::fs_resolver::{FsPath, FsResolver};
use crate::fs::utils::Dentry;
-use crate::fs::utils::{InodeMode, InodeType, IoctlCmd};
+use crate::fs::utils::{InodeMode, InodeType};
use crate::prelude::*;
-use crate::process::signal::Poller;
+
+use super::inode_handle::FileIo;
/// The abstract of device
-pub trait Device: Sync + Send {
+pub trait Device: Sync + Send + FileIo {
/// Return the device type.
fn type_(&self) -> DeviceType;
/// Return the device ID.
fn id(&self) -> DeviceId;
- /// Read from the device.
- fn read(&self, buf: &mut [u8]) -> Result<usize>;
-
- /// Write to the device.
- fn write(&self, buf: &[u8]) -> Result<usize>;
-
- /// Poll on the device.
- fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
- let events = IoEvents::IN | IoEvents::OUT;
- events & mask
- }
-
- /// Ioctl on the device.
- fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
- return_errno_with_message!(Errno::EINVAL, "ioctl is not supported");
+ /// Open a device.
+ fn open(&self) -> Result<Option<Arc<dyn FileIo>>> {
+ Ok(None)
}
}
diff --git a/services/libs/jinux-std/src/fs/devpts/master.rs /dev/null
--- a/services/libs/jinux-std/src/fs/devpts/master.rs
+++ /dev/null
@@ -1,106 +0,0 @@
-use crate::events::IoEvents;
-use crate::fs::file_handle::FileLike;
-use crate::prelude::*;
-use crate::process::signal::Poller;
-
-use super::*;
-
-use crate::device::PtyMaster;
-
-/// Pty master inode for the master device.
-pub struct PtyMasterInode(Arc<PtyMaster>);
-
-impl PtyMasterInode {
- pub fn new(device: Arc<PtyMaster>) -> Arc<Self> {
- Arc::new(Self(device))
- }
-}
-
-impl Drop for PtyMasterInode {
- fn drop(&mut self) {
- // Remove the slave from fs.
- let fs = self.0.ptmx().fs();
- let devpts = fs.downcast_ref::<DevPts>().unwrap();
-
- let index = self.0.index();
- devpts.remove_slave(index);
- }
-}
-
-impl Inode for PtyMasterInode {
- /// Do not cache dentry in DCACHE.
- ///
- /// Each file descriptor obtained by opening "/dev/ptmx" is an independent pty master
- /// with its own associated pty slave.
- fn is_dentry_cacheable(&self) -> bool {
- false
- }
-
- fn len(&self) -> usize {
- self.0.ptmx().metadata().size
- }
-
- fn resize(&self, new_size: usize) {}
-
- fn metadata(&self) -> Metadata {
- self.0.ptmx().metadata()
- }
-
- fn type_(&self) -> InodeType {
- self.0.ptmx().metadata().type_
- }
-
- fn mode(&self) -> InodeMode {
- self.0.ptmx().metadata().mode
- }
-
- fn set_mode(&self, mode: InodeMode) {}
-
- fn atime(&self) -> Duration {
- self.0.ptmx().metadata().atime
- }
-
- fn set_atime(&self, time: Duration) {}
-
- fn mtime(&self) -> Duration {
- self.0.ptmx().metadata().mtime
- }
-
- fn set_mtime(&self, time: Duration) {}
-
- fn read_page(&self, idx: usize, frame: &VmFrame) -> Result<()> {
- Ok(())
- }
-
- fn write_page(&self, idx: usize, frame: &VmFrame) -> Result<()> {
- Ok(())
- }
-
- fn read_at(&self, offset: usize, buf: &mut [u8]) -> Result<usize> {
- self.0.read(buf)
- }
-
- fn read_direct_at(&self, offset: usize, buf: &mut [u8]) -> Result<usize> {
- self.0.read(buf)
- }
-
- fn write_at(&self, offset: usize, buf: &[u8]) -> Result<usize> {
- self.0.write(buf)
- }
-
- fn write_direct_at(&self, offset: usize, buf: &[u8]) -> Result<usize> {
- self.0.write(buf)
- }
-
- fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
- self.0.ioctl(cmd, arg)
- }
-
- fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
- self.0.poll(mask, poller)
- }
-
- fn fs(&self) -> Arc<dyn FileSystem> {
- self.0.ptmx().fs()
- }
-}
diff --git a/services/libs/jinux-std/src/fs/devpts/master.rs /dev/null
--- a/services/libs/jinux-std/src/fs/devpts/master.rs
+++ /dev/null
@@ -1,106 +0,0 @@
-use crate::events::IoEvents;
-use crate::fs::file_handle::FileLike;
-use crate::prelude::*;
-use crate::process::signal::Poller;
-
-use super::*;
-
-use crate::device::PtyMaster;
-
-/// Pty master inode for the master device.
-pub struct PtyMasterInode(Arc<PtyMaster>);
-
-impl PtyMasterInode {
- pub fn new(device: Arc<PtyMaster>) -> Arc<Self> {
- Arc::new(Self(device))
- }
-}
-
-impl Drop for PtyMasterInode {
- fn drop(&mut self) {
- // Remove the slave from fs.
- let fs = self.0.ptmx().fs();
- let devpts = fs.downcast_ref::<DevPts>().unwrap();
-
- let index = self.0.index();
- devpts.remove_slave(index);
- }
-}
-
-impl Inode for PtyMasterInode {
- /// Do not cache dentry in DCACHE.
- ///
- /// Each file descriptor obtained by opening "/dev/ptmx" is an independent pty master
- /// with its own associated pty slave.
- fn is_dentry_cacheable(&self) -> bool {
- false
- }
-
- fn len(&self) -> usize {
- self.0.ptmx().metadata().size
- }
-
- fn resize(&self, new_size: usize) {}
-
- fn metadata(&self) -> Metadata {
- self.0.ptmx().metadata()
- }
-
- fn type_(&self) -> InodeType {
- self.0.ptmx().metadata().type_
- }
-
- fn mode(&self) -> InodeMode {
- self.0.ptmx().metadata().mode
- }
-
- fn set_mode(&self, mode: InodeMode) {}
-
- fn atime(&self) -> Duration {
- self.0.ptmx().metadata().atime
- }
-
- fn set_atime(&self, time: Duration) {}
-
- fn mtime(&self) -> Duration {
- self.0.ptmx().metadata().mtime
- }
-
- fn set_mtime(&self, time: Duration) {}
-
- fn read_page(&self, idx: usize, frame: &VmFrame) -> Result<()> {
- Ok(())
- }
-
- fn write_page(&self, idx: usize, frame: &VmFrame) -> Result<()> {
- Ok(())
- }
-
- fn read_at(&self, offset: usize, buf: &mut [u8]) -> Result<usize> {
- self.0.read(buf)
- }
-
- fn read_direct_at(&self, offset: usize, buf: &mut [u8]) -> Result<usize> {
- self.0.read(buf)
- }
-
- fn write_at(&self, offset: usize, buf: &[u8]) -> Result<usize> {
- self.0.write(buf)
- }
-
- fn write_direct_at(&self, offset: usize, buf: &[u8]) -> Result<usize> {
- self.0.write(buf)
- }
-
- fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
- self.0.ioctl(cmd, arg)
- }
-
- fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
- self.0.poll(mask, poller)
- }
-
- fn fs(&self) -> Arc<dyn FileSystem> {
- self.0.ptmx().fs()
- }
-}
diff --git a/services/libs/jinux-std/src/fs/devpts/mod.rs b/services/libs/jinux-std/src/fs/devpts/mod.rs
--- a/services/libs/jinux-std/src/fs/devpts/mod.rs
+++ b/services/libs/jinux-std/src/fs/devpts/mod.rs
@@ -1,3 +1,4 @@
+use crate::device::PtyMaster;
use crate::fs::device::{Device, DeviceId, DeviceType};
use crate::fs::utils::{
DirentVisitor, FileSystem, FsFlags, Inode, InodeMode, InodeType, IoctlCmd, Metadata,
diff --git a/services/libs/jinux-std/src/fs/devpts/mod.rs b/services/libs/jinux-std/src/fs/devpts/mod.rs
--- a/services/libs/jinux-std/src/fs/devpts/mod.rs
+++ b/services/libs/jinux-std/src/fs/devpts/mod.rs
@@ -1,3 +1,4 @@
+use crate::device::PtyMaster;
use crate::fs::device::{Device, DeviceId, DeviceType};
use crate::fs::utils::{
DirentVisitor, FileSystem, FsFlags, Inode, InodeMode, InodeType, IoctlCmd, Metadata,
diff --git a/services/libs/jinux-std/src/fs/devpts/mod.rs b/services/libs/jinux-std/src/fs/devpts/mod.rs
--- a/services/libs/jinux-std/src/fs/devpts/mod.rs
+++ b/services/libs/jinux-std/src/fs/devpts/mod.rs
@@ -9,11 +10,9 @@ use core::time::Duration;
use jinux_frame::vm::VmFrame;
use jinux_util::{id_allocator::IdAlloc, slot_vec::SlotVec};
-use self::master::PtyMasterInode;
use self::ptmx::Ptmx;
use self::slave::PtySlaveInode;
-mod master;
mod ptmx;
mod slave;
diff --git a/services/libs/jinux-std/src/fs/devpts/mod.rs b/services/libs/jinux-std/src/fs/devpts/mod.rs
--- a/services/libs/jinux-std/src/fs/devpts/mod.rs
+++ b/services/libs/jinux-std/src/fs/devpts/mod.rs
@@ -9,11 +10,9 @@ use core::time::Duration;
use jinux_frame::vm::VmFrame;
use jinux_util::{id_allocator::IdAlloc, slot_vec::SlotVec};
-use self::master::PtyMasterInode;
use self::ptmx::Ptmx;
use self::slave::PtySlaveInode;
-mod master;
mod ptmx;
mod slave;
diff --git a/services/libs/jinux-std/src/fs/devpts/mod.rs b/services/libs/jinux-std/src/fs/devpts/mod.rs
--- a/services/libs/jinux-std/src/fs/devpts/mod.rs
+++ b/services/libs/jinux-std/src/fs/devpts/mod.rs
@@ -52,7 +51,7 @@ impl DevPts {
}
/// Create the master and slave pair.
- fn create_master_slave_pair(&self) -> Result<(Arc<PtyMasterInode>, Arc<PtySlaveInode>)> {
+ fn create_master_slave_pair(&self) -> Result<(Arc<PtyMaster>, Arc<PtySlaveInode>)> {
let index = self
.index_alloc
.lock()
diff --git a/services/libs/jinux-std/src/fs/devpts/mod.rs b/services/libs/jinux-std/src/fs/devpts/mod.rs
--- a/services/libs/jinux-std/src/fs/devpts/mod.rs
+++ b/services/libs/jinux-std/src/fs/devpts/mod.rs
@@ -52,7 +51,7 @@ impl DevPts {
}
/// Create the master and slave pair.
- fn create_master_slave_pair(&self) -> Result<(Arc<PtyMasterInode>, Arc<PtySlaveInode>)> {
+ fn create_master_slave_pair(&self) -> Result<(Arc<PtyMaster>, Arc<PtySlaveInode>)> {
let index = self
.index_alloc
.lock()
diff --git a/services/libs/jinux-std/src/fs/devpts/mod.rs b/services/libs/jinux-std/src/fs/devpts/mod.rs
--- a/services/libs/jinux-std/src/fs/devpts/mod.rs
+++ b/services/libs/jinux-std/src/fs/devpts/mod.rs
@@ -61,17 +60,16 @@ impl DevPts {
let (master, slave) = crate::device::new_pty_pair(index as u32, self.root.ptmx.clone())?;
- let master_inode = PtyMasterInode::new(master);
let slave_inode = PtySlaveInode::new(slave, self.this.clone());
self.root.add_slave(index.to_string(), slave_inode.clone());
- Ok((master_inode, slave_inode))
+ Ok((master, slave_inode))
}
/// Remove the slave from fs.
///
/// This is called when the master is being dropped.
- fn remove_slave(&self, index: u32) -> Option<Arc<PtySlaveInode>> {
+ pub fn remove_slave(&self, index: u32) -> Option<Arc<PtySlaveInode>> {
let removed_slave = self.root.remove_slave(&index.to_string());
if removed_slave.is_some() {
self.index_alloc.lock().free(index as usize);
diff --git a/services/libs/jinux-std/src/fs/devpts/mod.rs b/services/libs/jinux-std/src/fs/devpts/mod.rs
--- a/services/libs/jinux-std/src/fs/devpts/mod.rs
+++ b/services/libs/jinux-std/src/fs/devpts/mod.rs
@@ -61,17 +60,16 @@ impl DevPts {
let (master, slave) = crate::device::new_pty_pair(index as u32, self.root.ptmx.clone())?;
- let master_inode = PtyMasterInode::new(master);
let slave_inode = PtySlaveInode::new(slave, self.this.clone());
self.root.add_slave(index.to_string(), slave_inode.clone());
- Ok((master_inode, slave_inode))
+ Ok((master, slave_inode))
}
/// Remove the slave from fs.
///
/// This is called when the master is being dropped.
- fn remove_slave(&self, index: u32) -> Option<Arc<PtySlaveInode>> {
+ pub fn remove_slave(&self, index: u32) -> Option<Arc<PtySlaveInode>> {
let removed_slave = self.root.remove_slave(&index.to_string());
if removed_slave.is_some() {
self.index_alloc.lock().free(index as usize);
diff --git a/services/libs/jinux-std/src/fs/devpts/mod.rs b/services/libs/jinux-std/src/fs/devpts/mod.rs
--- a/services/libs/jinux-std/src/fs/devpts/mod.rs
+++ b/services/libs/jinux-std/src/fs/devpts/mod.rs
@@ -241,7 +239,7 @@ impl Inode for RootInode {
let inode = match name {
"." | ".." => self.fs().root_inode(),
// Call the "open" method of ptmx to create a master and slave pair.
- "ptmx" => self.ptmx.open()?,
+ "ptmx" => self.ptmx.clone(),
slave => self
.slaves
.read()
diff --git a/services/libs/jinux-std/src/fs/devpts/mod.rs b/services/libs/jinux-std/src/fs/devpts/mod.rs
--- a/services/libs/jinux-std/src/fs/devpts/mod.rs
+++ b/services/libs/jinux-std/src/fs/devpts/mod.rs
@@ -241,7 +239,7 @@ impl Inode for RootInode {
let inode = match name {
"." | ".." => self.fs().root_inode(),
// Call the "open" method of ptmx to create a master and slave pair.
- "ptmx" => self.ptmx.open()?,
+ "ptmx" => self.ptmx.clone(),
slave => self
.slaves
.read()
diff --git a/services/libs/jinux-std/src/fs/devpts/ptmx.rs b/services/libs/jinux-std/src/fs/devpts/ptmx.rs
--- a/services/libs/jinux-std/src/fs/devpts/ptmx.rs
+++ b/services/libs/jinux-std/src/fs/devpts/ptmx.rs
@@ -1,4 +1,8 @@
+use crate::device::PtyMaster;
+use crate::events::IoEvents;
+use crate::fs::inode_handle::FileIo;
use crate::prelude::*;
+use crate::process::signal::Poller;
use super::*;
diff --git a/services/libs/jinux-std/src/fs/devpts/ptmx.rs b/services/libs/jinux-std/src/fs/devpts/ptmx.rs
--- a/services/libs/jinux-std/src/fs/devpts/ptmx.rs
+++ b/services/libs/jinux-std/src/fs/devpts/ptmx.rs
@@ -1,4 +1,8 @@
+use crate::device::PtyMaster;
+use crate::events::IoEvents;
+use crate::fs::inode_handle::FileIo;
use crate::prelude::*;
+use crate::process::signal::Poller;
use super::*;
diff --git a/services/libs/jinux-std/src/fs/devpts/ptmx.rs b/services/libs/jinux-std/src/fs/devpts/ptmx.rs
--- a/services/libs/jinux-std/src/fs/devpts/ptmx.rs
+++ b/services/libs/jinux-std/src/fs/devpts/ptmx.rs
@@ -14,12 +18,14 @@ const PTMX_MINOR_NUM: u32 = 2;
pub struct Ptmx {
inner: Inner,
metadata: Metadata,
- fs: Weak<DevPts>,
}
+#[derive(Clone)]
+struct Inner(Weak<DevPts>);
+
impl Ptmx {
pub fn new(sb: &SuperBlock, fs: Weak<DevPts>) -> Arc<Self> {
- let inner = Inner;
+ let inner = Inner(fs);
Arc::new(Self {
metadata: Metadata::new_device(
PTMX_INO,
diff --git a/services/libs/jinux-std/src/fs/devpts/ptmx.rs b/services/libs/jinux-std/src/fs/devpts/ptmx.rs
--- a/services/libs/jinux-std/src/fs/devpts/ptmx.rs
+++ b/services/libs/jinux-std/src/fs/devpts/ptmx.rs
@@ -14,12 +18,14 @@ const PTMX_MINOR_NUM: u32 = 2;
pub struct Ptmx {
inner: Inner,
metadata: Metadata,
- fs: Weak<DevPts>,
}
+#[derive(Clone)]
+struct Inner(Weak<DevPts>);
+
impl Ptmx {
pub fn new(sb: &SuperBlock, fs: Weak<DevPts>) -> Arc<Self> {
- let inner = Inner;
+ let inner = Inner(fs);
Arc::new(Self {
metadata: Metadata::new_device(
PTMX_INO,
diff --git a/services/libs/jinux-std/src/fs/devpts/ptmx.rs b/services/libs/jinux-std/src/fs/devpts/ptmx.rs
--- a/services/libs/jinux-std/src/fs/devpts/ptmx.rs
+++ b/services/libs/jinux-std/src/fs/devpts/ptmx.rs
@@ -28,20 +34,19 @@ impl Ptmx {
&inner,
),
inner,
- fs,
})
}
/// The open method for ptmx.
///
/// Creates a master and slave pair and returns the master inode.
- pub fn open(&self) -> Result<Arc<PtyMasterInode>> {
+ pub fn open(&self) -> Result<Arc<PtyMaster>> {
let (master, _) = self.devpts().create_master_slave_pair()?;
Ok(master)
}
pub fn devpts(&self) -> Arc<DevPts> {
- self.fs.upgrade().unwrap()
+ self.inner.0.upgrade().unwrap()
}
pub fn device_type(&self) -> DeviceType {
diff --git a/services/libs/jinux-std/src/fs/devpts/ptmx.rs b/services/libs/jinux-std/src/fs/devpts/ptmx.rs
--- a/services/libs/jinux-std/src/fs/devpts/ptmx.rs
+++ b/services/libs/jinux-std/src/fs/devpts/ptmx.rs
@@ -28,20 +34,19 @@ impl Ptmx {
&inner,
),
inner,
- fs,
})
}
/// The open method for ptmx.
///
/// Creates a master and slave pair and returns the master inode.
- pub fn open(&self) -> Result<Arc<PtyMasterInode>> {
+ pub fn open(&self) -> Result<Arc<PtyMaster>> {
let (master, _) = self.devpts().create_master_slave_pair()?;
Ok(master)
}
pub fn devpts(&self) -> Arc<DevPts> {
- self.fs.upgrade().unwrap()
+ self.inner.0.upgrade().unwrap()
}
pub fn device_type(&self) -> DeviceType {
diff --git a/services/libs/jinux-std/src/fs/devpts/ptmx.rs b/services/libs/jinux-std/src/fs/devpts/ptmx.rs
--- a/services/libs/jinux-std/src/fs/devpts/ptmx.rs
+++ b/services/libs/jinux-std/src/fs/devpts/ptmx.rs
@@ -119,9 +124,11 @@ impl Inode for Ptmx {
fn fs(&self) -> Arc<dyn FileSystem> {
self.devpts()
}
-}
-struct Inner;
+ fn as_device(&self) -> Option<Arc<dyn Device>> {
+ Some(Arc::new(self.inner.clone()))
+ }
+}
impl Device for Inner {
fn type_(&self) -> DeviceType {
diff --git a/services/libs/jinux-std/src/fs/devpts/ptmx.rs b/services/libs/jinux-std/src/fs/devpts/ptmx.rs
--- a/services/libs/jinux-std/src/fs/devpts/ptmx.rs
+++ b/services/libs/jinux-std/src/fs/devpts/ptmx.rs
@@ -119,9 +124,11 @@ impl Inode for Ptmx {
fn fs(&self) -> Arc<dyn FileSystem> {
self.devpts()
}
-}
-struct Inner;
+ fn as_device(&self) -> Option<Arc<dyn Device>> {
+ Some(Arc::new(self.inner.clone()))
+ }
+}
impl Device for Inner {
fn type_(&self) -> DeviceType {
diff --git a/services/libs/jinux-std/src/fs/devpts/ptmx.rs b/services/libs/jinux-std/src/fs/devpts/ptmx.rs
--- a/services/libs/jinux-std/src/fs/devpts/ptmx.rs
+++ b/services/libs/jinux-std/src/fs/devpts/ptmx.rs
@@ -132,13 +139,23 @@ impl Device for Inner {
DeviceId::new(PTMX_MAJOR_NUM, PTMX_MINOR_NUM)
}
+ fn open(&self) -> Result<Option<Arc<dyn FileIo>>> {
+ let devpts = self.0.upgrade().unwrap();
+ let (master, _) = devpts.create_master_slave_pair()?;
+ Ok(Some(master as _))
+ }
+}
+
+impl FileIo for Inner {
fn read(&self, buf: &mut [u8]) -> Result<usize> {
- // do nothing because it should not be used to read.
- Ok(0)
+ return_errno_with_message!(Errno::EINVAL, "cannot read ptmx");
}
fn write(&self, buf: &[u8]) -> Result<usize> {
- // do nothing because it should not be used to write.
- Ok(buf.len())
+ return_errno_with_message!(Errno::EINVAL, "cannot write ptmx");
+ }
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ IoEvents::empty()
}
}
diff --git a/services/libs/jinux-std/src/fs/devpts/ptmx.rs b/services/libs/jinux-std/src/fs/devpts/ptmx.rs
--- a/services/libs/jinux-std/src/fs/devpts/ptmx.rs
+++ b/services/libs/jinux-std/src/fs/devpts/ptmx.rs
@@ -132,13 +139,23 @@ impl Device for Inner {
DeviceId::new(PTMX_MAJOR_NUM, PTMX_MINOR_NUM)
}
+ fn open(&self) -> Result<Option<Arc<dyn FileIo>>> {
+ let devpts = self.0.upgrade().unwrap();
+ let (master, _) = devpts.create_master_slave_pair()?;
+ Ok(Some(master as _))
+ }
+}
+
+impl FileIo for Inner {
fn read(&self, buf: &mut [u8]) -> Result<usize> {
- // do nothing because it should not be used to read.
- Ok(0)
+ return_errno_with_message!(Errno::EINVAL, "cannot read ptmx");
}
fn write(&self, buf: &[u8]) -> Result<usize> {
- // do nothing because it should not be used to write.
- Ok(buf.len())
+ return_errno_with_message!(Errno::EINVAL, "cannot write ptmx");
+ }
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ IoEvents::empty()
}
}
diff --git a/services/libs/jinux-std/src/fs/devpts/slave.rs b/services/libs/jinux-std/src/fs/devpts/slave.rs
--- a/services/libs/jinux-std/src/fs/devpts/slave.rs
+++ b/services/libs/jinux-std/src/fs/devpts/slave.rs
@@ -1,4 +1,5 @@
use crate::events::IoEvents;
+use crate::fs::inode_handle::FileIo;
use crate::prelude::*;
use crate::process::signal::Poller;
diff --git a/services/libs/jinux-std/src/fs/devpts/slave.rs b/services/libs/jinux-std/src/fs/devpts/slave.rs
--- a/services/libs/jinux-std/src/fs/devpts/slave.rs
+++ b/services/libs/jinux-std/src/fs/devpts/slave.rs
@@ -1,4 +1,5 @@
use crate::events::IoEvents;
+use crate::fs::inode_handle::FileIo;
use crate::prelude::*;
use crate::process::signal::Poller;
diff --git a/services/libs/jinux-std/src/fs/devpts/slave.rs b/services/libs/jinux-std/src/fs/devpts/slave.rs
--- a/services/libs/jinux-std/src/fs/devpts/slave.rs
+++ b/services/libs/jinux-std/src/fs/devpts/slave.rs
@@ -107,4 +108,8 @@ impl Inode for PtySlaveInode {
fn fs(&self) -> Arc<dyn FileSystem> {
self.fs.upgrade().unwrap()
}
+
+ fn as_device(&self) -> Option<Arc<dyn Device>> {
+ Some(self.device.clone())
+ }
}
diff --git a/services/libs/jinux-std/src/fs/devpts/slave.rs b/services/libs/jinux-std/src/fs/devpts/slave.rs
--- a/services/libs/jinux-std/src/fs/devpts/slave.rs
+++ b/services/libs/jinux-std/src/fs/devpts/slave.rs
@@ -107,4 +108,8 @@ impl Inode for PtySlaveInode {
fn fs(&self) -> Arc<dyn FileSystem> {
self.fs.upgrade().unwrap()
}
+
+ fn as_device(&self) -> Option<Arc<dyn Device>> {
+ Some(self.device.clone())
+ }
}
diff --git a/services/libs/jinux-std/src/fs/file_handle.rs b/services/libs/jinux-std/src/fs/file_handle.rs
--- a/services/libs/jinux-std/src/fs/file_handle.rs
+++ b/services/libs/jinux-std/src/fs/file_handle.rs
@@ -1,6 +1,7 @@
//! Opend File Handle
use crate::events::{IoEvents, Observer};
+use crate::fs::device::Device;
use crate::fs::utils::{AccessMode, IoctlCmd, Metadata, SeekFrom, StatusFlags};
use crate::net::socket::Socket;
use crate::prelude::*;
diff --git a/services/libs/jinux-std/src/fs/file_handle.rs b/services/libs/jinux-std/src/fs/file_handle.rs
--- a/services/libs/jinux-std/src/fs/file_handle.rs
+++ b/services/libs/jinux-std/src/fs/file_handle.rs
@@ -1,6 +1,7 @@
//! Opend File Handle
use crate::events::{IoEvents, Observer};
+use crate::fs::device::Device;
use crate::fs::utils::{AccessMode, IoctlCmd, Metadata, SeekFrom, StatusFlags};
use crate::net::socket::Socket;
use crate::prelude::*;
diff --git a/services/libs/jinux-std/src/fs/file_handle.rs b/services/libs/jinux-std/src/fs/file_handle.rs
--- a/services/libs/jinux-std/src/fs/file_handle.rs
+++ b/services/libs/jinux-std/src/fs/file_handle.rs
@@ -73,6 +74,10 @@ pub trait FileLike: Send + Sync + Any {
fn as_socket(&self) -> Option<&dyn Socket> {
None
}
+
+ fn as_device(&self) -> Option<Arc<dyn Device>> {
+ None
+ }
}
impl dyn FileLike {
diff --git a/services/libs/jinux-std/src/fs/file_handle.rs b/services/libs/jinux-std/src/fs/file_handle.rs
--- a/services/libs/jinux-std/src/fs/file_handle.rs
+++ b/services/libs/jinux-std/src/fs/file_handle.rs
@@ -73,6 +74,10 @@ pub trait FileLike: Send + Sync + Any {
fn as_socket(&self) -> Option<&dyn Socket> {
None
}
+
+ fn as_device(&self) -> Option<Arc<dyn Device>> {
+ None
+ }
}
impl dyn FileLike {
diff --git a/services/libs/jinux-std/src/fs/file_table.rs b/services/libs/jinux-std/src/fs/file_table.rs
--- a/services/libs/jinux-std/src/fs/file_table.rs
+++ b/services/libs/jinux-std/src/fs/file_table.rs
@@ -27,7 +27,7 @@ impl FileTable {
pub fn new_with_stdio() -> Self {
let mut table = SlotVec::new();
let fs_resolver = FsResolver::new();
- let tty_path = FsPath::new(AT_FDCWD, "/dev/tty").expect("cannot find tty");
+ let tty_path = FsPath::new(AT_FDCWD, "/dev/console").expect("cannot find tty");
let stdin = {
let flags = AccessMode::O_RDONLY as u32;
let mode = InodeMode::S_IRUSR;
diff --git a/services/libs/jinux-std/src/fs/file_table.rs b/services/libs/jinux-std/src/fs/file_table.rs
--- a/services/libs/jinux-std/src/fs/file_table.rs
+++ b/services/libs/jinux-std/src/fs/file_table.rs
@@ -27,7 +27,7 @@ impl FileTable {
pub fn new_with_stdio() -> Self {
let mut table = SlotVec::new();
let fs_resolver = FsResolver::new();
- let tty_path = FsPath::new(AT_FDCWD, "/dev/tty").expect("cannot find tty");
+ let tty_path = FsPath::new(AT_FDCWD, "/dev/console").expect("cannot find tty");
let stdin = {
let flags = AccessMode::O_RDONLY as u32;
let mode = InodeMode::S_IRUSR;
diff --git a/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
@@ -21,8 +21,16 @@ impl InodeHandle<Rights> {
if access_mode.is_writable() && inode.type_() == InodeType::Dir {
return_errno_with_message!(Errno::EISDIR, "Directory cannot open to write");
}
+
+ let file_io = if let Some(device) = inode.as_device() {
+ device.open()?
+ } else {
+ None
+ };
+
let inner = Arc::new(InodeHandle_ {
dentry,
+ file_io,
offset: Mutex::new(0),
access_mode,
status_flags: AtomicU32::new(status_flags.bits()),
diff --git a/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
@@ -21,8 +21,16 @@ impl InodeHandle<Rights> {
if access_mode.is_writable() && inode.type_() == InodeType::Dir {
return_errno_with_message!(Errno::EISDIR, "Directory cannot open to write");
}
+
+ let file_io = if let Some(device) = inode.as_device() {
+ device.open()?
+ } else {
+ None
+ };
+
let inner = Arc::new(InodeHandle_ {
dentry,
+ file_io,
offset: Mutex::new(0),
access_mode,
status_flags: AtomicU32::new(status_flags.bits()),
diff --git a/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
@@ -42,6 +50,7 @@ impl InodeHandle<Rights> {
if !self.1.contains(Rights::READ) {
return_errno_with_message!(Errno::EBADF, "File is not readable");
}
+
self.0.read_to_end(buf)
}
diff --git a/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
@@ -42,6 +50,7 @@ impl InodeHandle<Rights> {
if !self.1.contains(Rights::READ) {
return_errno_with_message!(Errno::EBADF, "File is not readable");
}
+
self.0.read_to_end(buf)
}
diff --git a/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
@@ -75,11 +84,11 @@ impl FileLike for InodeHandle<Rights> {
}
fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
- self.dentry().inode().poll(mask, poller)
+ self.0.poll(mask, poller)
}
fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
- self.dentry().inode().ioctl(cmd, arg)
+ self.0.ioctl(cmd, arg)
}
fn metadata(&self) -> Metadata {
diff --git a/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
@@ -75,11 +84,11 @@ impl FileLike for InodeHandle<Rights> {
}
fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
- self.dentry().inode().poll(mask, poller)
+ self.0.poll(mask, poller)
}
fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
- self.dentry().inode().ioctl(cmd, arg)
+ self.0.ioctl(cmd, arg)
}
fn metadata(&self) -> Metadata {
diff --git a/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
@@ -107,4 +116,8 @@ impl FileLike for InodeHandle<Rights> {
// Close does not guarantee that the data has been successfully saved to disk.
Ok(())
}
+
+ fn as_device(&self) -> Option<Arc<dyn Device>> {
+ self.dentry().inode().as_device()
+ }
}
diff --git a/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
@@ -107,4 +116,8 @@ impl FileLike for InodeHandle<Rights> {
// Close does not guarantee that the data has been successfully saved to disk.
Ok(())
}
+
+ fn as_device(&self) -> Option<Arc<dyn Device>> {
+ self.dentry().inode().as_device()
+ }
}
diff --git a/services/libs/jinux-std/src/fs/inode_handle/mod.rs b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/mod.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
@@ -5,11 +5,14 @@ mod static_cap;
use core::sync::atomic::{AtomicU32, Ordering};
+use crate::events::IoEvents;
+use crate::fs::device::Device;
use crate::fs::file_handle::FileLike;
use crate::fs::utils::{
AccessMode, Dentry, DirentVisitor, InodeType, IoctlCmd, Metadata, SeekFrom, StatusFlags,
};
use crate::prelude::*;
+use crate::process::signal::Poller;
use jinux_rights::Rights;
#[derive(Debug)]
diff --git a/services/libs/jinux-std/src/fs/inode_handle/mod.rs b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/mod.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
@@ -5,11 +5,14 @@ mod static_cap;
use core::sync::atomic::{AtomicU32, Ordering};
+use crate::events::IoEvents;
+use crate::fs::device::Device;
use crate::fs::file_handle::FileLike;
use crate::fs::utils::{
AccessMode, Dentry, DirentVisitor, InodeType, IoctlCmd, Metadata, SeekFrom, StatusFlags,
};
use crate::prelude::*;
+use crate::process::signal::Poller;
use jinux_rights::Rights;
#[derive(Debug)]
diff --git a/services/libs/jinux-std/src/fs/inode_handle/mod.rs b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/mod.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
@@ -17,6 +20,10 @@ pub struct InodeHandle<R = Rights>(Arc<InodeHandle_>, R);
struct InodeHandle_ {
dentry: Arc<Dentry>,
+ /// `file_io` is Similar to `file_private` field in `file` structure in linux. If
+ /// `file_io` is Some, typical file operations including `read`, `write`, `poll`,
+ /// `ioctl` will be provided by `file_io`, instead of `dentry`.
+ file_io: Option<Arc<dyn FileIo>>,
offset: Mutex<usize>,
access_mode: AccessMode,
status_flags: AtomicU32,
diff --git a/services/libs/jinux-std/src/fs/inode_handle/mod.rs b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/mod.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
@@ -17,6 +20,10 @@ pub struct InodeHandle<R = Rights>(Arc<InodeHandle_>, R);
struct InodeHandle_ {
dentry: Arc<Dentry>,
+ /// `file_io` is Similar to `file_private` field in `file` structure in linux. If
+ /// `file_io` is Some, typical file operations including `read`, `write`, `poll`,
+ /// `ioctl` will be provided by `file_io`, instead of `dentry`.
+ file_io: Option<Arc<dyn FileIo>>,
offset: Mutex<usize>,
access_mode: AccessMode,
status_flags: AtomicU32,
diff --git a/services/libs/jinux-std/src/fs/inode_handle/mod.rs b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/mod.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
@@ -25,6 +32,11 @@ struct InodeHandle_ {
impl InodeHandle_ {
pub fn read(&self, buf: &mut [u8]) -> Result<usize> {
let mut offset = self.offset.lock();
+
+ if let Some(ref file_io) = self.file_io {
+ return file_io.read(buf);
+ }
+
let len = if self.status_flags().contains(StatusFlags::O_DIRECT) {
self.dentry.inode().read_direct_at(*offset, buf)?
} else {
diff --git a/services/libs/jinux-std/src/fs/inode_handle/mod.rs b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/mod.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
@@ -25,6 +32,11 @@ struct InodeHandle_ {
impl InodeHandle_ {
pub fn read(&self, buf: &mut [u8]) -> Result<usize> {
let mut offset = self.offset.lock();
+
+ if let Some(ref file_io) = self.file_io {
+ return file_io.read(buf);
+ }
+
let len = if self.status_flags().contains(StatusFlags::O_DIRECT) {
self.dentry.inode().read_direct_at(*offset, buf)?
} else {
diff --git a/services/libs/jinux-std/src/fs/inode_handle/mod.rs b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/mod.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
@@ -37,6 +49,11 @@ impl InodeHandle_ {
pub fn write(&self, buf: &[u8]) -> Result<usize> {
let mut offset = self.offset.lock();
+
+ if let Some(ref file_io) = self.file_io {
+ return file_io.write(buf);
+ }
+
if self.status_flags().contains(StatusFlags::O_APPEND) {
*offset = self.dentry.inode_len();
}
diff --git a/services/libs/jinux-std/src/fs/inode_handle/mod.rs b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/mod.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
@@ -37,6 +49,11 @@ impl InodeHandle_ {
pub fn write(&self, buf: &[u8]) -> Result<usize> {
let mut offset = self.offset.lock();
+
+ if let Some(ref file_io) = self.file_io {
+ return file_io.write(buf);
+ }
+
if self.status_flags().contains(StatusFlags::O_APPEND) {
*offset = self.dentry.inode_len();
}
diff --git a/services/libs/jinux-std/src/fs/inode_handle/mod.rs b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/mod.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
@@ -51,6 +68,10 @@ impl InodeHandle_ {
}
pub fn read_to_end(&self, buf: &mut Vec<u8>) -> Result<usize> {
+ if self.file_io.is_some() {
+ return_errno_with_message!(Errno::EINVAL, "file io does not support read to end");
+ }
+
let len = if self.status_flags().contains(StatusFlags::O_DIRECT) {
self.dentry.inode().read_direct_to_end(buf)?
} else {
diff --git a/services/libs/jinux-std/src/fs/inode_handle/mod.rs b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/mod.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
@@ -51,6 +68,10 @@ impl InodeHandle_ {
}
pub fn read_to_end(&self, buf: &mut Vec<u8>) -> Result<usize> {
+ if self.file_io.is_some() {
+ return_errno_with_message!(Errno::EINVAL, "file io does not support read to end");
+ }
+
let len = if self.status_flags().contains(StatusFlags::O_DIRECT) {
self.dentry.inode().read_direct_to_end(buf)?
} else {
diff --git a/services/libs/jinux-std/src/fs/inode_handle/mod.rs b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/mod.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
@@ -117,6 +138,22 @@ impl InodeHandle_ {
*offset += read_cnt;
Ok(read_cnt)
}
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ if let Some(ref file_io) = self.file_io {
+ return file_io.poll(mask, poller);
+ }
+
+ self.dentry.inode().poll(mask, poller)
+ }
+
+ fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
+ if let Some(ref file_io) = self.file_io {
+ return file_io.ioctl(cmd, arg);
+ }
+
+ self.dentry.inode().ioctl(cmd, arg)
+ }
}
impl Debug for InodeHandle_ {
diff --git a/services/libs/jinux-std/src/fs/inode_handle/mod.rs b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/mod.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
@@ -117,6 +138,22 @@ impl InodeHandle_ {
*offset += read_cnt;
Ok(read_cnt)
}
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ if let Some(ref file_io) = self.file_io {
+ return file_io.poll(mask, poller);
+ }
+
+ self.dentry.inode().poll(mask, poller)
+ }
+
+ fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
+ if let Some(ref file_io) = self.file_io {
+ return file_io.ioctl(cmd, arg);
+ }
+
+ self.dentry.inode().ioctl(cmd, arg)
+ }
}
impl Debug for InodeHandle_ {
diff --git a/services/libs/jinux-std/src/fs/inode_handle/mod.rs b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/mod.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
@@ -136,3 +173,15 @@ impl<R> InodeHandle<R> {
&self.0.dentry
}
}
+
+pub trait FileIo: Send + Sync + 'static {
+ fn read(&self, buf: &mut [u8]) -> Result<usize>;
+
+ fn write(&self, buf: &[u8]) -> Result<usize>;
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents;
+
+ fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
+ return_errno_with_message!(Errno::EINVAL, "ioctl is not supported");
+ }
+}
diff --git a/services/libs/jinux-std/src/fs/inode_handle/mod.rs b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
--- a/services/libs/jinux-std/src/fs/inode_handle/mod.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
@@ -136,3 +173,15 @@ impl<R> InodeHandle<R> {
&self.0.dentry
}
}
+
+pub trait FileIo: Send + Sync + 'static {
+ fn read(&self, buf: &mut [u8]) -> Result<usize>;
+
+ fn write(&self, buf: &[u8]) -> Result<usize>;
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents;
+
+ fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
+ return_errno_with_message!(Errno::EINVAL, "ioctl is not supported");
+ }
+}
diff --git a/services/libs/jinux-std/src/fs/procfs/mod.rs b/services/libs/jinux-std/src/fs/procfs/mod.rs
--- a/services/libs/jinux-std/src/fs/procfs/mod.rs
+++ b/services/libs/jinux-std/src/fs/procfs/mod.rs
@@ -91,7 +91,7 @@ impl DirOps for RootDirOps {
SelfSymOps::new_inode(this_ptr.clone())
} else if let Ok(pid) = name.parse::<Pid>() {
let process_ref =
- process_table::pid_to_process(pid).ok_or_else(|| Error::new(Errno::ENOENT))?;
+ process_table::get_process(&pid).ok_or_else(|| Error::new(Errno::ENOENT))?;
PidDirOps::new_inode(process_ref, this_ptr.clone())
} else {
return_errno!(Errno::ENOENT);
diff --git a/services/libs/jinux-std/src/fs/procfs/mod.rs b/services/libs/jinux-std/src/fs/procfs/mod.rs
--- a/services/libs/jinux-std/src/fs/procfs/mod.rs
+++ b/services/libs/jinux-std/src/fs/procfs/mod.rs
@@ -91,7 +91,7 @@ impl DirOps for RootDirOps {
SelfSymOps::new_inode(this_ptr.clone())
} else if let Ok(pid) = name.parse::<Pid>() {
let process_ref =
- process_table::pid_to_process(pid).ok_or_else(|| Error::new(Errno::ENOENT))?;
+ process_table::get_process(&pid).ok_or_else(|| Error::new(Errno::ENOENT))?;
PidDirOps::new_inode(process_ref, this_ptr.clone())
} else {
return_errno!(Errno::ENOENT);
diff --git a/services/libs/jinux-std/src/fs/ramfs/fs.rs b/services/libs/jinux-std/src/fs/ramfs/fs.rs
--- a/services/libs/jinux-std/src/fs/ramfs/fs.rs
+++ b/services/libs/jinux-std/src/fs/ramfs/fs.rs
@@ -574,6 +574,10 @@ impl Inode for RamInode {
Ok(device_inode)
}
+ fn as_device(&self) -> Option<Arc<dyn Device>> {
+ self.0.read().inner.as_device().cloned()
+ }
+
fn create(&self, name: &str, type_: InodeType, mode: InodeMode) -> Result<Arc<dyn Inode>> {
if self.0.read().metadata.type_ != InodeType::Dir {
return_errno_with_message!(Errno::ENOTDIR, "self is not dir");
diff --git a/services/libs/jinux-std/src/fs/ramfs/fs.rs b/services/libs/jinux-std/src/fs/ramfs/fs.rs
--- a/services/libs/jinux-std/src/fs/ramfs/fs.rs
+++ b/services/libs/jinux-std/src/fs/ramfs/fs.rs
@@ -574,6 +574,10 @@ impl Inode for RamInode {
Ok(device_inode)
}
+ fn as_device(&self) -> Option<Arc<dyn Device>> {
+ self.0.read().inner.as_device().cloned()
+ }
+
fn create(&self, name: &str, type_: InodeType, mode: InodeMode) -> Result<Arc<dyn Inode>> {
if self.0.read().metadata.type_ != InodeType::Dir {
return_errno_with_message!(Errno::ENOTDIR, "self is not dir");
diff --git a/services/libs/jinux-std/src/fs/rootfs.rs b/services/libs/jinux-std/src/fs/rootfs.rs
--- a/services/libs/jinux-std/src/fs/rootfs.rs
+++ b/services/libs/jinux-std/src/fs/rootfs.rs
@@ -84,7 +84,7 @@ pub fn init(initramfs_buf: &[u8]) -> Result<()> {
static ROOT_MOUNT: Once<Arc<MountNode>> = Once::new();
-fn init_root_mount() {
+pub fn init_root_mount() {
ROOT_MOUNT.call_once(|| -> Arc<MountNode> {
let rootfs = RamFS::new();
MountNode::new_root(rootfs)
diff --git a/services/libs/jinux-std/src/fs/rootfs.rs b/services/libs/jinux-std/src/fs/rootfs.rs
--- a/services/libs/jinux-std/src/fs/rootfs.rs
+++ b/services/libs/jinux-std/src/fs/rootfs.rs
@@ -84,7 +84,7 @@ pub fn init(initramfs_buf: &[u8]) -> Result<()> {
static ROOT_MOUNT: Once<Arc<MountNode>> = Once::new();
-fn init_root_mount() {
+pub fn init_root_mount() {
ROOT_MOUNT.call_once(|| -> Arc<MountNode> {
let rootfs = RamFS::new();
MountNode::new_root(rootfs)
diff --git a/services/libs/jinux-std/src/fs/utils/inode.rs b/services/libs/jinux-std/src/fs/utils/inode.rs
--- a/services/libs/jinux-std/src/fs/utils/inode.rs
+++ b/services/libs/jinux-std/src/fs/utils/inode.rs
@@ -285,6 +285,10 @@ pub trait Inode: Any + Sync + Send {
Err(Error::new(Errno::ENOTDIR))
}
+ fn as_device(&self) -> Option<Arc<dyn Device>> {
+ None
+ }
+
fn readdir_at(&self, offset: usize, visitor: &mut dyn DirentVisitor) -> Result<usize> {
Err(Error::new(Errno::ENOTDIR))
}
diff --git a/services/libs/jinux-std/src/fs/utils/inode.rs b/services/libs/jinux-std/src/fs/utils/inode.rs
--- a/services/libs/jinux-std/src/fs/utils/inode.rs
+++ b/services/libs/jinux-std/src/fs/utils/inode.rs
@@ -285,6 +285,10 @@ pub trait Inode: Any + Sync + Send {
Err(Error::new(Errno::ENOTDIR))
}
+ fn as_device(&self) -> Option<Arc<dyn Device>> {
+ None
+ }
+
fn readdir_at(&self, offset: usize, visitor: &mut dyn DirentVisitor) -> Result<usize> {
Err(Error::new(Errno::ENOTDIR))
}
diff --git a/services/libs/jinux-std/src/process/clone.rs b/services/libs/jinux-std/src/process/clone.rs
--- a/services/libs/jinux-std/src/process/clone.rs
+++ b/services/libs/jinux-std/src/process/clone.rs
@@ -1,26 +1,20 @@
-use jinux_frame::{cpu::UserContext, user::UserSpace, vm::VmIo};
-
+use super::posix_thread::{PosixThread, PosixThreadBuilder, PosixThreadExt, ThreadName};
+use super::process_vm::ProcessVm;
+use super::signal::sig_disposition::SigDispositions;
+use super::{process_table, Process, ProcessBuilder};
+use crate::current_thread;
+use crate::fs::file_table::FileTable;
+use crate::fs::fs_resolver::FsResolver;
+use crate::fs::utils::FileCreationMask;
+use crate::prelude::*;
+use crate::thread::{allocate_tid, thread_table, Thread, Tid};
+use crate::util::write_val_to_user;
+use crate::vm::vmar::Vmar;
+use jinux_frame::cpu::UserContext;
+use jinux_frame::user::UserSpace;
+use jinux_frame::vm::VmIo;
use jinux_rights::Full;
-use crate::{
- current_thread,
- fs::file_table::FileTable,
- fs::{fs_resolver::FsResolver, utils::FileCreationMask},
- prelude::*,
- process::{
- posix_thread::{PosixThreadBuilder, PosixThreadExt, ThreadName},
- process_table,
- },
- thread::{allocate_tid, thread_table, Thread, Tid},
- util::write_val_to_user,
- vm::vmar::Vmar,
-};
-
-use super::{
- posix_thread::PosixThread, process_vm::ProcessVm, signal::sig_disposition::SigDispositions,
- Process, ProcessBuilder,
-};
-
bitflags! {
pub struct CloneFlags: u32 {
const CLONE_VM = 0x00000100; /* Set if VM shared between processes. */
diff --git a/services/libs/jinux-std/src/process/clone.rs b/services/libs/jinux-std/src/process/clone.rs
--- a/services/libs/jinux-std/src/process/clone.rs
+++ b/services/libs/jinux-std/src/process/clone.rs
@@ -1,26 +1,20 @@
-use jinux_frame::{cpu::UserContext, user::UserSpace, vm::VmIo};
-
+use super::posix_thread::{PosixThread, PosixThreadBuilder, PosixThreadExt, ThreadName};
+use super::process_vm::ProcessVm;
+use super::signal::sig_disposition::SigDispositions;
+use super::{process_table, Process, ProcessBuilder};
+use crate::current_thread;
+use crate::fs::file_table::FileTable;
+use crate::fs::fs_resolver::FsResolver;
+use crate::fs::utils::FileCreationMask;
+use crate::prelude::*;
+use crate::thread::{allocate_tid, thread_table, Thread, Tid};
+use crate::util::write_val_to_user;
+use crate::vm::vmar::Vmar;
+use jinux_frame::cpu::UserContext;
+use jinux_frame::user::UserSpace;
+use jinux_frame::vm::VmIo;
use jinux_rights::Full;
-use crate::{
- current_thread,
- fs::file_table::FileTable,
- fs::{fs_resolver::FsResolver, utils::FileCreationMask},
- prelude::*,
- process::{
- posix_thread::{PosixThreadBuilder, PosixThreadExt, ThreadName},
- process_table,
- },
- thread::{allocate_tid, thread_table, Thread, Tid},
- util::write_val_to_user,
- vm::vmar::Vmar,
-};
-
-use super::{
- posix_thread::PosixThread, process_vm::ProcessVm, signal::sig_disposition::SigDispositions,
- Process, ProcessBuilder,
-};
-
bitflags! {
pub struct CloneFlags: u32 {
const CLONE_VM = 0x00000100; /* Set if VM shared between processes. */
diff --git a/services/libs/jinux-std/src/process/clone.rs b/services/libs/jinux-std/src/process/clone.rs
--- a/services/libs/jinux-std/src/process/clone.rs
+++ b/services/libs/jinux-std/src/process/clone.rs
@@ -275,16 +269,13 @@ fn clone_child_process(parent_context: UserContext, clone_args: CloneArgs) -> Re
.file_table(child_file_table)
.fs(child_fs)
.umask(child_umask)
- .sig_dispositions(child_sig_dispositions)
- .process_group(current.process_group().unwrap());
+ .sig_dispositions(child_sig_dispositions);
process_builder.build()?
};
- current!().add_child(child.clone());
- process_table::add_process(child.clone());
-
- let child_thread = thread_table::tid_to_thread(child_tid).unwrap();
+ // Deals with clone flags
+ let child_thread = thread_table::get_thread(child_tid).unwrap();
let child_posix_thread = child_thread.as_posix_thread().unwrap();
clone_parent_settid(child_tid, clone_args.parent_tidptr, clone_flags)?;
clone_child_cleartid(child_posix_thread, clone_args.child_tidptr, clone_flags)?;
diff --git a/services/libs/jinux-std/src/process/clone.rs b/services/libs/jinux-std/src/process/clone.rs
--- a/services/libs/jinux-std/src/process/clone.rs
+++ b/services/libs/jinux-std/src/process/clone.rs
@@ -275,16 +269,13 @@ fn clone_child_process(parent_context: UserContext, clone_args: CloneArgs) -> Re
.file_table(child_file_table)
.fs(child_fs)
.umask(child_umask)
- .sig_dispositions(child_sig_dispositions)
- .process_group(current.process_group().unwrap());
+ .sig_dispositions(child_sig_dispositions);
process_builder.build()?
};
- current!().add_child(child.clone());
- process_table::add_process(child.clone());
-
- let child_thread = thread_table::tid_to_thread(child_tid).unwrap();
+ // Deals with clone flags
+ let child_thread = thread_table::get_thread(child_tid).unwrap();
let child_posix_thread = child_thread.as_posix_thread().unwrap();
clone_parent_settid(child_tid, clone_args.parent_tidptr, clone_flags)?;
clone_child_cleartid(child_posix_thread, clone_args.child_tidptr, clone_flags)?;
diff --git a/services/libs/jinux-std/src/process/clone.rs b/services/libs/jinux-std/src/process/clone.rs
--- a/services/libs/jinux-std/src/process/clone.rs
+++ b/services/libs/jinux-std/src/process/clone.rs
@@ -296,6 +287,10 @@ fn clone_child_process(parent_context: UserContext, clone_args: CloneArgs) -> Re
clone_args.child_tidptr,
clone_flags,
)?;
+
+ // Sets parent process and group for child process.
+ set_parent_and_group(¤t, &child);
+
Ok(child)
}
diff --git a/services/libs/jinux-std/src/process/clone.rs b/services/libs/jinux-std/src/process/clone.rs
--- a/services/libs/jinux-std/src/process/clone.rs
+++ b/services/libs/jinux-std/src/process/clone.rs
@@ -296,6 +287,10 @@ fn clone_child_process(parent_context: UserContext, clone_args: CloneArgs) -> Re
clone_args.child_tidptr,
clone_flags,
)?;
+
+ // Sets parent process and group for child process.
+ set_parent_and_group(¤t, &child);
+
Ok(child)
}
diff --git a/services/libs/jinux-std/src/process/clone.rs b/services/libs/jinux-std/src/process/clone.rs
--- a/services/libs/jinux-std/src/process/clone.rs
+++ b/services/libs/jinux-std/src/process/clone.rs
@@ -414,3 +409,19 @@ fn clone_sysvsem(clone_flags: CloneFlags) -> Result<()> {
}
Ok(())
}
+
+fn set_parent_and_group(parent: &Arc<Process>, child: &Arc<Process>) {
+ let process_group = parent.process_group().unwrap();
+
+ let mut process_table_mut = process_table::process_table_mut();
+ let mut group_inner = process_group.inner.lock();
+ let mut child_group_mut = child.process_group.lock();
+ let mut children_mut = parent.children().lock();
+
+ children_mut.insert(child.pid(), child.clone());
+
+ group_inner.processes.insert(child.pid(), child.clone());
+ *child_group_mut = Arc::downgrade(&process_group);
+
+ process_table_mut.insert(child.pid(), child.clone());
+}
diff --git a/services/libs/jinux-std/src/process/clone.rs b/services/libs/jinux-std/src/process/clone.rs
--- a/services/libs/jinux-std/src/process/clone.rs
+++ b/services/libs/jinux-std/src/process/clone.rs
@@ -414,3 +409,19 @@ fn clone_sysvsem(clone_flags: CloneFlags) -> Result<()> {
}
Ok(())
}
+
+fn set_parent_and_group(parent: &Arc<Process>, child: &Arc<Process>) {
+ let process_group = parent.process_group().unwrap();
+
+ let mut process_table_mut = process_table::process_table_mut();
+ let mut group_inner = process_group.inner.lock();
+ let mut child_group_mut = child.process_group.lock();
+ let mut children_mut = parent.children().lock();
+
+ children_mut.insert(child.pid(), child.clone());
+
+ group_inner.processes.insert(child.pid(), child.clone());
+ *child_group_mut = Arc::downgrade(&process_group);
+
+ process_table_mut.insert(child.pid(), child.clone());
+}
diff --git a/services/libs/jinux-std/src/process/exit.rs b/services/libs/jinux-std/src/process/exit.rs
--- a/services/libs/jinux-std/src/process/exit.rs
+++ b/services/libs/jinux-std/src/process/exit.rs
@@ -37,9 +37,11 @@ pub fn do_exit_group(term_status: TermStatus) {
// Move children to the init process
if !is_init_process(¤t) {
if let Some(init_process) = get_init_process() {
+ let mut init_children = init_process.children().lock();
for (_, child_process) in current.children().lock().extract_if(|_, _| true) {
- child_process.set_parent(Arc::downgrade(&init_process));
- init_process.add_child(child_process);
+ let mut parent = child_process.parent.lock();
+ init_children.insert(child_process.pid(), child_process.clone());
+ *parent = Arc::downgrade(&init_process);
}
}
}
diff --git a/services/libs/jinux-std/src/process/exit.rs b/services/libs/jinux-std/src/process/exit.rs
--- a/services/libs/jinux-std/src/process/exit.rs
+++ b/services/libs/jinux-std/src/process/exit.rs
@@ -37,9 +37,11 @@ pub fn do_exit_group(term_status: TermStatus) {
// Move children to the init process
if !is_init_process(¤t) {
if let Some(init_process) = get_init_process() {
+ let mut init_children = init_process.children().lock();
for (_, child_process) in current.children().lock().extract_if(|_, _| true) {
- child_process.set_parent(Arc::downgrade(&init_process));
- init_process.add_child(child_process);
+ let mut parent = child_process.parent.lock();
+ init_children.insert(child_process.pid(), child_process.clone());
+ *parent = Arc::downgrade(&init_process);
}
}
}
diff --git a/services/libs/jinux-std/src/process/exit.rs b/services/libs/jinux-std/src/process/exit.rs
--- a/services/libs/jinux-std/src/process/exit.rs
+++ b/services/libs/jinux-std/src/process/exit.rs
@@ -56,7 +58,7 @@ const INIT_PROCESS_PID: Pid = 1;
/// Get the init process
fn get_init_process() -> Option<Arc<Process>> {
- process_table::pid_to_process(INIT_PROCESS_PID)
+ process_table::get_process(&INIT_PROCESS_PID)
}
fn is_init_process(process: &Process) -> bool {
diff --git a/services/libs/jinux-std/src/process/exit.rs b/services/libs/jinux-std/src/process/exit.rs
--- a/services/libs/jinux-std/src/process/exit.rs
+++ b/services/libs/jinux-std/src/process/exit.rs
@@ -56,7 +58,7 @@ const INIT_PROCESS_PID: Pid = 1;
/// Get the init process
fn get_init_process() -> Option<Arc<Process>> {
- process_table::pid_to_process(INIT_PROCESS_PID)
+ process_table::get_process(&INIT_PROCESS_PID)
}
fn is_init_process(process: &Process) -> bool {
diff --git a/services/libs/jinux-std/src/process/mod.rs b/services/libs/jinux-std/src/process/mod.rs
--- a/services/libs/jinux-std/src/process/mod.rs
+++ b/services/libs/jinux-std/src/process/mod.rs
@@ -4,7 +4,6 @@ pub mod posix_thread;
#[allow(clippy::module_inception)]
mod process;
mod process_filter;
-mod process_group;
pub mod process_table;
mod process_vm;
mod program_loader;
diff --git a/services/libs/jinux-std/src/process/mod.rs b/services/libs/jinux-std/src/process/mod.rs
--- a/services/libs/jinux-std/src/process/mod.rs
+++ b/services/libs/jinux-std/src/process/mod.rs
@@ -4,7 +4,6 @@ pub mod posix_thread;
#[allow(clippy::module_inception)]
mod process;
mod process_filter;
-mod process_group;
pub mod process_table;
mod process_vm;
mod program_loader;
diff --git a/services/libs/jinux-std/src/process/mod.rs b/services/libs/jinux-std/src/process/mod.rs
--- a/services/libs/jinux-std/src/process/mod.rs
+++ b/services/libs/jinux-std/src/process/mod.rs
@@ -17,9 +16,10 @@ mod wait;
pub use clone::{clone_child, CloneArgs, CloneFlags};
pub use exit::do_exit_group;
pub use process::ProcessBuilder;
-pub use process::{current, ExitCode, Pgid, Pid, Process};
+pub use process::{
+ current, ExitCode, JobControl, Pgid, Pid, Process, ProcessGroup, Session, Sid, Terminal,
+};
pub use process_filter::ProcessFilter;
-pub use process_group::ProcessGroup;
pub use program_loader::{check_executable_file, load_program_to_vm};
pub use rlimit::ResourceType;
pub use term_status::TermStatus;
diff --git a/services/libs/jinux-std/src/process/mod.rs b/services/libs/jinux-std/src/process/mod.rs
--- a/services/libs/jinux-std/src/process/mod.rs
+++ b/services/libs/jinux-std/src/process/mod.rs
@@ -17,9 +16,10 @@ mod wait;
pub use clone::{clone_child, CloneArgs, CloneFlags};
pub use exit::do_exit_group;
pub use process::ProcessBuilder;
-pub use process::{current, ExitCode, Pgid, Pid, Process};
+pub use process::{
+ current, ExitCode, JobControl, Pgid, Pid, Process, ProcessGroup, Session, Sid, Terminal,
+};
pub use process_filter::ProcessFilter;
-pub use process_group::ProcessGroup;
pub use program_loader::{check_executable_file, load_program_to_vm};
pub use rlimit::ResourceType;
pub use term_status::TermStatus;
diff --git a/services/libs/jinux-std/src/process/process/builder.rs b/services/libs/jinux-std/src/process/process/builder.rs
--- a/services/libs/jinux-std/src/process/process/builder.rs
+++ b/services/libs/jinux-std/src/process/process/builder.rs
@@ -1,12 +1,10 @@
use crate::fs::file_table::FileTable;
use crate::fs::fs_resolver::FsResolver;
use crate::fs::utils::FileCreationMask;
-use crate::process::posix_thread::PosixThreadBuilder;
-use crate::process::process_group::ProcessGroup;
-use crate::process::process_table;
+use crate::process::posix_thread::{PosixThreadBuilder, PosixThreadExt};
use crate::process::process_vm::ProcessVm;
use crate::process::rlimit::ResourceLimits;
-use crate::process::{posix_thread::PosixThreadExt, signal::sig_disposition::SigDispositions};
+use crate::process::signal::sig_disposition::SigDispositions;
use crate::thread::Thread;
use super::{Pid, Process};
diff --git a/services/libs/jinux-std/src/process/process/builder.rs b/services/libs/jinux-std/src/process/process/builder.rs
--- a/services/libs/jinux-std/src/process/process/builder.rs
+++ b/services/libs/jinux-std/src/process/process/builder.rs
@@ -1,12 +1,10 @@
use crate::fs::file_table::FileTable;
use crate::fs::fs_resolver::FsResolver;
use crate::fs::utils::FileCreationMask;
-use crate::process::posix_thread::PosixThreadBuilder;
-use crate::process::process_group::ProcessGroup;
-use crate::process::process_table;
+use crate::process::posix_thread::{PosixThreadBuilder, PosixThreadExt};
use crate::process::process_vm::ProcessVm;
use crate::process::rlimit::ResourceLimits;
-use crate::process::{posix_thread::PosixThreadExt, signal::sig_disposition::SigDispositions};
+use crate::process::signal::sig_disposition::SigDispositions;
use crate::thread::Thread;
use super::{Pid, Process};
diff --git a/services/libs/jinux-std/src/process/process/builder.rs b/services/libs/jinux-std/src/process/process/builder.rs
--- a/services/libs/jinux-std/src/process/process/builder.rs
+++ b/services/libs/jinux-std/src/process/process/builder.rs
@@ -23,7 +21,6 @@ pub struct ProcessBuilder<'a> {
argv: Option<Vec<CString>>,
envp: Option<Vec<CString>>,
process_vm: Option<ProcessVm>,
- process_group: Option<Arc<ProcessGroup>>,
file_table: Option<Arc<Mutex<FileTable>>>,
fs: Option<Arc<RwLock<FsResolver>>>,
umask: Option<Arc<RwLock<FileCreationMask>>>,
diff --git a/services/libs/jinux-std/src/process/process/builder.rs b/services/libs/jinux-std/src/process/process/builder.rs
--- a/services/libs/jinux-std/src/process/process/builder.rs
+++ b/services/libs/jinux-std/src/process/process/builder.rs
@@ -23,7 +21,6 @@ pub struct ProcessBuilder<'a> {
argv: Option<Vec<CString>>,
envp: Option<Vec<CString>>,
process_vm: Option<ProcessVm>,
- process_group: Option<Arc<ProcessGroup>>,
file_table: Option<Arc<Mutex<FileTable>>>,
fs: Option<Arc<RwLock<FsResolver>>>,
umask: Option<Arc<RwLock<FileCreationMask>>>,
diff --git a/services/libs/jinux-std/src/process/process/builder.rs b/services/libs/jinux-std/src/process/process/builder.rs
--- a/services/libs/jinux-std/src/process/process/builder.rs
+++ b/services/libs/jinux-std/src/process/process/builder.rs
@@ -41,7 +38,6 @@ impl<'a> ProcessBuilder<'a> {
argv: None,
envp: None,
process_vm: None,
- process_group: None,
file_table: None,
fs: None,
umask: None,
diff --git a/services/libs/jinux-std/src/process/process/builder.rs b/services/libs/jinux-std/src/process/process/builder.rs
--- a/services/libs/jinux-std/src/process/process/builder.rs
+++ b/services/libs/jinux-std/src/process/process/builder.rs
@@ -41,7 +38,6 @@ impl<'a> ProcessBuilder<'a> {
argv: None,
envp: None,
process_vm: None,
- process_group: None,
file_table: None,
fs: None,
umask: None,
diff --git a/services/libs/jinux-std/src/process/process/builder.rs b/services/libs/jinux-std/src/process/process/builder.rs
--- a/services/libs/jinux-std/src/process/process/builder.rs
+++ b/services/libs/jinux-std/src/process/process/builder.rs
@@ -60,11 +56,6 @@ impl<'a> ProcessBuilder<'a> {
self
}
- pub fn process_group(&mut self, process_group: Arc<ProcessGroup>) -> &mut Self {
- self.process_group = Some(process_group);
- self
- }
-
pub fn file_table(&mut self, file_table: Arc<Mutex<FileTable>>) -> &mut Self {
self.file_table = Some(file_table);
self
diff --git a/services/libs/jinux-std/src/process/process/builder.rs b/services/libs/jinux-std/src/process/process/builder.rs
--- a/services/libs/jinux-std/src/process/process/builder.rs
+++ b/services/libs/jinux-std/src/process/process/builder.rs
@@ -60,11 +56,6 @@ impl<'a> ProcessBuilder<'a> {
self
}
- pub fn process_group(&mut self, process_group: Arc<ProcessGroup>) -> &mut Self {
- self.process_group = Some(process_group);
- self
- }
-
pub fn file_table(&mut self, file_table: Arc<Mutex<FileTable>>) -> &mut Self {
self.file_table = Some(file_table);
self
diff --git a/services/libs/jinux-std/src/process/process/builder.rs b/services/libs/jinux-std/src/process/process/builder.rs
--- a/services/libs/jinux-std/src/process/process/builder.rs
+++ b/services/libs/jinux-std/src/process/process/builder.rs
@@ -126,7 +117,6 @@ impl<'a> ProcessBuilder<'a> {
argv,
envp,
process_vm,
- process_group,
file_table,
fs,
umask,
diff --git a/services/libs/jinux-std/src/process/process/builder.rs b/services/libs/jinux-std/src/process/process/builder.rs
--- a/services/libs/jinux-std/src/process/process/builder.rs
+++ b/services/libs/jinux-std/src/process/process/builder.rs
@@ -126,7 +117,6 @@ impl<'a> ProcessBuilder<'a> {
argv,
envp,
process_vm,
- process_group,
file_table,
fs,
umask,
diff --git a/services/libs/jinux-std/src/process/process/builder.rs b/services/libs/jinux-std/src/process/process/builder.rs
--- a/services/libs/jinux-std/src/process/process/builder.rs
+++ b/services/libs/jinux-std/src/process/process/builder.rs
@@ -136,10 +126,6 @@ impl<'a> ProcessBuilder<'a> {
let process_vm = process_vm.or_else(|| Some(ProcessVm::alloc())).unwrap();
- let process_group_ref = process_group
- .as_ref()
- .map_or_else(Weak::new, Arc::downgrade);
-
let file_table = file_table
.or_else(|| Some(Arc::new(Mutex::new(FileTable::new_with_stdio()))))
.unwrap();
diff --git a/services/libs/jinux-std/src/process/process/builder.rs b/services/libs/jinux-std/src/process/process/builder.rs
--- a/services/libs/jinux-std/src/process/process/builder.rs
+++ b/services/libs/jinux-std/src/process/process/builder.rs
@@ -136,10 +126,6 @@ impl<'a> ProcessBuilder<'a> {
let process_vm = process_vm.or_else(|| Some(ProcessVm::alloc())).unwrap();
- let process_group_ref = process_group
- .as_ref()
- .map_or_else(Weak::new, Arc::downgrade);
-
let file_table = file_table
.or_else(|| Some(Arc::new(Mutex::new(FileTable::new_with_stdio()))))
.unwrap();
diff --git a/services/libs/jinux-std/src/process/process/builder.rs b/services/libs/jinux-std/src/process/process/builder.rs
--- a/services/libs/jinux-std/src/process/process/builder.rs
+++ b/services/libs/jinux-std/src/process/process/builder.rs
@@ -168,7 +154,6 @@ impl<'a> ProcessBuilder<'a> {
threads,
executable_path.to_string(),
process_vm,
- process_group_ref,
file_table,
fs,
umask,
diff --git a/services/libs/jinux-std/src/process/process/builder.rs b/services/libs/jinux-std/src/process/process/builder.rs
--- a/services/libs/jinux-std/src/process/process/builder.rs
+++ b/services/libs/jinux-std/src/process/process/builder.rs
@@ -168,7 +154,6 @@ impl<'a> ProcessBuilder<'a> {
threads,
executable_path.to_string(),
process_vm,
- process_group_ref,
file_table,
fs,
umask,
diff --git a/services/libs/jinux-std/src/process/process/builder.rs b/services/libs/jinux-std/src/process/process/builder.rs
--- a/services/libs/jinux-std/src/process/process/builder.rs
+++ b/services/libs/jinux-std/src/process/process/builder.rs
@@ -194,15 +179,6 @@ impl<'a> ProcessBuilder<'a> {
process.threads().lock().push(thread);
- if let Some(process_group) = process_group {
- process_group.add_process(process.clone());
- } else {
- let new_process_group = Arc::new(ProcessGroup::new(process.clone()));
- let pgid = new_process_group.pgid();
- process.set_process_group(Arc::downgrade(&new_process_group));
- process_table::add_process_group(new_process_group);
- }
-
process.set_runnable();
Ok(process)
diff --git a/services/libs/jinux-std/src/process/process/builder.rs b/services/libs/jinux-std/src/process/process/builder.rs
--- a/services/libs/jinux-std/src/process/process/builder.rs
+++ b/services/libs/jinux-std/src/process/process/builder.rs
@@ -194,15 +179,6 @@ impl<'a> ProcessBuilder<'a> {
process.threads().lock().push(thread);
- if let Some(process_group) = process_group {
- process_group.add_process(process.clone());
- } else {
- let new_process_group = Arc::new(ProcessGroup::new(process.clone()));
- let pgid = new_process_group.pgid();
- process.set_process_group(Arc::downgrade(&new_process_group));
- process_table::add_process_group(new_process_group);
- }
-
process.set_runnable();
Ok(process)
diff --git /dev/null b/services/libs/jinux-std/src/process/process/job_control.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/process/process/job_control.rs
@@ -0,0 +1,161 @@
+use crate::prelude::*;
+use crate::process::signal::constants::{SIGCONT, SIGHUP};
+use crate::process::signal::signals::kernel::KernelSignal;
+use crate::process::signal::Pauser;
+use crate::process::{ProcessGroup, Session};
+
+/// The job control for terminals like tty and pty.
+///
+/// This struct is used to support shell job control, which allows users to
+/// run commands in the foreground or in the background. This struct manages
+/// the session and foreground process group for a terminal.
+pub struct JobControl {
+ foreground: SpinLock<Weak<ProcessGroup>>,
+ session: SpinLock<Weak<Session>>,
+ pauser: Arc<Pauser>,
+}
+
+impl JobControl {
+ /// Creates a new `TtyJobControl`
+ pub fn new() -> Self {
+ Self {
+ foreground: SpinLock::new(Weak::new()),
+ session: SpinLock::new(Weak::new()),
+ pauser: Pauser::new(),
+ }
+ }
+
+ // *************** Session ***************
+
+ /// Returns the session whose controlling terminal is the terminal.
+ fn session(&self) -> Option<Arc<Session>> {
+ self.session.lock().upgrade()
+ }
+
+ /// Sets the terminal as the controlling terminal of the `session`.
+ ///
+ /// # Panic
+ ///
+ /// This terminal should not belong to any session.
+ pub fn set_session(&self, session: &Arc<Session>) {
+ debug_assert!(self.session().is_none());
+ *self.session.lock() = Arc::downgrade(session);
+ }
+
+ /// Sets the terminal as the controlling terminal of the session of current process.
+ ///
+ /// # Panic
+ ///
+ /// This function should only be called in process context.
+ pub fn set_current_session(&self) -> Result<()> {
+ if self.session().is_some() {
+ return_errno_with_message!(
+ Errno::EPERM,
+ "the terminal is already controlling terminal of another session"
+ );
+ }
+
+ let current = current!();
+
+ let process_group = current.process_group().unwrap();
+ *self.foreground.lock() = Arc::downgrade(&process_group);
+
+ let session = current.session().unwrap();
+ *self.session.lock() = Arc::downgrade(&session);
+
+ self.pauser.resume_all();
+ Ok(())
+ }
+
+ /// Releases the current session from this terminal.
+ pub fn release_current_session(&self) -> Result<()> {
+ let Some(session) = self.session() else {
+ return_errno_with_message!(
+ Errno::ENOTTY,
+ "the terminal is not controlling terminal now"
+ );
+ };
+
+ if let Some(foreground) = self.foreground() {
+ foreground.broadcast_signal(KernelSignal::new(SIGHUP));
+ foreground.broadcast_signal(KernelSignal::new(SIGCONT));
+ }
+
+ Ok(())
+ }
+
+ // *************** Foreground process group ***************
+
+ /// Returns the foreground process group
+ pub fn foreground(&self) -> Option<Arc<ProcessGroup>> {
+ self.foreground.lock().upgrade()
+ }
+
+ /// Sets the foreground process group.
+ ///
+ /// # Panic
+ ///
+ /// The process group should belong to one session.
+ pub fn set_foreground(&self, process_group: Option<&Arc<ProcessGroup>>) -> Result<()> {
+ let Some(process_group) = process_group else {
+ // FIXME: should we allow this branch?
+ *self.foreground.lock() = Weak::new();
+ return Ok(());
+ };
+
+ let session = process_group.session().unwrap();
+ let Some(terminal_session) = self.session() else {
+ return_errno_with_message!(
+ Errno::EPERM,
+ "the terminal does not become controlling terminal of one session."
+ );
+ };
+
+ if !Arc::ptr_eq(&terminal_session, &session) {
+ return_errno_with_message!(
+ Errno::EPERM,
+ "the process proup belongs to different session"
+ );
+ }
+
+ *self.foreground.lock() = Arc::downgrade(process_group);
+ self.pauser.resume_all();
+ Ok(())
+ }
+
+ /// Wait until the current process is the foreground process group. If
+ /// the foreground process group is None, returns true.
+ ///
+ /// # Panic
+ ///
+ /// This function should only be called in process context.
+ pub fn wait_until_in_foreground(&self) -> Result<()> {
+ // Fast path
+ if self.current_belongs_to_foreground() {
+ return Ok(());
+ }
+
+ // Slow path
+ self.pauser.pause_until(|| {
+ if self.current_belongs_to_foreground() {
+ Some(())
+ } else {
+ None
+ }
+ })
+ }
+
+ fn current_belongs_to_foreground(&self) -> bool {
+ let Some(foreground) = self.foreground() else {
+ return true;
+ };
+
+ foreground.contains_process(current!().pid())
+ }
+}
+
+impl Default for JobControl {
+ fn default() -> Self {
+ Self::new()
+ }
+}
diff --git /dev/null b/services/libs/jinux-std/src/process/process/job_control.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/process/process/job_control.rs
@@ -0,0 +1,161 @@
+use crate::prelude::*;
+use crate::process::signal::constants::{SIGCONT, SIGHUP};
+use crate::process::signal::signals::kernel::KernelSignal;
+use crate::process::signal::Pauser;
+use crate::process::{ProcessGroup, Session};
+
+/// The job control for terminals like tty and pty.
+///
+/// This struct is used to support shell job control, which allows users to
+/// run commands in the foreground or in the background. This struct manages
+/// the session and foreground process group for a terminal.
+pub struct JobControl {
+ foreground: SpinLock<Weak<ProcessGroup>>,
+ session: SpinLock<Weak<Session>>,
+ pauser: Arc<Pauser>,
+}
+
+impl JobControl {
+ /// Creates a new `TtyJobControl`
+ pub fn new() -> Self {
+ Self {
+ foreground: SpinLock::new(Weak::new()),
+ session: SpinLock::new(Weak::new()),
+ pauser: Pauser::new(),
+ }
+ }
+
+ // *************** Session ***************
+
+ /// Returns the session whose controlling terminal is the terminal.
+ fn session(&self) -> Option<Arc<Session>> {
+ self.session.lock().upgrade()
+ }
+
+ /// Sets the terminal as the controlling terminal of the `session`.
+ ///
+ /// # Panic
+ ///
+ /// This terminal should not belong to any session.
+ pub fn set_session(&self, session: &Arc<Session>) {
+ debug_assert!(self.session().is_none());
+ *self.session.lock() = Arc::downgrade(session);
+ }
+
+ /// Sets the terminal as the controlling terminal of the session of current process.
+ ///
+ /// # Panic
+ ///
+ /// This function should only be called in process context.
+ pub fn set_current_session(&self) -> Result<()> {
+ if self.session().is_some() {
+ return_errno_with_message!(
+ Errno::EPERM,
+ "the terminal is already controlling terminal of another session"
+ );
+ }
+
+ let current = current!();
+
+ let process_group = current.process_group().unwrap();
+ *self.foreground.lock() = Arc::downgrade(&process_group);
+
+ let session = current.session().unwrap();
+ *self.session.lock() = Arc::downgrade(&session);
+
+ self.pauser.resume_all();
+ Ok(())
+ }
+
+ /// Releases the current session from this terminal.
+ pub fn release_current_session(&self) -> Result<()> {
+ let Some(session) = self.session() else {
+ return_errno_with_message!(
+ Errno::ENOTTY,
+ "the terminal is not controlling terminal now"
+ );
+ };
+
+ if let Some(foreground) = self.foreground() {
+ foreground.broadcast_signal(KernelSignal::new(SIGHUP));
+ foreground.broadcast_signal(KernelSignal::new(SIGCONT));
+ }
+
+ Ok(())
+ }
+
+ // *************** Foreground process group ***************
+
+ /// Returns the foreground process group
+ pub fn foreground(&self) -> Option<Arc<ProcessGroup>> {
+ self.foreground.lock().upgrade()
+ }
+
+ /// Sets the foreground process group.
+ ///
+ /// # Panic
+ ///
+ /// The process group should belong to one session.
+ pub fn set_foreground(&self, process_group: Option<&Arc<ProcessGroup>>) -> Result<()> {
+ let Some(process_group) = process_group else {
+ // FIXME: should we allow this branch?
+ *self.foreground.lock() = Weak::new();
+ return Ok(());
+ };
+
+ let session = process_group.session().unwrap();
+ let Some(terminal_session) = self.session() else {
+ return_errno_with_message!(
+ Errno::EPERM,
+ "the terminal does not become controlling terminal of one session."
+ );
+ };
+
+ if !Arc::ptr_eq(&terminal_session, &session) {
+ return_errno_with_message!(
+ Errno::EPERM,
+ "the process proup belongs to different session"
+ );
+ }
+
+ *self.foreground.lock() = Arc::downgrade(process_group);
+ self.pauser.resume_all();
+ Ok(())
+ }
+
+ /// Wait until the current process is the foreground process group. If
+ /// the foreground process group is None, returns true.
+ ///
+ /// # Panic
+ ///
+ /// This function should only be called in process context.
+ pub fn wait_until_in_foreground(&self) -> Result<()> {
+ // Fast path
+ if self.current_belongs_to_foreground() {
+ return Ok(());
+ }
+
+ // Slow path
+ self.pauser.pause_until(|| {
+ if self.current_belongs_to_foreground() {
+ Some(())
+ } else {
+ None
+ }
+ })
+ }
+
+ fn current_belongs_to_foreground(&self) -> bool {
+ let Some(foreground) = self.foreground() else {
+ return true;
+ };
+
+ foreground.contains_process(current!().pid())
+ }
+}
+
+impl Default for JobControl {
+ fn default() -> Self {
+ Self::new()
+ }
+}
diff --git a/services/libs/jinux-std/src/process/process/mod.rs b/services/libs/jinux-std/src/process/process/mod.rs
--- a/services/libs/jinux-std/src/process/process/mod.rs
+++ b/services/libs/jinux-std/src/process/process/mod.rs
@@ -1,7 +1,4 @@
-mod builder;
-
use super::posix_thread::PosixThreadExt;
-use super::process_group::ProcessGroup;
use super::process_vm::user_heap::UserHeap;
use super::process_vm::ProcessVm;
use super::rlimit::ResourceLimits;
diff --git a/services/libs/jinux-std/src/process/process/mod.rs b/services/libs/jinux-std/src/process/process/mod.rs
--- a/services/libs/jinux-std/src/process/process/mod.rs
+++ b/services/libs/jinux-std/src/process/process/mod.rs
@@ -1,7 +1,4 @@
-mod builder;
-
use super::posix_thread::PosixThreadExt;
-use super::process_group::ProcessGroup;
use super::process_vm::user_heap::UserHeap;
use super::process_vm::ProcessVm;
use super::rlimit::ResourceLimits;
diff --git a/services/libs/jinux-std/src/process/process/mod.rs b/services/libs/jinux-std/src/process/process/mod.rs
--- a/services/libs/jinux-std/src/process/process/mod.rs
+++ b/services/libs/jinux-std/src/process/process/mod.rs
@@ -13,7 +10,7 @@ use super::signal::signals::Signal;
use super::signal::{Pauser, SigEvents, SigEventsFilter};
use super::status::ProcessStatus;
use super::{process_table, TermStatus};
-use crate::device::tty::get_n_tty;
+use crate::device::tty::open_ntty_as_controlling_terminal;
use crate::events::Observer;
use crate::fs::file_table::FileTable;
use crate::fs::fs_resolver::FsResolver;
diff --git a/services/libs/jinux-std/src/process/process/mod.rs b/services/libs/jinux-std/src/process/process/mod.rs
--- a/services/libs/jinux-std/src/process/process/mod.rs
+++ b/services/libs/jinux-std/src/process/process/mod.rs
@@ -13,7 +10,7 @@ use super::signal::signals::Signal;
use super::signal::{Pauser, SigEvents, SigEventsFilter};
use super::status::ProcessStatus;
use super::{process_table, TermStatus};
-use crate::device::tty::get_n_tty;
+use crate::device::tty::open_ntty_as_controlling_terminal;
use crate::events::Observer;
use crate::fs::file_table::FileTable;
use crate::fs::fs_resolver::FsResolver;
diff --git a/services/libs/jinux-std/src/process/process/mod.rs b/services/libs/jinux-std/src/process/process/mod.rs
--- a/services/libs/jinux-std/src/process/process/mod.rs
+++ b/services/libs/jinux-std/src/process/process/mod.rs
@@ -23,10 +20,25 @@ use crate::thread::{allocate_tid, Thread};
use crate::vm::vmar::Vmar;
use jinux_rights::Full;
+mod builder;
+mod job_control;
+mod process_group;
+mod session;
+mod terminal;
+
pub use builder::ProcessBuilder;
+pub use job_control::JobControl;
+pub use process_group::ProcessGroup;
+pub use session::Session;
+pub use terminal::Terminal;
+/// Process id.
pub type Pid = u32;
+/// Process group id.
pub type Pgid = u32;
+/// Session Id.
+pub type Sid = u32;
+
pub type ExitCode = i32;
/// Process stands for a set of threads that shares the same userspace.
diff --git a/services/libs/jinux-std/src/process/process/mod.rs b/services/libs/jinux-std/src/process/process/mod.rs
--- a/services/libs/jinux-std/src/process/process/mod.rs
+++ b/services/libs/jinux-std/src/process/process/mod.rs
@@ -23,10 +20,25 @@ use crate::thread::{allocate_tid, Thread};
use crate::vm::vmar::Vmar;
use jinux_rights::Full;
+mod builder;
+mod job_control;
+mod process_group;
+mod session;
+mod terminal;
+
pub use builder::ProcessBuilder;
+pub use job_control::JobControl;
+pub use process_group::ProcessGroup;
+pub use session::Session;
+pub use terminal::Terminal;
+/// Process id.
pub type Pid = u32;
+/// Process group id.
pub type Pgid = u32;
+/// Session Id.
+pub type Sid = u32;
+
pub type ExitCode = i32;
/// Process stands for a set of threads that shares the same userspace.
diff --git a/services/libs/jinux-std/src/process/process/mod.rs b/services/libs/jinux-std/src/process/process/mod.rs
--- a/services/libs/jinux-std/src/process/process/mod.rs
+++ b/services/libs/jinux-std/src/process/process/mod.rs
@@ -46,11 +58,11 @@ pub struct Process {
/// Process status
status: Mutex<ProcessStatus>,
/// Parent process
- parent: Mutex<Weak<Process>>,
+ pub(super) parent: Mutex<Weak<Process>>,
/// Children processes
children: Mutex<BTreeMap<Pid, Arc<Process>>>,
/// Process group
- process_group: Mutex<Weak<ProcessGroup>>,
+ pub(super) process_group: Mutex<Weak<ProcessGroup>>,
/// File table
file_table: Arc<Mutex<FileTable>>,
/// FsResolver
diff --git a/services/libs/jinux-std/src/process/process/mod.rs b/services/libs/jinux-std/src/process/process/mod.rs
--- a/services/libs/jinux-std/src/process/process/mod.rs
+++ b/services/libs/jinux-std/src/process/process/mod.rs
@@ -46,11 +58,11 @@ pub struct Process {
/// Process status
status: Mutex<ProcessStatus>,
/// Parent process
- parent: Mutex<Weak<Process>>,
+ pub(super) parent: Mutex<Weak<Process>>,
/// Children processes
children: Mutex<BTreeMap<Pid, Arc<Process>>>,
/// Process group
- process_group: Mutex<Weak<ProcessGroup>>,
+ pub(super) process_group: Mutex<Weak<ProcessGroup>>,
/// File table
file_table: Arc<Mutex<FileTable>>,
/// FsResolver
diff --git a/services/libs/jinux-std/src/process/process/mod.rs b/services/libs/jinux-std/src/process/process/mod.rs
--- a/services/libs/jinux-std/src/process/process/mod.rs
+++ b/services/libs/jinux-std/src/process/process/mod.rs
@@ -75,7 +87,6 @@ impl Process {
threads: Vec<Arc<Thread>>,
executable_path: String,
process_vm: ProcessVm,
- process_group: Weak<ProcessGroup>,
file_table: Arc<Mutex<FileTable>>,
fs: Arc<RwLock<FsResolver>>,
umask: Arc<RwLock<FileCreationMask>>,
diff --git a/services/libs/jinux-std/src/process/process/mod.rs b/services/libs/jinux-std/src/process/process/mod.rs
--- a/services/libs/jinux-std/src/process/process/mod.rs
+++ b/services/libs/jinux-std/src/process/process/mod.rs
@@ -75,7 +87,6 @@ impl Process {
threads: Vec<Arc<Thread>>,
executable_path: String,
process_vm: ProcessVm,
- process_group: Weak<ProcessGroup>,
file_table: Arc<Mutex<FileTable>>,
fs: Arc<RwLock<FsResolver>>,
umask: Arc<RwLock<FileCreationMask>>,
diff --git a/services/libs/jinux-std/src/process/process/mod.rs b/services/libs/jinux-std/src/process/process/mod.rs
--- a/services/libs/jinux-std/src/process/process/mod.rs
+++ b/services/libs/jinux-std/src/process/process/mod.rs
@@ -99,7 +110,7 @@ impl Process {
status: Mutex::new(ProcessStatus::Uninit),
parent: Mutex::new(parent),
children: Mutex::new(BTreeMap::new()),
- process_group: Mutex::new(process_group),
+ process_group: Mutex::new(Weak::new()),
file_table,
fs,
umask,
diff --git a/services/libs/jinux-std/src/process/process/mod.rs b/services/libs/jinux-std/src/process/process/mod.rs
--- a/services/libs/jinux-std/src/process/process/mod.rs
+++ b/services/libs/jinux-std/src/process/process/mod.rs
@@ -99,7 +110,7 @@ impl Process {
status: Mutex::new(ProcessStatus::Uninit),
parent: Mutex::new(parent),
children: Mutex::new(BTreeMap::new()),
- process_group: Mutex::new(process_group),
+ process_group: Mutex::new(Weak::new()),
file_table,
fs,
umask,
diff --git a/services/libs/jinux-std/src/process/process/mod.rs b/services/libs/jinux-std/src/process/process/mod.rs
--- a/services/libs/jinux-std/src/process/process/mod.rs
+++ b/services/libs/jinux-std/src/process/process/mod.rs
@@ -118,11 +129,9 @@ impl Process {
// spawn user process should give an absolute path
debug_assert!(executable_path.starts_with('/'));
let process = Process::create_user_process(executable_path, argv, envp)?;
- // FIXME: How to determine the fg process group?
- let process_group = Weak::clone(&process.process_group.lock());
- // FIXME: tty should be a parameter?
- let tty = get_n_tty();
- tty.set_fg(process_group);
+
+ open_ntty_as_controlling_terminal(&process)?;
+
process.run();
Ok(process)
}
diff --git a/services/libs/jinux-std/src/process/process/mod.rs b/services/libs/jinux-std/src/process/process/mod.rs
--- a/services/libs/jinux-std/src/process/process/mod.rs
+++ b/services/libs/jinux-std/src/process/process/mod.rs
@@ -118,11 +129,9 @@ impl Process {
// spawn user process should give an absolute path
debug_assert!(executable_path.starts_with('/'));
let process = Process::create_user_process(executable_path, argv, envp)?;
- // FIXME: How to determine the fg process group?
- let process_group = Weak::clone(&process.process_group.lock());
- // FIXME: tty should be a parameter?
- let tty = get_n_tty();
- tty.set_fg(process_group);
+
+ open_ntty_as_controlling_terminal(&process)?;
+
process.run();
Ok(process)
}
diff --git a/services/libs/jinux-std/src/process/process/mod.rs b/services/libs/jinux-std/src/process/process/mod.rs
--- a/services/libs/jinux-std/src/process/process/mod.rs
+++ b/services/libs/jinux-std/src/process/process/mod.rs
@@ -141,7 +150,25 @@ impl Process {
};
let process = process_builder.build()?;
- process_table::add_process(process.clone());
+
+ // Lock order: session table -> group table -> process table -> group of process
+ // -> group inner -> session inner
+ let mut session_table_mut = process_table::session_table_mut();
+ let mut group_table_mut = process_table::group_table_mut();
+ let mut process_table_mut = process_table::process_table_mut();
+
+ // Creates new group
+ let group = ProcessGroup::new(process.clone());
+ *process.process_group.lock() = Arc::downgrade(&group);
+ group_table_mut.insert(group.pgid(), group.clone());
+
+ // Creates new session
+ let session = Session::new(group.clone());
+ group.inner.lock().session = Arc::downgrade(&session);
+ session.inner.lock().leader = Some(process.clone());
+ session_table_mut.insert(session.sid(), session);
+
+ process_table_mut.insert(process.pid(), process.clone());
Ok(process)
}
diff --git a/services/libs/jinux-std/src/process/process/mod.rs b/services/libs/jinux-std/src/process/process/mod.rs
--- a/services/libs/jinux-std/src/process/process/mod.rs
+++ b/services/libs/jinux-std/src/process/process/mod.rs
@@ -141,7 +150,25 @@ impl Process {
};
let process = process_builder.build()?;
- process_table::add_process(process.clone());
+
+ // Lock order: session table -> group table -> process table -> group of process
+ // -> group inner -> session inner
+ let mut session_table_mut = process_table::session_table_mut();
+ let mut group_table_mut = process_table::group_table_mut();
+ let mut process_table_mut = process_table::process_table_mut();
+
+ // Creates new group
+ let group = ProcessGroup::new(process.clone());
+ *process.process_group.lock() = Arc::downgrade(&group);
+ group_table_mut.insert(group.pgid(), group.clone());
+
+ // Creates new session
+ let session = Session::new(group.clone());
+ group.inner.lock().session = Arc::downgrade(&session);
+ session.inner.lock().leader = Some(process.clone());
+ session_table_mut.insert(session.sid(), session);
+
+ process_table_mut.insert(process.pid(), process.clone());
Ok(process)
}
diff --git a/services/libs/jinux-std/src/process/process/mod.rs b/services/libs/jinux-std/src/process/process/mod.rs
--- a/services/libs/jinux-std/src/process/process/mod.rs
+++ b/services/libs/jinux-std/src/process/process/mod.rs
@@ -180,30 +207,25 @@ impl Process {
}
// *********** Parent and child ***********
-
- pub fn add_child(&self, child: Arc<Process>) {
- let child_pid = child.pid();
- self.children.lock().insert(child_pid, child);
- }
-
- pub fn set_parent(&self, parent: Weak<Process>) {
- *self.parent.lock() = parent;
- }
-
pub fn parent(&self) -> Option<Arc<Process>> {
self.parent.lock().upgrade()
}
- pub fn children(&self) -> &Mutex<BTreeMap<Pid, Arc<Process>>> {
+ pub(super) fn children(&self) -> &Mutex<BTreeMap<Pid, Arc<Process>>> {
&self.children
}
+ pub fn has_child(&self, pid: &Pid) -> bool {
+ self.children.lock().contains_key(pid)
+ }
+
pub fn children_pauser(&self) -> &Arc<Pauser> {
&self.children_pauser
}
- // *********** Process group ***********
+ // *********** Process group & Session***********
+ /// Returns the process group id of the process.
pub fn pgid(&self) -> Pgid {
if let Some(process_group) = self.process_group.lock().upgrade() {
process_group.pgid()
diff --git a/services/libs/jinux-std/src/process/process/mod.rs b/services/libs/jinux-std/src/process/process/mod.rs
--- a/services/libs/jinux-std/src/process/process/mod.rs
+++ b/services/libs/jinux-std/src/process/process/mod.rs
@@ -180,30 +207,25 @@ impl Process {
}
// *********** Parent and child ***********
-
- pub fn add_child(&self, child: Arc<Process>) {
- let child_pid = child.pid();
- self.children.lock().insert(child_pid, child);
- }
-
- pub fn set_parent(&self, parent: Weak<Process>) {
- *self.parent.lock() = parent;
- }
-
pub fn parent(&self) -> Option<Arc<Process>> {
self.parent.lock().upgrade()
}
- pub fn children(&self) -> &Mutex<BTreeMap<Pid, Arc<Process>>> {
+ pub(super) fn children(&self) -> &Mutex<BTreeMap<Pid, Arc<Process>>> {
&self.children
}
+ pub fn has_child(&self, pid: &Pid) -> bool {
+ self.children.lock().contains_key(pid)
+ }
+
pub fn children_pauser(&self) -> &Arc<Pauser> {
&self.children_pauser
}
- // *********** Process group ***********
+ // *********** Process group & Session***********
+ /// Returns the process group id of the process.
pub fn pgid(&self) -> Pgid {
if let Some(process_group) = self.process_group.lock().upgrade() {
process_group.pgid()
diff --git a/services/libs/jinux-std/src/process/process/mod.rs b/services/libs/jinux-std/src/process/process/mod.rs
--- a/services/libs/jinux-std/src/process/process/mod.rs
+++ b/services/libs/jinux-std/src/process/process/mod.rs
@@ -212,17 +234,237 @@ impl Process {
}
}
- /// Set process group for current process. If old process group exists,
- /// remove current process from old process group.
- pub fn set_process_group(&self, process_group: Weak<ProcessGroup>) {
- if let Some(old_process_group) = self.process_group() {
- old_process_group.remove_process(self.pid());
+ /// Returns the process group which the process belongs to.
+ pub fn process_group(&self) -> Option<Arc<ProcessGroup>> {
+ self.process_group.lock().upgrade()
+ }
+
+ /// Returns whether `self` is the leader of process group.
+ fn is_group_leader(self: &Arc<Self>) -> bool {
+ let Some(process_group) = self.process_group() else {
+ return false;
+ };
+
+ let Some(leader) = process_group.leader() else {
+ return false;
+ };
+
+ Arc::ptr_eq(self, &leader)
+ }
+
+ /// Returns the session which the process belongs to.
+ pub fn session(&self) -> Option<Arc<Session>> {
+ let process_group = self.process_group()?;
+ process_group.session()
+ }
+
+ /// Returns whether the process is session leader.
+ pub fn is_session_leader(self: &Arc<Self>) -> bool {
+ let session = self.session().unwrap();
+
+ let Some(leading_process) = session.leader() else {
+ return false;
+ };
+
+ Arc::ptr_eq(self, &leading_process)
+ }
+
+ /// Moves the process to the new session.
+ ///
+ /// If the process is already session leader, this method does nothing.
+ ///
+ /// Otherwise, this method creates a new process group in a new session
+ /// and moves the process to the session, returning the new session.
+ ///
+ /// This method may return the following errors:
+ /// * `EPERM`, if the process is a process group leader, or some existing session
+ /// or process group has the same id as the process.
+ pub fn to_new_session(self: &Arc<Self>) -> Result<Arc<Session>> {
+ if self.is_session_leader() {
+ return Ok(self.session().unwrap());
+ }
+
+ if self.is_group_leader() {
+ return_errno_with_message!(
+ Errno::EPERM,
+ "process group leader cannot be moved to new session."
+ );
+ }
+
+ let session = self.session().unwrap();
+
+ // Lock order: session table -> group table -> group of process -> group inner -> session inner
+ let mut session_table_mut = process_table::session_table_mut();
+ let mut group_table_mut = process_table::group_table_mut();
+ let mut self_group_mut = self.process_group.lock();
+
+ if session_table_mut.contains_key(&self.pid) {
+ return_errno_with_message!(Errno::EPERM, "cannot create new session");
+ }
+
+ if group_table_mut.contains_key(&self.pid) {
+ return_errno_with_message!(Errno::EPERM, "cannot create process group");
+ }
+
+ // Removes the process from old group
+ if let Some(old_group) = self_group_mut.upgrade() {
+ let mut group_inner = old_group.inner.lock();
+ let mut session_inner = session.inner.lock();
+ group_inner.remove_process(&self.pid);
+ *self_group_mut = Weak::new();
+
+ if group_inner.is_empty() {
+ group_table_mut.remove(&old_group.pgid());
+ debug_assert!(session_inner.process_groups.contains_key(&old_group.pgid()));
+ session_inner.process_groups.remove(&old_group.pgid());
+
+ if session_inner.is_empty() {
+ session_table_mut.remove(&session.sid());
+ }
+ }
}
- *self.process_group.lock() = process_group;
+
+ // Creates a new process group
+ let new_group = ProcessGroup::new(self.clone());
+ *self_group_mut = Arc::downgrade(&new_group);
+ group_table_mut.insert(new_group.pgid(), new_group.clone());
+
+ // Creates a new session
+ let new_session = Session::new(new_group.clone());
+ let mut new_group_inner = new_group.inner.lock();
+ new_group_inner.session = Arc::downgrade(&new_session);
+ new_session.inner.lock().leader = Some(self.clone());
+ session_table_mut.insert(new_session.sid(), new_session.clone());
+
+ // Removes the process from session.
+ let mut session_inner = session.inner.lock();
+ session_inner.remove_process(self);
+
+ Ok(new_session)
+ }
+
+ /// Moves the process to other process group.
+ ///
+ /// * If the group already exists, the process and the group should belong to the same session.
+ /// * If the group does not exist, this method creates a new group for the process and move the
+ /// process to the group. The group is added to the session of the process.
+ ///
+ /// This method may return `EPERM` in following cases:
+ /// * The process is session leader;
+ /// * The group already exists, but the group does not belong to the same session as the process;
+ /// * The group does not exist, but `pgid` is not equal to `pid` of the process.
+ pub fn to_other_group(self: &Arc<Self>, pgid: Pgid) -> Result<()> {
+ // if the process already belongs to the process group
+ if self.pgid() == pgid {
+ return Ok(());
+ }
+
+ if self.is_session_leader() {
+ return_errno_with_message!(Errno::EPERM, "the process cannot be a session leader");
+ }
+
+ if let Some(process_group) = process_table::get_process_group(&pgid) {
+ let session = self.session().unwrap();
+ if !session.contains_process_group(&process_group) {
+ return_errno_with_message!(
+ Errno::EPERM,
+ "the group and process does not belong to same session"
+ );
+ }
+ self.to_specified_group(&process_group)?;
+ } else {
+ if pgid != self.pid() {
+ return_errno_with_message!(
+ Errno::EPERM,
+ "the new process group should have the same id as the process."
+ );
+ }
+
+ self.to_new_group()?;
+ }
+
+ Ok(())
+ }
+
+ /// Creates a new process group and moves the process to the group.
+ ///
+ /// The new group will be added to the same session as the process.
+ fn to_new_group(self: &Arc<Self>) -> Result<()> {
+ let session = self.session().unwrap();
+ // Lock order: group table -> group of process -> group inner -> session inner
+ let mut group_table_mut = process_table::group_table_mut();
+ let mut self_group_mut = self.process_group.lock();
+
+ // Removes the process from old group
+ if let Some(old_group) = self_group_mut.upgrade() {
+ let mut group_inner = old_group.inner.lock();
+ let mut session_inner = session.inner.lock();
+ group_inner.remove_process(&self.pid);
+ *self_group_mut = Weak::new();
+
+ if group_inner.is_empty() {
+ group_table_mut.remove(&old_group.pgid());
+ debug_assert!(session_inner.process_groups.contains_key(&old_group.pgid()));
+ // The old session won't be empty, since we will add a new group to the session.
+ session_inner.process_groups.remove(&old_group.pgid());
+ }
+ }
+
+ // Creates a new process group. Adds the new group to group table and session.
+ let new_group = ProcessGroup::new(self.clone());
+
+ let mut new_group_inner = new_group.inner.lock();
+ let mut session_inner = session.inner.lock();
+
+ *self_group_mut = Arc::downgrade(&new_group);
+
+ group_table_mut.insert(new_group.pgid(), new_group.clone());
+
+ new_group_inner.session = Arc::downgrade(&session);
+ session_inner
+ .process_groups
+ .insert(new_group.pgid(), new_group.clone());
+
+ Ok(())
}
- pub fn process_group(&self) -> Option<Arc<ProcessGroup>> {
- self.process_group.lock().upgrade()
+ /// Moves the process to a specified group.
+ ///
+ /// The caller needs to ensure that the process and the group belongs to the same session.
+ fn to_specified_group(self: &Arc<Process>, group: &Arc<ProcessGroup>) -> Result<()> {
+ // Lock order: group table -> group of process -> group inner (small pgid -> big pgid)
+ let mut group_table_mut = process_table::group_table_mut();
+ let mut self_group_mut = self.process_group.lock();
+
+ // Removes the process from old group
+ let mut group_inner = if let Some(old_group) = self_group_mut.upgrade() {
+ // Lock order: group with smaller pgid first
+ let (mut old_group_inner, group_inner) = match old_group.pgid().cmp(&group.pgid()) {
+ core::cmp::Ordering::Equal => return Ok(()),
+ core::cmp::Ordering::Less => (old_group.inner.lock(), group.inner.lock()),
+ core::cmp::Ordering::Greater => {
+ let group_inner = group.inner.lock();
+ let old_group_inner = old_group.inner.lock();
+ (old_group_inner, group_inner)
+ }
+ };
+ old_group_inner.remove_process(&self.pid);
+ *self_group_mut = Weak::new();
+
+ if old_group_inner.is_empty() {
+ group_table_mut.remove(&old_group.pgid());
+ }
+
+ group_inner
+ } else {
+ group.inner.lock()
+ };
+
+ // Adds the process to the specified group
+ group_inner.processes.insert(self.pid, self.clone());
+ *self_group_mut = Arc::downgrade(group);
+
+ Ok(())
}
// ************** Virtual Memory *************
diff --git a/services/libs/jinux-std/src/process/process/mod.rs b/services/libs/jinux-std/src/process/process/mod.rs
--- a/services/libs/jinux-std/src/process/process/mod.rs
+++ b/services/libs/jinux-std/src/process/process/mod.rs
@@ -212,17 +234,237 @@ impl Process {
}
}
- /// Set process group for current process. If old process group exists,
- /// remove current process from old process group.
- pub fn set_process_group(&self, process_group: Weak<ProcessGroup>) {
- if let Some(old_process_group) = self.process_group() {
- old_process_group.remove_process(self.pid());
+ /// Returns the process group which the process belongs to.
+ pub fn process_group(&self) -> Option<Arc<ProcessGroup>> {
+ self.process_group.lock().upgrade()
+ }
+
+ /// Returns whether `self` is the leader of process group.
+ fn is_group_leader(self: &Arc<Self>) -> bool {
+ let Some(process_group) = self.process_group() else {
+ return false;
+ };
+
+ let Some(leader) = process_group.leader() else {
+ return false;
+ };
+
+ Arc::ptr_eq(self, &leader)
+ }
+
+ /// Returns the session which the process belongs to.
+ pub fn session(&self) -> Option<Arc<Session>> {
+ let process_group = self.process_group()?;
+ process_group.session()
+ }
+
+ /// Returns whether the process is session leader.
+ pub fn is_session_leader(self: &Arc<Self>) -> bool {
+ let session = self.session().unwrap();
+
+ let Some(leading_process) = session.leader() else {
+ return false;
+ };
+
+ Arc::ptr_eq(self, &leading_process)
+ }
+
+ /// Moves the process to the new session.
+ ///
+ /// If the process is already session leader, this method does nothing.
+ ///
+ /// Otherwise, this method creates a new process group in a new session
+ /// and moves the process to the session, returning the new session.
+ ///
+ /// This method may return the following errors:
+ /// * `EPERM`, if the process is a process group leader, or some existing session
+ /// or process group has the same id as the process.
+ pub fn to_new_session(self: &Arc<Self>) -> Result<Arc<Session>> {
+ if self.is_session_leader() {
+ return Ok(self.session().unwrap());
+ }
+
+ if self.is_group_leader() {
+ return_errno_with_message!(
+ Errno::EPERM,
+ "process group leader cannot be moved to new session."
+ );
+ }
+
+ let session = self.session().unwrap();
+
+ // Lock order: session table -> group table -> group of process -> group inner -> session inner
+ let mut session_table_mut = process_table::session_table_mut();
+ let mut group_table_mut = process_table::group_table_mut();
+ let mut self_group_mut = self.process_group.lock();
+
+ if session_table_mut.contains_key(&self.pid) {
+ return_errno_with_message!(Errno::EPERM, "cannot create new session");
+ }
+
+ if group_table_mut.contains_key(&self.pid) {
+ return_errno_with_message!(Errno::EPERM, "cannot create process group");
+ }
+
+ // Removes the process from old group
+ if let Some(old_group) = self_group_mut.upgrade() {
+ let mut group_inner = old_group.inner.lock();
+ let mut session_inner = session.inner.lock();
+ group_inner.remove_process(&self.pid);
+ *self_group_mut = Weak::new();
+
+ if group_inner.is_empty() {
+ group_table_mut.remove(&old_group.pgid());
+ debug_assert!(session_inner.process_groups.contains_key(&old_group.pgid()));
+ session_inner.process_groups.remove(&old_group.pgid());
+
+ if session_inner.is_empty() {
+ session_table_mut.remove(&session.sid());
+ }
+ }
}
- *self.process_group.lock() = process_group;
+
+ // Creates a new process group
+ let new_group = ProcessGroup::new(self.clone());
+ *self_group_mut = Arc::downgrade(&new_group);
+ group_table_mut.insert(new_group.pgid(), new_group.clone());
+
+ // Creates a new session
+ let new_session = Session::new(new_group.clone());
+ let mut new_group_inner = new_group.inner.lock();
+ new_group_inner.session = Arc::downgrade(&new_session);
+ new_session.inner.lock().leader = Some(self.clone());
+ session_table_mut.insert(new_session.sid(), new_session.clone());
+
+ // Removes the process from session.
+ let mut session_inner = session.inner.lock();
+ session_inner.remove_process(self);
+
+ Ok(new_session)
+ }
+
+ /// Moves the process to other process group.
+ ///
+ /// * If the group already exists, the process and the group should belong to the same session.
+ /// * If the group does not exist, this method creates a new group for the process and move the
+ /// process to the group. The group is added to the session of the process.
+ ///
+ /// This method may return `EPERM` in following cases:
+ /// * The process is session leader;
+ /// * The group already exists, but the group does not belong to the same session as the process;
+ /// * The group does not exist, but `pgid` is not equal to `pid` of the process.
+ pub fn to_other_group(self: &Arc<Self>, pgid: Pgid) -> Result<()> {
+ // if the process already belongs to the process group
+ if self.pgid() == pgid {
+ return Ok(());
+ }
+
+ if self.is_session_leader() {
+ return_errno_with_message!(Errno::EPERM, "the process cannot be a session leader");
+ }
+
+ if let Some(process_group) = process_table::get_process_group(&pgid) {
+ let session = self.session().unwrap();
+ if !session.contains_process_group(&process_group) {
+ return_errno_with_message!(
+ Errno::EPERM,
+ "the group and process does not belong to same session"
+ );
+ }
+ self.to_specified_group(&process_group)?;
+ } else {
+ if pgid != self.pid() {
+ return_errno_with_message!(
+ Errno::EPERM,
+ "the new process group should have the same id as the process."
+ );
+ }
+
+ self.to_new_group()?;
+ }
+
+ Ok(())
+ }
+
+ /// Creates a new process group and moves the process to the group.
+ ///
+ /// The new group will be added to the same session as the process.
+ fn to_new_group(self: &Arc<Self>) -> Result<()> {
+ let session = self.session().unwrap();
+ // Lock order: group table -> group of process -> group inner -> session inner
+ let mut group_table_mut = process_table::group_table_mut();
+ let mut self_group_mut = self.process_group.lock();
+
+ // Removes the process from old group
+ if let Some(old_group) = self_group_mut.upgrade() {
+ let mut group_inner = old_group.inner.lock();
+ let mut session_inner = session.inner.lock();
+ group_inner.remove_process(&self.pid);
+ *self_group_mut = Weak::new();
+
+ if group_inner.is_empty() {
+ group_table_mut.remove(&old_group.pgid());
+ debug_assert!(session_inner.process_groups.contains_key(&old_group.pgid()));
+ // The old session won't be empty, since we will add a new group to the session.
+ session_inner.process_groups.remove(&old_group.pgid());
+ }
+ }
+
+ // Creates a new process group. Adds the new group to group table and session.
+ let new_group = ProcessGroup::new(self.clone());
+
+ let mut new_group_inner = new_group.inner.lock();
+ let mut session_inner = session.inner.lock();
+
+ *self_group_mut = Arc::downgrade(&new_group);
+
+ group_table_mut.insert(new_group.pgid(), new_group.clone());
+
+ new_group_inner.session = Arc::downgrade(&session);
+ session_inner
+ .process_groups
+ .insert(new_group.pgid(), new_group.clone());
+
+ Ok(())
}
- pub fn process_group(&self) -> Option<Arc<ProcessGroup>> {
- self.process_group.lock().upgrade()
+ /// Moves the process to a specified group.
+ ///
+ /// The caller needs to ensure that the process and the group belongs to the same session.
+ fn to_specified_group(self: &Arc<Process>, group: &Arc<ProcessGroup>) -> Result<()> {
+ // Lock order: group table -> group of process -> group inner (small pgid -> big pgid)
+ let mut group_table_mut = process_table::group_table_mut();
+ let mut self_group_mut = self.process_group.lock();
+
+ // Removes the process from old group
+ let mut group_inner = if let Some(old_group) = self_group_mut.upgrade() {
+ // Lock order: group with smaller pgid first
+ let (mut old_group_inner, group_inner) = match old_group.pgid().cmp(&group.pgid()) {
+ core::cmp::Ordering::Equal => return Ok(()),
+ core::cmp::Ordering::Less => (old_group.inner.lock(), group.inner.lock()),
+ core::cmp::Ordering::Greater => {
+ let group_inner = group.inner.lock();
+ let old_group_inner = old_group.inner.lock();
+ (old_group_inner, group_inner)
+ }
+ };
+ old_group_inner.remove_process(&self.pid);
+ *self_group_mut = Weak::new();
+
+ if old_group_inner.is_empty() {
+ group_table_mut.remove(&old_group.pgid());
+ }
+
+ group_inner
+ } else {
+ group.inner.lock()
+ };
+
+ // Adds the process to the specified group
+ group_inner.processes.insert(self.pid, self.clone());
+ *self_group_mut = Arc::downgrade(group);
+
+ Ok(())
}
// ************** Virtual Memory *************
diff --git a/services/libs/jinux-std/src/process/process/mod.rs b/services/libs/jinux-std/src/process/process/mod.rs
--- a/services/libs/jinux-std/src/process/process/mod.rs
+++ b/services/libs/jinux-std/src/process/process/mod.rs
@@ -319,3 +561,100 @@ pub fn current() -> Arc<Process> {
panic!("[Internal error]The current thread does not belong to a process");
}
}
+
+#[if_cfg_ktest]
+mod test {
+ use super::*;
+
+ fn new_process(parent: Option<Arc<Process>>) -> Arc<Process> {
+ crate::fs::rootfs::init_root_mount();
+ let pid = allocate_tid();
+ let parent = if let Some(parent) = parent {
+ Arc::downgrade(&parent)
+ } else {
+ Weak::new()
+ };
+ Arc::new(Process::new(
+ pid,
+ parent,
+ vec![],
+ String::new(),
+ ProcessVm::alloc(),
+ Arc::new(Mutex::new(FileTable::new())),
+ Arc::new(RwLock::new(FsResolver::new())),
+ Arc::new(RwLock::new(FileCreationMask::default())),
+ Arc::new(Mutex::new(SigDispositions::default())),
+ ResourceLimits::default(),
+ ))
+ }
+
+ fn new_process_in_session(parent: Option<Arc<Process>>) -> Arc<Process> {
+ // Lock order: session table -> group table -> group of process -> group inner
+ // -> session inner
+ let mut session_table_mut = process_table::session_table_mut();
+ let mut group_table_mut = process_table::group_table_mut();
+
+ let process = new_process(parent);
+ // Creates new group
+ let group = ProcessGroup::new(process.clone());
+ *process.process_group.lock() = Arc::downgrade(&group);
+
+ // Creates new session
+ let sess = Session::new(group.clone());
+ group.inner.lock().session = Arc::downgrade(&sess);
+ sess.inner.lock().leader = Some(process.clone());
+
+ group_table_mut.insert(group.pgid(), group);
+ session_table_mut.insert(sess.sid(), sess);
+
+ process
+ }
+
+ fn remove_session_and_group(process: Arc<Process>) {
+ // Lock order: session table -> group table
+ let mut session_table_mut = process_table::session_table_mut();
+ let mut group_table_mut = process_table::group_table_mut();
+ if let Some(sess) = process.session() {
+ session_table_mut.remove(&sess.sid());
+ }
+
+ if let Some(group) = process.process_group() {
+ group_table_mut.remove(&group.pgid());
+ }
+ }
+
+ #[ktest]
+ fn init_process() {
+ let process = new_process(None);
+ assert!(process.process_group().is_none());
+ assert!(process.session().is_none());
+ }
+
+ #[ktest]
+ fn init_process_in_session() {
+ let process = new_process_in_session(None);
+ assert!(process.is_group_leader());
+ assert!(process.is_session_leader());
+ remove_session_and_group(process);
+ }
+
+ #[ktest]
+ fn to_new_session() {
+ let process = new_process_in_session(None);
+ let sess = process.session().unwrap();
+ sess.inner.lock().leader = None;
+
+ assert!(!process.is_session_leader());
+ assert!(process
+ .to_new_session()
+ .is_err_and(|e| e.error() == Errno::EPERM));
+
+ let group = process.process_group().unwrap();
+ group.inner.lock().leader = None;
+ assert!(!process.is_group_leader());
+
+ assert!(process
+ .to_new_session()
+ .is_err_and(|e| e.error() == Errno::EPERM));
+ }
+}
diff --git /dev/null b/services/libs/jinux-std/src/process/process/process_group.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/process/process/process_group.rs
@@ -0,0 +1,84 @@
+use super::{Pgid, Pid, Process, Session};
+use crate::prelude::*;
+use crate::process::signal::signals::Signal;
+
+/// `ProcessGroup` represents a set of processes. Each `ProcessGroup` has a unique
+/// identifier `pgid`.
+pub struct ProcessGroup {
+ pgid: Pgid,
+ pub(in crate::process) inner: Mutex<Inner>,
+}
+
+pub(in crate::process) struct Inner {
+ pub(in crate::process) processes: BTreeMap<Pid, Arc<Process>>,
+ pub(in crate::process) leader: Option<Arc<Process>>,
+ pub(in crate::process) session: Weak<Session>,
+}
+
+impl Inner {
+ pub(in crate::process) fn remove_process(&mut self, pid: &Pid) {
+ let Some(process) = self.processes.remove(pid) else {
+ return;
+ };
+
+ if let Some(leader) = &self.leader && Arc::ptr_eq(leader, &process) {
+ self.leader = None;
+ }
+ }
+
+ pub(in crate::process) fn is_empty(&self) -> bool {
+ self.processes.is_empty()
+ }
+}
+
+impl ProcessGroup {
+ /// Creates a new process group with one process. The pgid is the same as the process
+ /// id. The process will become the leading process of the new process group.
+ ///
+ /// The caller needs to ensure that the process does not belong to any group.
+ pub(in crate::process) fn new(process: Arc<Process>) -> Arc<Self> {
+ let pid = process.pid();
+
+ let inner = {
+ let mut processes = BTreeMap::new();
+ processes.insert(pid, process.clone());
+ Inner {
+ processes,
+ leader: Some(process.clone()),
+ session: Weak::new(),
+ }
+ };
+
+ Arc::new(ProcessGroup {
+ pgid: pid,
+ inner: Mutex::new(inner),
+ })
+ }
+
+ /// Returns whether self contains a process with `pid`.
+ pub(in crate::process) fn contains_process(&self, pid: Pid) -> bool {
+ self.inner.lock().processes.contains_key(&pid)
+ }
+
+ /// Returns the process group identifier
+ pub fn pgid(&self) -> Pgid {
+ self.pgid
+ }
+
+ /// Broadcasts signal to all processes in the group.
+ pub fn broadcast_signal(&self, signal: impl Signal + Clone + 'static) {
+ for process in self.inner.lock().processes.values() {
+ process.enqueue_signal(Box::new(signal.clone()));
+ }
+ }
+
+ /// Returns the leader process.
+ pub fn leader(&self) -> Option<Arc<Process>> {
+ self.inner.lock().leader.clone()
+ }
+
+ /// Returns the session which the group belongs to
+ pub fn session(&self) -> Option<Arc<Session>> {
+ self.inner.lock().session.upgrade()
+ }
+}
diff --git /dev/null b/services/libs/jinux-std/src/process/process/process_group.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/process/process/process_group.rs
@@ -0,0 +1,84 @@
+use super::{Pgid, Pid, Process, Session};
+use crate::prelude::*;
+use crate::process::signal::signals::Signal;
+
+/// `ProcessGroup` represents a set of processes. Each `ProcessGroup` has a unique
+/// identifier `pgid`.
+pub struct ProcessGroup {
+ pgid: Pgid,
+ pub(in crate::process) inner: Mutex<Inner>,
+}
+
+pub(in crate::process) struct Inner {
+ pub(in crate::process) processes: BTreeMap<Pid, Arc<Process>>,
+ pub(in crate::process) leader: Option<Arc<Process>>,
+ pub(in crate::process) session: Weak<Session>,
+}
+
+impl Inner {
+ pub(in crate::process) fn remove_process(&mut self, pid: &Pid) {
+ let Some(process) = self.processes.remove(pid) else {
+ return;
+ };
+
+ if let Some(leader) = &self.leader && Arc::ptr_eq(leader, &process) {
+ self.leader = None;
+ }
+ }
+
+ pub(in crate::process) fn is_empty(&self) -> bool {
+ self.processes.is_empty()
+ }
+}
+
+impl ProcessGroup {
+ /// Creates a new process group with one process. The pgid is the same as the process
+ /// id. The process will become the leading process of the new process group.
+ ///
+ /// The caller needs to ensure that the process does not belong to any group.
+ pub(in crate::process) fn new(process: Arc<Process>) -> Arc<Self> {
+ let pid = process.pid();
+
+ let inner = {
+ let mut processes = BTreeMap::new();
+ processes.insert(pid, process.clone());
+ Inner {
+ processes,
+ leader: Some(process.clone()),
+ session: Weak::new(),
+ }
+ };
+
+ Arc::new(ProcessGroup {
+ pgid: pid,
+ inner: Mutex::new(inner),
+ })
+ }
+
+ /// Returns whether self contains a process with `pid`.
+ pub(in crate::process) fn contains_process(&self, pid: Pid) -> bool {
+ self.inner.lock().processes.contains_key(&pid)
+ }
+
+ /// Returns the process group identifier
+ pub fn pgid(&self) -> Pgid {
+ self.pgid
+ }
+
+ /// Broadcasts signal to all processes in the group.
+ pub fn broadcast_signal(&self, signal: impl Signal + Clone + 'static) {
+ for process in self.inner.lock().processes.values() {
+ process.enqueue_signal(Box::new(signal.clone()));
+ }
+ }
+
+ /// Returns the leader process.
+ pub fn leader(&self) -> Option<Arc<Process>> {
+ self.inner.lock().leader.clone()
+ }
+
+ /// Returns the session which the group belongs to
+ pub fn session(&self) -> Option<Arc<Session>> {
+ self.inner.lock().session.upgrade()
+ }
+}
diff --git /dev/null b/services/libs/jinux-std/src/process/process/session.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/process/process/session.rs
@@ -0,0 +1,133 @@
+use crate::prelude::*;
+
+use super::{Pgid, Process, ProcessGroup, Sid, Terminal};
+
+/// A `Session` is a collection of related process groups. Each session has a
+/// unique identifier `sid`. Process groups and sessions form a two-level
+/// hierarchical relationship between processes.
+///
+/// **Leader**: A *session leader* is the process that creates a new session and whose process
+/// ID becomes the session ID.
+///
+/// **Controlling terminal**: The terminal can be used to manage all processes in the session. The
+/// controlling terminal is established when the session leader first opens a terminal.
+pub struct Session {
+ sid: Sid,
+ pub(in crate::process) inner: Mutex<Inner>,
+}
+
+pub(in crate::process) struct Inner {
+ pub(in crate::process) process_groups: BTreeMap<Pgid, Arc<ProcessGroup>>,
+ pub(in crate::process) leader: Option<Arc<Process>>,
+ pub(in crate::process) terminal: Option<Arc<dyn Terminal>>,
+}
+
+impl Inner {
+ pub(in crate::process) fn is_empty(&self) -> bool {
+ self.process_groups.is_empty()
+ }
+
+ pub(in crate::process) fn remove_process(&mut self, process: &Arc<Process>) {
+ if let Some(leader) = &self.leader && Arc::ptr_eq(leader, process) {
+ self.leader = None;
+ }
+ }
+
+ pub(in crate::process) fn remove_process_group(&mut self, pgid: &Pgid) {
+ self.process_groups.remove(pgid);
+ }
+}
+
+impl Session {
+ /// Creates a new session for the process group. The process group becomes the member of
+ /// the new session.
+ ///
+ /// The caller needs to ensure that the group does not belong to any session, and the caller
+ /// should set the leader process after creating the session.
+ pub(in crate::process) fn new(group: Arc<ProcessGroup>) -> Arc<Self> {
+ let sid = group.pgid();
+ let inner = {
+ let mut process_groups = BTreeMap::new();
+ process_groups.insert(group.pgid(), group);
+
+ Inner {
+ process_groups,
+ leader: None,
+ terminal: None,
+ }
+ };
+ Arc::new(Self {
+ sid,
+ inner: Mutex::new(inner),
+ })
+ }
+
+ /// Returns the session id
+ pub fn sid(&self) -> Sid {
+ self.sid
+ }
+
+ /// Returns the leader process.
+ pub fn leader(&self) -> Option<Arc<Process>> {
+ self.inner.lock().leader.clone()
+ }
+
+ /// Returns whether `self` contains the `process_group`
+ pub(in crate::process) fn contains_process_group(
+ self: &Arc<Self>,
+ process_group: &Arc<ProcessGroup>,
+ ) -> bool {
+ self.inner
+ .lock()
+ .process_groups
+ .contains_key(&process_group.pgid())
+ }
+
+ /// Sets terminal as the controlling terminal of the session. The `get_terminal` method
+ /// should set the session for the terminal and returns the session.
+ ///
+ /// If the session already has controlling terminal, this method will return `Err(EPERM)`.
+ pub fn set_terminal<F>(&self, get_terminal: F) -> Result<()>
+ where
+ F: Fn() -> Result<Arc<dyn Terminal>>,
+ {
+ let mut inner = self.inner.lock();
+
+ if inner.terminal.is_some() {
+ return_errno_with_message!(
+ Errno::EPERM,
+ "current session already has controlling terminal"
+ );
+ }
+
+ let terminal = get_terminal()?;
+ inner.terminal = Some(terminal);
+ Ok(())
+ }
+
+ /// Releases the controlling terminal of the session.
+ ///
+ /// If the session does not have controlling terminal, this method will return `ENOTTY`.
+ pub fn release_terminal<F>(&self, release_session: F) -> Result<()>
+ where
+ F: Fn(&Arc<dyn Terminal>) -> Result<()>,
+ {
+ let mut inner = self.inner.lock();
+ if inner.terminal.is_none() {
+ return_errno_with_message!(
+ Errno::ENOTTY,
+ "current session does not has controlling terminal"
+ );
+ }
+
+ let terminal = inner.terminal.as_ref().unwrap();
+ release_session(terminal)?;
+ inner.terminal = None;
+ Ok(())
+ }
+
+ /// Returns the controlling terminal of `self`.
+ pub fn terminal(&self) -> Option<Arc<dyn Terminal>> {
+ self.inner.lock().terminal.clone()
+ }
+}
diff --git /dev/null b/services/libs/jinux-std/src/process/process/session.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/process/process/session.rs
@@ -0,0 +1,133 @@
+use crate::prelude::*;
+
+use super::{Pgid, Process, ProcessGroup, Sid, Terminal};
+
+/// A `Session` is a collection of related process groups. Each session has a
+/// unique identifier `sid`. Process groups and sessions form a two-level
+/// hierarchical relationship between processes.
+///
+/// **Leader**: A *session leader* is the process that creates a new session and whose process
+/// ID becomes the session ID.
+///
+/// **Controlling terminal**: The terminal can be used to manage all processes in the session. The
+/// controlling terminal is established when the session leader first opens a terminal.
+pub struct Session {
+ sid: Sid,
+ pub(in crate::process) inner: Mutex<Inner>,
+}
+
+pub(in crate::process) struct Inner {
+ pub(in crate::process) process_groups: BTreeMap<Pgid, Arc<ProcessGroup>>,
+ pub(in crate::process) leader: Option<Arc<Process>>,
+ pub(in crate::process) terminal: Option<Arc<dyn Terminal>>,
+}
+
+impl Inner {
+ pub(in crate::process) fn is_empty(&self) -> bool {
+ self.process_groups.is_empty()
+ }
+
+ pub(in crate::process) fn remove_process(&mut self, process: &Arc<Process>) {
+ if let Some(leader) = &self.leader && Arc::ptr_eq(leader, process) {
+ self.leader = None;
+ }
+ }
+
+ pub(in crate::process) fn remove_process_group(&mut self, pgid: &Pgid) {
+ self.process_groups.remove(pgid);
+ }
+}
+
+impl Session {
+ /// Creates a new session for the process group. The process group becomes the member of
+ /// the new session.
+ ///
+ /// The caller needs to ensure that the group does not belong to any session, and the caller
+ /// should set the leader process after creating the session.
+ pub(in crate::process) fn new(group: Arc<ProcessGroup>) -> Arc<Self> {
+ let sid = group.pgid();
+ let inner = {
+ let mut process_groups = BTreeMap::new();
+ process_groups.insert(group.pgid(), group);
+
+ Inner {
+ process_groups,
+ leader: None,
+ terminal: None,
+ }
+ };
+ Arc::new(Self {
+ sid,
+ inner: Mutex::new(inner),
+ })
+ }
+
+ /// Returns the session id
+ pub fn sid(&self) -> Sid {
+ self.sid
+ }
+
+ /// Returns the leader process.
+ pub fn leader(&self) -> Option<Arc<Process>> {
+ self.inner.lock().leader.clone()
+ }
+
+ /// Returns whether `self` contains the `process_group`
+ pub(in crate::process) fn contains_process_group(
+ self: &Arc<Self>,
+ process_group: &Arc<ProcessGroup>,
+ ) -> bool {
+ self.inner
+ .lock()
+ .process_groups
+ .contains_key(&process_group.pgid())
+ }
+
+ /// Sets terminal as the controlling terminal of the session. The `get_terminal` method
+ /// should set the session for the terminal and returns the session.
+ ///
+ /// If the session already has controlling terminal, this method will return `Err(EPERM)`.
+ pub fn set_terminal<F>(&self, get_terminal: F) -> Result<()>
+ where
+ F: Fn() -> Result<Arc<dyn Terminal>>,
+ {
+ let mut inner = self.inner.lock();
+
+ if inner.terminal.is_some() {
+ return_errno_with_message!(
+ Errno::EPERM,
+ "current session already has controlling terminal"
+ );
+ }
+
+ let terminal = get_terminal()?;
+ inner.terminal = Some(terminal);
+ Ok(())
+ }
+
+ /// Releases the controlling terminal of the session.
+ ///
+ /// If the session does not have controlling terminal, this method will return `ENOTTY`.
+ pub fn release_terminal<F>(&self, release_session: F) -> Result<()>
+ where
+ F: Fn(&Arc<dyn Terminal>) -> Result<()>,
+ {
+ let mut inner = self.inner.lock();
+ if inner.terminal.is_none() {
+ return_errno_with_message!(
+ Errno::ENOTTY,
+ "current session does not has controlling terminal"
+ );
+ }
+
+ let terminal = inner.terminal.as_ref().unwrap();
+ release_session(terminal)?;
+ inner.terminal = None;
+ Ok(())
+ }
+
+ /// Returns the controlling terminal of `self`.
+ pub fn terminal(&self) -> Option<Arc<dyn Terminal>> {
+ self.inner.lock().terminal.clone()
+ }
+}
diff --git /dev/null b/services/libs/jinux-std/src/process/process/terminal.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/process/process/terminal.rs
@@ -0,0 +1,104 @@
+use crate::fs::inode_handle::FileIo;
+use crate::prelude::*;
+use crate::process::{process_table, Pgid, ProcessGroup};
+
+use super::JobControl;
+
+/// A termial is used to interact with system. A terminal can support the shell
+/// job control.
+///
+/// We currently support two kinds of terminal, the tty and pty.
+pub trait Terminal: Send + Sync + FileIo {
+ // *************** Foreground ***************
+
+ /// Returns the foreground process group
+ fn foreground(&self) -> Option<Arc<ProcessGroup>> {
+ self.job_control().foreground()
+ }
+
+ /// Sets the foreground process group of this terminal.
+ ///
+ /// If the terminal is not controlling terminal, this method returns `ENOTTY`.
+ ///
+ /// # Panic
+ ///
+ /// This method should be called in process context.
+ fn set_foreground(&self, pgid: &Pgid) -> Result<()> {
+ if !self.is_controlling_terminal() {
+ return_errno_with_message!(Errno::ENOTTY, "self is not controlling terminal");
+ }
+
+ let foreground = process_table::get_process_group(pgid);
+
+ self.job_control().set_foreground(foreground.as_ref())
+ }
+
+ // *************** Session and controlling terminal ***************
+
+ /// Returns whether the terminal is the controlling terminal of current process.
+ ///
+ /// # Panic
+ ///
+ /// This method should be called in process context.
+ fn is_controlling_terminal(&self) -> bool {
+ let session = current!().session().unwrap();
+ let Some(terminal) = session.terminal() else {
+ return false;
+ };
+
+ let arc_self = self.arc_self();
+ Arc::ptr_eq(&terminal, &arc_self)
+ }
+
+ /// Sets the terminal as the controlling terminal of the session of current process.
+ ///
+ /// If self is not session leader, or the terminal is controlling terminal of other session,
+ /// or the session already has controlling terminal, this method returns `EPERM`.
+ ///
+ /// # Panic
+ ///
+ /// This method should only be called in process context.
+ fn set_current_session(&self) -> Result<()> {
+ if !current!().is_session_leader() {
+ return_errno_with_message!(Errno::EPERM, "current process is not session leader");
+ }
+
+ let get_terminal = || {
+ self.job_control().set_current_session()?;
+ Ok(self.arc_self())
+ };
+
+ let session = current!().session().unwrap();
+ session.set_terminal(get_terminal)
+ }
+
+ /// Releases the terminal from the session of current process if the terminal is the controlling
+ /// terminal of the session.
+ ///
+ /// If the terminal is not the controlling terminal of the session, this method will return `ENOTTY`.
+ ///
+ /// # Panic
+ ///
+ /// This method should only be called in process context.
+ fn release_current_session(&self) -> Result<()> {
+ if !self.is_controlling_terminal() {
+ return_errno_with_message!(Errno::ENOTTY, "release wrong tty");
+ }
+
+ let current = current!();
+ if !current.is_session_leader() {
+ warn!("TODO: release tty for process that is not session leader");
+ return Ok(());
+ }
+
+ let release_session = |_: &Arc<dyn Terminal>| self.job_control().release_current_session();
+
+ let session = current.session().unwrap();
+ session.release_terminal(release_session)
+ }
+
+ /// Returns the job control of the terminal.
+ fn job_control(&self) -> &JobControl;
+
+ fn arc_self(&self) -> Arc<dyn Terminal>;
+}
diff --git /dev/null b/services/libs/jinux-std/src/process/process/terminal.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/process/process/terminal.rs
@@ -0,0 +1,104 @@
+use crate::fs::inode_handle::FileIo;
+use crate::prelude::*;
+use crate::process::{process_table, Pgid, ProcessGroup};
+
+use super::JobControl;
+
+/// A termial is used to interact with system. A terminal can support the shell
+/// job control.
+///
+/// We currently support two kinds of terminal, the tty and pty.
+pub trait Terminal: Send + Sync + FileIo {
+ // *************** Foreground ***************
+
+ /// Returns the foreground process group
+ fn foreground(&self) -> Option<Arc<ProcessGroup>> {
+ self.job_control().foreground()
+ }
+
+ /// Sets the foreground process group of this terminal.
+ ///
+ /// If the terminal is not controlling terminal, this method returns `ENOTTY`.
+ ///
+ /// # Panic
+ ///
+ /// This method should be called in process context.
+ fn set_foreground(&self, pgid: &Pgid) -> Result<()> {
+ if !self.is_controlling_terminal() {
+ return_errno_with_message!(Errno::ENOTTY, "self is not controlling terminal");
+ }
+
+ let foreground = process_table::get_process_group(pgid);
+
+ self.job_control().set_foreground(foreground.as_ref())
+ }
+
+ // *************** Session and controlling terminal ***************
+
+ /// Returns whether the terminal is the controlling terminal of current process.
+ ///
+ /// # Panic
+ ///
+ /// This method should be called in process context.
+ fn is_controlling_terminal(&self) -> bool {
+ let session = current!().session().unwrap();
+ let Some(terminal) = session.terminal() else {
+ return false;
+ };
+
+ let arc_self = self.arc_self();
+ Arc::ptr_eq(&terminal, &arc_self)
+ }
+
+ /// Sets the terminal as the controlling terminal of the session of current process.
+ ///
+ /// If self is not session leader, or the terminal is controlling terminal of other session,
+ /// or the session already has controlling terminal, this method returns `EPERM`.
+ ///
+ /// # Panic
+ ///
+ /// This method should only be called in process context.
+ fn set_current_session(&self) -> Result<()> {
+ if !current!().is_session_leader() {
+ return_errno_with_message!(Errno::EPERM, "current process is not session leader");
+ }
+
+ let get_terminal = || {
+ self.job_control().set_current_session()?;
+ Ok(self.arc_self())
+ };
+
+ let session = current!().session().unwrap();
+ session.set_terminal(get_terminal)
+ }
+
+ /// Releases the terminal from the session of current process if the terminal is the controlling
+ /// terminal of the session.
+ ///
+ /// If the terminal is not the controlling terminal of the session, this method will return `ENOTTY`.
+ ///
+ /// # Panic
+ ///
+ /// This method should only be called in process context.
+ fn release_current_session(&self) -> Result<()> {
+ if !self.is_controlling_terminal() {
+ return_errno_with_message!(Errno::ENOTTY, "release wrong tty");
+ }
+
+ let current = current!();
+ if !current.is_session_leader() {
+ warn!("TODO: release tty for process that is not session leader");
+ return Ok(());
+ }
+
+ let release_session = |_: &Arc<dyn Terminal>| self.job_control().release_current_session();
+
+ let session = current.session().unwrap();
+ session.release_terminal(release_session)
+ }
+
+ /// Returns the job control of the terminal.
+ fn job_control(&self) -> &JobControl;
+
+ fn arc_self(&self) -> Arc<dyn Terminal>;
+}
diff --git a/services/libs/jinux-std/src/process/process_group.rs /dev/null
--- a/services/libs/jinux-std/src/process/process_group.rs
+++ /dev/null
@@ -1,85 +0,0 @@
-use super::{
- process_table,
- signal::signals::{kernel::KernelSignal, user::UserSignal},
- Pgid, Pid, Process,
-};
-use crate::prelude::*;
-
-pub struct ProcessGroup {
- inner: Mutex<ProcessGroupInner>,
-}
-
-struct ProcessGroupInner {
- pgid: Pgid,
- processes: BTreeMap<Pid, Arc<Process>>,
- leader_process: Option<Arc<Process>>,
-}
-
-impl ProcessGroup {
- fn default() -> Self {
- ProcessGroup {
- inner: Mutex::new(ProcessGroupInner {
- pgid: 0,
- processes: BTreeMap::new(),
- leader_process: None,
- }),
- }
- }
-
- pub fn new(process: Arc<Process>) -> Self {
- let process_group = ProcessGroup::default();
- let pid = process.pid();
- process_group.set_pgid(pid);
- process_group.add_process(process.clone());
- process_group.set_leader_process(process);
- process_group
- }
-
- pub fn set_pgid(&self, pgid: Pgid) {
- self.inner.lock().pgid = pgid;
- }
-
- pub fn set_leader_process(&self, leader_process: Arc<Process>) {
- self.inner.lock().leader_process = Some(leader_process);
- }
-
- pub fn add_process(&self, process: Arc<Process>) {
- self.inner.lock().processes.insert(process.pid(), process);
- }
-
- pub fn contains_process(&self, pid: Pid) -> bool {
- self.inner.lock().processes.contains_key(&pid)
- }
-
- /// remove a process from this process group.
- /// If this group contains no processes now, the group itself will be deleted from global table.
- pub fn remove_process(&self, pid: Pid) {
- let mut inner_lock = self.inner.lock();
- inner_lock.processes.remove(&pid);
- let len = inner_lock.processes.len();
- let pgid = inner_lock.pgid;
- // if self contains no process, remove self from table
- if len == 0 {
- // this must be the last statement
- process_table::remove_process_group(pgid);
- }
- }
-
- pub fn pgid(&self) -> Pgid {
- self.inner.lock().pgid
- }
-
- /// send kernel signal to all processes in the group
- pub fn kernel_signal(&self, signal: KernelSignal) {
- for process in self.inner.lock().processes.values() {
- process.enqueue_signal(Box::new(signal));
- }
- }
-
- /// send user signal to all processes in the group
- pub fn user_signal(&self, signal: UserSignal) {
- for process in self.inner.lock().processes.values() {
- process.enqueue_signal(Box::new(signal));
- }
- }
-}
diff --git a/services/libs/jinux-std/src/process/process_group.rs /dev/null
--- a/services/libs/jinux-std/src/process/process_group.rs
+++ /dev/null
@@ -1,85 +0,0 @@
-use super::{
- process_table,
- signal::signals::{kernel::KernelSignal, user::UserSignal},
- Pgid, Pid, Process,
-};
-use crate::prelude::*;
-
-pub struct ProcessGroup {
- inner: Mutex<ProcessGroupInner>,
-}
-
-struct ProcessGroupInner {
- pgid: Pgid,
- processes: BTreeMap<Pid, Arc<Process>>,
- leader_process: Option<Arc<Process>>,
-}
-
-impl ProcessGroup {
- fn default() -> Self {
- ProcessGroup {
- inner: Mutex::new(ProcessGroupInner {
- pgid: 0,
- processes: BTreeMap::new(),
- leader_process: None,
- }),
- }
- }
-
- pub fn new(process: Arc<Process>) -> Self {
- let process_group = ProcessGroup::default();
- let pid = process.pid();
- process_group.set_pgid(pid);
- process_group.add_process(process.clone());
- process_group.set_leader_process(process);
- process_group
- }
-
- pub fn set_pgid(&self, pgid: Pgid) {
- self.inner.lock().pgid = pgid;
- }
-
- pub fn set_leader_process(&self, leader_process: Arc<Process>) {
- self.inner.lock().leader_process = Some(leader_process);
- }
-
- pub fn add_process(&self, process: Arc<Process>) {
- self.inner.lock().processes.insert(process.pid(), process);
- }
-
- pub fn contains_process(&self, pid: Pid) -> bool {
- self.inner.lock().processes.contains_key(&pid)
- }
-
- /// remove a process from this process group.
- /// If this group contains no processes now, the group itself will be deleted from global table.
- pub fn remove_process(&self, pid: Pid) {
- let mut inner_lock = self.inner.lock();
- inner_lock.processes.remove(&pid);
- let len = inner_lock.processes.len();
- let pgid = inner_lock.pgid;
- // if self contains no process, remove self from table
- if len == 0 {
- // this must be the last statement
- process_table::remove_process_group(pgid);
- }
- }
-
- pub fn pgid(&self) -> Pgid {
- self.inner.lock().pgid
- }
-
- /// send kernel signal to all processes in the group
- pub fn kernel_signal(&self, signal: KernelSignal) {
- for process in self.inner.lock().processes.values() {
- process.enqueue_signal(Box::new(signal));
- }
- }
-
- /// send user signal to all processes in the group
- pub fn user_signal(&self, signal: UserSignal) {
- for process in self.inner.lock().processes.values() {
- process.enqueue_signal(Box::new(signal));
- }
- }
-}
diff --git a/services/libs/jinux-std/src/process/process_table.rs b/services/libs/jinux-std/src/process/process_table.rs
--- a/services/libs/jinux-std/src/process/process_table.rs
+++ b/services/libs/jinux-std/src/process/process_table.rs
@@ -5,35 +5,25 @@
use crate::events::{Events, Observer, Subject};
use crate::prelude::*;
-use super::{process_group::ProcessGroup, Pgid, Pid, Process};
+use super::{Pgid, Pid, Process, ProcessGroup, Session, Sid};
-lazy_static! {
- static ref PROCESS_TABLE: Mutex<BTreeMap<Pid, Arc<Process>>> = Mutex::new(BTreeMap::new());
- static ref PROCESS_GROUP_TABLE: Mutex<BTreeMap<Pgid, Arc<ProcessGroup>>> =
- Mutex::new(BTreeMap::new());
- static ref PROCESS_TABLE_SUBJECT: Subject<PidEvent> = Subject::new();
-}
-
-/// add a process to global table
-pub fn add_process(process: Arc<Process>) {
- let pid = process.pid();
- PROCESS_TABLE.lock().insert(pid, process);
-}
+static PROCESS_TABLE: Mutex<BTreeMap<Pid, Arc<Process>>> = Mutex::new(BTreeMap::new());
+static PROCESS_GROUP_TABLE: Mutex<BTreeMap<Pgid, Arc<ProcessGroup>>> = Mutex::new(BTreeMap::new());
+static PROCESS_TABLE_SUBJECT: Subject<PidEvent> = Subject::new();
+static SESSION_TABLE: Mutex<BTreeMap<Sid, Arc<Session>>> = Mutex::new(BTreeMap::new());
-/// remove a process from global table
-pub fn remove_process(pid: Pid) {
- PROCESS_TABLE.lock().remove(&pid);
+// ************ Process *************
- let events = PidEvent::Exit(pid);
- PROCESS_TABLE_SUBJECT.notify_observers(&events);
+/// Gets a process with pid
+pub fn get_process(pid: &Pid) -> Option<Arc<Process>> {
+ PROCESS_TABLE.lock().get(pid).cloned()
}
-/// get a process with pid
-pub fn pid_to_process(pid: Pid) -> Option<Arc<Process>> {
- PROCESS_TABLE.lock().get(&pid).cloned()
+pub(super) fn process_table_mut() -> MutexGuard<'static, BTreeMap<Pid, Arc<Process>>> {
+ PROCESS_TABLE.lock()
}
-/// get all processes
+/// Gets all processes
pub fn get_all_processes() -> Vec<Arc<Process>> {
PROCESS_TABLE
.lock()
diff --git a/services/libs/jinux-std/src/process/process_table.rs b/services/libs/jinux-std/src/process/process_table.rs
--- a/services/libs/jinux-std/src/process/process_table.rs
+++ b/services/libs/jinux-std/src/process/process_table.rs
@@ -5,35 +5,25 @@
use crate::events::{Events, Observer, Subject};
use crate::prelude::*;
-use super::{process_group::ProcessGroup, Pgid, Pid, Process};
+use super::{Pgid, Pid, Process, ProcessGroup, Session, Sid};
-lazy_static! {
- static ref PROCESS_TABLE: Mutex<BTreeMap<Pid, Arc<Process>>> = Mutex::new(BTreeMap::new());
- static ref PROCESS_GROUP_TABLE: Mutex<BTreeMap<Pgid, Arc<ProcessGroup>>> =
- Mutex::new(BTreeMap::new());
- static ref PROCESS_TABLE_SUBJECT: Subject<PidEvent> = Subject::new();
-}
-
-/// add a process to global table
-pub fn add_process(process: Arc<Process>) {
- let pid = process.pid();
- PROCESS_TABLE.lock().insert(pid, process);
-}
+static PROCESS_TABLE: Mutex<BTreeMap<Pid, Arc<Process>>> = Mutex::new(BTreeMap::new());
+static PROCESS_GROUP_TABLE: Mutex<BTreeMap<Pgid, Arc<ProcessGroup>>> = Mutex::new(BTreeMap::new());
+static PROCESS_TABLE_SUBJECT: Subject<PidEvent> = Subject::new();
+static SESSION_TABLE: Mutex<BTreeMap<Sid, Arc<Session>>> = Mutex::new(BTreeMap::new());
-/// remove a process from global table
-pub fn remove_process(pid: Pid) {
- PROCESS_TABLE.lock().remove(&pid);
+// ************ Process *************
- let events = PidEvent::Exit(pid);
- PROCESS_TABLE_SUBJECT.notify_observers(&events);
+/// Gets a process with pid
+pub fn get_process(pid: &Pid) -> Option<Arc<Process>> {
+ PROCESS_TABLE.lock().get(pid).cloned()
}
-/// get a process with pid
-pub fn pid_to_process(pid: Pid) -> Option<Arc<Process>> {
- PROCESS_TABLE.lock().get(&pid).cloned()
+pub(super) fn process_table_mut() -> MutexGuard<'static, BTreeMap<Pid, Arc<Process>>> {
+ PROCESS_TABLE.lock()
}
-/// get all processes
+/// Gets all processes
pub fn get_all_processes() -> Vec<Arc<Process>> {
PROCESS_TABLE
.lock()
diff --git a/services/libs/jinux-std/src/process/process_table.rs b/services/libs/jinux-std/src/process/process_table.rs
--- a/services/libs/jinux-std/src/process/process_table.rs
+++ b/services/libs/jinux-std/src/process/process_table.rs
@@ -42,26 +32,41 @@ pub fn get_all_processes() -> Vec<Arc<Process>> {
.collect()
}
-/// add process group to global table
-pub fn add_process_group(process_group: Arc<ProcessGroup>) {
- let pgid = process_group.pgid();
- PROCESS_GROUP_TABLE.lock().insert(pgid, process_group);
+// ************ Process Group *************
+
+/// Gets a process group with `pgid`
+pub fn get_process_group(pgid: &Pgid) -> Option<Arc<ProcessGroup>> {
+ PROCESS_GROUP_TABLE.lock().get(pgid).cloned()
+}
+
+/// Returns whether process table contains process group with pgid
+pub fn contain_process_group(pgid: &Pgid) -> bool {
+ PROCESS_GROUP_TABLE.lock().contains_key(pgid)
}
-/// remove process group from global table
-pub fn remove_process_group(pgid: Pgid) {
- PROCESS_GROUP_TABLE.lock().remove(&pgid);
+pub(super) fn group_table_mut() -> MutexGuard<'static, BTreeMap<Pgid, Arc<ProcessGroup>>> {
+ PROCESS_GROUP_TABLE.lock()
}
-/// get a process group with pgid
-pub fn pgid_to_process_group(pgid: Pgid) -> Option<Arc<ProcessGroup>> {
- PROCESS_GROUP_TABLE.lock().get(&pgid).cloned()
+// ************ Session *************
+
+/// Gets a session with `sid`.
+pub fn get_session(sid: &Sid) -> Option<Arc<Session>> {
+ SESSION_TABLE.lock().get(sid).map(Arc::clone)
}
+pub(super) fn session_table_mut() -> MutexGuard<'static, BTreeMap<Sid, Arc<Session>>> {
+ SESSION_TABLE.lock()
+}
+
+// ************ Observer *************
+
+/// Registers an observer which watches `PidEvent`.
pub fn register_observer(observer: Weak<dyn Observer<PidEvent>>) {
PROCESS_TABLE_SUBJECT.register_observer(observer, ());
}
+/// Unregisters an observer which watches `PidEvent`.
pub fn unregister_observer(observer: &Weak<dyn Observer<PidEvent>>) {
PROCESS_TABLE_SUBJECT.unregister_observer(observer);
}
diff --git a/services/libs/jinux-std/src/process/process_table.rs b/services/libs/jinux-std/src/process/process_table.rs
--- a/services/libs/jinux-std/src/process/process_table.rs
+++ b/services/libs/jinux-std/src/process/process_table.rs
@@ -42,26 +32,41 @@ pub fn get_all_processes() -> Vec<Arc<Process>> {
.collect()
}
-/// add process group to global table
-pub fn add_process_group(process_group: Arc<ProcessGroup>) {
- let pgid = process_group.pgid();
- PROCESS_GROUP_TABLE.lock().insert(pgid, process_group);
+// ************ Process Group *************
+
+/// Gets a process group with `pgid`
+pub fn get_process_group(pgid: &Pgid) -> Option<Arc<ProcessGroup>> {
+ PROCESS_GROUP_TABLE.lock().get(pgid).cloned()
+}
+
+/// Returns whether process table contains process group with pgid
+pub fn contain_process_group(pgid: &Pgid) -> bool {
+ PROCESS_GROUP_TABLE.lock().contains_key(pgid)
}
-/// remove process group from global table
-pub fn remove_process_group(pgid: Pgid) {
- PROCESS_GROUP_TABLE.lock().remove(&pgid);
+pub(super) fn group_table_mut() -> MutexGuard<'static, BTreeMap<Pgid, Arc<ProcessGroup>>> {
+ PROCESS_GROUP_TABLE.lock()
}
-/// get a process group with pgid
-pub fn pgid_to_process_group(pgid: Pgid) -> Option<Arc<ProcessGroup>> {
- PROCESS_GROUP_TABLE.lock().get(&pgid).cloned()
+// ************ Session *************
+
+/// Gets a session with `sid`.
+pub fn get_session(sid: &Sid) -> Option<Arc<Session>> {
+ SESSION_TABLE.lock().get(sid).map(Arc::clone)
}
+pub(super) fn session_table_mut() -> MutexGuard<'static, BTreeMap<Sid, Arc<Session>>> {
+ SESSION_TABLE.lock()
+}
+
+// ************ Observer *************
+
+/// Registers an observer which watches `PidEvent`.
pub fn register_observer(observer: Weak<dyn Observer<PidEvent>>) {
PROCESS_TABLE_SUBJECT.register_observer(observer, ());
}
+/// Unregisters an observer which watches `PidEvent`.
pub fn unregister_observer(observer: &Weak<dyn Observer<PidEvent>>) {
PROCESS_TABLE_SUBJECT.unregister_observer(observer);
}
diff --git a/services/libs/jinux-std/src/process/signal/sig_queues.rs b/services/libs/jinux-std/src/process/signal/sig_queues.rs
--- a/services/libs/jinux-std/src/process/signal/sig_queues.rs
+++ b/services/libs/jinux-std/src/process/signal/sig_queues.rs
@@ -81,8 +81,11 @@ impl SigQueues {
// POSIX leaves unspecified which to deliver first if there are multiple
// pending standard signals. So we are free to define our own. The
// principle is to give more urgent signals higher priority (like SIGKILL).
+
+ // FIXME: the gvisor pty_test JobControlTest::ReleaseTTY requires that
+ // the SIGHUP signal should be handled before SIGCONT.
const ORDERED_STD_SIGS: [SigNum; COUNT_STD_SIGS] = [
- SIGKILL, SIGTERM, SIGSTOP, SIGCONT, SIGSEGV, SIGILL, SIGHUP, SIGINT, SIGQUIT, SIGTRAP,
+ SIGKILL, SIGTERM, SIGSTOP, SIGSEGV, SIGILL, SIGHUP, SIGCONT, SIGINT, SIGQUIT, SIGTRAP,
SIGABRT, SIGBUS, SIGFPE, SIGUSR1, SIGUSR2, SIGPIPE, SIGALRM, SIGSTKFLT, SIGCHLD,
SIGTSTP, SIGTTIN, SIGTTOU, SIGURG, SIGXCPU, SIGXFSZ, SIGVTALRM, SIGPROF, SIGWINCH,
SIGIO, SIGPWR, SIGSYS,
diff --git a/services/libs/jinux-std/src/process/wait.rs b/services/libs/jinux-std/src/process/wait.rs
--- a/services/libs/jinux-std/src/process/wait.rs
+++ b/services/libs/jinux-std/src/process/wait.rs
@@ -80,9 +80,33 @@ fn reap_zombie_child(process: &Process, pid: Pid) -> u32 {
for thread in &*child_process.threads().lock() {
thread_table::remove_thread(thread.tid());
}
- process_table::remove_process(child_process.pid());
- if let Some(process_group) = child_process.process_group() {
- process_group.remove_process(child_process.pid());
+
+ // Lock order: session table -> group table -> process table -> group of process
+ // -> group inner -> session inner
+ let mut session_table_mut = process_table::session_table_mut();
+ let mut group_table_mut = process_table::group_table_mut();
+ let mut process_table_mut = process_table::process_table_mut();
+
+ let mut child_group_mut = child_process.process_group.lock();
+
+ let process_group = child_group_mut.upgrade().unwrap();
+ let mut group_inner = process_group.inner.lock();
+ let session = group_inner.session.upgrade().unwrap();
+ let mut session_inner = session.inner.lock();
+
+ group_inner.remove_process(&child_process.pid());
+ session_inner.remove_process(&child_process);
+ *child_group_mut = Weak::new();
+
+ if group_inner.is_empty() {
+ group_table_mut.remove(&process_group.pgid());
+ session_inner.remove_process_group(&process_group.pgid());
+
+ if session_inner.is_empty() {
+ session_table_mut.remove(&session.sid());
+ }
}
+
+ process_table_mut.remove(&child_process.pid());
child_process.exit_code().unwrap()
}
diff --git a/services/libs/jinux-std/src/process/wait.rs b/services/libs/jinux-std/src/process/wait.rs
--- a/services/libs/jinux-std/src/process/wait.rs
+++ b/services/libs/jinux-std/src/process/wait.rs
@@ -80,9 +80,33 @@ fn reap_zombie_child(process: &Process, pid: Pid) -> u32 {
for thread in &*child_process.threads().lock() {
thread_table::remove_thread(thread.tid());
}
- process_table::remove_process(child_process.pid());
- if let Some(process_group) = child_process.process_group() {
- process_group.remove_process(child_process.pid());
+
+ // Lock order: session table -> group table -> process table -> group of process
+ // -> group inner -> session inner
+ let mut session_table_mut = process_table::session_table_mut();
+ let mut group_table_mut = process_table::group_table_mut();
+ let mut process_table_mut = process_table::process_table_mut();
+
+ let mut child_group_mut = child_process.process_group.lock();
+
+ let process_group = child_group_mut.upgrade().unwrap();
+ let mut group_inner = process_group.inner.lock();
+ let session = group_inner.session.upgrade().unwrap();
+ let mut session_inner = session.inner.lock();
+
+ group_inner.remove_process(&child_process.pid());
+ session_inner.remove_process(&child_process);
+ *child_group_mut = Weak::new();
+
+ if group_inner.is_empty() {
+ group_table_mut.remove(&process_group.pgid());
+ session_inner.remove_process_group(&process_group.pgid());
+
+ if session_inner.is_empty() {
+ session_table_mut.remove(&session.sid());
+ }
}
+
+ process_table_mut.remove(&child_process.pid());
child_process.exit_code().unwrap()
}
diff --git /dev/null b/services/libs/jinux-std/src/syscall/getsid.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/syscall/getsid.rs
@@ -0,0 +1,30 @@
+use crate::log_syscall_entry;
+use crate::prelude::*;
+use crate::process::{process_table, Pid};
+
+use super::{SyscallReturn, SYS_GETSID};
+
+pub fn sys_getsid(pid: Pid) -> Result<SyscallReturn> {
+ log_syscall_entry!(SYS_GETSID);
+ debug!("pid = {}", pid);
+
+ let session = current!().session().unwrap();
+ let sid = session.sid();
+
+ if pid == 0 {
+ return Ok(SyscallReturn::Return(sid as _));
+ }
+
+ let Some(process) = process_table::get_process(&pid) else {
+ return_errno_with_message!(Errno::ESRCH, "the process does not exist")
+ };
+
+ if !Arc::ptr_eq(&session, &process.session().unwrap()) {
+ return_errno_with_message!(
+ Errno::EPERM,
+ "the process and current process does not belong to the same session"
+ );
+ }
+
+ Ok(SyscallReturn::Return(sid as _))
+}
diff --git /dev/null b/services/libs/jinux-std/src/syscall/getsid.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/syscall/getsid.rs
@@ -0,0 +1,30 @@
+use crate::log_syscall_entry;
+use crate::prelude::*;
+use crate::process::{process_table, Pid};
+
+use super::{SyscallReturn, SYS_GETSID};
+
+pub fn sys_getsid(pid: Pid) -> Result<SyscallReturn> {
+ log_syscall_entry!(SYS_GETSID);
+ debug!("pid = {}", pid);
+
+ let session = current!().session().unwrap();
+ let sid = session.sid();
+
+ if pid == 0 {
+ return Ok(SyscallReturn::Return(sid as _));
+ }
+
+ let Some(process) = process_table::get_process(&pid) else {
+ return_errno_with_message!(Errno::ESRCH, "the process does not exist")
+ };
+
+ if !Arc::ptr_eq(&session, &process.session().unwrap()) {
+ return_errno_with_message!(
+ Errno::EPERM,
+ "the process and current process does not belong to the same session"
+ );
+ }
+
+ Ok(SyscallReturn::Return(sid as _))
+}
diff --git a/services/libs/jinux-std/src/syscall/kill.rs b/services/libs/jinux-std/src/syscall/kill.rs
--- a/services/libs/jinux-std/src/syscall/kill.rs
+++ b/services/libs/jinux-std/src/syscall/kill.rs
@@ -34,15 +34,15 @@ pub fn do_sys_kill(filter: ProcessFilter, sig_num: SigNum) -> Result<()> {
}
}
ProcessFilter::WithPid(pid) => {
- if let Some(process) = process_table::pid_to_process(pid) {
+ if let Some(process) = process_table::get_process(&pid) {
process.enqueue_signal(Box::new(signal));
} else {
return_errno_with_message!(Errno::ESRCH, "No such process in process table");
}
}
ProcessFilter::WithPgid(pgid) => {
- if let Some(process_group) = process_table::pgid_to_process_group(pgid) {
- process_group.user_signal(signal);
+ if let Some(process_group) = process_table::get_process_group(&pgid) {
+ process_group.broadcast_signal(signal);
} else {
return_errno_with_message!(Errno::ESRCH, "No such process group in process table");
}
diff --git a/services/libs/jinux-std/src/syscall/kill.rs b/services/libs/jinux-std/src/syscall/kill.rs
--- a/services/libs/jinux-std/src/syscall/kill.rs
+++ b/services/libs/jinux-std/src/syscall/kill.rs
@@ -34,15 +34,15 @@ pub fn do_sys_kill(filter: ProcessFilter, sig_num: SigNum) -> Result<()> {
}
}
ProcessFilter::WithPid(pid) => {
- if let Some(process) = process_table::pid_to_process(pid) {
+ if let Some(process) = process_table::get_process(&pid) {
process.enqueue_signal(Box::new(signal));
} else {
return_errno_with_message!(Errno::ESRCH, "No such process in process table");
}
}
ProcessFilter::WithPgid(pgid) => {
- if let Some(process_group) = process_table::pgid_to_process_group(pgid) {
- process_group.user_signal(signal);
+ if let Some(process_group) = process_table::get_process_group(&pgid) {
+ process_group.broadcast_signal(signal);
} else {
return_errno_with_message!(Errno::ESRCH, "No such process group in process table");
}
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -77,12 +77,14 @@ use self::connect::sys_connect;
use self::execve::sys_execveat;
use self::getpeername::sys_getpeername;
use self::getrandom::sys_getrandom;
+use self::getsid::sys_getsid;
use self::getsockname::sys_getsockname;
use self::getsockopt::sys_getsockopt;
use self::listen::sys_listen;
use self::pread64::sys_pread64;
use self::recvfrom::sys_recvfrom;
use self::sendto::sys_sendto;
+use self::setsid::sys_setsid;
use self::setsockopt::sys_setsockopt;
use self::shutdown::sys_shutdown;
use self::socket::sys_socket;
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -77,12 +77,14 @@ use self::connect::sys_connect;
use self::execve::sys_execveat;
use self::getpeername::sys_getpeername;
use self::getrandom::sys_getrandom;
+use self::getsid::sys_getsid;
use self::getsockname::sys_getsockname;
use self::getsockopt::sys_getsockopt;
use self::listen::sys_listen;
use self::pread64::sys_pread64;
use self::recvfrom::sys_recvfrom;
use self::sendto::sys_sendto;
+use self::setsid::sys_setsid;
use self::setsockopt::sys_setsockopt;
use self::shutdown::sys_shutdown;
use self::socket::sys_socket;
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -119,6 +121,7 @@ mod getpgrp;
mod getpid;
mod getppid;
mod getrandom;
+mod getsid;
mod getsockname;
mod getsockopt;
mod gettid;
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -119,6 +121,7 @@ mod getpgrp;
mod getpid;
mod getppid;
mod getrandom;
+mod getsid;
mod getsockname;
mod getsockopt;
mod gettid;
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -155,6 +158,7 @@ mod sendto;
mod set_robust_list;
mod set_tid_address;
mod setpgid;
+mod setsid;
mod setsockopt;
mod shutdown;
mod socket;
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -155,6 +158,7 @@ mod sendto;
mod set_robust_list;
mod set_tid_address;
mod setpgid;
+mod setsid;
mod setsockopt;
mod shutdown;
mod socket;
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -274,6 +278,8 @@ define_syscall_nums!(
SYS_SETPGID = 109,
SYS_GETPPID = 110,
SYS_GETPGRP = 111,
+ SYS_SETSID = 112,
+ SYS_GETSID = 124,
SYS_STATFS = 137,
SYS_FSTATFS = 138,
SYS_PRCTL = 157,
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -274,6 +278,8 @@ define_syscall_nums!(
SYS_SETPGID = 109,
SYS_GETPPID = 110,
SYS_GETPGRP = 111,
+ SYS_SETSID = 112,
+ SYS_GETSID = 124,
SYS_STATFS = 137,
SYS_FSTATFS = 138,
SYS_PRCTL = 157,
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -435,6 +441,8 @@ pub fn syscall_dispatch(
SYS_SETPGID => syscall_handler!(2, sys_setpgid, args),
SYS_GETPPID => syscall_handler!(0, sys_getppid),
SYS_GETPGRP => syscall_handler!(0, sys_getpgrp),
+ SYS_SETSID => syscall_handler!(0, sys_setsid),
+ SYS_GETSID => syscall_handler!(1, sys_getsid, args),
SYS_STATFS => syscall_handler!(2, sys_statfs, args),
SYS_FSTATFS => syscall_handler!(2, sys_fstatfs, args),
SYS_PRCTL => syscall_handler!(5, sys_prctl, args),
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -435,6 +441,8 @@ pub fn syscall_dispatch(
SYS_SETPGID => syscall_handler!(2, sys_setpgid, args),
SYS_GETPPID => syscall_handler!(0, sys_getppid),
SYS_GETPGRP => syscall_handler!(0, sys_getpgrp),
+ SYS_SETSID => syscall_handler!(0, sys_setsid),
+ SYS_GETSID => syscall_handler!(1, sys_getsid, args),
SYS_STATFS => syscall_handler!(2, sys_statfs, args),
SYS_FSTATFS => syscall_handler!(2, sys_fstatfs, args),
SYS_PRCTL => syscall_handler!(5, sys_prctl, args),
diff --git a/services/libs/jinux-std/src/syscall/setpgid.rs b/services/libs/jinux-std/src/syscall/setpgid.rs
--- a/services/libs/jinux-std/src/syscall/setpgid.rs
+++ b/services/libs/jinux-std/src/syscall/setpgid.rs
@@ -1,8 +1,6 @@
-use crate::{
- log_syscall_entry,
- prelude::*,
- process::{process_table, Pgid, Pid, ProcessGroup},
-};
+use crate::log_syscall_entry;
+use crate::prelude::*;
+use crate::process::{process_table, Pgid, Pid};
use super::{SyscallReturn, SYS_SETPGID};
diff --git a/services/libs/jinux-std/src/syscall/setpgid.rs b/services/libs/jinux-std/src/syscall/setpgid.rs
--- a/services/libs/jinux-std/src/syscall/setpgid.rs
+++ b/services/libs/jinux-std/src/syscall/setpgid.rs
@@ -1,8 +1,6 @@
-use crate::{
- log_syscall_entry,
- prelude::*,
- process::{process_table, Pgid, Pid, ProcessGroup},
-};
+use crate::log_syscall_entry;
+use crate::prelude::*;
+use crate::process::{process_table, Pgid, Pid};
use super::{SyscallReturn, SYS_SETPGID};
diff --git a/services/libs/jinux-std/src/syscall/setpgid.rs b/services/libs/jinux-std/src/syscall/setpgid.rs
--- a/services/libs/jinux-std/src/syscall/setpgid.rs
+++ b/services/libs/jinux-std/src/syscall/setpgid.rs
@@ -15,7 +13,7 @@ pub fn sys_setpgid(pid: Pid, pgid: Pgid) -> Result<SyscallReturn> {
let pgid = if pgid == 0 { pid } else { pgid };
debug!("pid = {}, pgid = {}", pid, pgid);
- if pid != current.pid() && !current.children().lock().contains_key(&pid) {
+ if pid != current.pid() && !current.has_child(&pid) {
return_errno_with_message!(
Errno::ESRCH,
"cannot set pgid for process other than current or children of current"
diff --git a/services/libs/jinux-std/src/syscall/setpgid.rs b/services/libs/jinux-std/src/syscall/setpgid.rs
--- a/services/libs/jinux-std/src/syscall/setpgid.rs
+++ b/services/libs/jinux-std/src/syscall/setpgid.rs
@@ -15,7 +13,7 @@ pub fn sys_setpgid(pid: Pid, pgid: Pgid) -> Result<SyscallReturn> {
let pgid = if pgid == 0 { pid } else { pgid };
debug!("pid = {}, pgid = {}", pid, pgid);
- if pid != current.pid() && !current.children().lock().contains_key(&pid) {
+ if pid != current.pid() && !current.has_child(&pid) {
return_errno_with_message!(
Errno::ESRCH,
"cannot set pgid for process other than current or children of current"
diff --git a/services/libs/jinux-std/src/syscall/setpgid.rs b/services/libs/jinux-std/src/syscall/setpgid.rs
--- a/services/libs/jinux-std/src/syscall/setpgid.rs
+++ b/services/libs/jinux-std/src/syscall/setpgid.rs
@@ -25,27 +23,14 @@ pub fn sys_setpgid(pid: Pid, pgid: Pgid) -> Result<SyscallReturn> {
// How can we determine a child process has called execve?
// only can move process to an existing group or self
- if pgid != pid && process_table::pgid_to_process_group(pgid).is_none() {
+ if pgid != pid && !process_table::contain_process_group(&pgid) {
return_errno_with_message!(Errno::EPERM, "process group must exist");
}
- let process = process_table::pid_to_process(pid)
+ let process = process_table::get_process(&pid)
.ok_or(Error::with_message(Errno::ESRCH, "process does not exist"))?;
- // if the process already belongs to the process group
- if process.pgid() == pgid {
- return Ok(SyscallReturn::Return(0));
- }
-
- if let Some(process_group) = process_table::pgid_to_process_group(pgid) {
- process_group.add_process(process.clone());
- process.set_process_group(Arc::downgrade(&process_group));
- } else {
- let new_process_group = Arc::new(ProcessGroup::new(process.clone()));
- // new_process_group.add_process(process.clone());
- process.set_process_group(Arc::downgrade(&new_process_group));
- process_table::add_process_group(new_process_group);
- }
+ process.to_other_group(pgid)?;
Ok(SyscallReturn::Return(0))
}
diff --git a/services/libs/jinux-std/src/syscall/setpgid.rs b/services/libs/jinux-std/src/syscall/setpgid.rs
--- a/services/libs/jinux-std/src/syscall/setpgid.rs
+++ b/services/libs/jinux-std/src/syscall/setpgid.rs
@@ -25,27 +23,14 @@ pub fn sys_setpgid(pid: Pid, pgid: Pgid) -> Result<SyscallReturn> {
// How can we determine a child process has called execve?
// only can move process to an existing group or self
- if pgid != pid && process_table::pgid_to_process_group(pgid).is_none() {
+ if pgid != pid && !process_table::contain_process_group(&pgid) {
return_errno_with_message!(Errno::EPERM, "process group must exist");
}
- let process = process_table::pid_to_process(pid)
+ let process = process_table::get_process(&pid)
.ok_or(Error::with_message(Errno::ESRCH, "process does not exist"))?;
- // if the process already belongs to the process group
- if process.pgid() == pgid {
- return Ok(SyscallReturn::Return(0));
- }
-
- if let Some(process_group) = process_table::pgid_to_process_group(pgid) {
- process_group.add_process(process.clone());
- process.set_process_group(Arc::downgrade(&process_group));
- } else {
- let new_process_group = Arc::new(ProcessGroup::new(process.clone()));
- // new_process_group.add_process(process.clone());
- process.set_process_group(Arc::downgrade(&new_process_group));
- process_table::add_process_group(new_process_group);
- }
+ process.to_other_group(pgid)?;
Ok(SyscallReturn::Return(0))
}
diff --git /dev/null b/services/libs/jinux-std/src/syscall/setsid.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/syscall/setsid.rs
@@ -0,0 +1,13 @@
+use crate::log_syscall_entry;
+use crate::prelude::*;
+
+use super::{SyscallReturn, SYS_SETSID};
+
+pub fn sys_setsid() -> Result<SyscallReturn> {
+ log_syscall_entry!(SYS_SETSID);
+
+ let current = current!();
+ let session = current.to_new_session()?;
+
+ Ok(SyscallReturn::Return(session.sid() as _))
+}
diff --git /dev/null b/services/libs/jinux-std/src/syscall/setsid.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/syscall/setsid.rs
@@ -0,0 +1,13 @@
+use crate::log_syscall_entry;
+use crate::prelude::*;
+
+use super::{SyscallReturn, SYS_SETSID};
+
+pub fn sys_setsid() -> Result<SyscallReturn> {
+ log_syscall_entry!(SYS_SETSID);
+
+ let current = current!();
+ let session = current.to_new_session()?;
+
+ Ok(SyscallReturn::Return(session.sid() as _))
+}
diff --git a/services/libs/jinux-std/src/syscall/tgkill.rs b/services/libs/jinux-std/src/syscall/tgkill.rs
--- a/services/libs/jinux-std/src/syscall/tgkill.rs
+++ b/services/libs/jinux-std/src/syscall/tgkill.rs
@@ -16,8 +16,8 @@ pub fn sys_tgkill(tgid: Pid, tid: Tid, sig_num: u8) -> Result<SyscallReturn> {
log_syscall_entry!(SYS_TGKILL);
let sig_num = SigNum::from_u8(sig_num);
info!("tgid = {}, pid = {}, sig_num = {:?}", tgid, tid, sig_num);
- let target_thread = thread_table::tid_to_thread(tid)
- .ok_or(Error::with_message(Errno::EINVAL, "Invalid pid"))?;
+ let target_thread =
+ thread_table::get_thread(tid).ok_or(Error::with_message(Errno::EINVAL, "Invalid pid"))?;
let posix_thread = target_thread.as_posix_thread().unwrap();
let pid = posix_thread.process().pid();
if pid != tgid {
diff --git a/services/libs/jinux-std/src/syscall/tgkill.rs b/services/libs/jinux-std/src/syscall/tgkill.rs
--- a/services/libs/jinux-std/src/syscall/tgkill.rs
+++ b/services/libs/jinux-std/src/syscall/tgkill.rs
@@ -16,8 +16,8 @@ pub fn sys_tgkill(tgid: Pid, tid: Tid, sig_num: u8) -> Result<SyscallReturn> {
log_syscall_entry!(SYS_TGKILL);
let sig_num = SigNum::from_u8(sig_num);
info!("tgid = {}, pid = {}, sig_num = {:?}", tgid, tid, sig_num);
- let target_thread = thread_table::tid_to_thread(tid)
- .ok_or(Error::with_message(Errno::EINVAL, "Invalid pid"))?;
+ let target_thread =
+ thread_table::get_thread(tid).ok_or(Error::with_message(Errno::EINVAL, "Invalid pid"))?;
let posix_thread = target_thread.as_posix_thread().unwrap();
let pid = posix_thread.process().pid();
if pid != tgid {
diff --git a/services/libs/jinux-std/src/thread/thread_table.rs b/services/libs/jinux-std/src/thread/thread_table.rs
--- a/services/libs/jinux-std/src/thread/thread_table.rs
+++ b/services/libs/jinux-std/src/thread/thread_table.rs
@@ -15,6 +15,6 @@ pub fn remove_thread(tid: Tid) {
THREAD_TABLE.lock().remove(&tid);
}
-pub fn tid_to_thread(tid: Tid) -> Option<Arc<Thread>> {
+pub fn get_thread(tid: Tid) -> Option<Arc<Thread>> {
THREAD_TABLE.lock().get(&tid).cloned()
}
diff --git a/services/libs/jinux-std/src/thread/thread_table.rs b/services/libs/jinux-std/src/thread/thread_table.rs
--- a/services/libs/jinux-std/src/thread/thread_table.rs
+++ b/services/libs/jinux-std/src/thread/thread_table.rs
@@ -15,6 +15,6 @@ pub fn remove_thread(tid: Tid) {
THREAD_TABLE.lock().remove(&tid);
}
-pub fn tid_to_thread(tid: Tid) -> Option<Arc<Thread>> {
+pub fn get_thread(tid: Tid) -> Option<Arc<Thread>> {
THREAD_TABLE.lock().get(&tid).cloned()
}
|
2023-08-30T11:25:32Z
|
6dbf5d560deafea0dcec228e4cb2d5e53c756174
|
|
asterinas/asterinas
|
diff --git /dev/null b/regression/apps/pty/Makefile
new file mode 100644
--- /dev/null
+++ b/regression/apps/pty/Makefile
@@ -0,0 +1,3 @@
+include ../test_common.mk
+
+EXTRA_C_FLAGS :=
diff --git a/regression/apps/scripts/run_tests.sh b/regression/apps/scripts/run_tests.sh
--- a/regression/apps/scripts/run_tests.sh
+++ b/regression/apps/scripts/run_tests.sh
@@ -6,7 +6,7 @@ SCRIPT_DIR=/regression
cd ${SCRIPT_DIR}/..
echo "Running tests......"
-tests="hello_world/hello_world fork/fork execve/execve fork_c/fork signal_c/signal_test pthread/pthread_test hello_pie/hello"
+tests="hello_world/hello_world fork/fork execve/execve fork_c/fork signal_c/signal_test pthread/pthread_test hello_pie/hello pty/open_pty"
for testcase in ${tests}
do
echo "Running test ${testcase}......"
diff --git a/regression/syscall_test/Makefile b/regression/syscall_test/Makefile
--- a/regression/syscall_test/Makefile
+++ b/regression/syscall_test/Makefile
@@ -1,4 +1,4 @@
-TESTS ?= open_test read_test statfs_test chmod_test
+TESTS ?= open_test read_test statfs_test chmod_test pty_test
MKFILE_PATH := $(abspath $(lastword $(MAKEFILE_LIST)))
CUR_DIR := $(patsubst %/,%,$(dir $(MKFILE_PATH)))
diff --git /dev/null b/regression/syscall_test/blocklists/pty_test
new file mode 100644
--- /dev/null
+++ b/regression/syscall_test/blocklists/pty_test
@@ -0,0 +1,42 @@
+PtyTrunc.Truncate
+PtyTest.MasterTermiosUnchangable
+PtyTest.TermiosICRNL
+PtyTest.TermiosONLCR
+PtyTest.TermiosINLCR
+PtyTest.TermiosOCRNL
+PtyTest.SwitchCanonToNonCanonNewline
+PtyTest.TermiosICANONNewline
+PtyTest.TermiosICANONEOF
+PtyTest.CanonDiscard
+PtyTest.CanonMultiline
+PtyTest.SimpleEcho
+PtyTest.TermiosIGNCR
+PtyTest.TermiosONOCR
+PtyTest.VEOLTermination
+PtyTest.CanonBigWrite
+PtyTest.SwitchCanonToNoncanon
+PtyTest.SwitchNoncanonToCanonNewlineBig
+PtyTest.SwitchNoncanonToCanonNoNewline
+PtyTest.SwitchNoncanonToCanonNoNewlineBig
+PtyTest.NoncanonBigWrite
+PtyTest.SwitchNoncanonToCanonMultiline
+PtyTest.SwitchTwiceMultiline
+JobControlTest.SetTTYMaster
+JobControlTest.SetTTY
+JobControlTest.SetTTYNonLeader
+JobControlTest.SetTTYBadArg
+JobControlTest.SetTTYDifferentSession
+JobControlTest.ReleaseTTY
+JobControlTest.ReleaseUnsetTTY
+JobControlTest.ReleaseWrongTTY
+JobControlTest.ReleaseTTYNonLeader
+JobControlTest.ReleaseTTYDifferentSession
+JobControlTest.ReleaseTTYSignals
+JobControlTest.GetForegroundProcessGroup
+JobControlTest.GetForegroundProcessGroupNonControlling
+JobControlTest.SetForegroundProcessGroup
+JobControlTest.SetForegroundProcessGroupWrongTTY
+JobControlTest.SetForegroundProcessGroupNegPgid
+JobControlTest.SetForegroundProcessGroupEmptyProcessGroup
+JobControlTest.SetForegroundProcessGroupDifferentSession
+JobControlTest.OrphanRegression
\ No newline at end of file
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -3,13 +3,13 @@ use crate::process::process_group::ProcessGroup;
use crate::process::signal::constants::{SIGINT, SIGQUIT};
use crate::{
prelude::*,
- process::{process_table, signal::signals::kernel::KernelSignal, Pgid},
+ process::{signal::signals::kernel::KernelSignal, Pgid},
};
use alloc::format;
use jinux_frame::trap::disable_local;
use ringbuf::{ring_buffer::RbBase, Rb, StaticRb};
-use super::termio::{KernelTermios, CC_C_CHAR};
+use super::termio::{KernelTermios, WinSize, CC_C_CHAR};
// This implementation refers the implementation of linux
// https://elixir.bootlin.com/linux/latest/source/include/linux/tty_ldisc.h
|
[
"214"
] |
0.1
|
25c4f0f2bcaa0bc8c650b0f4ee7b0d78e2a836b2
|
Implement pseudo terminals
Maybe we need #209 for pty, since each pty will be a device under devfs.
|
asterinas__asterinas-334
| 334
|
diff --git a/regression/apps/Makefile b/regression/apps/Makefile
--- a/regression/apps/Makefile
+++ b/regression/apps/Makefile
@@ -3,7 +3,7 @@ MKFILE_PATH := $(abspath $(lastword $(MAKEFILE_LIST)))
CUR_DIR := $(patsubst %/,%,$(dir $(MKFILE_PATH)))
INITRAMFS ?= $(CUR_DIR)/../build/initramfs
REGRESSION_BUILD_DIR ?= $(INITRAMFS)/regression
-TEST_APPS := signal_c pthread network hello_world hello_pie hello_c fork_c fork execve
+TEST_APPS := signal_c pthread network hello_world hello_pie hello_c fork_c fork execve pty
.PHONY: all
diff --git a/regression/apps/Makefile b/regression/apps/Makefile
--- a/regression/apps/Makefile
+++ b/regression/apps/Makefile
@@ -3,7 +3,7 @@ MKFILE_PATH := $(abspath $(lastword $(MAKEFILE_LIST)))
CUR_DIR := $(patsubst %/,%,$(dir $(MKFILE_PATH)))
INITRAMFS ?= $(CUR_DIR)/../build/initramfs
REGRESSION_BUILD_DIR ?= $(INITRAMFS)/regression
-TEST_APPS := signal_c pthread network hello_world hello_pie hello_c fork_c fork execve
+TEST_APPS := signal_c pthread network hello_world hello_pie hello_c fork_c fork execve pty
.PHONY: all
diff --git /dev/null b/regression/apps/pty/Makefile
new file mode 100644
--- /dev/null
+++ b/regression/apps/pty/Makefile
@@ -0,0 +1,3 @@
+include ../test_common.mk
+
+EXTRA_C_FLAGS :=
diff --git /dev/null b/regression/apps/pty/open_pty.c
new file mode 100644
--- /dev/null
+++ b/regression/apps/pty/open_pty.c
@@ -0,0 +1,51 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <termios.h>
+#include <pty.h>
+
+int main() {
+ int master, slave;
+ char name[256];
+ struct termios term;
+
+ if (openpty(&master, &slave, name, NULL, NULL) == -1) {
+ perror("openpty");
+ exit(EXIT_FAILURE);
+ }
+
+ printf("slave name: %s\n", name);
+
+ // Set pty slave terminal attributes
+ tcgetattr(slave, &term);
+ term.c_lflag &= ~(ICANON | ECHO);
+ term.c_cc[VMIN] = 1;
+ term.c_cc[VTIME] = 0;
+ tcsetattr(slave, TCSANOW, &term);
+
+ // Print to pty slave
+ dprintf(slave, "Hello world!\n");
+
+ // Read from pty slave
+ char buf[256];
+ ssize_t n = read(master, buf, sizeof(buf));
+ if (n > 0) {
+ printf("read %ld bytes from slave: %.*s", n, (int)n, buf);
+ }
+
+ // Write to pty master
+ dprintf(master, "hello world from master\n");
+
+ // Read from pty master
+ char nbuf[256];
+ ssize_t nn = read(slave, nbuf, sizeof(nbuf));
+ if (nn > 0) {
+ printf("read %ld bytes from master: %.*s", nn, (int)nn, nbuf);
+ }
+
+ close(master);
+ close(slave);
+
+ return 0;
+}
diff --git /dev/null b/regression/apps/pty/open_pty.c
new file mode 100644
--- /dev/null
+++ b/regression/apps/pty/open_pty.c
@@ -0,0 +1,51 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <termios.h>
+#include <pty.h>
+
+int main() {
+ int master, slave;
+ char name[256];
+ struct termios term;
+
+ if (openpty(&master, &slave, name, NULL, NULL) == -1) {
+ perror("openpty");
+ exit(EXIT_FAILURE);
+ }
+
+ printf("slave name: %s\n", name);
+
+ // Set pty slave terminal attributes
+ tcgetattr(slave, &term);
+ term.c_lflag &= ~(ICANON | ECHO);
+ term.c_cc[VMIN] = 1;
+ term.c_cc[VTIME] = 0;
+ tcsetattr(slave, TCSANOW, &term);
+
+ // Print to pty slave
+ dprintf(slave, "Hello world!\n");
+
+ // Read from pty slave
+ char buf[256];
+ ssize_t n = read(master, buf, sizeof(buf));
+ if (n > 0) {
+ printf("read %ld bytes from slave: %.*s", n, (int)n, buf);
+ }
+
+ // Write to pty master
+ dprintf(master, "hello world from master\n");
+
+ // Read from pty master
+ char nbuf[256];
+ ssize_t nn = read(slave, nbuf, sizeof(nbuf));
+ if (nn > 0) {
+ printf("read %ld bytes from master: %.*s", nn, (int)nn, nbuf);
+ }
+
+ close(master);
+ close(slave);
+
+ return 0;
+}
diff --git a/regression/apps/scripts/run_tests.sh b/regression/apps/scripts/run_tests.sh
--- a/regression/apps/scripts/run_tests.sh
+++ b/regression/apps/scripts/run_tests.sh
@@ -6,7 +6,7 @@ SCRIPT_DIR=/regression
cd ${SCRIPT_DIR}/..
echo "Running tests......"
-tests="hello_world/hello_world fork/fork execve/execve fork_c/fork signal_c/signal_test pthread/pthread_test hello_pie/hello"
+tests="hello_world/hello_world fork/fork execve/execve fork_c/fork signal_c/signal_test pthread/pthread_test hello_pie/hello pty/open_pty"
for testcase in ${tests}
do
echo "Running test ${testcase}......"
diff --git a/regression/syscall_test/Makefile b/regression/syscall_test/Makefile
--- a/regression/syscall_test/Makefile
+++ b/regression/syscall_test/Makefile
@@ -1,4 +1,4 @@
-TESTS ?= open_test read_test statfs_test chmod_test
+TESTS ?= open_test read_test statfs_test chmod_test pty_test
MKFILE_PATH := $(abspath $(lastword $(MAKEFILE_LIST)))
CUR_DIR := $(patsubst %/,%,$(dir $(MKFILE_PATH)))
diff --git /dev/null b/regression/syscall_test/blocklists/pty_test
new file mode 100644
--- /dev/null
+++ b/regression/syscall_test/blocklists/pty_test
@@ -0,0 +1,42 @@
+PtyTrunc.Truncate
+PtyTest.MasterTermiosUnchangable
+PtyTest.TermiosICRNL
+PtyTest.TermiosONLCR
+PtyTest.TermiosINLCR
+PtyTest.TermiosOCRNL
+PtyTest.SwitchCanonToNonCanonNewline
+PtyTest.TermiosICANONNewline
+PtyTest.TermiosICANONEOF
+PtyTest.CanonDiscard
+PtyTest.CanonMultiline
+PtyTest.SimpleEcho
+PtyTest.TermiosIGNCR
+PtyTest.TermiosONOCR
+PtyTest.VEOLTermination
+PtyTest.CanonBigWrite
+PtyTest.SwitchCanonToNoncanon
+PtyTest.SwitchNoncanonToCanonNewlineBig
+PtyTest.SwitchNoncanonToCanonNoNewline
+PtyTest.SwitchNoncanonToCanonNoNewlineBig
+PtyTest.NoncanonBigWrite
+PtyTest.SwitchNoncanonToCanonMultiline
+PtyTest.SwitchTwiceMultiline
+JobControlTest.SetTTYMaster
+JobControlTest.SetTTY
+JobControlTest.SetTTYNonLeader
+JobControlTest.SetTTYBadArg
+JobControlTest.SetTTYDifferentSession
+JobControlTest.ReleaseTTY
+JobControlTest.ReleaseUnsetTTY
+JobControlTest.ReleaseWrongTTY
+JobControlTest.ReleaseTTYNonLeader
+JobControlTest.ReleaseTTYDifferentSession
+JobControlTest.ReleaseTTYSignals
+JobControlTest.GetForegroundProcessGroup
+JobControlTest.GetForegroundProcessGroupNonControlling
+JobControlTest.SetForegroundProcessGroup
+JobControlTest.SetForegroundProcessGroupWrongTTY
+JobControlTest.SetForegroundProcessGroupNegPgid
+JobControlTest.SetForegroundProcessGroupEmptyProcessGroup
+JobControlTest.SetForegroundProcessGroupDifferentSession
+JobControlTest.OrphanRegression
\ No newline at end of file
diff --git a/services/libs/jinux-std/src/device/mod.rs b/services/libs/jinux-std/src/device/mod.rs
--- a/services/libs/jinux-std/src/device/mod.rs
+++ b/services/libs/jinux-std/src/device/mod.rs
@@ -7,6 +7,8 @@ mod zero;
use crate::fs::device::{add_node, Device, DeviceId, DeviceType};
use crate::prelude::*;
+pub use pty::new_pty_pair;
+pub use pty::{PtyMaster, PtySlave};
pub use random::Random;
pub use urandom::Urandom;
diff --git a/services/libs/jinux-std/src/device/mod.rs b/services/libs/jinux-std/src/device/mod.rs
--- a/services/libs/jinux-std/src/device/mod.rs
+++ b/services/libs/jinux-std/src/device/mod.rs
@@ -7,6 +7,8 @@ mod zero;
use crate::fs::device::{add_node, Device, DeviceId, DeviceType};
use crate::prelude::*;
+pub use pty::new_pty_pair;
+pub use pty::{PtyMaster, PtySlave};
pub use random::Random;
pub use urandom::Urandom;
diff --git a/services/libs/jinux-std/src/device/pty.rs /dev/null
--- a/services/libs/jinux-std/src/device/pty.rs
+++ /dev/null
@@ -1,24 +0,0 @@
-use crate::fs::{
- devpts::DevPts,
- fs_resolver::{FsPath, FsResolver},
- utils::{InodeMode, InodeType},
-};
-use crate::prelude::*;
-
-pub fn init() -> Result<()> {
- let fs = FsResolver::new();
-
- let dev = fs.lookup(&FsPath::try_from("/dev")?)?;
- // Create the "pts" directory and mount devpts on it.
- let devpts = dev.create("pts", InodeType::Dir, InodeMode::from_bits_truncate(0o755))?;
- devpts.mount(DevPts::new())?;
-
- // Create the "ptmx" symlink.
- let ptmx = dev.create(
- "ptmx",
- InodeType::SymLink,
- InodeMode::from_bits_truncate(0o777),
- )?;
- ptmx.write_link("pts/ptmx")?;
- Ok(())
-}
diff --git a/services/libs/jinux-std/src/device/pty.rs /dev/null
--- a/services/libs/jinux-std/src/device/pty.rs
+++ /dev/null
@@ -1,24 +0,0 @@
-use crate::fs::{
- devpts::DevPts,
- fs_resolver::{FsPath, FsResolver},
- utils::{InodeMode, InodeType},
-};
-use crate::prelude::*;
-
-pub fn init() -> Result<()> {
- let fs = FsResolver::new();
-
- let dev = fs.lookup(&FsPath::try_from("/dev")?)?;
- // Create the "pts" directory and mount devpts on it.
- let devpts = dev.create("pts", InodeType::Dir, InodeMode::from_bits_truncate(0o755))?;
- devpts.mount(DevPts::new())?;
-
- // Create the "ptmx" symlink.
- let ptmx = dev.create(
- "ptmx",
- InodeType::SymLink,
- InodeMode::from_bits_truncate(0o777),
- )?;
- ptmx.write_link("pts/ptmx")?;
- Ok(())
-}
diff --git /dev/null b/services/libs/jinux-std/src/device/pty/mod.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/device/pty/mod.rs
@@ -0,0 +1,38 @@
+use crate::fs::devpts::DevPts;
+use crate::fs::fs_resolver::{FsPath, FsResolver};
+use crate::fs::utils::{Dentry, Inode, InodeMode, InodeType};
+use crate::prelude::*;
+
+mod pty;
+
+pub use pty::{PtyMaster, PtySlave};
+use spin::Once;
+
+static DEV_PTS: Once<Arc<Dentry>> = Once::new();
+
+pub fn init() -> Result<()> {
+ let fs = FsResolver::new();
+
+ let dev = fs.lookup(&FsPath::try_from("/dev")?)?;
+ // Create the "pts" directory and mount devpts on it.
+ let devpts = dev.create("pts", InodeType::Dir, InodeMode::from_bits_truncate(0o755))?;
+ devpts.mount(DevPts::new())?;
+
+ DEV_PTS.call_once(|| devpts);
+
+ // Create the "ptmx" symlink.
+ let ptmx = dev.create(
+ "ptmx",
+ InodeType::SymLink,
+ InodeMode::from_bits_truncate(0o777),
+ )?;
+ ptmx.write_link("pts/ptmx")?;
+ Ok(())
+}
+
+pub fn new_pty_pair(index: u32, ptmx: Arc<dyn Inode>) -> Result<(Arc<PtyMaster>, Arc<PtySlave>)> {
+ debug!("pty index = {}", index);
+ let master = Arc::new(PtyMaster::new(ptmx, index));
+ let slave = Arc::new(PtySlave::new(master.clone()));
+ Ok((master, slave))
+}
diff --git /dev/null b/services/libs/jinux-std/src/device/pty/mod.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/device/pty/mod.rs
@@ -0,0 +1,38 @@
+use crate::fs::devpts::DevPts;
+use crate::fs::fs_resolver::{FsPath, FsResolver};
+use crate::fs::utils::{Dentry, Inode, InodeMode, InodeType};
+use crate::prelude::*;
+
+mod pty;
+
+pub use pty::{PtyMaster, PtySlave};
+use spin::Once;
+
+static DEV_PTS: Once<Arc<Dentry>> = Once::new();
+
+pub fn init() -> Result<()> {
+ let fs = FsResolver::new();
+
+ let dev = fs.lookup(&FsPath::try_from("/dev")?)?;
+ // Create the "pts" directory and mount devpts on it.
+ let devpts = dev.create("pts", InodeType::Dir, InodeMode::from_bits_truncate(0o755))?;
+ devpts.mount(DevPts::new())?;
+
+ DEV_PTS.call_once(|| devpts);
+
+ // Create the "ptmx" symlink.
+ let ptmx = dev.create(
+ "ptmx",
+ InodeType::SymLink,
+ InodeMode::from_bits_truncate(0o777),
+ )?;
+ ptmx.write_link("pts/ptmx")?;
+ Ok(())
+}
+
+pub fn new_pty_pair(index: u32, ptmx: Arc<dyn Inode>) -> Result<(Arc<PtyMaster>, Arc<PtySlave>)> {
+ debug!("pty index = {}", index);
+ let master = Arc::new(PtyMaster::new(ptmx, index));
+ let slave = Arc::new(PtySlave::new(master.clone()));
+ Ok((master, slave))
+}
diff --git /dev/null b/services/libs/jinux-std/src/device/pty/pty.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/device/pty/pty.rs
@@ -0,0 +1,312 @@
+use alloc::format;
+use ringbuf::{ring_buffer::RbBase, HeapRb, Rb};
+
+use crate::device::tty::line_discipline::LineDiscipline;
+use crate::fs::device::{Device, DeviceId, DeviceType};
+use crate::fs::file_handle::FileLike;
+use crate::fs::fs_resolver::FsPath;
+use crate::fs::utils::{AccessMode, Inode, InodeMode, IoEvents, IoctlCmd, Pollee, Poller};
+use crate::prelude::*;
+use crate::util::{read_val_from_user, write_val_to_user};
+
+const PTS_DIR: &str = "/dev/pts";
+const BUFFER_CAPACITY: usize = 4096;
+
+/// Pesudo terminal master.
+/// Internally, it has two buffers.
+/// One is inside ldisc, which is written by master and read by slave,
+/// the other is a ring buffer, which is written by slave and read by master.
+pub struct PtyMaster {
+ ptmx: Arc<dyn Inode>,
+ index: u32,
+ output: LineDiscipline,
+ input: SpinLock<HeapRb<u8>>,
+ /// The state of input buffer
+ pollee: Pollee,
+}
+
+impl PtyMaster {
+ pub fn new(ptmx: Arc<dyn Inode>, index: u32) -> Self {
+ Self {
+ ptmx,
+ index,
+ output: LineDiscipline::new(),
+ input: SpinLock::new(HeapRb::new(BUFFER_CAPACITY)),
+ pollee: Pollee::new(IoEvents::OUT),
+ }
+ }
+
+ pub fn index(&self) -> u32 {
+ self.index
+ }
+
+ pub fn ptmx(&self) -> &Arc<dyn Inode> {
+ &self.ptmx
+ }
+
+ pub(super) fn slave_push_byte(&self, byte: u8) {
+ let mut input = self.input.lock_irq_disabled();
+ input.push_overwrite(byte);
+ self.update_state(&input);
+ }
+
+ pub(super) fn slave_read(&self, buf: &mut [u8]) -> Result<usize> {
+ self.output.read(buf)
+ }
+
+ pub(super) fn slave_poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ let mut poll_status = IoEvents::empty();
+
+ let poll_in_mask = mask & IoEvents::IN;
+ if !poll_in_mask.is_empty() {
+ let poll_in_status = self.output.poll(poll_in_mask, poller);
+ poll_status |= poll_in_status;
+ }
+
+ let poll_out_mask = mask & IoEvents::OUT;
+ if !poll_out_mask.is_empty() {
+ let poll_out_status = self.pollee.poll(poll_out_mask, poller);
+ poll_status |= poll_out_status;
+ }
+
+ poll_status
+ }
+
+ pub(super) fn slave_buf_len(&self) -> usize {
+ self.output.buffer_len()
+ }
+
+ fn update_state(&self, buf: &HeapRb<u8>) {
+ if buf.is_empty() {
+ self.pollee.del_events(IoEvents::IN)
+ } else {
+ self.pollee.add_events(IoEvents::IN);
+ }
+ }
+}
+
+impl FileLike for PtyMaster {
+ fn read(&self, buf: &mut [u8]) -> Result<usize> {
+ // TODO: deal with nonblocking read
+ if buf.len() == 0 {
+ return Ok(0);
+ }
+
+ let poller = Poller::new();
+ loop {
+ let mut input = self.input.lock_irq_disabled();
+
+ if input.is_empty() {
+ let events = self.pollee.poll(IoEvents::IN, Some(&poller));
+
+ if events.contains(IoEvents::ERR) {
+ return_errno_with_message!(Errno::EACCES, "unexpected err");
+ }
+
+ if events.is_empty() {
+ drop(input);
+ poller.wait();
+ }
+ continue;
+ }
+
+ let read_len = input.len().min(buf.len());
+ input.pop_slice(&mut buf[..read_len]);
+ self.update_state(&input);
+ return Ok(read_len);
+ }
+ }
+
+ fn write(&self, buf: &[u8]) -> Result<usize> {
+ let mut input = self.input.lock();
+
+ for character in buf {
+ self.output.push_char(*character, |content| {
+ for byte in content.as_bytes() {
+ input.push_overwrite(*byte);
+ }
+ });
+ }
+
+ self.update_state(&input);
+ Ok(buf.len())
+ }
+
+ fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
+ match cmd {
+ IoctlCmd::TCGETS => {
+ let termios = self.output.termios();
+ write_val_to_user(arg, &termios)?;
+ Ok(0)
+ }
+ IoctlCmd::TCSETS => {
+ let termios = read_val_from_user(arg)?;
+ self.output.set_termios(termios);
+ Ok(0)
+ }
+ IoctlCmd::TIOCSPTLCK => {
+ // TODO: lock/unlock pty
+ Ok(0)
+ }
+ IoctlCmd::TIOCGPTN => {
+ let idx = self.index();
+ write_val_to_user(arg, &idx)?;
+ Ok(0)
+ }
+ IoctlCmd::TIOCGPTPEER => {
+ let current = current!();
+
+ // TODO: deal with open options
+ let slave = {
+ let slave_name = {
+ let devpts_path = super::DEV_PTS.get().unwrap().abs_path();
+ format!("{}/{}", devpts_path, self.index())
+ };
+
+ let fs_path = FsPath::try_from(slave_name.as_str())?;
+
+ let inode_handle = {
+ let fs = current.fs().read();
+ let flags = AccessMode::O_RDWR as u32;
+ let mode = (InodeMode::S_IRUSR | InodeMode::S_IWUSR).bits();
+ fs.open(&fs_path, flags, mode)?
+ };
+ Arc::new(inode_handle)
+ };
+
+ let fd = {
+ let mut file_table = current.file_table().lock();
+ file_table.insert(slave)
+ };
+ Ok(fd)
+ }
+ IoctlCmd::TIOCGWINSZ => {
+ let winsize = self.output.window_size();
+ write_val_to_user(arg, &winsize)?;
+ Ok(0)
+ }
+ IoctlCmd::TIOCSWINSZ => {
+ let winsize = read_val_from_user(arg)?;
+ self.output.set_window_size(winsize);
+ Ok(0)
+ }
+ IoctlCmd::TIOCSCTTY => {
+ // TODO: reimplement when adding session.
+ let foreground = {
+ let current = current!();
+ let process_group = current.process_group().lock();
+ process_group.clone()
+ };
+ self.output.set_fg(foreground);
+ Ok(0)
+ }
+ IoctlCmd::TIOCGPGRP => {
+ let Some(fg_pgid) = self.output.fg_pgid() else {
+ return_errno_with_message!(
+ Errno::ESRCH,
+ "the foreground process group does not exist"
+ );
+ };
+ write_val_to_user(arg, &fg_pgid)?;
+ Ok(0)
+ }
+ IoctlCmd::TIOCNOTTY => {
+ // TODO: reimplement when adding session.
+ self.output.set_fg(Weak::new());
+ Ok(0)
+ }
+ IoctlCmd::FIONREAD => {
+ let len = self.input.lock().len() as i32;
+ write_val_to_user(arg, &len)?;
+ Ok(0)
+ }
+ _ => Ok(0),
+ }
+ }
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ let mut poll_status = IoEvents::empty();
+
+ let poll_in_mask = mask & IoEvents::IN;
+ if !poll_in_mask.is_empty() {
+ let poll_in_status = self.pollee.poll(poll_in_mask, poller);
+ poll_status |= poll_in_status;
+ }
+
+ let poll_out_mask = mask & IoEvents::OUT;
+ if !poll_out_mask.is_empty() {
+ let poll_out_status = self.output.poll(poll_out_mask, poller);
+ poll_status |= poll_out_status;
+ }
+
+ poll_status
+ }
+}
+
+pub struct PtySlave(Arc<PtyMaster>);
+
+impl PtySlave {
+ pub fn new(master: Arc<PtyMaster>) -> Self {
+ PtySlave(master)
+ }
+
+ pub fn index(&self) -> u32 {
+ self.0.index()
+ }
+}
+
+impl Device for PtySlave {
+ fn type_(&self) -> DeviceType {
+ DeviceType::CharDevice
+ }
+
+ fn id(&self) -> crate::fs::device::DeviceId {
+ DeviceId::new(88, self.index() as u32)
+ }
+
+ fn read(&self, buf: &mut [u8]) -> Result<usize> {
+ self.0.slave_read(buf)
+ }
+
+ fn write(&self, buf: &[u8]) -> Result<usize> {
+ for ch in buf {
+ // do we need to add '\r' here?
+ if *ch == b'\n' {
+ self.0.slave_push_byte(b'\r');
+ self.0.slave_push_byte(b'\n');
+ } else {
+ self.0.slave_push_byte(*ch);
+ }
+ }
+ Ok(buf.len())
+ }
+
+ fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
+ match cmd {
+ IoctlCmd::TCGETS
+ | IoctlCmd::TCSETS
+ | IoctlCmd::TIOCGPGRP
+ | IoctlCmd::TIOCGPTN
+ | IoctlCmd::TIOCGWINSZ
+ | IoctlCmd::TIOCSWINSZ => self.0.ioctl(cmd, arg),
+ IoctlCmd::TIOCSCTTY => {
+ // TODO:
+ Ok(0)
+ }
+ IoctlCmd::TIOCNOTTY => {
+ // TODO:
+ Ok(0)
+ }
+ IoctlCmd::FIONREAD => {
+ let buffer_len = self.0.slave_buf_len() as i32;
+ write_val_to_user(arg, &buffer_len)?;
+ Ok(0)
+ }
+ _ => Ok(0),
+ }
+ }
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ self.0.slave_poll(mask, poller)
+ }
+}
diff --git /dev/null b/services/libs/jinux-std/src/device/pty/pty.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/device/pty/pty.rs
@@ -0,0 +1,312 @@
+use alloc::format;
+use ringbuf::{ring_buffer::RbBase, HeapRb, Rb};
+
+use crate::device::tty::line_discipline::LineDiscipline;
+use crate::fs::device::{Device, DeviceId, DeviceType};
+use crate::fs::file_handle::FileLike;
+use crate::fs::fs_resolver::FsPath;
+use crate::fs::utils::{AccessMode, Inode, InodeMode, IoEvents, IoctlCmd, Pollee, Poller};
+use crate::prelude::*;
+use crate::util::{read_val_from_user, write_val_to_user};
+
+const PTS_DIR: &str = "/dev/pts";
+const BUFFER_CAPACITY: usize = 4096;
+
+/// Pesudo terminal master.
+/// Internally, it has two buffers.
+/// One is inside ldisc, which is written by master and read by slave,
+/// the other is a ring buffer, which is written by slave and read by master.
+pub struct PtyMaster {
+ ptmx: Arc<dyn Inode>,
+ index: u32,
+ output: LineDiscipline,
+ input: SpinLock<HeapRb<u8>>,
+ /// The state of input buffer
+ pollee: Pollee,
+}
+
+impl PtyMaster {
+ pub fn new(ptmx: Arc<dyn Inode>, index: u32) -> Self {
+ Self {
+ ptmx,
+ index,
+ output: LineDiscipline::new(),
+ input: SpinLock::new(HeapRb::new(BUFFER_CAPACITY)),
+ pollee: Pollee::new(IoEvents::OUT),
+ }
+ }
+
+ pub fn index(&self) -> u32 {
+ self.index
+ }
+
+ pub fn ptmx(&self) -> &Arc<dyn Inode> {
+ &self.ptmx
+ }
+
+ pub(super) fn slave_push_byte(&self, byte: u8) {
+ let mut input = self.input.lock_irq_disabled();
+ input.push_overwrite(byte);
+ self.update_state(&input);
+ }
+
+ pub(super) fn slave_read(&self, buf: &mut [u8]) -> Result<usize> {
+ self.output.read(buf)
+ }
+
+ pub(super) fn slave_poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ let mut poll_status = IoEvents::empty();
+
+ let poll_in_mask = mask & IoEvents::IN;
+ if !poll_in_mask.is_empty() {
+ let poll_in_status = self.output.poll(poll_in_mask, poller);
+ poll_status |= poll_in_status;
+ }
+
+ let poll_out_mask = mask & IoEvents::OUT;
+ if !poll_out_mask.is_empty() {
+ let poll_out_status = self.pollee.poll(poll_out_mask, poller);
+ poll_status |= poll_out_status;
+ }
+
+ poll_status
+ }
+
+ pub(super) fn slave_buf_len(&self) -> usize {
+ self.output.buffer_len()
+ }
+
+ fn update_state(&self, buf: &HeapRb<u8>) {
+ if buf.is_empty() {
+ self.pollee.del_events(IoEvents::IN)
+ } else {
+ self.pollee.add_events(IoEvents::IN);
+ }
+ }
+}
+
+impl FileLike for PtyMaster {
+ fn read(&self, buf: &mut [u8]) -> Result<usize> {
+ // TODO: deal with nonblocking read
+ if buf.len() == 0 {
+ return Ok(0);
+ }
+
+ let poller = Poller::new();
+ loop {
+ let mut input = self.input.lock_irq_disabled();
+
+ if input.is_empty() {
+ let events = self.pollee.poll(IoEvents::IN, Some(&poller));
+
+ if events.contains(IoEvents::ERR) {
+ return_errno_with_message!(Errno::EACCES, "unexpected err");
+ }
+
+ if events.is_empty() {
+ drop(input);
+ poller.wait();
+ }
+ continue;
+ }
+
+ let read_len = input.len().min(buf.len());
+ input.pop_slice(&mut buf[..read_len]);
+ self.update_state(&input);
+ return Ok(read_len);
+ }
+ }
+
+ fn write(&self, buf: &[u8]) -> Result<usize> {
+ let mut input = self.input.lock();
+
+ for character in buf {
+ self.output.push_char(*character, |content| {
+ for byte in content.as_bytes() {
+ input.push_overwrite(*byte);
+ }
+ });
+ }
+
+ self.update_state(&input);
+ Ok(buf.len())
+ }
+
+ fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
+ match cmd {
+ IoctlCmd::TCGETS => {
+ let termios = self.output.termios();
+ write_val_to_user(arg, &termios)?;
+ Ok(0)
+ }
+ IoctlCmd::TCSETS => {
+ let termios = read_val_from_user(arg)?;
+ self.output.set_termios(termios);
+ Ok(0)
+ }
+ IoctlCmd::TIOCSPTLCK => {
+ // TODO: lock/unlock pty
+ Ok(0)
+ }
+ IoctlCmd::TIOCGPTN => {
+ let idx = self.index();
+ write_val_to_user(arg, &idx)?;
+ Ok(0)
+ }
+ IoctlCmd::TIOCGPTPEER => {
+ let current = current!();
+
+ // TODO: deal with open options
+ let slave = {
+ let slave_name = {
+ let devpts_path = super::DEV_PTS.get().unwrap().abs_path();
+ format!("{}/{}", devpts_path, self.index())
+ };
+
+ let fs_path = FsPath::try_from(slave_name.as_str())?;
+
+ let inode_handle = {
+ let fs = current.fs().read();
+ let flags = AccessMode::O_RDWR as u32;
+ let mode = (InodeMode::S_IRUSR | InodeMode::S_IWUSR).bits();
+ fs.open(&fs_path, flags, mode)?
+ };
+ Arc::new(inode_handle)
+ };
+
+ let fd = {
+ let mut file_table = current.file_table().lock();
+ file_table.insert(slave)
+ };
+ Ok(fd)
+ }
+ IoctlCmd::TIOCGWINSZ => {
+ let winsize = self.output.window_size();
+ write_val_to_user(arg, &winsize)?;
+ Ok(0)
+ }
+ IoctlCmd::TIOCSWINSZ => {
+ let winsize = read_val_from_user(arg)?;
+ self.output.set_window_size(winsize);
+ Ok(0)
+ }
+ IoctlCmd::TIOCSCTTY => {
+ // TODO: reimplement when adding session.
+ let foreground = {
+ let current = current!();
+ let process_group = current.process_group().lock();
+ process_group.clone()
+ };
+ self.output.set_fg(foreground);
+ Ok(0)
+ }
+ IoctlCmd::TIOCGPGRP => {
+ let Some(fg_pgid) = self.output.fg_pgid() else {
+ return_errno_with_message!(
+ Errno::ESRCH,
+ "the foreground process group does not exist"
+ );
+ };
+ write_val_to_user(arg, &fg_pgid)?;
+ Ok(0)
+ }
+ IoctlCmd::TIOCNOTTY => {
+ // TODO: reimplement when adding session.
+ self.output.set_fg(Weak::new());
+ Ok(0)
+ }
+ IoctlCmd::FIONREAD => {
+ let len = self.input.lock().len() as i32;
+ write_val_to_user(arg, &len)?;
+ Ok(0)
+ }
+ _ => Ok(0),
+ }
+ }
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ let mut poll_status = IoEvents::empty();
+
+ let poll_in_mask = mask & IoEvents::IN;
+ if !poll_in_mask.is_empty() {
+ let poll_in_status = self.pollee.poll(poll_in_mask, poller);
+ poll_status |= poll_in_status;
+ }
+
+ let poll_out_mask = mask & IoEvents::OUT;
+ if !poll_out_mask.is_empty() {
+ let poll_out_status = self.output.poll(poll_out_mask, poller);
+ poll_status |= poll_out_status;
+ }
+
+ poll_status
+ }
+}
+
+pub struct PtySlave(Arc<PtyMaster>);
+
+impl PtySlave {
+ pub fn new(master: Arc<PtyMaster>) -> Self {
+ PtySlave(master)
+ }
+
+ pub fn index(&self) -> u32 {
+ self.0.index()
+ }
+}
+
+impl Device for PtySlave {
+ fn type_(&self) -> DeviceType {
+ DeviceType::CharDevice
+ }
+
+ fn id(&self) -> crate::fs::device::DeviceId {
+ DeviceId::new(88, self.index() as u32)
+ }
+
+ fn read(&self, buf: &mut [u8]) -> Result<usize> {
+ self.0.slave_read(buf)
+ }
+
+ fn write(&self, buf: &[u8]) -> Result<usize> {
+ for ch in buf {
+ // do we need to add '\r' here?
+ if *ch == b'\n' {
+ self.0.slave_push_byte(b'\r');
+ self.0.slave_push_byte(b'\n');
+ } else {
+ self.0.slave_push_byte(*ch);
+ }
+ }
+ Ok(buf.len())
+ }
+
+ fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
+ match cmd {
+ IoctlCmd::TCGETS
+ | IoctlCmd::TCSETS
+ | IoctlCmd::TIOCGPGRP
+ | IoctlCmd::TIOCGPTN
+ | IoctlCmd::TIOCGWINSZ
+ | IoctlCmd::TIOCSWINSZ => self.0.ioctl(cmd, arg),
+ IoctlCmd::TIOCSCTTY => {
+ // TODO:
+ Ok(0)
+ }
+ IoctlCmd::TIOCNOTTY => {
+ // TODO:
+ Ok(0)
+ }
+ IoctlCmd::FIONREAD => {
+ let buffer_len = self.0.slave_buf_len() as i32;
+ write_val_to_user(arg, &buffer_len)?;
+ Ok(0)
+ }
+ _ => Ok(0),
+ }
+ }
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ self.0.slave_poll(mask, poller)
+ }
+}
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -3,13 +3,13 @@ use crate::process::process_group::ProcessGroup;
use crate::process::signal::constants::{SIGINT, SIGQUIT};
use crate::{
prelude::*,
- process::{process_table, signal::signals::kernel::KernelSignal, Pgid},
+ process::{signal::signals::kernel::KernelSignal, Pgid},
};
use alloc::format;
use jinux_frame::trap::disable_local;
use ringbuf::{ring_buffer::RbBase, Rb, StaticRb};
-use super::termio::{KernelTermios, CC_C_CHAR};
+use super::termio::{KernelTermios, WinSize, CC_C_CHAR};
// This implementation refers the implementation of linux
// https://elixir.bootlin.com/linux/latest/source/include/linux/tty_ldisc.h
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -25,6 +25,8 @@ pub struct LineDiscipline {
foreground: SpinLock<Weak<ProcessGroup>>,
/// termios
termios: SpinLock<KernelTermios>,
+ /// Windows size,
+ winsize: SpinLock<WinSize>,
/// Pollee
pollee: Pollee,
}
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -25,6 +25,8 @@ pub struct LineDiscipline {
foreground: SpinLock<Weak<ProcessGroup>>,
/// termios
termios: SpinLock<KernelTermios>,
+ /// Windows size,
+ winsize: SpinLock<WinSize>,
/// Pollee
pollee: Pollee,
}
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -72,12 +74,13 @@ impl LineDiscipline {
read_buffer: SpinLock::new(StaticRb::default()),
foreground: SpinLock::new(Weak::new()),
termios: SpinLock::new(KernelTermios::default()),
+ winsize: SpinLock::new(WinSize::default()),
pollee: Pollee::new(IoEvents::empty()),
}
}
/// Push char to line discipline.
- pub fn push_char(&self, mut item: u8, echo_callback: fn(&str)) {
+ pub fn push_char<F: FnMut(&str)>(&self, mut item: u8, echo_callback: F) {
let termios = self.termios.lock_irq_disabled();
if termios.contains_icrnl() && item == b'\r' {
item = b'\n'
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -72,12 +74,13 @@ impl LineDiscipline {
read_buffer: SpinLock::new(StaticRb::default()),
foreground: SpinLock::new(Weak::new()),
termios: SpinLock::new(KernelTermios::default()),
+ winsize: SpinLock::new(WinSize::default()),
pollee: Pollee::new(IoEvents::empty()),
}
}
/// Push char to line discipline.
- pub fn push_char(&self, mut item: u8, echo_callback: fn(&str)) {
+ pub fn push_char<F: FnMut(&str)>(&self, mut item: u8, echo_callback: F) {
let termios = self.termios.lock_irq_disabled();
if termios.contains_icrnl() && item == b'\r' {
item = b'\n'
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -162,7 +165,7 @@ impl LineDiscipline {
}
// TODO: respect output flags
- fn output_char(&self, item: u8, termios: &KernelTermios, echo_callback: fn(&str)) {
+ fn output_char<F: FnMut(&str)>(&self, item: u8, termios: &KernelTermios, mut echo_callback: F) {
match item {
b'\n' => echo_callback("\n"),
b'\r' => echo_callback("\r\n"),
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -162,7 +165,7 @@ impl LineDiscipline {
}
// TODO: respect output flags
- fn output_char(&self, item: u8, termios: &KernelTermios, echo_callback: fn(&str)) {
+ fn output_char<F: FnMut(&str)>(&self, item: u8, termios: &KernelTermios, mut echo_callback: F) {
match item {
b'\n' => echo_callback("\n"),
b'\r' => echo_callback("\r\n"),
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -350,6 +353,18 @@ impl LineDiscipline {
self.current_line.lock().drain();
let _: Vec<_> = self.read_buffer.lock().pop_iter().collect();
}
+
+ pub fn buffer_len(&self) -> usize {
+ self.read_buffer.lock().len()
+ }
+
+ pub fn window_size(&self) -> WinSize {
+ self.winsize.lock().clone()
+ }
+
+ pub fn set_window_size(&self, winsize: WinSize) {
+ *self.winsize.lock() = winsize;
+ }
}
fn meet_new_line(item: u8, termios: &KernelTermios) -> bool {
diff --git a/services/libs/jinux-std/src/device/tty/line_discipline.rs b/services/libs/jinux-std/src/device/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/device/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/device/tty/line_discipline.rs
@@ -350,6 +353,18 @@ impl LineDiscipline {
self.current_line.lock().drain();
let _: Vec<_> = self.read_buffer.lock().pop_iter().collect();
}
+
+ pub fn buffer_len(&self) -> usize {
+ self.read_buffer.lock().len()
+ }
+
+ pub fn window_size(&self) -> WinSize {
+ self.winsize.lock().clone()
+ }
+
+ pub fn set_window_size(&self, winsize: WinSize) {
+ *self.winsize.lock() = winsize;
+ }
}
fn meet_new_line(item: u8, termios: &KernelTermios) -> bool {
diff --git a/services/libs/jinux-std/src/device/tty/mod.rs b/services/libs/jinux-std/src/device/tty/mod.rs
--- a/services/libs/jinux-std/src/device/tty/mod.rs
+++ b/services/libs/jinux-std/src/device/tty/mod.rs
@@ -6,7 +6,7 @@ use super::*;
use crate::fs::utils::{IoEvents, IoctlCmd, Poller};
use crate::prelude::*;
use crate::process::process_group::ProcessGroup;
-use crate::process::{process_table, Pgid};
+use crate::process::process_table;
use crate::util::{read_val_from_user, write_val_to_user};
pub mod driver;
diff --git a/services/libs/jinux-std/src/device/tty/mod.rs b/services/libs/jinux-std/src/device/tty/mod.rs
--- a/services/libs/jinux-std/src/device/tty/mod.rs
+++ b/services/libs/jinux-std/src/device/tty/mod.rs
@@ -6,7 +6,7 @@ use super::*;
use crate::fs::utils::{IoEvents, IoctlCmd, Poller};
use crate::prelude::*;
use crate::process::process_group::ProcessGroup;
-use crate::process::{process_table, Pgid};
+use crate::process::process_table;
use crate::util::{read_val_from_user, write_val_to_user};
pub mod driver;
diff --git a/services/libs/jinux-std/src/device/tty/mod.rs b/services/libs/jinux-std/src/device/tty/mod.rs
--- a/services/libs/jinux-std/src/device/tty/mod.rs
+++ b/services/libs/jinux-std/src/device/tty/mod.rs
@@ -130,7 +130,13 @@ impl Device for Tty {
Ok(0)
}
IoctlCmd::TIOCGWINSZ => {
- // TODO:get window size
+ let winsize = self.ldisc.window_size();
+ write_val_to_user(arg, &winsize)?;
+ Ok(0)
+ }
+ IoctlCmd::TIOCSWINSZ => {
+ let winsize = read_val_from_user(arg)?;
+ self.ldisc.set_window_size(winsize);
Ok(0)
}
_ => todo!(),
diff --git a/services/libs/jinux-std/src/device/tty/mod.rs b/services/libs/jinux-std/src/device/tty/mod.rs
--- a/services/libs/jinux-std/src/device/tty/mod.rs
+++ b/services/libs/jinux-std/src/device/tty/mod.rs
@@ -130,7 +130,13 @@ impl Device for Tty {
Ok(0)
}
IoctlCmd::TIOCGWINSZ => {
- // TODO:get window size
+ let winsize = self.ldisc.window_size();
+ write_val_to_user(arg, &winsize)?;
+ Ok(0)
+ }
+ IoctlCmd::TIOCSWINSZ => {
+ let winsize = read_val_from_user(arg)?;
+ self.ldisc.set_window_size(winsize);
Ok(0)
}
_ => todo!(),
diff --git a/services/libs/jinux-std/src/device/tty/termio.rs b/services/libs/jinux-std/src/device/tty/termio.rs
--- a/services/libs/jinux-std/src/device/tty/termio.rs
+++ b/services/libs/jinux-std/src/device/tty/termio.rs
@@ -14,22 +14,28 @@ bitflags! {
#[repr(C)]
pub struct C_IFLAGS: u32 {
// https://elixir.bootlin.com/linux/v6.0.9/source/include/uapi/asm-generic/termbits-common.h
- const IGNBRK = 0x001; /* Ignore break condition */
- const BRKINT = 0x002; /* Signal interrupt on break */
- const IGNPAR = 0x004; /* Ignore characters with parity errors */
- const PARMRK = 0x008; /* Mark parity and framing errors */
- const INPCK = 0x010; /* Enable input parity check */
- const ISTRIP = 0x020; /* Strip 8th bit off characters */
- const INLCR = 0x040; /* Map NL to CR on input */
- const IGNCR = 0x080; /* Ignore CR */
- const ICRNL = 0x100; /* Map CR to NL on input */
- const IXANY = 0x800; /* Any character will restart after stop */
+ const IGNBRK = 0x001; /* Ignore break condition */
+ const BRKINT = 0x002; /* Signal interrupt on break */
+ const IGNPAR = 0x004; /* Ignore characters with parity errors */
+ const PARMRK = 0x008; /* Mark parity and framing errors */
+ const INPCK = 0x010; /* Enable input parity check */
+ const ISTRIP = 0x020; /* Strip 8th bit off characters */
+ const INLCR = 0x040; /* Map NL to CR on input */
+ const IGNCR = 0x080; /* Ignore CR */
+ const ICRNL = 0x100; /* Map CR to NL on input */
+ const IXANY = 0x800; /* Any character will restart after stop */
// https://elixir.bootlin.com/linux/v6.0.9/source/include/uapi/asm-generic/termbits.h
- const IUCLC = 0x0200;
- const IXON = 0x0400;
- const IXOFF = 0x1000;
- const IMAXBEL = 0x2000;
- const IUTF8 = 0x4000;
+ const IUCLC = 0x0200;
+ const IXON = 0x0400;
+ const IXOFF = 0x1000;
+ const IMAXBEL = 0x2000;
+ const IUTF8 = 0x4000;
+ }
+}
+
+impl Default for C_IFLAGS {
+ fn default() -> Self {
+ C_IFLAGS::ICRNL | C_IFLAGS::IXON
}
}
diff --git a/services/libs/jinux-std/src/device/tty/termio.rs b/services/libs/jinux-std/src/device/tty/termio.rs
--- a/services/libs/jinux-std/src/device/tty/termio.rs
+++ b/services/libs/jinux-std/src/device/tty/termio.rs
@@ -14,22 +14,28 @@ bitflags! {
#[repr(C)]
pub struct C_IFLAGS: u32 {
// https://elixir.bootlin.com/linux/v6.0.9/source/include/uapi/asm-generic/termbits-common.h
- const IGNBRK = 0x001; /* Ignore break condition */
- const BRKINT = 0x002; /* Signal interrupt on break */
- const IGNPAR = 0x004; /* Ignore characters with parity errors */
- const PARMRK = 0x008; /* Mark parity and framing errors */
- const INPCK = 0x010; /* Enable input parity check */
- const ISTRIP = 0x020; /* Strip 8th bit off characters */
- const INLCR = 0x040; /* Map NL to CR on input */
- const IGNCR = 0x080; /* Ignore CR */
- const ICRNL = 0x100; /* Map CR to NL on input */
- const IXANY = 0x800; /* Any character will restart after stop */
+ const IGNBRK = 0x001; /* Ignore break condition */
+ const BRKINT = 0x002; /* Signal interrupt on break */
+ const IGNPAR = 0x004; /* Ignore characters with parity errors */
+ const PARMRK = 0x008; /* Mark parity and framing errors */
+ const INPCK = 0x010; /* Enable input parity check */
+ const ISTRIP = 0x020; /* Strip 8th bit off characters */
+ const INLCR = 0x040; /* Map NL to CR on input */
+ const IGNCR = 0x080; /* Ignore CR */
+ const ICRNL = 0x100; /* Map CR to NL on input */
+ const IXANY = 0x800; /* Any character will restart after stop */
// https://elixir.bootlin.com/linux/v6.0.9/source/include/uapi/asm-generic/termbits.h
- const IUCLC = 0x0200;
- const IXON = 0x0400;
- const IXOFF = 0x1000;
- const IMAXBEL = 0x2000;
- const IUTF8 = 0x4000;
+ const IUCLC = 0x0200;
+ const IXON = 0x0400;
+ const IXOFF = 0x1000;
+ const IMAXBEL = 0x2000;
+ const IUTF8 = 0x4000;
+ }
+}
+
+impl Default for C_IFLAGS {
+ fn default() -> Self {
+ C_IFLAGS::ICRNL | C_IFLAGS::IXON
}
}
diff --git a/services/libs/jinux-std/src/device/tty/termio.rs b/services/libs/jinux-std/src/device/tty/termio.rs
--- a/services/libs/jinux-std/src/device/tty/termio.rs
+++ b/services/libs/jinux-std/src/device/tty/termio.rs
@@ -37,18 +43,68 @@ bitflags! {
#[repr(C)]
#[derive(Pod)]
pub struct C_OFLAGS: u32 {
- const OPOST = 0x01; /* Perform output processing */
- const OCRNL = 0x08;
- const ONOCR = 0x10;
- const ONLRET= 0x20;
- const OFILL = 0x40;
- const OFDEL = 0x80;
+ const OPOST = 1 << 0; /* Perform output processing */
+ const OLCUC = 1 << 1;
+ const ONLCR = 1 << 2;
+ const OCRNL = 1 << 3;
+ const ONOCR = 1 << 4;
+ const ONLRET = 1 << 5;
+ const OFILL = 1 << 6;
+ const OFDEL = 1 << 7;
}
}
-#[repr(u32)]
+impl Default for C_OFLAGS {
+ fn default() -> Self {
+ C_OFLAGS::OPOST | C_OFLAGS::ONLCR
+ }
+}
+
+#[repr(C)]
#[derive(Debug, Clone, Copy, Pod)]
-pub enum C_CFLAGS {
+pub struct C_CFLAGS(u32);
+
+impl Default for C_CFLAGS {
+ fn default() -> Self {
+ let cbaud = C_CFLAGS_BAUD::B38400 as u32;
+ let csize = C_CFLAGS_CSIZE::CS8 as u32;
+ let c_cflags = cbaud | csize | CREAD;
+ Self(c_cflags)
+ }
+}
+
+impl C_CFLAGS {
+ pub fn cbaud(&self) -> Result<C_CFLAGS_BAUD> {
+ let cbaud = self.0 & CBAUD_MASK;
+ Ok(C_CFLAGS_BAUD::try_from(cbaud)?)
+ }
+
+ pub fn csize(&self) -> Result<C_CFLAGS_CSIZE> {
+ let csize = self.0 & CSIZE_MASK;
+ Ok(C_CFLAGS_CSIZE::try_from(csize)?)
+ }
+
+ pub fn cread(&self) -> bool {
+ self.0 & CREAD != 0
+ }
+}
+
+const CREAD: u32 = 0x00000080;
+const CBAUD_MASK: u32 = 0x0000100f;
+const CSIZE_MASK: u32 = 0x00000030;
+
+#[repr(u32)]
+#[derive(Clone, Copy, TryFromInt)]
+pub enum C_CFLAGS_CSIZE {
+ CS5 = 0x00000000,
+ CS6 = 0x00000010,
+ CS7 = 0x00000020,
+ CS8 = 0x00000030,
+}
+
+#[repr(u32)]
+#[derive(Debug, Clone, Copy, TryFromInt)]
+pub enum C_CFLAGS_BAUD {
B0 = 0x00000000, /* hang up */
B50 = 0x00000001,
B75 = 0x00000002,
diff --git a/services/libs/jinux-std/src/device/tty/termio.rs b/services/libs/jinux-std/src/device/tty/termio.rs
--- a/services/libs/jinux-std/src/device/tty/termio.rs
+++ b/services/libs/jinux-std/src/device/tty/termio.rs
@@ -37,18 +43,68 @@ bitflags! {
#[repr(C)]
#[derive(Pod)]
pub struct C_OFLAGS: u32 {
- const OPOST = 0x01; /* Perform output processing */
- const OCRNL = 0x08;
- const ONOCR = 0x10;
- const ONLRET= 0x20;
- const OFILL = 0x40;
- const OFDEL = 0x80;
+ const OPOST = 1 << 0; /* Perform output processing */
+ const OLCUC = 1 << 1;
+ const ONLCR = 1 << 2;
+ const OCRNL = 1 << 3;
+ const ONOCR = 1 << 4;
+ const ONLRET = 1 << 5;
+ const OFILL = 1 << 6;
+ const OFDEL = 1 << 7;
}
}
-#[repr(u32)]
+impl Default for C_OFLAGS {
+ fn default() -> Self {
+ C_OFLAGS::OPOST | C_OFLAGS::ONLCR
+ }
+}
+
+#[repr(C)]
#[derive(Debug, Clone, Copy, Pod)]
-pub enum C_CFLAGS {
+pub struct C_CFLAGS(u32);
+
+impl Default for C_CFLAGS {
+ fn default() -> Self {
+ let cbaud = C_CFLAGS_BAUD::B38400 as u32;
+ let csize = C_CFLAGS_CSIZE::CS8 as u32;
+ let c_cflags = cbaud | csize | CREAD;
+ Self(c_cflags)
+ }
+}
+
+impl C_CFLAGS {
+ pub fn cbaud(&self) -> Result<C_CFLAGS_BAUD> {
+ let cbaud = self.0 & CBAUD_MASK;
+ Ok(C_CFLAGS_BAUD::try_from(cbaud)?)
+ }
+
+ pub fn csize(&self) -> Result<C_CFLAGS_CSIZE> {
+ let csize = self.0 & CSIZE_MASK;
+ Ok(C_CFLAGS_CSIZE::try_from(csize)?)
+ }
+
+ pub fn cread(&self) -> bool {
+ self.0 & CREAD != 0
+ }
+}
+
+const CREAD: u32 = 0x00000080;
+const CBAUD_MASK: u32 = 0x0000100f;
+const CSIZE_MASK: u32 = 0x00000030;
+
+#[repr(u32)]
+#[derive(Clone, Copy, TryFromInt)]
+pub enum C_CFLAGS_CSIZE {
+ CS5 = 0x00000000,
+ CS6 = 0x00000010,
+ CS7 = 0x00000020,
+ CS8 = 0x00000030,
+}
+
+#[repr(u32)]
+#[derive(Debug, Clone, Copy, TryFromInt)]
+pub enum C_CFLAGS_BAUD {
B0 = 0x00000000, /* hang up */
B50 = 0x00000001,
B75 = 0x00000002,
diff --git a/services/libs/jinux-std/src/device/tty/termio.rs b/services/libs/jinux-std/src/device/tty/termio.rs
--- a/services/libs/jinux-std/src/device/tty/termio.rs
+++ b/services/libs/jinux-std/src/device/tty/termio.rs
@@ -71,28 +127,41 @@ bitflags! {
#[repr(C)]
#[derive(Pod)]
pub struct C_LFLAGS: u32 {
- const ISIG = 0x00001;
- const ICANON= 0x00002;
- const XCASE = 0x00004;
- const ECHO = 0x00008;
- const ECHOE = 0x00010;
- const ECHOK = 0x00020;
- const ECHONL= 0x00040;
- const NOFLSH= 0x00080;
- const TOSTOP= 0x00100;
- const ECHOCTL= 0x00200;
- const ECHOPRT= 0x00400;
- const ECHOKE= 0x00800;
- const FLUSHO= 0x01000;
- const PENDIN= 0x04000;
- const IEXTEN= 0x08000;
- const EXTPROC= 0x10000;
+ const ISIG = 0x00001;
+ const ICANON = 0x00002;
+ const XCASE = 0x00004;
+ const ECHO = 0x00008;
+ const ECHOE = 0x00010;
+ const ECHOK = 0x00020;
+ const ECHONL = 0x00040;
+ const NOFLSH = 0x00080;
+ const TOSTOP = 0x00100;
+ const ECHOCTL = 0x00200;
+ const ECHOPRT = 0x00400;
+ const ECHOKE = 0x00800;
+ const FLUSHO = 0x01000;
+ const PENDIN = 0x04000;
+ const IEXTEN = 0x08000;
+ const EXTPROC = 0x10000;
+ }
+}
+
+impl Default for C_LFLAGS {
+ fn default() -> Self {
+ C_LFLAGS::ICANON
+ | C_LFLAGS::ECHO
+ | C_LFLAGS::ISIG
+ | C_LFLAGS::ECHOE
+ | C_LFLAGS::ECHOK
+ | C_LFLAGS::ECHOCTL
+ | C_LFLAGS::ECHOKE
+ | C_LFLAGS::IEXTEN
}
}
/* c_cc characters index*/
#[repr(u32)]
-#[derive(Debug, Clone, Copy, Pod)]
+#[derive(Debug, Clone, Copy, TryFromInt)]
pub enum CC_C_CHAR {
VINTR = 0,
VQUIT = 1,
diff --git a/services/libs/jinux-std/src/device/tty/termio.rs b/services/libs/jinux-std/src/device/tty/termio.rs
--- a/services/libs/jinux-std/src/device/tty/termio.rs
+++ b/services/libs/jinux-std/src/device/tty/termio.rs
@@ -71,28 +127,41 @@ bitflags! {
#[repr(C)]
#[derive(Pod)]
pub struct C_LFLAGS: u32 {
- const ISIG = 0x00001;
- const ICANON= 0x00002;
- const XCASE = 0x00004;
- const ECHO = 0x00008;
- const ECHOE = 0x00010;
- const ECHOK = 0x00020;
- const ECHONL= 0x00040;
- const NOFLSH= 0x00080;
- const TOSTOP= 0x00100;
- const ECHOCTL= 0x00200;
- const ECHOPRT= 0x00400;
- const ECHOKE= 0x00800;
- const FLUSHO= 0x01000;
- const PENDIN= 0x04000;
- const IEXTEN= 0x08000;
- const EXTPROC= 0x10000;
+ const ISIG = 0x00001;
+ const ICANON = 0x00002;
+ const XCASE = 0x00004;
+ const ECHO = 0x00008;
+ const ECHOE = 0x00010;
+ const ECHOK = 0x00020;
+ const ECHONL = 0x00040;
+ const NOFLSH = 0x00080;
+ const TOSTOP = 0x00100;
+ const ECHOCTL = 0x00200;
+ const ECHOPRT = 0x00400;
+ const ECHOKE = 0x00800;
+ const FLUSHO = 0x01000;
+ const PENDIN = 0x04000;
+ const IEXTEN = 0x08000;
+ const EXTPROC = 0x10000;
+ }
+}
+
+impl Default for C_LFLAGS {
+ fn default() -> Self {
+ C_LFLAGS::ICANON
+ | C_LFLAGS::ECHO
+ | C_LFLAGS::ISIG
+ | C_LFLAGS::ECHOE
+ | C_LFLAGS::ECHOK
+ | C_LFLAGS::ECHOCTL
+ | C_LFLAGS::ECHOKE
+ | C_LFLAGS::IEXTEN
}
}
/* c_cc characters index*/
#[repr(u32)]
-#[derive(Debug, Clone, Copy, Pod)]
+#[derive(Debug, Clone, Copy, TryFromInt)]
pub enum CC_C_CHAR {
VINTR = 0,
VQUIT = 1,
diff --git a/services/libs/jinux-std/src/device/tty/termio.rs b/services/libs/jinux-std/src/device/tty/termio.rs
--- a/services/libs/jinux-std/src/device/tty/termio.rs
+++ b/services/libs/jinux-std/src/device/tty/termio.rs
@@ -114,61 +183,28 @@ pub enum CC_C_CHAR {
}
impl CC_C_CHAR {
- // The special char is the same as ubuntu
- pub fn char(&self) -> u8 {
+ // The special char is from gvisor
+ pub fn default_char(&self) -> u8 {
match self {
- CC_C_CHAR::VINTR => 3,
- CC_C_CHAR::VQUIT => 28,
- CC_C_CHAR::VERASE => 127,
- CC_C_CHAR::VKILL => 21,
- CC_C_CHAR::VEOF => 4,
- CC_C_CHAR::VTIME => 0,
+ CC_C_CHAR::VINTR => control_character('C'),
+ CC_C_CHAR::VQUIT => control_character('\\'),
+ CC_C_CHAR::VERASE => '\x7f' as u8,
+ CC_C_CHAR::VKILL => control_character('U'),
+ CC_C_CHAR::VEOF => control_character('D'),
+ CC_C_CHAR::VTIME => '\0' as u8,
CC_C_CHAR::VMIN => 1,
- CC_C_CHAR::VSWTC => 0,
- CC_C_CHAR::VSTART => 17,
- CC_C_CHAR::VSTOP => 19,
- CC_C_CHAR::VSUSP => 26,
- CC_C_CHAR::VEOL => 255,
- CC_C_CHAR::VREPRINT => 18,
- CC_C_CHAR::VDISCARD => 15,
- CC_C_CHAR::VWERASE => 23,
- CC_C_CHAR::VLNEXT => 22,
- CC_C_CHAR::VEOL2 => 255,
+ CC_C_CHAR::VSWTC => '\0' as u8,
+ CC_C_CHAR::VSTART => control_character('Q'),
+ CC_C_CHAR::VSTOP => control_character('S'),
+ CC_C_CHAR::VSUSP => control_character('Z'),
+ CC_C_CHAR::VEOL => '\0' as u8,
+ CC_C_CHAR::VREPRINT => control_character('R'),
+ CC_C_CHAR::VDISCARD => control_character('O'),
+ CC_C_CHAR::VWERASE => control_character('W'),
+ CC_C_CHAR::VLNEXT => control_character('V'),
+ CC_C_CHAR::VEOL2 => '\0' as u8,
}
}
-
- pub fn as_usize(&self) -> usize {
- *self as usize
- }
-
- pub fn from_char(item: u8) -> Result<Self> {
- if item == Self::VINTR.char() {
- return Ok(Self::VINTR);
- }
- if item == Self::VQUIT.char() {
- return Ok(Self::VQUIT);
- }
- if item == Self::VINTR.char() {
- return Ok(Self::VINTR);
- }
- if item == Self::VERASE.char() {
- return Ok(Self::VERASE);
- }
- if item == Self::VEOF.char() {
- return Ok(Self::VEOF);
- }
- if item == Self::VSTART.char() {
- return Ok(Self::VSTART);
- }
- if item == Self::VSTOP.char() {
- return Ok(Self::VSTOP);
- }
- if item == Self::VSUSP.char() {
- return Ok(Self::VSUSP);
- }
-
- return_errno_with_message!(Errno::EINVAL, "Not a valid cc_char");
- }
}
#[derive(Debug, Clone, Copy, Pod)]
diff --git a/services/libs/jinux-std/src/device/tty/termio.rs b/services/libs/jinux-std/src/device/tty/termio.rs
--- a/services/libs/jinux-std/src/device/tty/termio.rs
+++ b/services/libs/jinux-std/src/device/tty/termio.rs
@@ -114,61 +183,28 @@ pub enum CC_C_CHAR {
}
impl CC_C_CHAR {
- // The special char is the same as ubuntu
- pub fn char(&self) -> u8 {
+ // The special char is from gvisor
+ pub fn default_char(&self) -> u8 {
match self {
- CC_C_CHAR::VINTR => 3,
- CC_C_CHAR::VQUIT => 28,
- CC_C_CHAR::VERASE => 127,
- CC_C_CHAR::VKILL => 21,
- CC_C_CHAR::VEOF => 4,
- CC_C_CHAR::VTIME => 0,
+ CC_C_CHAR::VINTR => control_character('C'),
+ CC_C_CHAR::VQUIT => control_character('\\'),
+ CC_C_CHAR::VERASE => '\x7f' as u8,
+ CC_C_CHAR::VKILL => control_character('U'),
+ CC_C_CHAR::VEOF => control_character('D'),
+ CC_C_CHAR::VTIME => '\0' as u8,
CC_C_CHAR::VMIN => 1,
- CC_C_CHAR::VSWTC => 0,
- CC_C_CHAR::VSTART => 17,
- CC_C_CHAR::VSTOP => 19,
- CC_C_CHAR::VSUSP => 26,
- CC_C_CHAR::VEOL => 255,
- CC_C_CHAR::VREPRINT => 18,
- CC_C_CHAR::VDISCARD => 15,
- CC_C_CHAR::VWERASE => 23,
- CC_C_CHAR::VLNEXT => 22,
- CC_C_CHAR::VEOL2 => 255,
+ CC_C_CHAR::VSWTC => '\0' as u8,
+ CC_C_CHAR::VSTART => control_character('Q'),
+ CC_C_CHAR::VSTOP => control_character('S'),
+ CC_C_CHAR::VSUSP => control_character('Z'),
+ CC_C_CHAR::VEOL => '\0' as u8,
+ CC_C_CHAR::VREPRINT => control_character('R'),
+ CC_C_CHAR::VDISCARD => control_character('O'),
+ CC_C_CHAR::VWERASE => control_character('W'),
+ CC_C_CHAR::VLNEXT => control_character('V'),
+ CC_C_CHAR::VEOL2 => '\0' as u8,
}
}
-
- pub fn as_usize(&self) -> usize {
- *self as usize
- }
-
- pub fn from_char(item: u8) -> Result<Self> {
- if item == Self::VINTR.char() {
- return Ok(Self::VINTR);
- }
- if item == Self::VQUIT.char() {
- return Ok(Self::VQUIT);
- }
- if item == Self::VINTR.char() {
- return Ok(Self::VINTR);
- }
- if item == Self::VERASE.char() {
- return Ok(Self::VERASE);
- }
- if item == Self::VEOF.char() {
- return Ok(Self::VEOF);
- }
- if item == Self::VSTART.char() {
- return Ok(Self::VSTART);
- }
- if item == Self::VSTOP.char() {
- return Ok(Self::VSTOP);
- }
- if item == Self::VSUSP.char() {
- return Ok(Self::VSUSP);
- }
-
- return_errno_with_message!(Errno::EINVAL, "Not a valid cc_char");
- }
}
#[derive(Debug, Clone, Copy, Pod)]
diff --git a/services/libs/jinux-std/src/device/tty/termio.rs b/services/libs/jinux-std/src/device/tty/termio.rs
--- a/services/libs/jinux-std/src/device/tty/termio.rs
+++ b/services/libs/jinux-std/src/device/tty/termio.rs
@@ -185,50 +221,39 @@ pub struct KernelTermios {
impl KernelTermios {
pub fn default() -> Self {
let mut termios = Self {
- c_iflags: C_IFLAGS::ICRNL,
- c_oflags: C_OFLAGS::empty(),
- c_cflags: C_CFLAGS::B0,
- c_lflags: C_LFLAGS::ICANON | C_LFLAGS::ECHO,
+ c_iflags: C_IFLAGS::default(),
+ c_oflags: C_OFLAGS::default(),
+ c_cflags: C_CFLAGS::default(),
+ c_lflags: C_LFLAGS::default(),
c_line: 0,
- c_cc: [0; KERNEL_NCCS],
+ c_cc: [CcT::default(); KERNEL_NCCS],
};
- *termios.get_special_char_mut(CC_C_CHAR::VINTR) = CC_C_CHAR::VINTR.char();
- *termios.get_special_char_mut(CC_C_CHAR::VQUIT) = CC_C_CHAR::VQUIT.char();
- *termios.get_special_char_mut(CC_C_CHAR::VERASE) = CC_C_CHAR::VERASE.char();
- *termios.get_special_char_mut(CC_C_CHAR::VKILL) = CC_C_CHAR::VKILL.char();
- *termios.get_special_char_mut(CC_C_CHAR::VEOF) = CC_C_CHAR::VEOF.char();
- *termios.get_special_char_mut(CC_C_CHAR::VTIME) = CC_C_CHAR::VTIME.char();
- *termios.get_special_char_mut(CC_C_CHAR::VMIN) = CC_C_CHAR::VMIN.char();
- *termios.get_special_char_mut(CC_C_CHAR::VSWTC) = CC_C_CHAR::VSWTC.char();
- *termios.get_special_char_mut(CC_C_CHAR::VSTART) = CC_C_CHAR::VSTART.char();
- *termios.get_special_char_mut(CC_C_CHAR::VSTOP) = CC_C_CHAR::VSTOP.char();
- *termios.get_special_char_mut(CC_C_CHAR::VSUSP) = CC_C_CHAR::VSUSP.char();
- *termios.get_special_char_mut(CC_C_CHAR::VEOL) = CC_C_CHAR::VEOL.char();
- *termios.get_special_char_mut(CC_C_CHAR::VREPRINT) = CC_C_CHAR::VREPRINT.char();
- *termios.get_special_char_mut(CC_C_CHAR::VDISCARD) = CC_C_CHAR::VDISCARD.char();
- *termios.get_special_char_mut(CC_C_CHAR::VWERASE) = CC_C_CHAR::VWERASE.char();
- *termios.get_special_char_mut(CC_C_CHAR::VLNEXT) = CC_C_CHAR::VLNEXT.char();
- *termios.get_special_char_mut(CC_C_CHAR::VEOL2) = CC_C_CHAR::VEOL2.char();
+ *termios.get_special_char_mut(CC_C_CHAR::VINTR) = CC_C_CHAR::VINTR.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VQUIT) = CC_C_CHAR::VQUIT.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VERASE) = CC_C_CHAR::VERASE.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VKILL) = CC_C_CHAR::VKILL.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VEOF) = CC_C_CHAR::VEOF.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VTIME) = CC_C_CHAR::VTIME.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VMIN) = CC_C_CHAR::VMIN.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VSWTC) = CC_C_CHAR::VSWTC.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VSTART) = CC_C_CHAR::VSTART.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VSTOP) = CC_C_CHAR::VSTOP.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VSUSP) = CC_C_CHAR::VSUSP.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VEOL) = CC_C_CHAR::VEOL.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VREPRINT) = CC_C_CHAR::VREPRINT.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VDISCARD) = CC_C_CHAR::VDISCARD.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VWERASE) = CC_C_CHAR::VWERASE.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VLNEXT) = CC_C_CHAR::VLNEXT.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VEOL2) = CC_C_CHAR::VEOL2.default_char();
termios
}
- fn new() -> Self {
- KernelTermios {
- c_iflags: C_IFLAGS::empty(),
- c_oflags: C_OFLAGS::empty(),
- c_cflags: C_CFLAGS::B0,
- c_lflags: C_LFLAGS::empty(),
- c_line: 0,
- c_cc: [0; KERNEL_NCCS],
- }
- }
-
pub fn get_special_char(&self, cc_c_char: CC_C_CHAR) -> &CcT {
- &self.c_cc[cc_c_char.as_usize()]
+ &self.c_cc[cc_c_char as usize]
}
pub fn get_special_char_mut(&mut self, cc_c_char: CC_C_CHAR) -> &mut CcT {
- &mut self.c_cc[cc_c_char.as_usize()]
+ &mut self.c_cc[cc_c_char as usize]
}
/// Canonical mode means we will handle input by lines, not by single character
diff --git a/services/libs/jinux-std/src/device/tty/termio.rs b/services/libs/jinux-std/src/device/tty/termio.rs
--- a/services/libs/jinux-std/src/device/tty/termio.rs
+++ b/services/libs/jinux-std/src/device/tty/termio.rs
@@ -185,50 +221,39 @@ pub struct KernelTermios {
impl KernelTermios {
pub fn default() -> Self {
let mut termios = Self {
- c_iflags: C_IFLAGS::ICRNL,
- c_oflags: C_OFLAGS::empty(),
- c_cflags: C_CFLAGS::B0,
- c_lflags: C_LFLAGS::ICANON | C_LFLAGS::ECHO,
+ c_iflags: C_IFLAGS::default(),
+ c_oflags: C_OFLAGS::default(),
+ c_cflags: C_CFLAGS::default(),
+ c_lflags: C_LFLAGS::default(),
c_line: 0,
- c_cc: [0; KERNEL_NCCS],
+ c_cc: [CcT::default(); KERNEL_NCCS],
};
- *termios.get_special_char_mut(CC_C_CHAR::VINTR) = CC_C_CHAR::VINTR.char();
- *termios.get_special_char_mut(CC_C_CHAR::VQUIT) = CC_C_CHAR::VQUIT.char();
- *termios.get_special_char_mut(CC_C_CHAR::VERASE) = CC_C_CHAR::VERASE.char();
- *termios.get_special_char_mut(CC_C_CHAR::VKILL) = CC_C_CHAR::VKILL.char();
- *termios.get_special_char_mut(CC_C_CHAR::VEOF) = CC_C_CHAR::VEOF.char();
- *termios.get_special_char_mut(CC_C_CHAR::VTIME) = CC_C_CHAR::VTIME.char();
- *termios.get_special_char_mut(CC_C_CHAR::VMIN) = CC_C_CHAR::VMIN.char();
- *termios.get_special_char_mut(CC_C_CHAR::VSWTC) = CC_C_CHAR::VSWTC.char();
- *termios.get_special_char_mut(CC_C_CHAR::VSTART) = CC_C_CHAR::VSTART.char();
- *termios.get_special_char_mut(CC_C_CHAR::VSTOP) = CC_C_CHAR::VSTOP.char();
- *termios.get_special_char_mut(CC_C_CHAR::VSUSP) = CC_C_CHAR::VSUSP.char();
- *termios.get_special_char_mut(CC_C_CHAR::VEOL) = CC_C_CHAR::VEOL.char();
- *termios.get_special_char_mut(CC_C_CHAR::VREPRINT) = CC_C_CHAR::VREPRINT.char();
- *termios.get_special_char_mut(CC_C_CHAR::VDISCARD) = CC_C_CHAR::VDISCARD.char();
- *termios.get_special_char_mut(CC_C_CHAR::VWERASE) = CC_C_CHAR::VWERASE.char();
- *termios.get_special_char_mut(CC_C_CHAR::VLNEXT) = CC_C_CHAR::VLNEXT.char();
- *termios.get_special_char_mut(CC_C_CHAR::VEOL2) = CC_C_CHAR::VEOL2.char();
+ *termios.get_special_char_mut(CC_C_CHAR::VINTR) = CC_C_CHAR::VINTR.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VQUIT) = CC_C_CHAR::VQUIT.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VERASE) = CC_C_CHAR::VERASE.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VKILL) = CC_C_CHAR::VKILL.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VEOF) = CC_C_CHAR::VEOF.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VTIME) = CC_C_CHAR::VTIME.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VMIN) = CC_C_CHAR::VMIN.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VSWTC) = CC_C_CHAR::VSWTC.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VSTART) = CC_C_CHAR::VSTART.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VSTOP) = CC_C_CHAR::VSTOP.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VSUSP) = CC_C_CHAR::VSUSP.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VEOL) = CC_C_CHAR::VEOL.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VREPRINT) = CC_C_CHAR::VREPRINT.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VDISCARD) = CC_C_CHAR::VDISCARD.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VWERASE) = CC_C_CHAR::VWERASE.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VLNEXT) = CC_C_CHAR::VLNEXT.default_char();
+ *termios.get_special_char_mut(CC_C_CHAR::VEOL2) = CC_C_CHAR::VEOL2.default_char();
termios
}
- fn new() -> Self {
- KernelTermios {
- c_iflags: C_IFLAGS::empty(),
- c_oflags: C_OFLAGS::empty(),
- c_cflags: C_CFLAGS::B0,
- c_lflags: C_LFLAGS::empty(),
- c_line: 0,
- c_cc: [0; KERNEL_NCCS],
- }
- }
-
pub fn get_special_char(&self, cc_c_char: CC_C_CHAR) -> &CcT {
- &self.c_cc[cc_c_char.as_usize()]
+ &self.c_cc[cc_c_char as usize]
}
pub fn get_special_char_mut(&mut self, cc_c_char: CC_C_CHAR) -> &mut CcT {
- &mut self.c_cc[cc_c_char.as_usize()]
+ &mut self.c_cc[cc_c_char as usize]
}
/// Canonical mode means we will handle input by lines, not by single character
diff --git a/services/libs/jinux-std/src/device/tty/termio.rs b/services/libs/jinux-std/src/device/tty/termio.rs
--- a/services/libs/jinux-std/src/device/tty/termio.rs
+++ b/services/libs/jinux-std/src/device/tty/termio.rs
@@ -265,3 +290,17 @@ impl KernelTermios {
self.c_lflags.contains(C_LFLAGS::IEXTEN)
}
}
+
+const fn control_character(c: char) -> u8 {
+ debug_assert!(c as u8 >= 'A' as u8);
+ c as u8 - 'A' as u8 + 1u8
+}
+
+#[derive(Debug, Clone, Copy, Default, Pod)]
+#[repr(C)]
+pub struct WinSize {
+ ws_row: u16,
+ ws_col: u16,
+ ws_xpixel: u16,
+ ws_ypixel: u16,
+}
diff --git a/services/libs/jinux-std/src/device/tty/termio.rs b/services/libs/jinux-std/src/device/tty/termio.rs
--- a/services/libs/jinux-std/src/device/tty/termio.rs
+++ b/services/libs/jinux-std/src/device/tty/termio.rs
@@ -265,3 +290,17 @@ impl KernelTermios {
self.c_lflags.contains(C_LFLAGS::IEXTEN)
}
}
+
+const fn control_character(c: char) -> u8 {
+ debug_assert!(c as u8 >= 'A' as u8);
+ c as u8 - 'A' as u8 + 1u8
+}
+
+#[derive(Debug, Clone, Copy, Default, Pod)]
+#[repr(C)]
+pub struct WinSize {
+ ws_row: u16,
+ ws_col: u16,
+ ws_xpixel: u16,
+ ws_ypixel: u16,
+}
diff --git a/services/libs/jinux-std/src/fs/devpts/master.rs b/services/libs/jinux-std/src/fs/devpts/master.rs
--- a/services/libs/jinux-std/src/fs/devpts/master.rs
+++ b/services/libs/jinux-std/src/fs/devpts/master.rs
@@ -1,7 +1,9 @@
-use crate::prelude::*;
+use crate::{fs::file_handle::FileLike, prelude::*};
use super::*;
+use crate::device::PtyMaster;
+
/// Pty master inode for the master device.
pub struct PtyMasterInode(Arc<PtyMaster>);
diff --git a/services/libs/jinux-std/src/fs/devpts/master.rs b/services/libs/jinux-std/src/fs/devpts/master.rs
--- a/services/libs/jinux-std/src/fs/devpts/master.rs
+++ b/services/libs/jinux-std/src/fs/devpts/master.rs
@@ -1,7 +1,9 @@
-use crate::prelude::*;
+use crate::{fs::file_handle::FileLike, prelude::*};
use super::*;
+use crate::device::PtyMaster;
+
/// Pty master inode for the master device.
pub struct PtyMasterInode(Arc<PtyMaster>);
diff --git a/services/libs/jinux-std/src/fs/devpts/master.rs b/services/libs/jinux-std/src/fs/devpts/master.rs
--- a/services/libs/jinux-std/src/fs/devpts/master.rs
+++ b/services/libs/jinux-std/src/fs/devpts/master.rs
@@ -14,8 +16,11 @@ impl PtyMasterInode {
impl Drop for PtyMasterInode {
fn drop(&mut self) {
// Remove the slave from fs.
- let index = self.0.slave_index();
- let _ = self.0.ptmx().devpts().remove_slave(index);
+ let fs = self.0.ptmx().fs();
+ let devpts = fs.downcast_ref::<DevPts>().unwrap();
+
+ let index = self.0.index();
+ devpts.remove_slave(index);
}
}
diff --git a/services/libs/jinux-std/src/fs/devpts/master.rs b/services/libs/jinux-std/src/fs/devpts/master.rs
--- a/services/libs/jinux-std/src/fs/devpts/master.rs
+++ b/services/libs/jinux-std/src/fs/devpts/master.rs
@@ -14,8 +16,11 @@ impl PtyMasterInode {
impl Drop for PtyMasterInode {
fn drop(&mut self) {
// Remove the slave from fs.
- let index = self.0.slave_index();
- let _ = self.0.ptmx().devpts().remove_slave(index);
+ let fs = self.0.ptmx().fs();
+ let devpts = fs.downcast_ref::<DevPts>().unwrap();
+
+ let index = self.0.index();
+ devpts.remove_slave(index);
}
}
diff --git a/services/libs/jinux-std/src/fs/devpts/master.rs b/services/libs/jinux-std/src/fs/devpts/master.rs
--- a/services/libs/jinux-std/src/fs/devpts/master.rs
+++ b/services/libs/jinux-std/src/fs/devpts/master.rs
@@ -77,52 +82,6 @@ impl Inode for PtyMasterInode {
}
fn fs(&self) -> Arc<dyn FileSystem> {
- self.0.ptmx().devpts()
- }
-}
-
-// TODO: implement real pty master.
-pub struct PtyMaster {
- slave_index: u32,
- ptmx: Arc<Ptmx>,
-}
-
-impl PtyMaster {
- pub fn new(slave_index: u32, ptmx: Arc<Ptmx>) -> Arc<Self> {
- Arc::new(Self { slave_index, ptmx })
- }
-
- pub fn slave_index(&self) -> u32 {
- self.slave_index
- }
-
- fn ptmx(&self) -> &Ptmx {
- &self.ptmx
- }
-}
-
-impl Device for PtyMaster {
- fn type_(&self) -> DeviceType {
- self.ptmx.device_type()
- }
-
- fn id(&self) -> DeviceId {
- self.ptmx.device_id()
- }
-
- fn read(&self, buf: &mut [u8]) -> Result<usize> {
- todo!();
- }
-
- fn write(&self, buf: &[u8]) -> Result<usize> {
- todo!();
- }
-
- fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
- todo!();
- }
-
- fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
- todo!();
+ self.0.ptmx().fs()
}
}
diff --git a/services/libs/jinux-std/src/fs/devpts/master.rs b/services/libs/jinux-std/src/fs/devpts/master.rs
--- a/services/libs/jinux-std/src/fs/devpts/master.rs
+++ b/services/libs/jinux-std/src/fs/devpts/master.rs
@@ -77,52 +82,6 @@ impl Inode for PtyMasterInode {
}
fn fs(&self) -> Arc<dyn FileSystem> {
- self.0.ptmx().devpts()
- }
-}
-
-// TODO: implement real pty master.
-pub struct PtyMaster {
- slave_index: u32,
- ptmx: Arc<Ptmx>,
-}
-
-impl PtyMaster {
- pub fn new(slave_index: u32, ptmx: Arc<Ptmx>) -> Arc<Self> {
- Arc::new(Self { slave_index, ptmx })
- }
-
- pub fn slave_index(&self) -> u32 {
- self.slave_index
- }
-
- fn ptmx(&self) -> &Ptmx {
- &self.ptmx
- }
-}
-
-impl Device for PtyMaster {
- fn type_(&self) -> DeviceType {
- self.ptmx.device_type()
- }
-
- fn id(&self) -> DeviceId {
- self.ptmx.device_id()
- }
-
- fn read(&self, buf: &mut [u8]) -> Result<usize> {
- todo!();
- }
-
- fn write(&self, buf: &[u8]) -> Result<usize> {
- todo!();
- }
-
- fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
- todo!();
- }
-
- fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
- todo!();
+ self.0.ptmx().fs()
}
}
diff --git a/services/libs/jinux-std/src/fs/devpts/mod.rs b/services/libs/jinux-std/src/fs/devpts/mod.rs
--- a/services/libs/jinux-std/src/fs/devpts/mod.rs
+++ b/services/libs/jinux-std/src/fs/devpts/mod.rs
@@ -9,9 +9,9 @@ use core::time::Duration;
use jinux_frame::vm::VmFrame;
use jinux_util::{id_allocator::IdAlloc, slot_vec::SlotVec};
-use self::master::{PtyMaster, PtyMasterInode};
+use self::master::PtyMasterInode;
use self::ptmx::Ptmx;
-use self::slave::{PtySlave, PtySlaveInode};
+use self::slave::PtySlaveInode;
mod master;
mod ptmx;
diff --git a/services/libs/jinux-std/src/fs/devpts/mod.rs b/services/libs/jinux-std/src/fs/devpts/mod.rs
--- a/services/libs/jinux-std/src/fs/devpts/mod.rs
+++ b/services/libs/jinux-std/src/fs/devpts/mod.rs
@@ -9,9 +9,9 @@ use core::time::Duration;
use jinux_frame::vm::VmFrame;
use jinux_util::{id_allocator::IdAlloc, slot_vec::SlotVec};
-use self::master::{PtyMaster, PtyMasterInode};
+use self::master::PtyMasterInode;
use self::ptmx::Ptmx;
-use self::slave::{PtySlave, PtySlaveInode};
+use self::slave::PtySlaveInode;
mod master;
mod ptmx;
diff --git a/services/libs/jinux-std/src/fs/devpts/mod.rs b/services/libs/jinux-std/src/fs/devpts/mod.rs
--- a/services/libs/jinux-std/src/fs/devpts/mod.rs
+++ b/services/libs/jinux-std/src/fs/devpts/mod.rs
@@ -60,8 +60,7 @@ impl DevPts {
.alloc()
.ok_or_else(|| Error::with_message(Errno::EIO, "cannot alloc index"))?;
- let master = PtyMaster::new(index as u32, self.root.ptmx.clone());
- let slave = PtySlave::new(master.clone());
+ let (master, slave) = crate::device::new_pty_pair(index as u32, self.root.ptmx.clone())?;
let master_inode = PtyMasterInode::new(master);
let slave_inode = PtySlaveInode::new(slave, self.this.clone());
diff --git a/services/libs/jinux-std/src/fs/devpts/mod.rs b/services/libs/jinux-std/src/fs/devpts/mod.rs
--- a/services/libs/jinux-std/src/fs/devpts/mod.rs
+++ b/services/libs/jinux-std/src/fs/devpts/mod.rs
@@ -60,8 +60,7 @@ impl DevPts {
.alloc()
.ok_or_else(|| Error::with_message(Errno::EIO, "cannot alloc index"))?;
- let master = PtyMaster::new(index as u32, self.root.ptmx.clone());
- let slave = PtySlave::new(master.clone());
+ let (master, slave) = crate::device::new_pty_pair(index as u32, self.root.ptmx.clone())?;
let master_inode = PtyMasterInode::new(master);
let slave_inode = PtySlaveInode::new(slave, self.this.clone());
diff --git a/services/libs/jinux-std/src/fs/devpts/slave.rs b/services/libs/jinux-std/src/fs/devpts/slave.rs
--- a/services/libs/jinux-std/src/fs/devpts/slave.rs
+++ b/services/libs/jinux-std/src/fs/devpts/slave.rs
@@ -2,6 +2,8 @@ use crate::prelude::*;
use super::*;
+use crate::device::PtySlave;
+
/// Same major number with Linux, the minor number is the index of slave.
const SLAVE_MAJOR_NUM: u32 = 3;
diff --git a/services/libs/jinux-std/src/fs/devpts/slave.rs b/services/libs/jinux-std/src/fs/devpts/slave.rs
--- a/services/libs/jinux-std/src/fs/devpts/slave.rs
+++ b/services/libs/jinux-std/src/fs/devpts/slave.rs
@@ -2,6 +2,8 @@ use crate::prelude::*;
use super::*;
+use crate::device::PtySlave;
+
/// Same major number with Linux, the minor number is the index of slave.
const SLAVE_MAJOR_NUM: u32 = 3;
diff --git a/services/libs/jinux-std/src/fs/devpts/slave.rs b/services/libs/jinux-std/src/fs/devpts/slave.rs
--- a/services/libs/jinux-std/src/fs/devpts/slave.rs
+++ b/services/libs/jinux-std/src/fs/devpts/slave.rs
@@ -88,44 +90,3 @@ impl Inode for PtySlaveInode {
self.fs.upgrade().unwrap()
}
}
-
-// TODO: implement real pty slave.
-pub struct PtySlave {
- master: Arc<PtyMaster>,
-}
-
-impl PtySlave {
- pub fn new(master: Arc<PtyMaster>) -> Arc<Self> {
- Arc::new(Self { master })
- }
-
- pub fn index(&self) -> u32 {
- self.master.slave_index()
- }
-}
-
-impl Device for PtySlave {
- fn type_(&self) -> DeviceType {
- DeviceType::CharDevice
- }
-
- fn id(&self) -> DeviceId {
- DeviceId::new(SLAVE_MAJOR_NUM, self.index())
- }
-
- fn read(&self, buf: &mut [u8]) -> Result<usize> {
- todo!();
- }
-
- fn write(&self, buf: &[u8]) -> Result<usize> {
- todo!();
- }
-
- fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
- todo!();
- }
-
- fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
- todo!();
- }
-}
diff --git a/services/libs/jinux-std/src/fs/devpts/slave.rs b/services/libs/jinux-std/src/fs/devpts/slave.rs
--- a/services/libs/jinux-std/src/fs/devpts/slave.rs
+++ b/services/libs/jinux-std/src/fs/devpts/slave.rs
@@ -88,44 +90,3 @@ impl Inode for PtySlaveInode {
self.fs.upgrade().unwrap()
}
}
-
-// TODO: implement real pty slave.
-pub struct PtySlave {
- master: Arc<PtyMaster>,
-}
-
-impl PtySlave {
- pub fn new(master: Arc<PtyMaster>) -> Arc<Self> {
- Arc::new(Self { master })
- }
-
- pub fn index(&self) -> u32 {
- self.master.slave_index()
- }
-}
-
-impl Device for PtySlave {
- fn type_(&self) -> DeviceType {
- DeviceType::CharDevice
- }
-
- fn id(&self) -> DeviceId {
- DeviceId::new(SLAVE_MAJOR_NUM, self.index())
- }
-
- fn read(&self, buf: &mut [u8]) -> Result<usize> {
- todo!();
- }
-
- fn write(&self, buf: &[u8]) -> Result<usize> {
- todo!();
- }
-
- fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
- todo!();
- }
-
- fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
- todo!();
- }
-}
diff --git a/services/libs/jinux-std/src/fs/utils/ioctl.rs b/services/libs/jinux-std/src/fs/utils/ioctl.rs
--- a/services/libs/jinux-std/src/fs/utils/ioctl.rs
+++ b/services/libs/jinux-std/src/fs/utils/ioctl.rs
@@ -3,18 +3,30 @@ use crate::prelude::*;
#[repr(u32)]
#[derive(Debug, Clone, Copy, TryFromInt)]
pub enum IoctlCmd {
- // Get terminal attributes
+ /// Get terminal attributes
TCGETS = 0x5401,
TCSETS = 0x5402,
- // Drain the output buffer and set attributes
+ /// Drain the output buffer and set attributes
TCSETSW = 0x5403,
- // Drain the output buffer, and discard pending input, and set attributes
+ /// Drain the output buffer, and discard pending input, and set attributes
TCSETSF = 0x5404,
- // Get the process group ID of the foreground process group on this terminal
+ /// Make the given terminal the controlling terminal of the calling process.
+ TIOCSCTTY = 0x540e,
+ /// Get the process group ID of the foreground process group on this terminal
TIOCGPGRP = 0x540f,
- // Set the foreground process group ID of this terminal.
+ /// Set the foreground process group ID of this terminal.
TIOCSPGRP = 0x5410,
- // Set window size
+ /// Get the number of bytes in the input buffer.
+ FIONREAD = 0x541B,
+ /// Set window size
TIOCGWINSZ = 0x5413,
TIOCSWINSZ = 0x5414,
+ /// the calling process gives up this controlling terminal
+ TIOCNOTTY = 0x5422,
+ /// Get Pty Number
+ TIOCGPTN = 0x80045430,
+ /// Lock/unlock Pty
+ TIOCSPTLCK = 0x40045431,
+ /// Safely open the slave
+ TIOCGPTPEER = 0x40045441,
}
diff --git a/services/libs/jinux-std/src/fs/utils/ioctl.rs b/services/libs/jinux-std/src/fs/utils/ioctl.rs
--- a/services/libs/jinux-std/src/fs/utils/ioctl.rs
+++ b/services/libs/jinux-std/src/fs/utils/ioctl.rs
@@ -3,18 +3,30 @@ use crate::prelude::*;
#[repr(u32)]
#[derive(Debug, Clone, Copy, TryFromInt)]
pub enum IoctlCmd {
- // Get terminal attributes
+ /// Get terminal attributes
TCGETS = 0x5401,
TCSETS = 0x5402,
- // Drain the output buffer and set attributes
+ /// Drain the output buffer and set attributes
TCSETSW = 0x5403,
- // Drain the output buffer, and discard pending input, and set attributes
+ /// Drain the output buffer, and discard pending input, and set attributes
TCSETSF = 0x5404,
- // Get the process group ID of the foreground process group on this terminal
+ /// Make the given terminal the controlling terminal of the calling process.
+ TIOCSCTTY = 0x540e,
+ /// Get the process group ID of the foreground process group on this terminal
TIOCGPGRP = 0x540f,
- // Set the foreground process group ID of this terminal.
+ /// Set the foreground process group ID of this terminal.
TIOCSPGRP = 0x5410,
- // Set window size
+ /// Get the number of bytes in the input buffer.
+ FIONREAD = 0x541B,
+ /// Set window size
TIOCGWINSZ = 0x5413,
TIOCSWINSZ = 0x5414,
+ /// the calling process gives up this controlling terminal
+ TIOCNOTTY = 0x5422,
+ /// Get Pty Number
+ TIOCGPTN = 0x80045430,
+ /// Lock/unlock Pty
+ TIOCSPTLCK = 0x40045431,
+ /// Safely open the slave
+ TIOCGPTPEER = 0x40045441,
}
diff --git a/services/libs/jinux-std/src/fs/utils/vnode.rs b/services/libs/jinux-std/src/fs/utils/vnode.rs
--- a/services/libs/jinux-std/src/fs/utils/vnode.rs
+++ b/services/libs/jinux-std/src/fs/utils/vnode.rs
@@ -146,6 +146,7 @@ impl Vnode {
if let Some(page_cache) = &inner.page_cache {
page_cache.evict_range(0..file_len);
}
+
inner.inode.read_at(0, &mut buf[..file_len])
}
diff --git a/services/libs/jinux-std/src/fs/utils/vnode.rs b/services/libs/jinux-std/src/fs/utils/vnode.rs
--- a/services/libs/jinux-std/src/fs/utils/vnode.rs
+++ b/services/libs/jinux-std/src/fs/utils/vnode.rs
@@ -146,6 +146,7 @@ impl Vnode {
if let Some(page_cache) = &inner.page_cache {
page_cache.evict_range(0..file_len);
}
+
inner.inode.read_at(0, &mut buf[..file_len])
}
diff --git a/services/libs/jinux-std/src/fs/utils/vnode.rs b/services/libs/jinux-std/src/fs/utils/vnode.rs
--- a/services/libs/jinux-std/src/fs/utils/vnode.rs
+++ b/services/libs/jinux-std/src/fs/utils/vnode.rs
@@ -196,11 +197,13 @@ impl Vnode {
}
pub fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
- self.inner.read().inode.poll(mask, poller)
+ let inode = self.inner.read().inode.clone();
+ inode.poll(mask, poller)
}
pub fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
- self.inner.read().inode.ioctl(cmd, arg)
+ let inode = self.inner.read().inode.clone();
+ inode.ioctl(cmd, arg)
}
pub fn fs(&self) -> Arc<dyn FileSystem> {
diff --git a/services/libs/jinux-std/src/fs/utils/vnode.rs b/services/libs/jinux-std/src/fs/utils/vnode.rs
--- a/services/libs/jinux-std/src/fs/utils/vnode.rs
+++ b/services/libs/jinux-std/src/fs/utils/vnode.rs
@@ -196,11 +197,13 @@ impl Vnode {
}
pub fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
- self.inner.read().inode.poll(mask, poller)
+ let inode = self.inner.read().inode.clone();
+ inode.poll(mask, poller)
}
pub fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
- self.inner.read().inode.ioctl(cmd, arg)
+ let inode = self.inner.read().inode.clone();
+ inode.ioctl(cmd, arg)
}
pub fn fs(&self) -> Arc<dyn FileSystem> {
diff --git a/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs b/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
--- a/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
+++ b/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
@@ -150,12 +150,27 @@ impl VmMapping {
}
pub fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> Result<()> {
let vmo_read_offset = self.vmo_offset() + offset;
+
+ // TODO: the current logic is vulnerable to TOCTTOU attack, since the permission may change after check.
+ let page_idx_range = get_page_idx_range(&(vmo_read_offset..vmo_read_offset + buf.len()));
+ let read_perm = VmPerm::R;
+ for page_idx in page_idx_range {
+ self.check_perm(&page_idx, &read_perm)?;
+ }
+
self.vmo.read_bytes(vmo_read_offset, buf)?;
Ok(())
}
pub fn write_bytes(&self, offset: usize, buf: &[u8]) -> Result<()> {
let vmo_write_offset = self.vmo_offset() + offset;
+
+ let page_idx_range = get_page_idx_range(&(vmo_write_offset..vmo_write_offset + buf.len()));
+ let write_perm = VmPerm::W;
+ for page_idx in page_idx_range {
+ self.check_perm(&page_idx, &write_perm)?;
+ }
+
self.vmo.write_bytes(vmo_write_offset, buf)?;
Ok(())
}
diff --git a/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs b/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
--- a/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
+++ b/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
@@ -150,12 +150,27 @@ impl VmMapping {
}
pub fn read_bytes(&self, offset: usize, buf: &mut [u8]) -> Result<()> {
let vmo_read_offset = self.vmo_offset() + offset;
+
+ // TODO: the current logic is vulnerable to TOCTTOU attack, since the permission may change after check.
+ let page_idx_range = get_page_idx_range(&(vmo_read_offset..vmo_read_offset + buf.len()));
+ let read_perm = VmPerm::R;
+ for page_idx in page_idx_range {
+ self.check_perm(&page_idx, &read_perm)?;
+ }
+
self.vmo.read_bytes(vmo_read_offset, buf)?;
Ok(())
}
pub fn write_bytes(&self, offset: usize, buf: &[u8]) -> Result<()> {
let vmo_write_offset = self.vmo_offset() + offset;
+
+ let page_idx_range = get_page_idx_range(&(vmo_write_offset..vmo_write_offset + buf.len()));
+ let write_perm = VmPerm::W;
+ for page_idx in page_idx_range {
+ self.check_perm(&page_idx, &write_perm)?;
+ }
+
self.vmo.write_bytes(vmo_write_offset, buf)?;
Ok(())
}
diff --git a/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs b/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
--- a/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
+++ b/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
@@ -198,7 +213,9 @@ impl VmMapping {
} else {
self.vmo.check_rights(Rights::READ)?;
}
- self.check_perm(&page_idx, write)?;
+
+ let required_perm = if write { VmPerm::W } else { VmPerm::R };
+ self.check_perm(&page_idx, &required_perm)?;
let frame = self.vmo.get_committed_frame(page_idx, write)?;
diff --git a/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs b/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
--- a/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
+++ b/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
@@ -198,7 +213,9 @@ impl VmMapping {
} else {
self.vmo.check_rights(Rights::READ)?;
}
- self.check_perm(&page_idx, write)?;
+
+ let required_perm = if write { VmPerm::W } else { VmPerm::R };
+ self.check_perm(&page_idx, &required_perm)?;
let frame = self.vmo.get_committed_frame(page_idx, write)?;
diff --git a/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs b/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
--- a/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
+++ b/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
@@ -300,8 +317,8 @@ impl VmMapping {
self.inner.lock().trim_right(vm_space, vaddr)
}
- fn check_perm(&self, page_idx: &usize, write: bool) -> Result<()> {
- self.inner.lock().check_perm(page_idx, write)
+ fn check_perm(&self, page_idx: &usize, perm: &VmPerm) -> Result<()> {
+ self.inner.lock().check_perm(page_idx, perm)
}
}
diff --git a/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs b/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
--- a/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
+++ b/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
@@ -300,8 +317,8 @@ impl VmMapping {
self.inner.lock().trim_right(vm_space, vaddr)
}
- fn check_perm(&self, page_idx: &usize, write: bool) -> Result<()> {
- self.inner.lock().check_perm(page_idx, write)
+ fn check_perm(&self, page_idx: &usize, perm: &VmPerm) -> Result<()> {
+ self.inner.lock().check_perm(page_idx, perm)
}
}
diff --git a/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs b/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
--- a/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
+++ b/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
@@ -457,16 +474,14 @@ impl VmMappingInner {
self.map_to_addr..self.map_to_addr + self.map_size
}
- fn check_perm(&self, page_idx: &usize, write: bool) -> Result<()> {
+ fn check_perm(&self, page_idx: &usize, perm: &VmPerm) -> Result<()> {
let page_perm = self
.page_perms
.get(&page_idx)
.ok_or(Error::with_message(Errno::EINVAL, "invalid page idx"))?;
- if !page_perm.contains(VmPerm::R) {
- return_errno_with_message!(Errno::EINVAL, "perm should at least contain read");
- }
- if write && !page_perm.contains(VmPerm::W) {
- return_errno_with_message!(Errno::EINVAL, "perm should contain write for write access");
+
+ if !page_perm.contains(*perm) {
+ return_errno_with_message!(Errno::EACCES, "perm check fails");
}
Ok(())
diff --git a/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs b/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
--- a/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
+++ b/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
@@ -457,16 +474,14 @@ impl VmMappingInner {
self.map_to_addr..self.map_to_addr + self.map_size
}
- fn check_perm(&self, page_idx: &usize, write: bool) -> Result<()> {
+ fn check_perm(&self, page_idx: &usize, perm: &VmPerm) -> Result<()> {
let page_perm = self
.page_perms
.get(&page_idx)
.ok_or(Error::with_message(Errno::EINVAL, "invalid page idx"))?;
- if !page_perm.contains(VmPerm::R) {
- return_errno_with_message!(Errno::EINVAL, "perm should at least contain read");
- }
- if write && !page_perm.contains(VmPerm::W) {
- return_errno_with_message!(Errno::EINVAL, "perm should contain write for write access");
+
+ if !page_perm.contains(*perm) {
+ return_errno_with_message!(Errno::EACCES, "perm check fails");
}
Ok(())
|
2023-08-01T06:37:18Z
|
25c4f0f2bcaa0bc8c650b0f4ee7b0d78e2a836b2
|
|
asterinas/asterinas
|
diff --git a/regression/syscall_test/Makefile b/regression/syscall_test/Makefile
--- a/regression/syscall_test/Makefile
+++ b/regression/syscall_test/Makefile
@@ -2,9 +2,13 @@ TESTS ?= open_test read_test statfs_test chmod_test
MKFILE_PATH := $(abspath $(lastword $(MAKEFILE_LIST)))
CUR_DIR := $(patsubst %/,%,$(dir $(MKFILE_PATH)))
-BUILD_DIR := $(CUR_DIR)/../build
-SRC_DIR := $(BUILD_DIR)/gvisor_src
-BIN_DIR := $(BUILD_DIR)/syscall_test_bins
+BUILD_DIR ?= $(CUR_DIR)/../build
+ifdef JINUX_PREBUILT_SYSCALL_TEST
+ BIN_DIR := $(JINUX_PREBUILT_SYSCALL_TEST)
+else
+ BIN_DIR := $(BUILD_DIR)/syscall_test_bins
+ SRC_DIR := $(BUILD_DIR)/gvisor_src
+endif
INITRAMFS ?= $(CUR_DIR)/../build/initramfs
TARGET_DIR := $(INITRAMFS)/opt/syscall_test
RUN_BASH := $(CUR_DIR)/run_syscall_test.sh
diff --git a/regression/syscall_test/Makefile b/regression/syscall_test/Makefile
--- a/regression/syscall_test/Makefile
+++ b/regression/syscall_test/Makefile
@@ -14,20 +18,25 @@ BLOCK_LIST := $(CUR_DIR)/blocklists
all: $(TESTS)
-$(SRC_DIR):
+$(TESTS): $(BIN_DIR) $(TARGET_DIR)
+ @cp -f $</$@ $(TARGET_DIR)/tests
+
+ifndef JINUX_PREBUILT_SYSCALL_TEST
+$(BIN_DIR): $(SRC_DIR)
@if ! type bazel > /dev/null; then \
echo "bazel is not installed, please run $(CUR_DIR)/install_bazel.sh with sudo permission to install it."; \
- exit 1 ; \
+ exit 1; \
fi
- @rm -rf $@ && mkdir -p $@
- @cd $@ && git clone -b 20200921.0 https://github.com/jinzhao-dev/gvisor.git .
-
-$(BIN_DIR): $(SRC_DIR)
@rm -rf $@ && mkdir -p $@
@cd $(SRC_DIR) && bazel build --test_tag_filters=native //test/syscalls/...
@cp $(SRC_DIR)/bazel-bin/test/syscalls/linux/*_test $@
-$(TARGET_DIR): $(RUN_BASH) $(BLOCK_LIST) $(BIN_DIR)
+$(SRC_DIR):
+ @rm -rf $@ && mkdir -p $@
+ @cd $@ && git clone -b 20200921.0 https://github.com/jinzhao-dev/gvisor.git .
+endif
+
+$(TARGET_DIR): $(RUN_BASH) $(BLOCK_LIST)
@rm -rf $@ && mkdir -p $@
@# Prepare tests dir for test binaries
@mkdir $@/tests
diff --git a/regression/syscall_test/Makefile b/regression/syscall_test/Makefile
--- a/regression/syscall_test/Makefile
+++ b/regression/syscall_test/Makefile
@@ -36,8 +45,5 @@ $(TARGET_DIR): $(RUN_BASH) $(BLOCK_LIST) $(BIN_DIR)
@# Copy bash script
@cp -f $(RUN_BASH) $@
-$(TESTS): $(TARGET_DIR)
- @cp -f $(BIN_DIR)/$@ $(TARGET_DIR)/tests
-
clean:
- @rm -rf $(BIN_DIR) $(TARGET_DIR)
+ @rm -rf $(TARGET_DIR)
\ No newline at end of file
diff --git a/tools/docker/Dockerfile.ubuntu22.04 b/tools/docker/Dockerfile.ubuntu22.04
--- a/tools/docker/Dockerfile.ubuntu22.04
+++ b/tools/docker/Dockerfile.ubuntu22.04
@@ -1,27 +1,47 @@
-FROM ubuntu:22.04
+FROM ubuntu:22.04 as ubuntu-22.04-with-bazel
SHELL ["/bin/bash", "-c"]
ARG DEBIAN_FRONTEND=noninteractive
+
+# Install all Bazel dependent packages
RUN apt update && apt-get install -y --no-install-recommends \
build-essential \
ca-certificates \
+ curl \
+ git-core \
+ gnupg \
+ python-is-python3 \
+ python3-pip
+
+# Install bazel, which is required by the system call test suite from Gvisor project
+COPY bom/syscall_test/install_bazel.sh /tmp/
+WORKDIR /tmp
+RUN ./install_bazel.sh && rm -f /tmp/install_bazel.sh
+
+FROM ubuntu-22.04-with-bazel as syscall_test
+
+# Build the syscall test binaries
+COPY bom/syscall_test /root/syscall_test
+WORKDIR /root/syscall_test
+RUN export BUILD_DIR=build && \
+ make ${BUILD_DIR}/syscall_test_bins
+
+FROM ubuntu-22.04-with-bazel
+
+# Install all Jinux dependent packages
+RUN apt update && apt-get install -y --no-install-recommends \
cpio \
cpuid \
- curl \
file \
g++ \
gdb \
- git-core \
- gnupg \
grub-common \
grub-pc \
libssl-dev \
net-tools \
openssh-server \
pkg-config \
- python-is-python3 \
- python3-pip \
qemu-system-x86 \
strace \
sudo \
diff --git a/tools/docker/Dockerfile.ubuntu22.04 b/tools/docker/Dockerfile.ubuntu22.04
--- a/tools/docker/Dockerfile.ubuntu22.04
+++ b/tools/docker/Dockerfile.ubuntu22.04
@@ -31,17 +51,14 @@ RUN apt update && apt-get install -y --no-install-recommends \
xorriso \
zip
-# Install bazel, , which is required by the system call test suite from Gvisor project
-RUN curl -fsSL https://bazel.build/bazel-release.pub.gpg | gpg --dearmor > bazel.gpg \
- && mv bazel.gpg /etc/apt/trusted.gpg.d/ \
- && echo 'deb [arch=amd64] https://storage.googleapis.com/bazel-apt stable jdk1.8' | tee /etc/apt/sources.list.d/bazel.list \
- && apt update \
- && apt install bazel=5.4.0 -y
-
# Clean apt cache
RUN apt clean \
&& rm -rf /var/lib/apt/lists/*
+# Prepare the system call test suite
+COPY --from=syscall_test /root/syscall_test/build/syscall_test_bins /root/syscall_test_bins
+ENV JINUX_PREBUILT_SYSCALL_TEST=/root/syscall_test_bins
+
# Install Rust
ENV PATH="/root/.cargo/bin:${PATH}"
ARG JINUX_RUST_VERSION
diff --git a/tools/docker/build_image.sh b/tools/docker/build_image.sh
--- a/tools/docker/build_image.sh
+++ b/tools/docker/build_image.sh
@@ -7,10 +7,19 @@ CARGO_TOML_PATH=${SCRIPT_DIR}/../../Cargo.toml
VERSION=$( grep -m1 -o '[0-9]\+\.[0-9]\+\.[0-9]\+' ${CARGO_TOML_PATH} | sed 's/[^0-9\.]//g' )
IMAGE_NAME=jinuxdev/jinux:${VERSION}
DOCKER_FILE=${SCRIPT_DIR}/Dockerfile.ubuntu22.04
+BOM_DIR=${SCRIPT_DIR}/bom
+TOP_DIR=${SCRIPT_DIR}/../../
ARCH=linux/amd64
RUST_TOOLCHAIN_PATH=${SCRIPT_DIR}/../../rust-toolchain.toml
JINUX_RUST_VERSION=$( grep -m1 -o 'nightly-[0-9]\+-[0-9]\+-[0-9]\+' ${RUST_TOOLCHAIN_PATH} )
+# Prpare the BOM (bill of materials) directory to copy files or dirs into the docker image.
+# This is because the `docker build` can not access the parent directory of the context.
+if [ ! -d ${BOM_DIR} ]; then
+ mkdir -p ${BOM_DIR}
+ cp -rf ${TOP_DIR}/regression/syscall_test ${BOM_DIR}/
+fi
+
# Build docker
cd ${SCRIPT_DIR}
docker buildx build -f ${DOCKER_FILE} \
|
[
"340"
] |
0.1
|
dbfb2e1a62a9981a67cc01ff7310981744ec2ac5
|
Precompile syscall tests in the dev docker image to accelerate CI
Currently the syscall tests are compiled every-time when CI triggers, which is at a cost of around 12 minutes on Github runners.
|
asterinas__asterinas-327
| 327
|
diff --git a/regression/syscall_test/Makefile b/regression/syscall_test/Makefile
--- a/regression/syscall_test/Makefile
+++ b/regression/syscall_test/Makefile
@@ -2,9 +2,13 @@ TESTS ?= open_test read_test statfs_test chmod_test
MKFILE_PATH := $(abspath $(lastword $(MAKEFILE_LIST)))
CUR_DIR := $(patsubst %/,%,$(dir $(MKFILE_PATH)))
-BUILD_DIR := $(CUR_DIR)/../build
-SRC_DIR := $(BUILD_DIR)/gvisor_src
-BIN_DIR := $(BUILD_DIR)/syscall_test_bins
+BUILD_DIR ?= $(CUR_DIR)/../build
+ifdef JINUX_PREBUILT_SYSCALL_TEST
+ BIN_DIR := $(JINUX_PREBUILT_SYSCALL_TEST)
+else
+ BIN_DIR := $(BUILD_DIR)/syscall_test_bins
+ SRC_DIR := $(BUILD_DIR)/gvisor_src
+endif
INITRAMFS ?= $(CUR_DIR)/../build/initramfs
TARGET_DIR := $(INITRAMFS)/opt/syscall_test
RUN_BASH := $(CUR_DIR)/run_syscall_test.sh
diff --git a/regression/syscall_test/Makefile b/regression/syscall_test/Makefile
--- a/regression/syscall_test/Makefile
+++ b/regression/syscall_test/Makefile
@@ -14,20 +18,25 @@ BLOCK_LIST := $(CUR_DIR)/blocklists
all: $(TESTS)
-$(SRC_DIR):
+$(TESTS): $(BIN_DIR) $(TARGET_DIR)
+ @cp -f $</$@ $(TARGET_DIR)/tests
+
+ifndef JINUX_PREBUILT_SYSCALL_TEST
+$(BIN_DIR): $(SRC_DIR)
@if ! type bazel > /dev/null; then \
echo "bazel is not installed, please run $(CUR_DIR)/install_bazel.sh with sudo permission to install it."; \
- exit 1 ; \
+ exit 1; \
fi
- @rm -rf $@ && mkdir -p $@
- @cd $@ && git clone -b 20200921.0 https://github.com/jinzhao-dev/gvisor.git .
-
-$(BIN_DIR): $(SRC_DIR)
@rm -rf $@ && mkdir -p $@
@cd $(SRC_DIR) && bazel build --test_tag_filters=native //test/syscalls/...
@cp $(SRC_DIR)/bazel-bin/test/syscalls/linux/*_test $@
-$(TARGET_DIR): $(RUN_BASH) $(BLOCK_LIST) $(BIN_DIR)
+$(SRC_DIR):
+ @rm -rf $@ && mkdir -p $@
+ @cd $@ && git clone -b 20200921.0 https://github.com/jinzhao-dev/gvisor.git .
+endif
+
+$(TARGET_DIR): $(RUN_BASH) $(BLOCK_LIST)
@rm -rf $@ && mkdir -p $@
@# Prepare tests dir for test binaries
@mkdir $@/tests
diff --git a/regression/syscall_test/Makefile b/regression/syscall_test/Makefile
--- a/regression/syscall_test/Makefile
+++ b/regression/syscall_test/Makefile
@@ -36,8 +45,5 @@ $(TARGET_DIR): $(RUN_BASH) $(BLOCK_LIST) $(BIN_DIR)
@# Copy bash script
@cp -f $(RUN_BASH) $@
-$(TESTS): $(TARGET_DIR)
- @cp -f $(BIN_DIR)/$@ $(TARGET_DIR)/tests
-
clean:
- @rm -rf $(BIN_DIR) $(TARGET_DIR)
+ @rm -rf $(TARGET_DIR)
\ No newline at end of file
diff --git /dev/null b/tools/docker/.gitignore
new file mode 100644
--- /dev/null
+++ b/tools/docker/.gitignore
@@ -0,0 +1,1 @@
+bom/
diff --git /dev/null b/tools/docker/.gitignore
new file mode 100644
--- /dev/null
+++ b/tools/docker/.gitignore
@@ -0,0 +1,1 @@
+bom/
diff --git a/tools/docker/Dockerfile.ubuntu22.04 b/tools/docker/Dockerfile.ubuntu22.04
--- a/tools/docker/Dockerfile.ubuntu22.04
+++ b/tools/docker/Dockerfile.ubuntu22.04
@@ -1,27 +1,47 @@
-FROM ubuntu:22.04
+FROM ubuntu:22.04 as ubuntu-22.04-with-bazel
SHELL ["/bin/bash", "-c"]
ARG DEBIAN_FRONTEND=noninteractive
+
+# Install all Bazel dependent packages
RUN apt update && apt-get install -y --no-install-recommends \
build-essential \
ca-certificates \
+ curl \
+ git-core \
+ gnupg \
+ python-is-python3 \
+ python3-pip
+
+# Install bazel, which is required by the system call test suite from Gvisor project
+COPY bom/syscall_test/install_bazel.sh /tmp/
+WORKDIR /tmp
+RUN ./install_bazel.sh && rm -f /tmp/install_bazel.sh
+
+FROM ubuntu-22.04-with-bazel as syscall_test
+
+# Build the syscall test binaries
+COPY bom/syscall_test /root/syscall_test
+WORKDIR /root/syscall_test
+RUN export BUILD_DIR=build && \
+ make ${BUILD_DIR}/syscall_test_bins
+
+FROM ubuntu-22.04-with-bazel
+
+# Install all Jinux dependent packages
+RUN apt update && apt-get install -y --no-install-recommends \
cpio \
cpuid \
- curl \
file \
g++ \
gdb \
- git-core \
- gnupg \
grub-common \
grub-pc \
libssl-dev \
net-tools \
openssh-server \
pkg-config \
- python-is-python3 \
- python3-pip \
qemu-system-x86 \
strace \
sudo \
diff --git a/tools/docker/Dockerfile.ubuntu22.04 b/tools/docker/Dockerfile.ubuntu22.04
--- a/tools/docker/Dockerfile.ubuntu22.04
+++ b/tools/docker/Dockerfile.ubuntu22.04
@@ -31,17 +51,14 @@ RUN apt update && apt-get install -y --no-install-recommends \
xorriso \
zip
-# Install bazel, , which is required by the system call test suite from Gvisor project
-RUN curl -fsSL https://bazel.build/bazel-release.pub.gpg | gpg --dearmor > bazel.gpg \
- && mv bazel.gpg /etc/apt/trusted.gpg.d/ \
- && echo 'deb [arch=amd64] https://storage.googleapis.com/bazel-apt stable jdk1.8' | tee /etc/apt/sources.list.d/bazel.list \
- && apt update \
- && apt install bazel=5.4.0 -y
-
# Clean apt cache
RUN apt clean \
&& rm -rf /var/lib/apt/lists/*
+# Prepare the system call test suite
+COPY --from=syscall_test /root/syscall_test/build/syscall_test_bins /root/syscall_test_bins
+ENV JINUX_PREBUILT_SYSCALL_TEST=/root/syscall_test_bins
+
# Install Rust
ENV PATH="/root/.cargo/bin:${PATH}"
ARG JINUX_RUST_VERSION
diff --git a/tools/docker/build_image.sh b/tools/docker/build_image.sh
--- a/tools/docker/build_image.sh
+++ b/tools/docker/build_image.sh
@@ -7,10 +7,19 @@ CARGO_TOML_PATH=${SCRIPT_DIR}/../../Cargo.toml
VERSION=$( grep -m1 -o '[0-9]\+\.[0-9]\+\.[0-9]\+' ${CARGO_TOML_PATH} | sed 's/[^0-9\.]//g' )
IMAGE_NAME=jinuxdev/jinux:${VERSION}
DOCKER_FILE=${SCRIPT_DIR}/Dockerfile.ubuntu22.04
+BOM_DIR=${SCRIPT_DIR}/bom
+TOP_DIR=${SCRIPT_DIR}/../../
ARCH=linux/amd64
RUST_TOOLCHAIN_PATH=${SCRIPT_DIR}/../../rust-toolchain.toml
JINUX_RUST_VERSION=$( grep -m1 -o 'nightly-[0-9]\+-[0-9]\+-[0-9]\+' ${RUST_TOOLCHAIN_PATH} )
+# Prpare the BOM (bill of materials) directory to copy files or dirs into the docker image.
+# This is because the `docker build` can not access the parent directory of the context.
+if [ ! -d ${BOM_DIR} ]; then
+ mkdir -p ${BOM_DIR}
+ cp -rf ${TOP_DIR}/regression/syscall_test ${BOM_DIR}/
+fi
+
# Build docker
cd ${SCRIPT_DIR}
docker buildx build -f ${DOCKER_FILE} \
|
2023-07-27T07:11:21Z
|
25c4f0f2bcaa0bc8c650b0f4ee7b0d78e2a836b2
|
|
asterinas/asterinas
|
diff --git /dev/null b/services/libs/keyable-arc/src/lib.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/keyable-arc/src/lib.rs
@@ -0,0 +1,362 @@
+//! Same as the standard `Arc`, except that it can be used as the key type of a hash table.
+//!
+//! # Motivation
+//!
+//! A type `K` is _keyable_ if it can be used as the key type for a hash map. Specifically,
+//! according to the document of `std::collections::HashMap`, the type `K` must satisfy
+//! the following properties.
+//!
+//! 1. It implements the `Eq` and `Hash` traits.
+//! 2. The two values of `k1` and `k2` of type `K` equal to each other,
+//! if and only if their hash values equal to each other.
+//! 3. The hashes of a value of `k` of type `K` cannot change while it
+//! is in a map.
+//!
+//! Sometimes we want to use `Arc<T>` as the key type for a hash map but cannot do so
+//! since `T` does not satisfy the properties above. For example, a lot of types
+//! do not or cannot implemennt the `Eq` trait. This is when `KeyableArc<T>` can come
+//! to your aid.
+//!
+//! # Overview
+//!
+//! For any type `T`, `KeyableArc<T>` satisfies all the properties to be keyable.
+//! This can be achieved easily and efficiently as we can simply use the address
+//! of the data (of `T` type) of a `KeyableArc<T>` object in the heap to determine the
+//! equality and hash of the `KeyableArc<T>` object. As the address won't change for
+//! an immutable `KeyableArc<T>` object, the hash and equality also stay the same.
+//!
+//! This crate is `#[no_std]` compatible, but requires the `alloc` crate.
+//!
+//! # Usage
+//!
+//! Here is a basic example to how that `KeyableArc<T>` is keyable even when `T`
+//! is not.
+//!
+//! ```rust
+//! use std::collections::HashMap;
+//! use std::sync::Arc;
+//! use keyable_arc::KeyableArc;
+//!
+//! struct Dummy; // Does not implement Eq and Hash
+//!
+//! let map: HashMap<KeyableArc<Dummy>, String> = HashMap::new();
+//! ```
+//!
+//! `KeyableArc` is a reference counter-based smart pointer, just like `Arc`.
+//! So you can use `KeyableArc` the same way you would use `Arc`.
+//!
+//! ```rust
+//! use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
+//! use keyable_arc::KeyableArc;
+//!
+//! let key_arc0 = KeyableArc::new(AtomicU64::new(0));
+//! let key_arc1 = key_arc0.clone();
+//! assert!(key_arc0.load(Relaxed) == 0 && key_arc1.load(Relaxed) == 0);
+//!
+//! key_arc0.fetch_add(1, Relaxed);
+//! assert!(key_arc0.load(Relaxed) == 1 && key_arc1.load(Relaxed) == 1);
+//! ```
+//!
+//! # Differences from `Arc<T>`
+//!
+//! Notice how `KeyableArc` differs from standard smart pointers in determining equality?
+//! Two `KeyableArc` objects are considered different even when their data have the same
+//! value.
+//!
+//! ```rust
+//! use keyable_arc::KeyableArc;
+//!
+//! let key_arc0 = KeyableArc::new(0);
+//! let key_arc1 = key_arc0.clone();
+//! assert!(key_arc0 == key_arc1);
+//! assert!(*key_arc0 == *key_arc1);
+//!
+//! let key_arc1 = KeyableArc::new(0);
+//! assert!(key_arc0 != key_arc1);
+//! assert!(*key_arc0 == *key_arc1);
+//! ```
+//!
+//! `KeyableArc<T>` is simply a wrapper of `Arc<T>. So converting between them
+//! through the `From` and `Into` traits is zero cost.
+//!
+//! ```rust
+//! use std::sync::Arc;
+//! use keyable_arc::KeyableArc;
+//!
+//! let key_arc: KeyableArc<u32> = Arc::new(0).into();
+//! let arc: Arc<u32> = KeyableArc::new(0).into();
+//! ```
+//!
+//! # The weak version
+//!
+//! `KeyableWeak<T>` is the weak version of `KeyableArc<T>`, just like `Weak<T>` is
+//! that of `Arc<T>`. And of course, `KeyableWeak<T>` is also _keyable_ for any
+//! type `T`.
+
+// TODO: Add `KeyableBox<T>` or other keyable versions of smart pointers.
+// If this is needed in the future, this crate should be renamed to `keyable`.
+
+// TODO: Add the missing methods offered by `Arc` or `Weak` but not their
+// keyable counterparts.
+
+#![cfg_attr(not(test), no_std)]
+#![feature(coerce_unsized)]
+#![feature(unsize)]
+#![forbid(unsafe_code)]
+
+extern crate alloc;
+
+use alloc::sync::{Arc, Weak};
+use core::borrow::Borrow;
+use core::cmp::Ordering;
+use core::convert::AsRef;
+use core::fmt;
+use core::hash::{Hash, Hasher};
+use core::marker::Unsize;
+use core::ops::{CoerceUnsized, Deref};
+
+/// Same as the standard `Arc`, except that it can be used as the key type of a hash table.
+#[repr(transparent)]
+pub struct KeyableArc<T: ?Sized>(Arc<T>);
+
+impl<T> KeyableArc<T> {
+ /// Constructs a new instance of `KeyableArc<T>`.
+ #[inline]
+ pub fn new(data: T) -> Self {
+ Self(Arc::new(data))
+ }
+}
+
+impl<T: ?Sized> KeyableArc<T> {
+ /// Returns a raw pointer to the object `T` pointed to by this `KeyableArc<T>`.
+ #[inline]
+ pub fn as_ptr(this: &Self) -> *const T {
+ Arc::as_ptr(&this.0)
+ }
+
+ /// Creates a new `KeyableWeak` pointer to this allocation.
+ pub fn downgrade(this: &Self) -> KeyableWeak<T> {
+ Arc::downgrade(&this.0).into()
+ }
+}
+
+impl<T: ?Sized> Deref for KeyableArc<T> {
+ type Target = T;
+
+ #[inline]
+ fn deref(&self) -> &T {
+ &*self.0
+ }
+}
+
+impl<T: ?Sized> AsRef<T> for KeyableArc<T> {
+ #[inline]
+ fn as_ref(&self) -> &T {
+ &**self
+ }
+}
+
+impl<T: ?Sized> Borrow<T> for KeyableArc<T> {
+ #[inline]
+ fn borrow(&self) -> &T {
+ &**self
+ }
+}
+
+impl<T: ?Sized> From<Arc<T>> for KeyableArc<T> {
+ #[inline]
+ fn from(arc: Arc<T>) -> Self {
+ Self(arc)
+ }
+}
+
+impl<T: ?Sized> Into<Arc<T>> for KeyableArc<T> {
+ #[inline]
+ fn into(self) -> Arc<T> {
+ self.0
+ }
+}
+
+impl<T: ?Sized> PartialEq for KeyableArc<T> {
+ fn eq(&self, other: &Self) -> bool {
+ Arc::as_ptr(&self.0) == Arc::as_ptr(&other.0)
+ }
+}
+
+impl<T: ?Sized> Eq for KeyableArc<T> {}
+
+impl<T: ?Sized> PartialOrd for KeyableArc<T> {
+ fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+ Some(Arc::as_ptr(&self.0).cmp(&Arc::as_ptr(&other.0)))
+ }
+}
+
+impl<T: ?Sized> Ord for KeyableArc<T> {
+ fn cmp(&self, other: &Self) -> Ordering {
+ Arc::as_ptr(&self.0).cmp(&Arc::as_ptr(&other.0))
+ }
+}
+
+impl<T: ?Sized> Hash for KeyableArc<T> {
+ fn hash<H: Hasher>(&self, s: &mut H) {
+ Arc::as_ptr(&self.0).hash(s)
+ }
+}
+
+impl<T: ?Sized> Clone for KeyableArc<T> {
+ fn clone(&self) -> Self {
+ Self(self.0.clone())
+ }
+}
+
+impl<T: ?Sized + fmt::Debug> fmt::Debug for KeyableArc<T> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ fmt::Debug::fmt(&**self, f)
+ }
+}
+
+//=========================================================
+// The weak version
+//=========================================================
+
+/// The weak counterpart of `KeyableArc<T>`, similar to `Weak<T>`.
+///
+/// `KeyableWeak<T>` is also _keyable_ for any type `T` just like
+/// `KeyableArc<T>`.
+#[repr(transparent)]
+pub struct KeyableWeak<T: ?Sized>(Weak<T>);
+
+impl<T> KeyableWeak<T> {
+ /// Constructs a new `KeyableWeak<T>`, without allocating any memory.
+ /// Calling `upgrade` on the return value always gives `None`.
+ #[inline]
+ pub fn new() -> Self {
+ Self(Weak::new())
+ }
+
+ /// Returns a raw pointer to the object `T` pointed to by this `KeyableWeak<T>`.
+ ///
+ /// The pointer is valid only if there are some strong references.
+ /// The pointer may be dangling, unaligned or even null otherwise.
+ #[inline]
+ pub fn as_ptr(&self) -> *const T {
+ self.0.as_ptr()
+ }
+}
+
+impl<T: ?Sized> KeyableWeak<T> {
+ /// Attempts to upgrade the Weak pointer to an Arc,
+ /// delaying dropping of the inner value if successful.
+ ///
+ /// Returns None if the inner value has since been dropped.
+ #[inline]
+ pub fn upgrade(&self) -> Option<KeyableArc<T>> {
+ self.0.upgrade().map(|arc| arc.into())
+ }
+
+ /// Gets the number of strong pointers pointing to this allocation.
+ #[inline]
+ pub fn strong_count(&self) -> usize {
+ self.0.strong_count()
+ }
+
+ /// Gets the number of weak pointers pointing to this allocation.
+ #[inline]
+ pub fn weak_count(&self) -> usize {
+ self.0.weak_count()
+ }
+}
+
+impl<T: ?Sized> PartialEq for KeyableWeak<T> {
+ fn eq(&self, other: &Self) -> bool {
+ self.0.as_ptr() == other.0.as_ptr()
+ }
+}
+
+impl<T: ?Sized> Eq for KeyableWeak<T> {}
+
+impl<T: ?Sized> PartialOrd for KeyableWeak<T> {
+ fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+ Some(self.0.as_ptr().cmp(&other.0.as_ptr()))
+ }
+}
+
+impl<T: ?Sized> Ord for KeyableWeak<T> {
+ fn cmp(&self, other: &Self) -> Ordering {
+ self.0.as_ptr().cmp(&other.0.as_ptr())
+ }
+}
+
+impl<T: ?Sized> Hash for KeyableWeak<T> {
+ fn hash<H: Hasher>(&self, s: &mut H) {
+ self.0.as_ptr().hash(s)
+ }
+}
+
+impl<T: ?Sized> From<Weak<T>> for KeyableWeak<T> {
+ #[inline]
+ fn from(weak: Weak<T>) -> Self {
+ Self(weak)
+ }
+}
+
+impl<T: ?Sized> Into<Weak<T>> for KeyableWeak<T> {
+ #[inline]
+ fn into(self) -> Weak<T> {
+ self.0
+ }
+}
+
+impl<T: ?Sized + fmt::Debug> fmt::Debug for KeyableWeak<T> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "(KeyableWeak)")
+ }
+}
+
+// Enabling type coercing, e.g., converting from `KeyableArc<T>` to `KeyableArc<dyn S>`,
+// where `T` implements `S`.
+impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<KeyableArc<U>> for KeyableArc<T> {}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn downgrade_and_upgrade() {
+ let arc = KeyableArc::new(1);
+ let weak = KeyableArc::downgrade(&arc);
+ assert!(arc.clone() == weak.upgrade().unwrap());
+ assert!(weak == KeyableArc::downgrade(&arc));
+ }
+
+ #[test]
+ fn debug_format() {
+ println!("{:?}", KeyableArc::new(1u32));
+ println!("{:?}", KeyableWeak::<u32>::new());
+ }
+
+ #[test]
+ fn use_as_key() {
+ use std::collections::HashMap;
+
+ let mut map: HashMap<KeyableArc<u32>, u32> = HashMap::new();
+ let key = KeyableArc::new(1);
+ let val = 1;
+ map.insert(key.clone(), val);
+ assert!(map.get(&key) == Some(&val));
+ assert!(map.remove(&key) == Some(val));
+ assert!(map.keys().count() == 0);
+ }
+
+ #[test]
+ fn as_trait_object() {
+ trait DummyTrait {}
+ struct DummyStruct;
+ impl DummyTrait for DummyStruct {}
+
+ let arc_struct = KeyableArc::new(DummyStruct);
+ let arc_dyn0: KeyableArc<dyn DummyTrait> = arc_struct.clone();
+ let arc_dyn1: KeyableArc<dyn DummyTrait> = arc_struct.clone();
+ assert!(arc_dyn0 == arc_dyn1);
+ }
+}
|
[
"124"
] |
0.1
|
7e1584fca9b0bb818ea8f115ab471bc21613b7bd
|
Implement the epoll system call
|
asterinas__asterinas-193
| 193
|
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -145,6 +145,15 @@ dependencies = [
name = "cpio-decoder"
version = "0.1.0"
+[[package]]
+name = "crossbeam-utils"
+version = "0.8.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c063cd8cc95f5c377ed0d4b49a4b21f632396ff690e8470c29b3359b346984b"
+dependencies = [
+ "cfg-if",
+]
+
[[package]]
name = "ctor"
version = "0.1.25"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -145,6 +145,15 @@ dependencies = [
name = "cpio-decoder"
version = "0.1.0"
+[[package]]
+name = "crossbeam-utils"
+version = "0.8.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c063cd8cc95f5c377ed0d4b49a4b21f632396ff690e8470c29b3359b346984b"
+dependencies = [
+ "cfg-if",
+]
+
[[package]]
name = "ctor"
version = "0.1.25"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -359,11 +368,12 @@ dependencies = [
"jinux-rights-proc",
"jinux-time",
"jinux-util",
+ "keyable-arc",
"lazy_static",
"log",
"lru",
"pod",
- "ringbuffer",
+ "ringbuf",
"spin 0.9.4",
"time",
"typeflags",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -359,11 +368,12 @@ dependencies = [
"jinux-rights-proc",
"jinux-time",
"jinux-util",
+ "keyable-arc",
"lazy_static",
"log",
"lru",
"pod",
- "ringbuffer",
+ "ringbuf",
"spin 0.9.4",
"time",
"typeflags",
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -411,6 +421,10 @@ version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "078e285eafdfb6c4b434e0d31e8cfcb5115b651496faca5749b88fafd4f23bfd"
+[[package]]
+name = "keyable-arc"
+version = "0.1.0"
+
[[package]]
name = "lazy_static"
version = "1.4.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -411,6 +421,10 @@ version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "078e285eafdfb6c4b434e0d31e8cfcb5115b651496faca5749b88fafd4f23bfd"
+[[package]]
+name = "keyable-arc"
+version = "0.1.0"
+
[[package]]
name = "lazy_static"
version = "1.4.0"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -536,10 +550,13 @@ dependencies = [
]
[[package]]
-name = "ringbuffer"
-version = "0.10.0"
+name = "ringbuf"
+version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "310a2514cb46bb500a2f2ad70c79c51c5a475cc23faa245d2c675faabe889370"
+checksum = "93ca10b9c9e53ac855a2d6953bce34cef6edbac32c4b13047a4d59d67299420a"
+dependencies = [
+ "crossbeam-utils",
+]
[[package]]
name = "rsdp"
diff --git a/Cargo.lock b/Cargo.lock
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -536,10 +550,13 @@ dependencies = [
]
[[package]]
-name = "ringbuffer"
-version = "0.10.0"
+name = "ringbuf"
+version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "310a2514cb46bb500a2f2ad70c79c51c5a475cc23faa245d2c675faabe889370"
+checksum = "93ca10b9c9e53ac855a2d6953bce34cef6edbac32c4b13047a4d59d67299420a"
+dependencies = [
+ "crossbeam-utils",
+]
[[package]]
name = "rsdp"
diff --git a/services/libs/jinux-std/Cargo.toml b/services/libs/jinux-std/Cargo.toml
--- a/services/libs/jinux-std/Cargo.toml
+++ b/services/libs/jinux-std/Cargo.toml
@@ -28,7 +28,8 @@ xmas-elf = "0.8.0"
# goblin = {version= "0.5.3", default-features = false, features = ["elf64"]}
# data-structures
bitflags = "1.3"
-ringbuffer = "0.10.0"
+ringbuf = { version = "0.3.2", default-features = false, features = ["alloc"] }
+keyable-arc = { path = "../keyable-arc" }
spin = "0.9.4"
vte = "0.10"
diff --git a/services/libs/jinux-std/Cargo.toml b/services/libs/jinux-std/Cargo.toml
--- a/services/libs/jinux-std/Cargo.toml
+++ b/services/libs/jinux-std/Cargo.toml
@@ -28,7 +28,8 @@ xmas-elf = "0.8.0"
# goblin = {version= "0.5.3", default-features = false, features = ["elf64"]}
# data-structures
bitflags = "1.3"
-ringbuffer = "0.10.0"
+ringbuf = { version = "0.3.2", default-features = false, features = ["alloc"] }
+keyable-arc = { path = "../keyable-arc" }
spin = "0.9.4"
vte = "0.10"
diff --git a/services/libs/jinux-std/src/events/events.rs b/services/libs/jinux-std/src/events/events.rs
--- a/services/libs/jinux-std/src/events/events.rs
+++ b/services/libs/jinux-std/src/events/events.rs
@@ -1,2 +1,34 @@
/// A trait to represent any events.
pub trait Events: Copy + Clone + Send + Sync + 'static {}
+
+/// A trait to filter events.
+///
+/// # The no-op event filter
+///
+/// The unit type `()` can serve as a no-op event filter.
+/// It implements `EventsFilter<E>` for any events type `E`,
+/// with a `filter` method that always returns `true`.
+/// If the `F` type of `Subject<E, F>` is not specified explicitly,
+/// then the unit type `()` is chosen as the event filter.
+///
+/// # Per-object event filter
+///
+/// Any `Option<F: EventsFilter>` is also an event filter thanks to
+/// the blanket implementations the `EventsFilter` trait.
+/// By using `Option<F: EventsFilter>`, we can decide, on a per-observer basis,
+/// if an observer needs an event filter.
+pub trait EventsFilter<E: Events>: Send + Sync + 'static {
+ fn filter(&self, event: &E) -> bool;
+}
+
+impl<E: Events> EventsFilter<E> for () {
+ fn filter(&self, _events: &E) -> bool {
+ true
+ }
+}
+
+impl<E: Events, F: EventsFilter<E>> EventsFilter<E> for Option<F> {
+ fn filter(&self, events: &E) -> bool {
+ self.as_ref().map_or(true, |f| f.filter(events))
+ }
+}
diff --git a/services/libs/jinux-std/src/events/events.rs b/services/libs/jinux-std/src/events/events.rs
--- a/services/libs/jinux-std/src/events/events.rs
+++ b/services/libs/jinux-std/src/events/events.rs
@@ -1,2 +1,34 @@
/// A trait to represent any events.
pub trait Events: Copy + Clone + Send + Sync + 'static {}
+
+/// A trait to filter events.
+///
+/// # The no-op event filter
+///
+/// The unit type `()` can serve as a no-op event filter.
+/// It implements `EventsFilter<E>` for any events type `E`,
+/// with a `filter` method that always returns `true`.
+/// If the `F` type of `Subject<E, F>` is not specified explicitly,
+/// then the unit type `()` is chosen as the event filter.
+///
+/// # Per-object event filter
+///
+/// Any `Option<F: EventsFilter>` is also an event filter thanks to
+/// the blanket implementations the `EventsFilter` trait.
+/// By using `Option<F: EventsFilter>`, we can decide, on a per-observer basis,
+/// if an observer needs an event filter.
+pub trait EventsFilter<E: Events>: Send + Sync + 'static {
+ fn filter(&self, event: &E) -> bool;
+}
+
+impl<E: Events> EventsFilter<E> for () {
+ fn filter(&self, _events: &E) -> bool {
+ true
+ }
+}
+
+impl<E: Events, F: EventsFilter<E>> EventsFilter<E> for Option<F> {
+ fn filter(&self, events: &E) -> bool {
+ self.as_ref().map_or(true, |f| f.filter(events))
+ }
+}
diff --git a/services/libs/jinux-std/src/events/mod.rs b/services/libs/jinux-std/src/events/mod.rs
--- a/services/libs/jinux-std/src/events/mod.rs
+++ b/services/libs/jinux-std/src/events/mod.rs
@@ -2,6 +2,6 @@ mod events;
mod observer;
mod subject;
-pub use self::events::Events;
+pub use self::events::{Events, EventsFilter};
pub use self::observer::Observer;
pub use self::subject::Subject;
diff --git a/services/libs/jinux-std/src/events/mod.rs b/services/libs/jinux-std/src/events/mod.rs
--- a/services/libs/jinux-std/src/events/mod.rs
+++ b/services/libs/jinux-std/src/events/mod.rs
@@ -2,6 +2,6 @@ mod events;
mod observer;
mod subject;
-pub use self::events::Events;
+pub use self::events::{Events, EventsFilter};
pub use self::observer::Observer;
pub use self::subject::Subject;
diff --git a/services/libs/jinux-std/src/events/subject.rs b/services/libs/jinux-std/src/events/subject.rs
--- a/services/libs/jinux-std/src/events/subject.rs
+++ b/services/libs/jinux-std/src/events/subject.rs
@@ -1,43 +1,86 @@
use crate::prelude::*;
-use super::{Events, Observer};
+use core::sync::atomic::{AtomicUsize, Ordering};
+use keyable_arc::KeyableWeak;
-/// A Subject notify interesting events to registered observers.
-pub struct Subject<E: Events> {
- observers: Mutex<Vec<Weak<dyn Observer<E>>>>,
+use super::{Events, EventsFilter, Observer};
+
+/// A Subject notifies interesting events to registered observers.
+pub struct Subject<E: Events, F: EventsFilter<E> = ()> {
+ // A table that maintains all interesting observers.
+ observers: Mutex<BTreeMap<KeyableWeak<dyn Observer<E>>, F>>,
+ // To reduce lock contentions, we maintain a counter for the size of the table
+ num_observers: AtomicUsize,
}
-impl<E: Events> Subject<E> {
+impl<E: Events, F: EventsFilter<E>> Subject<E, F> {
pub fn new() -> Self {
Self {
- observers: Mutex::new(Vec::new()),
+ observers: Mutex::new(BTreeMap::new()),
+ num_observers: AtomicUsize::new(0),
}
}
/// Register an observer.
- pub fn register_observer(&self, observer: Weak<dyn Observer<E>>) {
+ ///
+ /// A registered observer will get notified through its `on_events` method.
+ /// If events `filter` is provided, only filtered events will notify the observer.
+ ///
+ /// If the given observer has already been registered, then its registered events
+ /// filter will be updated.
+ pub fn register_observer(&self, observer: Weak<dyn Observer<E>>, filter: F) {
let mut observers = self.observers.lock();
- observers.push(observer);
+ let is_new = {
+ let observer: KeyableWeak<dyn Observer<E>> = observer.into();
+ observers.insert(observer, filter).is_none()
+ };
+ if is_new {
+ self.num_observers.fetch_add(1, Ordering::Release);
+ }
}
/// Unregister an observer.
- pub fn unregister_observer(&self, observer: Weak<dyn Observer<E>>) {
+ ///
+ /// If such an observer is found, then the registered observer will be
+ /// removed from the subject and returned as the return value. Otherwise,
+ /// a `None` will be returned.
+ pub fn unregister_observer(
+ &self,
+ observer: &Weak<dyn Observer<E>>,
+ ) -> Option<Weak<dyn Observer<E>>> {
+ let observer: KeyableWeak<dyn Observer<E>> = observer.clone().into();
let mut observers = self.observers.lock();
- observers.retain(|e| !Weak::ptr_eq(&e, &observer));
+ let observer = observers
+ .remove_entry(&observer)
+ .map(|(observer, _)| observer.into());
+ if observer.is_some() {
+ self.num_observers.fetch_sub(1, Ordering::Relaxed);
+ }
+ observer
}
/// Notify events to all registered observers.
+ ///
/// It will remove the observers which have been freed.
pub fn notify_observers(&self, events: &E) {
+ // Fast path.
+ if self.num_observers.load(Ordering::Relaxed) == 0 {
+ return;
+ }
+
+ // Slow path: broadcast the new events to all observers.
let mut observers = self.observers.lock();
- let mut idx = 0;
- while idx < observers.len() {
- if let Some(observer) = observers[idx].upgrade() {
+ observers.retain(|observer, filter| {
+ if let Some(observer) = observer.upgrade() {
+ if !filter.filter(events) {
+ return true;
+ }
observer.on_events(events);
- idx += 1;
+ true
} else {
- observers.remove(idx);
+ self.num_observers.fetch_sub(1, Ordering::Relaxed);
+ false
}
- }
+ });
}
}
diff --git a/services/libs/jinux-std/src/events/subject.rs b/services/libs/jinux-std/src/events/subject.rs
--- a/services/libs/jinux-std/src/events/subject.rs
+++ b/services/libs/jinux-std/src/events/subject.rs
@@ -1,43 +1,86 @@
use crate::prelude::*;
-use super::{Events, Observer};
+use core::sync::atomic::{AtomicUsize, Ordering};
+use keyable_arc::KeyableWeak;
-/// A Subject notify interesting events to registered observers.
-pub struct Subject<E: Events> {
- observers: Mutex<Vec<Weak<dyn Observer<E>>>>,
+use super::{Events, EventsFilter, Observer};
+
+/// A Subject notifies interesting events to registered observers.
+pub struct Subject<E: Events, F: EventsFilter<E> = ()> {
+ // A table that maintains all interesting observers.
+ observers: Mutex<BTreeMap<KeyableWeak<dyn Observer<E>>, F>>,
+ // To reduce lock contentions, we maintain a counter for the size of the table
+ num_observers: AtomicUsize,
}
-impl<E: Events> Subject<E> {
+impl<E: Events, F: EventsFilter<E>> Subject<E, F> {
pub fn new() -> Self {
Self {
- observers: Mutex::new(Vec::new()),
+ observers: Mutex::new(BTreeMap::new()),
+ num_observers: AtomicUsize::new(0),
}
}
/// Register an observer.
- pub fn register_observer(&self, observer: Weak<dyn Observer<E>>) {
+ ///
+ /// A registered observer will get notified through its `on_events` method.
+ /// If events `filter` is provided, only filtered events will notify the observer.
+ ///
+ /// If the given observer has already been registered, then its registered events
+ /// filter will be updated.
+ pub fn register_observer(&self, observer: Weak<dyn Observer<E>>, filter: F) {
let mut observers = self.observers.lock();
- observers.push(observer);
+ let is_new = {
+ let observer: KeyableWeak<dyn Observer<E>> = observer.into();
+ observers.insert(observer, filter).is_none()
+ };
+ if is_new {
+ self.num_observers.fetch_add(1, Ordering::Release);
+ }
}
/// Unregister an observer.
- pub fn unregister_observer(&self, observer: Weak<dyn Observer<E>>) {
+ ///
+ /// If such an observer is found, then the registered observer will be
+ /// removed from the subject and returned as the return value. Otherwise,
+ /// a `None` will be returned.
+ pub fn unregister_observer(
+ &self,
+ observer: &Weak<dyn Observer<E>>,
+ ) -> Option<Weak<dyn Observer<E>>> {
+ let observer: KeyableWeak<dyn Observer<E>> = observer.clone().into();
let mut observers = self.observers.lock();
- observers.retain(|e| !Weak::ptr_eq(&e, &observer));
+ let observer = observers
+ .remove_entry(&observer)
+ .map(|(observer, _)| observer.into());
+ if observer.is_some() {
+ self.num_observers.fetch_sub(1, Ordering::Relaxed);
+ }
+ observer
}
/// Notify events to all registered observers.
+ ///
/// It will remove the observers which have been freed.
pub fn notify_observers(&self, events: &E) {
+ // Fast path.
+ if self.num_observers.load(Ordering::Relaxed) == 0 {
+ return;
+ }
+
+ // Slow path: broadcast the new events to all observers.
let mut observers = self.observers.lock();
- let mut idx = 0;
- while idx < observers.len() {
- if let Some(observer) = observers[idx].upgrade() {
+ observers.retain(|observer, filter| {
+ if let Some(observer) = observer.upgrade() {
+ if !filter.filter(events) {
+ return true;
+ }
observer.on_events(events);
- idx += 1;
+ true
} else {
- observers.remove(idx);
+ self.num_observers.fetch_sub(1, Ordering::Relaxed);
+ false
}
- }
+ });
}
}
diff --git /dev/null b/services/libs/jinux-std/src/fs/epoll/epoll_file.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/fs/epoll/epoll_file.rs
@@ -0,0 +1,490 @@
+use crate::events::Observer;
+use crate::fs::file_handle::FileLike;
+use crate::fs::file_table::{FdEvents, FileDescripter};
+use crate::fs::utils::{IoEvents, IoctlCmd, Pollee, Poller};
+
+use core::sync::atomic::{AtomicBool, Ordering};
+use core::time::Duration;
+
+use super::*;
+
+/// A file-like object that provides epoll API.
+///
+/// Conceptually, we maintain two lists: one consists of all interesting files,
+/// which can be managed by the epoll ctl commands; the other are for ready files,
+/// which are files that have some events. A epoll wait only needs to iterate the
+/// ready list and poll each file to see if the file is ready for the interesting
+/// I/O.
+///
+/// To maintain the ready list, we need to monitor interesting events that happen
+/// on the files. To do so, the `EpollFile` registers itself as an `Observer` to
+/// the monotored files. Thus, we can add a file to the ready list when an interesting
+/// event happens on the file.
+pub struct EpollFile {
+ // All interesting entries.
+ interest: Mutex<BTreeMap<FileDescripter, Arc<EpollEntry>>>,
+ // Entries that are probably ready (having events happened).
+ ready: Mutex<VecDeque<Arc<EpollEntry>>>,
+ // EpollFile itself is also pollable
+ pollee: Pollee,
+ // Any EpollFile is wrapped with Arc when created.
+ weak_self: Weak<Self>,
+}
+
+impl EpollFile {
+ /// Creates a new epoll file.
+ pub fn new() -> Arc<Self> {
+ Arc::new_cyclic(|me| Self {
+ interest: Mutex::new(BTreeMap::new()),
+ ready: Mutex::new(VecDeque::new()),
+ pollee: Pollee::new(IoEvents::empty()),
+ weak_self: me.clone(),
+ })
+ }
+
+ /// Control the interest list of the epoll file.
+ pub fn control(&self, cmd: &EpollCtl) -> Result<()> {
+ match *cmd {
+ EpollCtl::Add(fd, ep_event, ep_flags) => self.add_interest(fd, ep_event, ep_flags),
+ EpollCtl::Del(fd) => {
+ self.del_interest(fd)?;
+ self.unregister_from_file_table_entry(fd);
+ Ok(())
+ }
+ EpollCtl::Mod(fd, ep_event, ep_flags) => self.mod_interest(fd, ep_event, ep_flags),
+ }
+ }
+
+ fn add_interest(
+ &self,
+ fd: FileDescripter,
+ ep_event: EpollEvent,
+ ep_flags: EpollFlags,
+ ) -> Result<()> {
+ self.warn_unsupported_flags(&ep_flags);
+
+ let current = current!();
+ let file_table = current.file_table().lock();
+ let file_table_entry = file_table.get_entry(fd)?;
+ let file = file_table_entry.file();
+ let weak_file = Arc::downgrade(file);
+ let mask = ep_event.events;
+ let entry = EpollEntry::new(fd, weak_file, ep_event, ep_flags, self.weak_self.clone());
+
+ // Add the new entry to the interest list and start monitering its events
+ let mut interest = self.interest.lock();
+ if interest.contains_key(&fd) {
+ return_errno_with_message!(Errno::EEXIST, "the fd has been added");
+ }
+ file.register_observer(entry.self_weak() as _, IoEvents::all())?;
+ interest.insert(fd, entry.clone());
+ // Register self to the file table entry
+ file_table_entry.register_observer(self.weak_self.clone() as _);
+ let file = file.clone();
+ drop(file_table);
+ drop(interest);
+
+ // Add the new entry to the ready list if the file is ready
+ let events = file.poll(mask, None);
+ if !events.is_empty() {
+ self.push_ready(entry);
+ }
+ Ok(())
+ }
+
+ fn del_interest(&self, fd: FileDescripter) -> Result<()> {
+ let mut interest = self.interest.lock();
+ let entry = interest
+ .remove(&fd)
+ .ok_or_else(|| Error::with_message(Errno::ENOENT, "fd is not in the interest list"))?;
+
+ // If this epoll entry is in the ready list, then we should delete it.
+ // But unfortunately, deleting an entry from the ready list has a
+ // complexity of O(N).
+ //
+ // To optimize the performance, we only mark the epoll entry as
+ // deleted at this moment. The real deletion happens when the ready list
+ // is scanned in EpolFile::wait.
+ entry.set_deleted();
+
+ let file = match entry.file() {
+ Some(file) => file,
+ // TODO: should we warn about it?
+ None => return Ok(()),
+ };
+
+ file.unregister_observer(&(entry.self_weak() as _)).unwrap();
+ Ok(())
+ }
+
+ fn mod_interest(
+ &self,
+ fd: FileDescripter,
+ new_ep_event: EpollEvent,
+ new_ep_flags: EpollFlags,
+ ) -> Result<()> {
+ self.warn_unsupported_flags(&new_ep_flags);
+
+ // Update the epoll entry
+ let interest = self.interest.lock();
+ let entry = interest
+ .get(&fd)
+ .ok_or_else(|| Error::with_message(Errno::ENOENT, "fd is not in the interest list"))?;
+ if entry.is_deleted() {
+ return_errno_with_message!(Errno::ENOENT, "fd is not in the interest list");
+ }
+ let new_mask = new_ep_event.events;
+ entry.update(new_ep_event, new_ep_flags);
+ let entry = entry.clone();
+ drop(interest);
+
+ // Add the updated entry to the ready list if the file is ready
+ let file = match entry.file() {
+ Some(file) => file,
+ None => return Ok(()),
+ };
+ let events = file.poll(new_mask, None);
+ if !events.is_empty() {
+ self.push_ready(entry);
+ }
+ Ok(())
+ }
+
+ fn unregister_from_file_table_entry(&self, fd: FileDescripter) {
+ let current = current!();
+ let file_table = current.file_table().lock();
+ if let Ok(entry) = file_table.get_entry(fd) {
+ entry.unregister_observer(&(self.weak_self.clone() as _));
+ }
+ }
+
+ /// Wait for interesting events happen on the files in the interest list
+ /// of the epoll file.
+ ///
+ /// This method blocks until either some interesting events happen or
+ /// the timeout expires or a signal arrives. The first case returns
+ /// `Ok(events)`, where `events` is a `Vec` containing at most `max_events`
+ /// number of `EpollEvent`s. The second and third case returns errors.
+ ///
+ /// When `max_events` equals to zero, the method returns when the timeout
+ /// expires or a signal arrives.
+ pub fn wait(&self, max_events: usize, timeout: Option<&Duration>) -> Result<Vec<EpollEvent>> {
+ let mut ep_events = Vec::new();
+ let mut poller = None;
+ loop {
+ // Try to pop some ready entries
+ if self.pop_ready(max_events, &mut ep_events) > 0 {
+ return Ok(ep_events);
+ }
+
+ // Return immediately if specifying a timeout of zero
+ if timeout.is_some() && timeout.as_ref().unwrap().is_zero() {
+ return Ok(ep_events);
+ }
+
+ // If no ready entries for now, wait for them
+ if poller.is_none() {
+ poller = Some(Poller::new());
+ let events = self.pollee.poll(IoEvents::IN, poller.as_ref());
+ if !events.is_empty() {
+ continue;
+ }
+ }
+
+ // FIXME: respect timeout parameter
+ poller.as_ref().unwrap().wait();
+ }
+ }
+
+ fn push_ready(&self, entry: Arc<EpollEntry>) {
+ let mut ready = self.ready.lock();
+ if entry.is_deleted() {
+ return;
+ }
+
+ if !entry.is_ready() {
+ entry.set_ready();
+ ready.push_back(entry);
+ }
+
+ // Even if the entry is already set to ready, there might be new events that we are interested in.
+ // Wake the poller anyway.
+ self.pollee.add_events(IoEvents::IN);
+ }
+
+ fn pop_ready(&self, max_events: usize, ep_events: &mut Vec<EpollEvent>) -> usize {
+ let mut count_events = 0;
+ let mut ready = self.ready.lock();
+ let mut pop_quota = ready.len();
+ loop {
+ // Pop some ready entries per round.
+ //
+ // Since the popped ready entries may contain "false positive" and
+ // we want to return as many results as possible, this has to
+ // be done in a loop.
+ let pop_count = (max_events - count_events).min(pop_quota);
+ if pop_count == 0 {
+ break;
+ }
+ let ready_entries: Vec<Arc<EpollEntry>> = ready
+ .drain(..pop_count)
+ .filter(|entry| !entry.is_deleted())
+ .collect();
+ pop_quota -= pop_count;
+
+ // Examine these ready entries, which are candidates for the results
+ // to be returned.
+ for entry in ready_entries {
+ let (ep_event, ep_flags) = entry.event_and_flags();
+ // If this entry's file is ready, save it in the output array.
+ // EPOLLHUP and EPOLLERR should always be reported.
+ let ready_events = entry.poll() & (ep_event.events | IoEvents::HUP | IoEvents::ERR);
+ if !ready_events.is_empty() {
+ ep_events.push(EpollEvent::new(ready_events, ep_event.user_data));
+ count_events += 1;
+ }
+
+ // If the epoll entry is neither edge-triggered or one-shot, then we should
+ // keep the entry in the ready list.
+ if !ep_flags.intersects(EpollFlags::ONE_SHOT | EpollFlags::EDGE_TRIGGER) {
+ ready.push_back(entry);
+ }
+ // Otherwise, the entry is indeed removed the ready list and we should reset
+ // its ready flag.
+ else {
+ entry.reset_ready();
+ // For EPOLLONESHOT flag, this entry should also be removed from the interest list
+ if ep_flags.intersects(EpollFlags::ONE_SHOT) {
+ self.del_interest(entry.fd())
+ .expect("this entry should be in the interest list");
+ }
+ }
+ }
+ }
+
+ // Clear the epoll file's events if no ready entries
+ if ready.len() == 0 {
+ self.pollee.del_events(IoEvents::IN);
+ }
+ count_events
+ }
+
+ fn warn_unsupported_flags(&self, flags: &EpollFlags) {
+ if flags.intersects(EpollFlags::EXCLUSIVE | EpollFlags::WAKE_UP) {
+ warn!("{:?} contains unsupported flags", flags);
+ }
+ }
+}
+
+impl Observer<FdEvents> for EpollFile {
+ fn on_events(&self, events: &FdEvents) {
+ // Delete the file from the interest list if it is closed.
+ if let FdEvents::Close(fd) = events {
+ let _ = self.del_interest(*fd);
+ }
+ }
+}
+
+impl Drop for EpollFile {
+ fn drop(&mut self) {
+ trace!("EpollFile Drop");
+ let mut interest = self.interest.lock();
+ let fds: Vec<_> = interest
+ .drain_filter(|_, _| true)
+ .map(|(fd, entry)| {
+ entry.set_deleted();
+ if let Some(file) = entry.file() {
+ let _ = file.unregister_observer(&(entry.self_weak() as _));
+ }
+ fd
+ })
+ .collect();
+ drop(interest);
+
+ fds.iter()
+ .for_each(|&fd| self.unregister_from_file_table_entry(fd));
+ }
+}
+
+// Implement the common methods required by FileHandle
+impl FileLike for EpollFile {
+ fn read(&self, buf: &mut [u8]) -> Result<usize> {
+ return_errno_with_message!(Errno::EINVAL, "epoll files do not support read");
+ }
+
+ fn write(&self, buf: &[u8]) -> Result<usize> {
+ return_errno_with_message!(Errno::EINVAL, "epoll files do not support write");
+ }
+
+ fn ioctl(&self, _cmd: IoctlCmd, _arg: usize) -> Result<i32> {
+ return_errno_with_message!(Errno::EINVAL, "epoll files do not support ioctl");
+ }
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ self.pollee.poll(mask, poller)
+ }
+
+ fn register_observer(
+ &self,
+ observer: Weak<dyn Observer<IoEvents>>,
+ mask: IoEvents,
+ ) -> Result<()> {
+ self.pollee.register_observer(observer, mask);
+ Ok(())
+ }
+
+ fn unregister_observer(
+ &self,
+ observer: &Weak<dyn Observer<IoEvents>>,
+ ) -> Result<Weak<dyn Observer<IoEvents>>> {
+ self.pollee
+ .unregister_observer(observer)
+ .ok_or_else(|| Error::with_message(Errno::ENOENT, "observer is not registered"))
+ }
+
+ fn as_any_ref(&self) -> &dyn Any {
+ self
+ }
+}
+
+/// An epoll entry contained in an epoll file. Each epoll entry is added, modified,
+/// or deleted by the `EpollCtl` command.
+pub struct EpollEntry {
+ fd: FileDescripter,
+ file: Weak<dyn FileLike>,
+ inner: Mutex<Inner>,
+ // Whether the entry is in the ready list
+ is_ready: AtomicBool,
+ // Whether the entry has been deleted from the interest list
+ is_deleted: AtomicBool,
+ // Refers to the epoll file containing this epoll entry
+ weak_epoll: Weak<EpollFile>,
+ // An EpollEntry is always contained inside Arc
+ weak_self: Weak<Self>,
+}
+
+struct Inner {
+ event: EpollEvent,
+ flags: EpollFlags,
+}
+
+impl EpollEntry {
+ /// Creates a new epoll entry associated with the given epoll file.
+ pub fn new(
+ fd: FileDescripter,
+ file: Weak<dyn FileLike>,
+ event: EpollEvent,
+ flags: EpollFlags,
+ weak_epoll: Weak<EpollFile>,
+ ) -> Arc<Self> {
+ Arc::new_cyclic(|me| Self {
+ fd,
+ file,
+ inner: Mutex::new(Inner { event, flags }),
+ is_ready: AtomicBool::new(false),
+ is_deleted: AtomicBool::new(false),
+ weak_epoll,
+ weak_self: me.clone(),
+ })
+ }
+
+ /// Get the epoll file associated with this epoll entry.
+ pub fn epoll_file(&self) -> Option<Arc<EpollFile>> {
+ self.weak_epoll.upgrade()
+ }
+
+ /// Get an instance of `Arc` that refers to this epoll entry.
+ pub fn self_arc(&self) -> Arc<Self> {
+ self.weak_self.upgrade().unwrap()
+ }
+
+ /// Get an instance of `Weak` that refers to this epoll entry.
+ pub fn self_weak(&self) -> Weak<Self> {
+ self.weak_self.clone()
+ }
+
+ /// Get the file associated with this epoll entry.
+ ///
+ /// Since an epoll entry only holds a weak reference to the file,
+ /// it is possible (albeit unlikely) that the file has been dropped.
+ pub fn file(&self) -> Option<Arc<dyn FileLike>> {
+ self.file.upgrade()
+ }
+
+ /// Get the epoll event associated with the epoll entry.
+ pub fn event(&self) -> EpollEvent {
+ let inner = self.inner.lock();
+ inner.event
+ }
+
+ /// Get the epoll flags associated with the epoll entry.
+ pub fn flags(&self) -> EpollFlags {
+ let inner = self.inner.lock();
+ inner.flags
+ }
+
+ /// Get the epoll event and flags that are associated with this epoll entry.
+ pub fn event_and_flags(&self) -> (EpollEvent, EpollFlags) {
+ let inner = self.inner.lock();
+ (inner.event, inner.flags)
+ }
+
+ /// Poll the events of the file associated with this epoll entry.
+ ///
+ /// If the returned events is not empty, then the file is considered ready.
+ pub fn poll(&self) -> IoEvents {
+ match self.file.upgrade() {
+ Some(file) => file.poll(IoEvents::all(), None),
+ None => IoEvents::empty(),
+ }
+ }
+
+ /// Update the epoll entry, most likely to be triggered via `EpollCtl::Mod`.
+ pub fn update(&self, event: EpollEvent, flags: EpollFlags) {
+ let mut inner = self.inner.lock();
+ *inner = Inner { event, flags }
+ }
+
+ /// Returns whether the epoll entry is in the ready list.
+ pub fn is_ready(&self) -> bool {
+ self.is_ready.load(Ordering::Relaxed)
+ }
+
+ /// Mark the epoll entry as being in the ready list.
+ pub fn set_ready(&self) {
+ self.is_ready.store(true, Ordering::Relaxed);
+ }
+
+ /// Mark the epoll entry as not being in the ready list.
+ pub fn reset_ready(&self) {
+ self.is_ready.store(false, Ordering::Relaxed)
+ }
+
+ /// Returns whether the epoll entry has been deleted from the interest list.
+ pub fn is_deleted(&self) -> bool {
+ self.is_deleted.load(Ordering::Relaxed)
+ }
+
+ /// Mark the epoll entry as having been deleted from the interest list.
+ pub fn set_deleted(&self) {
+ self.is_deleted.store(true, Ordering::Relaxed);
+ }
+
+ /// Get the file descriptor associated with the epoll entry.
+ pub fn fd(&self) -> FileDescripter {
+ self.fd
+ }
+}
+
+impl Observer<IoEvents> for EpollEntry {
+ fn on_events(&self, _events: &IoEvents) {
+ // Fast path
+ if self.is_deleted() {
+ return;
+ }
+
+ if let Some(epoll_file) = self.epoll_file() {
+ epoll_file.push_ready(self.self_arc());
+ }
+ }
+}
diff --git /dev/null b/services/libs/jinux-std/src/fs/epoll/epoll_file.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/fs/epoll/epoll_file.rs
@@ -0,0 +1,490 @@
+use crate::events::Observer;
+use crate::fs::file_handle::FileLike;
+use crate::fs::file_table::{FdEvents, FileDescripter};
+use crate::fs::utils::{IoEvents, IoctlCmd, Pollee, Poller};
+
+use core::sync::atomic::{AtomicBool, Ordering};
+use core::time::Duration;
+
+use super::*;
+
+/// A file-like object that provides epoll API.
+///
+/// Conceptually, we maintain two lists: one consists of all interesting files,
+/// which can be managed by the epoll ctl commands; the other are for ready files,
+/// which are files that have some events. A epoll wait only needs to iterate the
+/// ready list and poll each file to see if the file is ready for the interesting
+/// I/O.
+///
+/// To maintain the ready list, we need to monitor interesting events that happen
+/// on the files. To do so, the `EpollFile` registers itself as an `Observer` to
+/// the monotored files. Thus, we can add a file to the ready list when an interesting
+/// event happens on the file.
+pub struct EpollFile {
+ // All interesting entries.
+ interest: Mutex<BTreeMap<FileDescripter, Arc<EpollEntry>>>,
+ // Entries that are probably ready (having events happened).
+ ready: Mutex<VecDeque<Arc<EpollEntry>>>,
+ // EpollFile itself is also pollable
+ pollee: Pollee,
+ // Any EpollFile is wrapped with Arc when created.
+ weak_self: Weak<Self>,
+}
+
+impl EpollFile {
+ /// Creates a new epoll file.
+ pub fn new() -> Arc<Self> {
+ Arc::new_cyclic(|me| Self {
+ interest: Mutex::new(BTreeMap::new()),
+ ready: Mutex::new(VecDeque::new()),
+ pollee: Pollee::new(IoEvents::empty()),
+ weak_self: me.clone(),
+ })
+ }
+
+ /// Control the interest list of the epoll file.
+ pub fn control(&self, cmd: &EpollCtl) -> Result<()> {
+ match *cmd {
+ EpollCtl::Add(fd, ep_event, ep_flags) => self.add_interest(fd, ep_event, ep_flags),
+ EpollCtl::Del(fd) => {
+ self.del_interest(fd)?;
+ self.unregister_from_file_table_entry(fd);
+ Ok(())
+ }
+ EpollCtl::Mod(fd, ep_event, ep_flags) => self.mod_interest(fd, ep_event, ep_flags),
+ }
+ }
+
+ fn add_interest(
+ &self,
+ fd: FileDescripter,
+ ep_event: EpollEvent,
+ ep_flags: EpollFlags,
+ ) -> Result<()> {
+ self.warn_unsupported_flags(&ep_flags);
+
+ let current = current!();
+ let file_table = current.file_table().lock();
+ let file_table_entry = file_table.get_entry(fd)?;
+ let file = file_table_entry.file();
+ let weak_file = Arc::downgrade(file);
+ let mask = ep_event.events;
+ let entry = EpollEntry::new(fd, weak_file, ep_event, ep_flags, self.weak_self.clone());
+
+ // Add the new entry to the interest list and start monitering its events
+ let mut interest = self.interest.lock();
+ if interest.contains_key(&fd) {
+ return_errno_with_message!(Errno::EEXIST, "the fd has been added");
+ }
+ file.register_observer(entry.self_weak() as _, IoEvents::all())?;
+ interest.insert(fd, entry.clone());
+ // Register self to the file table entry
+ file_table_entry.register_observer(self.weak_self.clone() as _);
+ let file = file.clone();
+ drop(file_table);
+ drop(interest);
+
+ // Add the new entry to the ready list if the file is ready
+ let events = file.poll(mask, None);
+ if !events.is_empty() {
+ self.push_ready(entry);
+ }
+ Ok(())
+ }
+
+ fn del_interest(&self, fd: FileDescripter) -> Result<()> {
+ let mut interest = self.interest.lock();
+ let entry = interest
+ .remove(&fd)
+ .ok_or_else(|| Error::with_message(Errno::ENOENT, "fd is not in the interest list"))?;
+
+ // If this epoll entry is in the ready list, then we should delete it.
+ // But unfortunately, deleting an entry from the ready list has a
+ // complexity of O(N).
+ //
+ // To optimize the performance, we only mark the epoll entry as
+ // deleted at this moment. The real deletion happens when the ready list
+ // is scanned in EpolFile::wait.
+ entry.set_deleted();
+
+ let file = match entry.file() {
+ Some(file) => file,
+ // TODO: should we warn about it?
+ None => return Ok(()),
+ };
+
+ file.unregister_observer(&(entry.self_weak() as _)).unwrap();
+ Ok(())
+ }
+
+ fn mod_interest(
+ &self,
+ fd: FileDescripter,
+ new_ep_event: EpollEvent,
+ new_ep_flags: EpollFlags,
+ ) -> Result<()> {
+ self.warn_unsupported_flags(&new_ep_flags);
+
+ // Update the epoll entry
+ let interest = self.interest.lock();
+ let entry = interest
+ .get(&fd)
+ .ok_or_else(|| Error::with_message(Errno::ENOENT, "fd is not in the interest list"))?;
+ if entry.is_deleted() {
+ return_errno_with_message!(Errno::ENOENT, "fd is not in the interest list");
+ }
+ let new_mask = new_ep_event.events;
+ entry.update(new_ep_event, new_ep_flags);
+ let entry = entry.clone();
+ drop(interest);
+
+ // Add the updated entry to the ready list if the file is ready
+ let file = match entry.file() {
+ Some(file) => file,
+ None => return Ok(()),
+ };
+ let events = file.poll(new_mask, None);
+ if !events.is_empty() {
+ self.push_ready(entry);
+ }
+ Ok(())
+ }
+
+ fn unregister_from_file_table_entry(&self, fd: FileDescripter) {
+ let current = current!();
+ let file_table = current.file_table().lock();
+ if let Ok(entry) = file_table.get_entry(fd) {
+ entry.unregister_observer(&(self.weak_self.clone() as _));
+ }
+ }
+
+ /// Wait for interesting events happen on the files in the interest list
+ /// of the epoll file.
+ ///
+ /// This method blocks until either some interesting events happen or
+ /// the timeout expires or a signal arrives. The first case returns
+ /// `Ok(events)`, where `events` is a `Vec` containing at most `max_events`
+ /// number of `EpollEvent`s. The second and third case returns errors.
+ ///
+ /// When `max_events` equals to zero, the method returns when the timeout
+ /// expires or a signal arrives.
+ pub fn wait(&self, max_events: usize, timeout: Option<&Duration>) -> Result<Vec<EpollEvent>> {
+ let mut ep_events = Vec::new();
+ let mut poller = None;
+ loop {
+ // Try to pop some ready entries
+ if self.pop_ready(max_events, &mut ep_events) > 0 {
+ return Ok(ep_events);
+ }
+
+ // Return immediately if specifying a timeout of zero
+ if timeout.is_some() && timeout.as_ref().unwrap().is_zero() {
+ return Ok(ep_events);
+ }
+
+ // If no ready entries for now, wait for them
+ if poller.is_none() {
+ poller = Some(Poller::new());
+ let events = self.pollee.poll(IoEvents::IN, poller.as_ref());
+ if !events.is_empty() {
+ continue;
+ }
+ }
+
+ // FIXME: respect timeout parameter
+ poller.as_ref().unwrap().wait();
+ }
+ }
+
+ fn push_ready(&self, entry: Arc<EpollEntry>) {
+ let mut ready = self.ready.lock();
+ if entry.is_deleted() {
+ return;
+ }
+
+ if !entry.is_ready() {
+ entry.set_ready();
+ ready.push_back(entry);
+ }
+
+ // Even if the entry is already set to ready, there might be new events that we are interested in.
+ // Wake the poller anyway.
+ self.pollee.add_events(IoEvents::IN);
+ }
+
+ fn pop_ready(&self, max_events: usize, ep_events: &mut Vec<EpollEvent>) -> usize {
+ let mut count_events = 0;
+ let mut ready = self.ready.lock();
+ let mut pop_quota = ready.len();
+ loop {
+ // Pop some ready entries per round.
+ //
+ // Since the popped ready entries may contain "false positive" and
+ // we want to return as many results as possible, this has to
+ // be done in a loop.
+ let pop_count = (max_events - count_events).min(pop_quota);
+ if pop_count == 0 {
+ break;
+ }
+ let ready_entries: Vec<Arc<EpollEntry>> = ready
+ .drain(..pop_count)
+ .filter(|entry| !entry.is_deleted())
+ .collect();
+ pop_quota -= pop_count;
+
+ // Examine these ready entries, which are candidates for the results
+ // to be returned.
+ for entry in ready_entries {
+ let (ep_event, ep_flags) = entry.event_and_flags();
+ // If this entry's file is ready, save it in the output array.
+ // EPOLLHUP and EPOLLERR should always be reported.
+ let ready_events = entry.poll() & (ep_event.events | IoEvents::HUP | IoEvents::ERR);
+ if !ready_events.is_empty() {
+ ep_events.push(EpollEvent::new(ready_events, ep_event.user_data));
+ count_events += 1;
+ }
+
+ // If the epoll entry is neither edge-triggered or one-shot, then we should
+ // keep the entry in the ready list.
+ if !ep_flags.intersects(EpollFlags::ONE_SHOT | EpollFlags::EDGE_TRIGGER) {
+ ready.push_back(entry);
+ }
+ // Otherwise, the entry is indeed removed the ready list and we should reset
+ // its ready flag.
+ else {
+ entry.reset_ready();
+ // For EPOLLONESHOT flag, this entry should also be removed from the interest list
+ if ep_flags.intersects(EpollFlags::ONE_SHOT) {
+ self.del_interest(entry.fd())
+ .expect("this entry should be in the interest list");
+ }
+ }
+ }
+ }
+
+ // Clear the epoll file's events if no ready entries
+ if ready.len() == 0 {
+ self.pollee.del_events(IoEvents::IN);
+ }
+ count_events
+ }
+
+ fn warn_unsupported_flags(&self, flags: &EpollFlags) {
+ if flags.intersects(EpollFlags::EXCLUSIVE | EpollFlags::WAKE_UP) {
+ warn!("{:?} contains unsupported flags", flags);
+ }
+ }
+}
+
+impl Observer<FdEvents> for EpollFile {
+ fn on_events(&self, events: &FdEvents) {
+ // Delete the file from the interest list if it is closed.
+ if let FdEvents::Close(fd) = events {
+ let _ = self.del_interest(*fd);
+ }
+ }
+}
+
+impl Drop for EpollFile {
+ fn drop(&mut self) {
+ trace!("EpollFile Drop");
+ let mut interest = self.interest.lock();
+ let fds: Vec<_> = interest
+ .drain_filter(|_, _| true)
+ .map(|(fd, entry)| {
+ entry.set_deleted();
+ if let Some(file) = entry.file() {
+ let _ = file.unregister_observer(&(entry.self_weak() as _));
+ }
+ fd
+ })
+ .collect();
+ drop(interest);
+
+ fds.iter()
+ .for_each(|&fd| self.unregister_from_file_table_entry(fd));
+ }
+}
+
+// Implement the common methods required by FileHandle
+impl FileLike for EpollFile {
+ fn read(&self, buf: &mut [u8]) -> Result<usize> {
+ return_errno_with_message!(Errno::EINVAL, "epoll files do not support read");
+ }
+
+ fn write(&self, buf: &[u8]) -> Result<usize> {
+ return_errno_with_message!(Errno::EINVAL, "epoll files do not support write");
+ }
+
+ fn ioctl(&self, _cmd: IoctlCmd, _arg: usize) -> Result<i32> {
+ return_errno_with_message!(Errno::EINVAL, "epoll files do not support ioctl");
+ }
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ self.pollee.poll(mask, poller)
+ }
+
+ fn register_observer(
+ &self,
+ observer: Weak<dyn Observer<IoEvents>>,
+ mask: IoEvents,
+ ) -> Result<()> {
+ self.pollee.register_observer(observer, mask);
+ Ok(())
+ }
+
+ fn unregister_observer(
+ &self,
+ observer: &Weak<dyn Observer<IoEvents>>,
+ ) -> Result<Weak<dyn Observer<IoEvents>>> {
+ self.pollee
+ .unregister_observer(observer)
+ .ok_or_else(|| Error::with_message(Errno::ENOENT, "observer is not registered"))
+ }
+
+ fn as_any_ref(&self) -> &dyn Any {
+ self
+ }
+}
+
+/// An epoll entry contained in an epoll file. Each epoll entry is added, modified,
+/// or deleted by the `EpollCtl` command.
+pub struct EpollEntry {
+ fd: FileDescripter,
+ file: Weak<dyn FileLike>,
+ inner: Mutex<Inner>,
+ // Whether the entry is in the ready list
+ is_ready: AtomicBool,
+ // Whether the entry has been deleted from the interest list
+ is_deleted: AtomicBool,
+ // Refers to the epoll file containing this epoll entry
+ weak_epoll: Weak<EpollFile>,
+ // An EpollEntry is always contained inside Arc
+ weak_self: Weak<Self>,
+}
+
+struct Inner {
+ event: EpollEvent,
+ flags: EpollFlags,
+}
+
+impl EpollEntry {
+ /// Creates a new epoll entry associated with the given epoll file.
+ pub fn new(
+ fd: FileDescripter,
+ file: Weak<dyn FileLike>,
+ event: EpollEvent,
+ flags: EpollFlags,
+ weak_epoll: Weak<EpollFile>,
+ ) -> Arc<Self> {
+ Arc::new_cyclic(|me| Self {
+ fd,
+ file,
+ inner: Mutex::new(Inner { event, flags }),
+ is_ready: AtomicBool::new(false),
+ is_deleted: AtomicBool::new(false),
+ weak_epoll,
+ weak_self: me.clone(),
+ })
+ }
+
+ /// Get the epoll file associated with this epoll entry.
+ pub fn epoll_file(&self) -> Option<Arc<EpollFile>> {
+ self.weak_epoll.upgrade()
+ }
+
+ /// Get an instance of `Arc` that refers to this epoll entry.
+ pub fn self_arc(&self) -> Arc<Self> {
+ self.weak_self.upgrade().unwrap()
+ }
+
+ /// Get an instance of `Weak` that refers to this epoll entry.
+ pub fn self_weak(&self) -> Weak<Self> {
+ self.weak_self.clone()
+ }
+
+ /// Get the file associated with this epoll entry.
+ ///
+ /// Since an epoll entry only holds a weak reference to the file,
+ /// it is possible (albeit unlikely) that the file has been dropped.
+ pub fn file(&self) -> Option<Arc<dyn FileLike>> {
+ self.file.upgrade()
+ }
+
+ /// Get the epoll event associated with the epoll entry.
+ pub fn event(&self) -> EpollEvent {
+ let inner = self.inner.lock();
+ inner.event
+ }
+
+ /// Get the epoll flags associated with the epoll entry.
+ pub fn flags(&self) -> EpollFlags {
+ let inner = self.inner.lock();
+ inner.flags
+ }
+
+ /// Get the epoll event and flags that are associated with this epoll entry.
+ pub fn event_and_flags(&self) -> (EpollEvent, EpollFlags) {
+ let inner = self.inner.lock();
+ (inner.event, inner.flags)
+ }
+
+ /// Poll the events of the file associated with this epoll entry.
+ ///
+ /// If the returned events is not empty, then the file is considered ready.
+ pub fn poll(&self) -> IoEvents {
+ match self.file.upgrade() {
+ Some(file) => file.poll(IoEvents::all(), None),
+ None => IoEvents::empty(),
+ }
+ }
+
+ /// Update the epoll entry, most likely to be triggered via `EpollCtl::Mod`.
+ pub fn update(&self, event: EpollEvent, flags: EpollFlags) {
+ let mut inner = self.inner.lock();
+ *inner = Inner { event, flags }
+ }
+
+ /// Returns whether the epoll entry is in the ready list.
+ pub fn is_ready(&self) -> bool {
+ self.is_ready.load(Ordering::Relaxed)
+ }
+
+ /// Mark the epoll entry as being in the ready list.
+ pub fn set_ready(&self) {
+ self.is_ready.store(true, Ordering::Relaxed);
+ }
+
+ /// Mark the epoll entry as not being in the ready list.
+ pub fn reset_ready(&self) {
+ self.is_ready.store(false, Ordering::Relaxed)
+ }
+
+ /// Returns whether the epoll entry has been deleted from the interest list.
+ pub fn is_deleted(&self) -> bool {
+ self.is_deleted.load(Ordering::Relaxed)
+ }
+
+ /// Mark the epoll entry as having been deleted from the interest list.
+ pub fn set_deleted(&self) {
+ self.is_deleted.store(true, Ordering::Relaxed);
+ }
+
+ /// Get the file descriptor associated with the epoll entry.
+ pub fn fd(&self) -> FileDescripter {
+ self.fd
+ }
+}
+
+impl Observer<IoEvents> for EpollEntry {
+ fn on_events(&self, _events: &IoEvents) {
+ // Fast path
+ if self.is_deleted() {
+ return;
+ }
+
+ if let Some(epoll_file) = self.epoll_file() {
+ epoll_file.push_ready(self.self_arc());
+ }
+ }
+}
diff --git /dev/null b/services/libs/jinux-std/src/fs/epoll/mod.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/fs/epoll/mod.rs
@@ -0,0 +1,72 @@
+use super::file_table::FileDescripter;
+use super::utils::IoEvents;
+use crate::prelude::*;
+
+mod epoll_file;
+
+pub use self::epoll_file::EpollFile;
+
+/// An epoll control command.
+#[derive(Copy, Clone, Debug, PartialEq)]
+pub enum EpollCtl {
+ Add(FileDescripter, EpollEvent, EpollFlags),
+ Del(FileDescripter),
+ Mod(FileDescripter, EpollEvent, EpollFlags),
+}
+
+bitflags! {
+ /// Linux's epoll flags.
+ pub struct EpollFlags: u32 {
+ const EXCLUSIVE = (1 << 28);
+ const WAKE_UP = (1 << 29);
+ const ONE_SHOT = (1 << 30);
+ const EDGE_TRIGGER = (1 << 31);
+ }
+}
+
+/// An epoll event.
+///
+/// This could be used as either an input of epoll ctl or an output of epoll wait.
+/// The memory layout is compatible with that of C's struct epoll_event.
+#[derive(Copy, Clone, Debug, PartialEq)]
+pub struct EpollEvent {
+ /// I/O events.
+ ///
+ /// When `EpollEvent` is used as inputs, this is treated as a mask of events.
+ /// When `EpollEvent` is used as outputs, this is the active events.
+ pub events: IoEvents,
+ /// A 64-bit, user-given data.
+ pub user_data: u64,
+}
+
+impl EpollEvent {
+ /// Create a new epoll event.
+ pub fn new(events: IoEvents, user_data: u64) -> Self {
+ Self { events, user_data }
+ }
+}
+
+impl From<&c_epoll_event> for EpollEvent {
+ fn from(c_event: &c_epoll_event) -> Self {
+ Self {
+ events: IoEvents::from_bits_truncate(c_event.events as u32),
+ user_data: c_event.data,
+ }
+ }
+}
+
+impl From<&EpollEvent> for c_epoll_event {
+ fn from(ep_event: &EpollEvent) -> Self {
+ Self {
+ events: ep_event.events.bits() as u32,
+ data: ep_event.user_data,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, Pod)]
+#[repr(C)]
+pub struct c_epoll_event {
+ pub events: u32,
+ pub data: u64,
+}
diff --git /dev/null b/services/libs/jinux-std/src/fs/epoll/mod.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/fs/epoll/mod.rs
@@ -0,0 +1,72 @@
+use super::file_table::FileDescripter;
+use super::utils::IoEvents;
+use crate::prelude::*;
+
+mod epoll_file;
+
+pub use self::epoll_file::EpollFile;
+
+/// An epoll control command.
+#[derive(Copy, Clone, Debug, PartialEq)]
+pub enum EpollCtl {
+ Add(FileDescripter, EpollEvent, EpollFlags),
+ Del(FileDescripter),
+ Mod(FileDescripter, EpollEvent, EpollFlags),
+}
+
+bitflags! {
+ /// Linux's epoll flags.
+ pub struct EpollFlags: u32 {
+ const EXCLUSIVE = (1 << 28);
+ const WAKE_UP = (1 << 29);
+ const ONE_SHOT = (1 << 30);
+ const EDGE_TRIGGER = (1 << 31);
+ }
+}
+
+/// An epoll event.
+///
+/// This could be used as either an input of epoll ctl or an output of epoll wait.
+/// The memory layout is compatible with that of C's struct epoll_event.
+#[derive(Copy, Clone, Debug, PartialEq)]
+pub struct EpollEvent {
+ /// I/O events.
+ ///
+ /// When `EpollEvent` is used as inputs, this is treated as a mask of events.
+ /// When `EpollEvent` is used as outputs, this is the active events.
+ pub events: IoEvents,
+ /// A 64-bit, user-given data.
+ pub user_data: u64,
+}
+
+impl EpollEvent {
+ /// Create a new epoll event.
+ pub fn new(events: IoEvents, user_data: u64) -> Self {
+ Self { events, user_data }
+ }
+}
+
+impl From<&c_epoll_event> for EpollEvent {
+ fn from(c_event: &c_epoll_event) -> Self {
+ Self {
+ events: IoEvents::from_bits_truncate(c_event.events as u32),
+ user_data: c_event.data,
+ }
+ }
+}
+
+impl From<&EpollEvent> for c_epoll_event {
+ fn from(ep_event: &EpollEvent) -> Self {
+ Self {
+ events: ep_event.events.bits() as u32,
+ data: ep_event.user_data,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, Pod)]
+#[repr(C)]
+pub struct c_epoll_event {
+ pub events: u32,
+ pub data: u64,
+}
diff --git /dev/null b/services/libs/jinux-std/src/fs/file_handle.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/fs/file_handle.rs
@@ -0,0 +1,74 @@
+//! Opend File Handle
+
+use crate::events::Observer;
+use crate::fs::utils::{IoEvents, IoctlCmd, Metadata, Poller, SeekFrom};
+use crate::prelude::*;
+use crate::tty::get_n_tty;
+
+use core::any::Any;
+
+/// The basic operations defined on a file
+pub trait FileLike: Send + Sync + Any {
+ fn read(&self, buf: &mut [u8]) -> Result<usize> {
+ return_errno_with_message!(Errno::EINVAL, "read is not supported");
+ }
+
+ fn write(&self, buf: &[u8]) -> Result<usize> {
+ return_errno_with_message!(Errno::EINVAL, "write is not supported");
+ }
+
+ fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
+ match cmd {
+ IoctlCmd::TCGETS => {
+ // FIXME: only a work around
+ let tty = get_n_tty();
+ tty.ioctl(cmd, arg)
+ }
+ _ => panic!("Ioctl unsupported"),
+ }
+ }
+
+ fn poll(&self, _mask: IoEvents, _poller: Option<&Poller>) -> IoEvents {
+ IoEvents::empty()
+ }
+
+ fn flush(&self) -> Result<()> {
+ Ok(())
+ }
+
+ fn metadata(&self) -> Metadata {
+ panic!("metadata unsupported");
+ }
+
+ fn seek(&self, seek_from: SeekFrom) -> Result<usize> {
+ return_errno_with_message!(Errno::EINVAL, "seek is not supported");
+ }
+
+ fn clean_for_close(&self) -> Result<()> {
+ self.flush()?;
+ Ok(())
+ }
+
+ fn register_observer(
+ &self,
+ observer: Weak<dyn Observer<IoEvents>>,
+ mask: IoEvents,
+ ) -> Result<()> {
+ return_errno_with_message!(Errno::EINVAL, "register_observer is not supported")
+ }
+
+ fn unregister_observer(
+ &self,
+ observer: &Weak<dyn Observer<IoEvents>>,
+ ) -> Result<Weak<dyn Observer<IoEvents>>> {
+ return_errno_with_message!(Errno::EINVAL, "unregister_observer is not supported")
+ }
+
+ fn as_any_ref(&self) -> &dyn Any;
+}
+
+impl dyn FileLike {
+ pub fn downcast_ref<T: FileLike>(&self) -> Option<&T> {
+ self.as_any_ref().downcast_ref::<T>()
+ }
+}
diff --git /dev/null b/services/libs/jinux-std/src/fs/file_handle.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/fs/file_handle.rs
@@ -0,0 +1,74 @@
+//! Opend File Handle
+
+use crate::events::Observer;
+use crate::fs::utils::{IoEvents, IoctlCmd, Metadata, Poller, SeekFrom};
+use crate::prelude::*;
+use crate::tty::get_n_tty;
+
+use core::any::Any;
+
+/// The basic operations defined on a file
+pub trait FileLike: Send + Sync + Any {
+ fn read(&self, buf: &mut [u8]) -> Result<usize> {
+ return_errno_with_message!(Errno::EINVAL, "read is not supported");
+ }
+
+ fn write(&self, buf: &[u8]) -> Result<usize> {
+ return_errno_with_message!(Errno::EINVAL, "write is not supported");
+ }
+
+ fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
+ match cmd {
+ IoctlCmd::TCGETS => {
+ // FIXME: only a work around
+ let tty = get_n_tty();
+ tty.ioctl(cmd, arg)
+ }
+ _ => panic!("Ioctl unsupported"),
+ }
+ }
+
+ fn poll(&self, _mask: IoEvents, _poller: Option<&Poller>) -> IoEvents {
+ IoEvents::empty()
+ }
+
+ fn flush(&self) -> Result<()> {
+ Ok(())
+ }
+
+ fn metadata(&self) -> Metadata {
+ panic!("metadata unsupported");
+ }
+
+ fn seek(&self, seek_from: SeekFrom) -> Result<usize> {
+ return_errno_with_message!(Errno::EINVAL, "seek is not supported");
+ }
+
+ fn clean_for_close(&self) -> Result<()> {
+ self.flush()?;
+ Ok(())
+ }
+
+ fn register_observer(
+ &self,
+ observer: Weak<dyn Observer<IoEvents>>,
+ mask: IoEvents,
+ ) -> Result<()> {
+ return_errno_with_message!(Errno::EINVAL, "register_observer is not supported")
+ }
+
+ fn unregister_observer(
+ &self,
+ observer: &Weak<dyn Observer<IoEvents>>,
+ ) -> Result<Weak<dyn Observer<IoEvents>>> {
+ return_errno_with_message!(Errno::EINVAL, "unregister_observer is not supported")
+ }
+
+ fn as_any_ref(&self) -> &dyn Any;
+}
+
+impl dyn FileLike {
+ pub fn downcast_ref<T: FileLike>(&self) -> Option<&T> {
+ self.as_any_ref().downcast_ref::<T>()
+ }
+}
diff --git a/services/libs/jinux-std/src/fs/file_handle/file.rs /dev/null
--- a/services/libs/jinux-std/src/fs/file_handle/file.rs
+++ /dev/null
@@ -1,43 +0,0 @@
-use crate::fs::utils::{IoEvents, IoctlCmd, Metadata, SeekFrom};
-use crate::prelude::*;
-use crate::tty::get_n_tty;
-
-use core::any::Any;
-
-/// The basic operations defined on a file
-pub trait File: Send + Sync + Any {
- fn read(&self, buf: &mut [u8]) -> Result<usize> {
- panic!("read unsupported");
- }
-
- fn write(&self, buf: &[u8]) -> Result<usize> {
- panic!("write unsupported");
- }
-
- fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
- match cmd {
- IoctlCmd::TCGETS => {
- // FIXME: only a work around
- let tty = get_n_tty();
- tty.ioctl(cmd, arg)
- }
- _ => panic!("Ioctl unsupported"),
- }
- }
-
- fn poll(&self) -> IoEvents {
- IoEvents::empty()
- }
-
- fn flush(&self) -> Result<()> {
- Ok(())
- }
-
- fn metadata(&self) -> Metadata {
- panic!("metadata unsupported");
- }
-
- fn seek(&self, seek_from: SeekFrom) -> Result<usize> {
- panic!("seek unsupported");
- }
-}
diff --git a/services/libs/jinux-std/src/fs/file_handle/file.rs /dev/null
--- a/services/libs/jinux-std/src/fs/file_handle/file.rs
+++ /dev/null
@@ -1,43 +0,0 @@
-use crate::fs::utils::{IoEvents, IoctlCmd, Metadata, SeekFrom};
-use crate::prelude::*;
-use crate::tty::get_n_tty;
-
-use core::any::Any;
-
-/// The basic operations defined on a file
-pub trait File: Send + Sync + Any {
- fn read(&self, buf: &mut [u8]) -> Result<usize> {
- panic!("read unsupported");
- }
-
- fn write(&self, buf: &[u8]) -> Result<usize> {
- panic!("write unsupported");
- }
-
- fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
- match cmd {
- IoctlCmd::TCGETS => {
- // FIXME: only a work around
- let tty = get_n_tty();
- tty.ioctl(cmd, arg)
- }
- _ => panic!("Ioctl unsupported"),
- }
- }
-
- fn poll(&self) -> IoEvents {
- IoEvents::empty()
- }
-
- fn flush(&self) -> Result<()> {
- Ok(())
- }
-
- fn metadata(&self) -> Metadata {
- panic!("metadata unsupported");
- }
-
- fn seek(&self, seek_from: SeekFrom) -> Result<usize> {
- panic!("seek unsupported");
- }
-}
diff --git a/services/libs/jinux-std/src/fs/file_handle/mod.rs /dev/null
--- a/services/libs/jinux-std/src/fs/file_handle/mod.rs
+++ /dev/null
@@ -1,93 +0,0 @@
-//! Opend File Handle
-
-mod file;
-mod inode_handle;
-
-use crate::fs::utils::{Metadata, SeekFrom};
-use crate::prelude::*;
-use crate::rights::{ReadOp, WriteOp};
-use alloc::sync::Arc;
-
-pub use self::file::File;
-pub use self::inode_handle::InodeHandle;
-
-#[derive(Clone)]
-pub struct FileHandle {
- inner: Inner,
-}
-
-#[derive(Clone)]
-enum Inner {
- File(Arc<dyn File>),
- Inode(InodeHandle),
-}
-
-impl FileHandle {
- pub fn new_file(file: Arc<dyn File>) -> Self {
- let inner = Inner::File(file);
- Self { inner }
- }
-
- pub fn new_inode_handle(inode_handle: InodeHandle) -> Self {
- let inner = Inner::Inode(inode_handle);
- Self { inner }
- }
-
- pub fn as_file(&self) -> Option<&Arc<dyn File>> {
- match &self.inner {
- Inner::File(file) => Some(file),
- _ => None,
- }
- }
-
- pub fn as_inode_handle(&self) -> Option<&InodeHandle> {
- match &self.inner {
- Inner::Inode(inode_handle) => Some(inode_handle),
- _ => None,
- }
- }
-
- pub fn read(&self, buf: &mut [u8]) -> Result<usize> {
- match &self.inner {
- Inner::File(file) => file.read(buf),
- Inner::Inode(inode_handle) => {
- let static_handle = inode_handle.clone().to_static::<ReadOp>()?;
- static_handle.read(buf)
- }
- }
- }
-
- pub fn write(&self, buf: &[u8]) -> Result<usize> {
- match &self.inner {
- Inner::File(file) => file.write(buf),
- Inner::Inode(inode_handle) => {
- let static_handle = inode_handle.clone().to_static::<WriteOp>()?;
- static_handle.write(buf)
- }
- }
- }
-
- pub fn metadata(&self) -> Metadata {
- match &self.inner {
- Inner::File(file) => file.metadata(),
- Inner::Inode(inode_handle) => inode_handle.dentry().vnode().metadata(),
- }
- }
-
- pub fn seek(&self, seek_from: SeekFrom) -> Result<usize> {
- match &self.inner {
- Inner::File(file) => file.seek(seek_from),
- Inner::Inode(inode_handle) => inode_handle.seek(seek_from),
- }
- }
-
- pub fn clean_for_close(&self) -> Result<()> {
- match &self.inner {
- Inner::Inode(_) => {
- // Close does not guarantee that the data has been successfully saved to disk.
- }
- Inner::File(file) => file.flush()?,
- }
- Ok(())
- }
-}
diff --git a/services/libs/jinux-std/src/fs/file_handle/mod.rs /dev/null
--- a/services/libs/jinux-std/src/fs/file_handle/mod.rs
+++ /dev/null
@@ -1,93 +0,0 @@
-//! Opend File Handle
-
-mod file;
-mod inode_handle;
-
-use crate::fs::utils::{Metadata, SeekFrom};
-use crate::prelude::*;
-use crate::rights::{ReadOp, WriteOp};
-use alloc::sync::Arc;
-
-pub use self::file::File;
-pub use self::inode_handle::InodeHandle;
-
-#[derive(Clone)]
-pub struct FileHandle {
- inner: Inner,
-}
-
-#[derive(Clone)]
-enum Inner {
- File(Arc<dyn File>),
- Inode(InodeHandle),
-}
-
-impl FileHandle {
- pub fn new_file(file: Arc<dyn File>) -> Self {
- let inner = Inner::File(file);
- Self { inner }
- }
-
- pub fn new_inode_handle(inode_handle: InodeHandle) -> Self {
- let inner = Inner::Inode(inode_handle);
- Self { inner }
- }
-
- pub fn as_file(&self) -> Option<&Arc<dyn File>> {
- match &self.inner {
- Inner::File(file) => Some(file),
- _ => None,
- }
- }
-
- pub fn as_inode_handle(&self) -> Option<&InodeHandle> {
- match &self.inner {
- Inner::Inode(inode_handle) => Some(inode_handle),
- _ => None,
- }
- }
-
- pub fn read(&self, buf: &mut [u8]) -> Result<usize> {
- match &self.inner {
- Inner::File(file) => file.read(buf),
- Inner::Inode(inode_handle) => {
- let static_handle = inode_handle.clone().to_static::<ReadOp>()?;
- static_handle.read(buf)
- }
- }
- }
-
- pub fn write(&self, buf: &[u8]) -> Result<usize> {
- match &self.inner {
- Inner::File(file) => file.write(buf),
- Inner::Inode(inode_handle) => {
- let static_handle = inode_handle.clone().to_static::<WriteOp>()?;
- static_handle.write(buf)
- }
- }
- }
-
- pub fn metadata(&self) -> Metadata {
- match &self.inner {
- Inner::File(file) => file.metadata(),
- Inner::Inode(inode_handle) => inode_handle.dentry().vnode().metadata(),
- }
- }
-
- pub fn seek(&self, seek_from: SeekFrom) -> Result<usize> {
- match &self.inner {
- Inner::File(file) => file.seek(seek_from),
- Inner::Inode(inode_handle) => inode_handle.seek(seek_from),
- }
- }
-
- pub fn clean_for_close(&self) -> Result<()> {
- match &self.inner {
- Inner::Inode(_) => {
- // Close does not guarantee that the data has been successfully saved to disk.
- }
- Inner::File(file) => file.flush()?,
- }
- Ok(())
- }
-}
diff --git a/services/libs/jinux-std/src/fs/file_table.rs b/services/libs/jinux-std/src/fs/file_table.rs
--- a/services/libs/jinux-std/src/fs/file_table.rs
+++ b/services/libs/jinux-std/src/fs/file_table.rs
@@ -1,105 +1,128 @@
use crate::events::{Events, Observer, Subject};
use crate::prelude::*;
+use core::cell::Cell;
+use jinux_util::slot_vec::SlotVec;
+
use super::{
- file_handle::FileHandle,
- stdio::{Stderr, Stdin, Stdout, FD_STDERR, FD_STDIN, FD_STDOUT},
+ file_handle::FileLike,
+ stdio::{Stderr, Stdin, Stdout},
};
pub type FileDescripter = i32;
pub struct FileTable {
- table: BTreeMap<FileDescripter, FileHandle>,
+ table: SlotVec<FileTableEntry>,
subject: Subject<FdEvents>,
}
impl FileTable {
pub fn new() -> Self {
Self {
- table: BTreeMap::new(),
+ table: SlotVec::new(),
subject: Subject::new(),
}
}
pub fn new_with_stdio() -> Self {
- let mut table = BTreeMap::new();
+ let mut table = SlotVec::new();
let stdin = Stdin::new_with_default_console();
let stdout = Stdout::new_with_default_console();
let stderr = Stderr::new_with_default_console();
- table.insert(FD_STDIN, FileHandle::new_file(Arc::new(stdin)));
- table.insert(FD_STDOUT, FileHandle::new_file(Arc::new(stdout)));
- table.insert(FD_STDERR, FileHandle::new_file(Arc::new(stderr)));
+ table.put(FileTableEntry::new(Arc::new(stdin), false));
+ table.put(FileTableEntry::new(Arc::new(stdout), false));
+ table.put(FileTableEntry::new(Arc::new(stderr), false));
Self {
table,
subject: Subject::new(),
}
}
- pub fn dup(&mut self, fd: FileDescripter, new_fd: Option<FileDescripter>) -> Result<()> {
- let file = self.table.get(&fd).map_or_else(
+ pub fn dup(&mut self, fd: FileDescripter, new_fd: FileDescripter) -> Result<FileDescripter> {
+ let entry = self.table.get(fd as usize).map_or_else(
|| return_errno_with_message!(Errno::ENOENT, "No such file"),
- |f| Ok(f.clone()),
+ |e| Ok(e.clone()),
)?;
- let new_fd = if let Some(new_fd) = new_fd {
- new_fd
- } else {
- self.max_fd() + 1
+
+ // Get the lowest-numbered available fd equal to or greater than `new_fd`.
+ let get_min_free_fd = || -> usize {
+ let new_fd = new_fd as usize;
+ if self.table.get(new_fd).is_none() {
+ return new_fd;
+ }
+
+ for idx in new_fd + 1..self.table.slots_len() {
+ if self.table.get(idx).is_none() {
+ return idx;
+ }
+ }
+ self.table.slots_len()
};
- if self.table.contains_key(&new_fd) {
- return_errno_with_message!(Errno::EBADF, "Fd exists");
- }
- self.table.insert(new_fd, file);
- Ok(())
+ let min_free_fd = get_min_free_fd();
+ self.table.put_at(min_free_fd, entry);
+ Ok(min_free_fd as FileDescripter)
}
- fn max_fd(&self) -> FileDescripter {
- self.table.iter().map(|(fd, _)| fd.clone()).max().unwrap()
+ pub fn insert(&mut self, item: Arc<dyn FileLike>) -> FileDescripter {
+ let entry = FileTableEntry::new(item, false);
+ self.table.put(entry) as FileDescripter
}
- pub fn insert(&mut self, item: FileHandle) -> FileDescripter {
- let fd = self.max_fd() + 1;
- self.table.insert(fd, item);
- fd
+ pub fn insert_at(
+ &mut self,
+ fd: FileDescripter,
+ item: Arc<dyn FileLike>,
+ ) -> Option<Arc<dyn FileLike>> {
+ let entry = FileTableEntry::new(item, false);
+ let entry = self.table.put_at(fd as usize, entry);
+ if entry.is_some() {
+ let events = FdEvents::Close(fd);
+ self.notify_fd_events(&events);
+ entry.as_ref().unwrap().notify_fd_events(&events);
+ }
+ entry.map(|e| e.file)
}
- pub fn insert_at(&mut self, fd: FileDescripter, item: FileHandle) -> Option<FileHandle> {
- let file = self.table.insert(fd, item);
- if file.is_some() {
- self.notify_close_fd_event(fd);
+ pub fn close_file(&mut self, fd: FileDescripter) -> Option<Arc<dyn FileLike>> {
+ let entry = self.table.remove(fd as usize);
+ if entry.is_some() {
+ let events = FdEvents::Close(fd);
+ self.notify_fd_events(&events);
+ entry.as_ref().unwrap().notify_fd_events(&events);
}
- file
+ entry.map(|e| e.file)
}
- pub fn close_file(&mut self, fd: FileDescripter) -> Option<FileHandle> {
- let file = self.table.remove(&fd);
- if file.is_some() {
- self.notify_close_fd_event(fd);
- }
- file
+ pub fn get_file(&self, fd: FileDescripter) -> Result<&Arc<dyn FileLike>> {
+ self.table
+ .get(fd as usize)
+ .map(|entry| &entry.file)
+ .ok_or(Error::with_message(Errno::EBADF, "fd not exits"))
}
- pub fn get_file(&self, fd: FileDescripter) -> Result<&FileHandle> {
+ pub fn get_entry(&self, fd: FileDescripter) -> Result<&FileTableEntry> {
self.table
- .get(&fd)
+ .get(fd as usize)
.ok_or(Error::with_message(Errno::EBADF, "fd not exits"))
}
- pub fn fds_and_files(&self) -> impl Iterator<Item = (&'_ FileDescripter, &'_ FileHandle)> {
- self.table.iter()
+ pub fn fds_and_files(&self) -> impl Iterator<Item = (FileDescripter, &'_ Arc<dyn FileLike>)> {
+ self.table
+ .idxes_and_items()
+ .map(|(idx, entry)| (idx as FileDescripter, &entry.file))
}
pub fn register_observer(&self, observer: Weak<dyn Observer<FdEvents>>) {
- self.subject.register_observer(observer);
+ self.subject.register_observer(observer, ());
}
- pub fn unregister_observer(&self, observer: Weak<dyn Observer<FdEvents>>) {
+ pub fn unregister_observer(&self, observer: &Weak<dyn Observer<FdEvents>>) {
self.subject.unregister_observer(observer);
}
- fn notify_close_fd_event(&self, fd: FileDescripter) {
- let events = FdEvents::Close(fd);
- self.subject.notify_observers(&events);
+ fn notify_fd_events(&self, events: &FdEvents) {
+ self.subject.notify_observers(events);
}
}
diff --git a/services/libs/jinux-std/src/fs/file_table.rs b/services/libs/jinux-std/src/fs/file_table.rs
--- a/services/libs/jinux-std/src/fs/file_table.rs
+++ b/services/libs/jinux-std/src/fs/file_table.rs
@@ -1,105 +1,128 @@
use crate::events::{Events, Observer, Subject};
use crate::prelude::*;
+use core::cell::Cell;
+use jinux_util::slot_vec::SlotVec;
+
use super::{
- file_handle::FileHandle,
- stdio::{Stderr, Stdin, Stdout, FD_STDERR, FD_STDIN, FD_STDOUT},
+ file_handle::FileLike,
+ stdio::{Stderr, Stdin, Stdout},
};
pub type FileDescripter = i32;
pub struct FileTable {
- table: BTreeMap<FileDescripter, FileHandle>,
+ table: SlotVec<FileTableEntry>,
subject: Subject<FdEvents>,
}
impl FileTable {
pub fn new() -> Self {
Self {
- table: BTreeMap::new(),
+ table: SlotVec::new(),
subject: Subject::new(),
}
}
pub fn new_with_stdio() -> Self {
- let mut table = BTreeMap::new();
+ let mut table = SlotVec::new();
let stdin = Stdin::new_with_default_console();
let stdout = Stdout::new_with_default_console();
let stderr = Stderr::new_with_default_console();
- table.insert(FD_STDIN, FileHandle::new_file(Arc::new(stdin)));
- table.insert(FD_STDOUT, FileHandle::new_file(Arc::new(stdout)));
- table.insert(FD_STDERR, FileHandle::new_file(Arc::new(stderr)));
+ table.put(FileTableEntry::new(Arc::new(stdin), false));
+ table.put(FileTableEntry::new(Arc::new(stdout), false));
+ table.put(FileTableEntry::new(Arc::new(stderr), false));
Self {
table,
subject: Subject::new(),
}
}
- pub fn dup(&mut self, fd: FileDescripter, new_fd: Option<FileDescripter>) -> Result<()> {
- let file = self.table.get(&fd).map_or_else(
+ pub fn dup(&mut self, fd: FileDescripter, new_fd: FileDescripter) -> Result<FileDescripter> {
+ let entry = self.table.get(fd as usize).map_or_else(
|| return_errno_with_message!(Errno::ENOENT, "No such file"),
- |f| Ok(f.clone()),
+ |e| Ok(e.clone()),
)?;
- let new_fd = if let Some(new_fd) = new_fd {
- new_fd
- } else {
- self.max_fd() + 1
+
+ // Get the lowest-numbered available fd equal to or greater than `new_fd`.
+ let get_min_free_fd = || -> usize {
+ let new_fd = new_fd as usize;
+ if self.table.get(new_fd).is_none() {
+ return new_fd;
+ }
+
+ for idx in new_fd + 1..self.table.slots_len() {
+ if self.table.get(idx).is_none() {
+ return idx;
+ }
+ }
+ self.table.slots_len()
};
- if self.table.contains_key(&new_fd) {
- return_errno_with_message!(Errno::EBADF, "Fd exists");
- }
- self.table.insert(new_fd, file);
- Ok(())
+ let min_free_fd = get_min_free_fd();
+ self.table.put_at(min_free_fd, entry);
+ Ok(min_free_fd as FileDescripter)
}
- fn max_fd(&self) -> FileDescripter {
- self.table.iter().map(|(fd, _)| fd.clone()).max().unwrap()
+ pub fn insert(&mut self, item: Arc<dyn FileLike>) -> FileDescripter {
+ let entry = FileTableEntry::new(item, false);
+ self.table.put(entry) as FileDescripter
}
- pub fn insert(&mut self, item: FileHandle) -> FileDescripter {
- let fd = self.max_fd() + 1;
- self.table.insert(fd, item);
- fd
+ pub fn insert_at(
+ &mut self,
+ fd: FileDescripter,
+ item: Arc<dyn FileLike>,
+ ) -> Option<Arc<dyn FileLike>> {
+ let entry = FileTableEntry::new(item, false);
+ let entry = self.table.put_at(fd as usize, entry);
+ if entry.is_some() {
+ let events = FdEvents::Close(fd);
+ self.notify_fd_events(&events);
+ entry.as_ref().unwrap().notify_fd_events(&events);
+ }
+ entry.map(|e| e.file)
}
- pub fn insert_at(&mut self, fd: FileDescripter, item: FileHandle) -> Option<FileHandle> {
- let file = self.table.insert(fd, item);
- if file.is_some() {
- self.notify_close_fd_event(fd);
+ pub fn close_file(&mut self, fd: FileDescripter) -> Option<Arc<dyn FileLike>> {
+ let entry = self.table.remove(fd as usize);
+ if entry.is_some() {
+ let events = FdEvents::Close(fd);
+ self.notify_fd_events(&events);
+ entry.as_ref().unwrap().notify_fd_events(&events);
}
- file
+ entry.map(|e| e.file)
}
- pub fn close_file(&mut self, fd: FileDescripter) -> Option<FileHandle> {
- let file = self.table.remove(&fd);
- if file.is_some() {
- self.notify_close_fd_event(fd);
- }
- file
+ pub fn get_file(&self, fd: FileDescripter) -> Result<&Arc<dyn FileLike>> {
+ self.table
+ .get(fd as usize)
+ .map(|entry| &entry.file)
+ .ok_or(Error::with_message(Errno::EBADF, "fd not exits"))
}
- pub fn get_file(&self, fd: FileDescripter) -> Result<&FileHandle> {
+ pub fn get_entry(&self, fd: FileDescripter) -> Result<&FileTableEntry> {
self.table
- .get(&fd)
+ .get(fd as usize)
.ok_or(Error::with_message(Errno::EBADF, "fd not exits"))
}
- pub fn fds_and_files(&self) -> impl Iterator<Item = (&'_ FileDescripter, &'_ FileHandle)> {
- self.table.iter()
+ pub fn fds_and_files(&self) -> impl Iterator<Item = (FileDescripter, &'_ Arc<dyn FileLike>)> {
+ self.table
+ .idxes_and_items()
+ .map(|(idx, entry)| (idx as FileDescripter, &entry.file))
}
pub fn register_observer(&self, observer: Weak<dyn Observer<FdEvents>>) {
- self.subject.register_observer(observer);
+ self.subject.register_observer(observer, ());
}
- pub fn unregister_observer(&self, observer: Weak<dyn Observer<FdEvents>>) {
+ pub fn unregister_observer(&self, observer: &Weak<dyn Observer<FdEvents>>) {
self.subject.unregister_observer(observer);
}
- fn notify_close_fd_event(&self, fd: FileDescripter) {
- let events = FdEvents::Close(fd);
- self.subject.notify_observers(&events);
+ fn notify_fd_events(&self, events: &FdEvents) {
+ self.subject.notify_observers(events);
}
}
diff --git a/services/libs/jinux-std/src/fs/file_table.rs b/services/libs/jinux-std/src/fs/file_table.rs
--- a/services/libs/jinux-std/src/fs/file_table.rs
+++ b/services/libs/jinux-std/src/fs/file_table.rs
@@ -126,3 +149,45 @@ pub enum FdEvents {
}
impl Events for FdEvents {}
+
+pub struct FileTableEntry {
+ file: Arc<dyn FileLike>,
+ close_on_exec: Cell<bool>,
+ subject: Subject<FdEvents>,
+}
+
+impl FileTableEntry {
+ pub fn new(file: Arc<dyn FileLike>, close_on_exec: bool) -> Self {
+ Self {
+ file,
+ close_on_exec: Cell::new(close_on_exec),
+ subject: Subject::new(),
+ }
+ }
+
+ pub fn file(&self) -> &Arc<dyn FileLike> {
+ &self.file
+ }
+
+ pub fn register_observer(&self, epoll: Weak<dyn Observer<FdEvents>>) {
+ self.subject.register_observer(epoll, ());
+ }
+
+ pub fn unregister_observer(&self, epoll: &Weak<dyn Observer<FdEvents>>) {
+ self.subject.unregister_observer(epoll);
+ }
+
+ pub fn notify_fd_events(&self, events: &FdEvents) {
+ self.subject.notify_observers(events);
+ }
+}
+
+impl Clone for FileTableEntry {
+ fn clone(&self) -> Self {
+ Self {
+ file: self.file.clone(),
+ close_on_exec: self.close_on_exec.clone(),
+ subject: Subject::new(),
+ }
+ }
+}
diff --git a/services/libs/jinux-std/src/fs/file_table.rs b/services/libs/jinux-std/src/fs/file_table.rs
--- a/services/libs/jinux-std/src/fs/file_table.rs
+++ b/services/libs/jinux-std/src/fs/file_table.rs
@@ -126,3 +149,45 @@ pub enum FdEvents {
}
impl Events for FdEvents {}
+
+pub struct FileTableEntry {
+ file: Arc<dyn FileLike>,
+ close_on_exec: Cell<bool>,
+ subject: Subject<FdEvents>,
+}
+
+impl FileTableEntry {
+ pub fn new(file: Arc<dyn FileLike>, close_on_exec: bool) -> Self {
+ Self {
+ file,
+ close_on_exec: Cell::new(close_on_exec),
+ subject: Subject::new(),
+ }
+ }
+
+ pub fn file(&self) -> &Arc<dyn FileLike> {
+ &self.file
+ }
+
+ pub fn register_observer(&self, epoll: Weak<dyn Observer<FdEvents>>) {
+ self.subject.register_observer(epoll, ());
+ }
+
+ pub fn unregister_observer(&self, epoll: &Weak<dyn Observer<FdEvents>>) {
+ self.subject.unregister_observer(epoll);
+ }
+
+ pub fn notify_fd_events(&self, events: &FdEvents) {
+ self.subject.notify_observers(events);
+ }
+}
+
+impl Clone for FileTableEntry {
+ fn clone(&self) -> Self {
+ Self {
+ file: self.file.clone(),
+ close_on_exec: self.close_on_exec.clone(),
+ subject: Subject::new(),
+ }
+ }
+}
diff --git a/services/libs/jinux-std/src/fs/fs_resolver.rs b/services/libs/jinux-std/src/fs/fs_resolver.rs
--- a/services/libs/jinux-std/src/fs/fs_resolver.rs
+++ b/services/libs/jinux-std/src/fs/fs_resolver.rs
@@ -2,8 +2,8 @@ use crate::prelude::*;
use alloc::str;
use alloc::string::String;
-use super::file_handle::InodeHandle;
use super::file_table::FileDescripter;
+use super::inode_handle::InodeHandle;
use super::procfs::ProcFS;
use super::ramfs::RamFS;
use super::utils::{
diff --git a/services/libs/jinux-std/src/fs/fs_resolver.rs b/services/libs/jinux-std/src/fs/fs_resolver.rs
--- a/services/libs/jinux-std/src/fs/fs_resolver.rs
+++ b/services/libs/jinux-std/src/fs/fs_resolver.rs
@@ -2,8 +2,8 @@ use crate::prelude::*;
use alloc::str;
use alloc::string::String;
-use super::file_handle::InodeHandle;
use super::file_table::FileDescripter;
+use super::inode_handle::InodeHandle;
use super::procfs::ProcFS;
use super::ramfs::RamFS;
use super::utils::{
diff --git a/services/libs/jinux-std/src/fs/fs_resolver.rs b/services/libs/jinux-std/src/fs/fs_resolver.rs
--- a/services/libs/jinux-std/src/fs/fs_resolver.rs
+++ b/services/libs/jinux-std/src/fs/fs_resolver.rs
@@ -253,7 +253,7 @@ impl FsResolver {
let file_table = current.file_table().lock();
let inode_handle = file_table
.get_file(fd)?
- .as_inode_handle()
+ .downcast_ref::<InodeHandle>()
.ok_or(Error::with_message(Errno::EBADE, "not inode"))?;
Ok(inode_handle.dentry().clone())
}
diff --git a/services/libs/jinux-std/src/fs/fs_resolver.rs b/services/libs/jinux-std/src/fs/fs_resolver.rs
--- a/services/libs/jinux-std/src/fs/fs_resolver.rs
+++ b/services/libs/jinux-std/src/fs/fs_resolver.rs
@@ -253,7 +253,7 @@ impl FsResolver {
let file_table = current.file_table().lock();
let inode_handle = file_table
.get_file(fd)?
- .as_inode_handle()
+ .downcast_ref::<InodeHandle>()
.ok_or(Error::with_message(Errno::EBADE, "not inode"))?;
Ok(inode_handle.dentry().clone())
}
diff --git a/services/libs/jinux-std/src/fs/file_handle/inode_handle/dyn_cap.rs b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
--- a/services/libs/jinux-std/src/fs/file_handle/inode_handle/dyn_cap.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
@@ -36,13 +36,6 @@ impl InodeHandle<Rights> {
Ok(InodeHandle(self.0, R1::new()))
}
- pub fn read(&self, buf: &mut [u8]) -> Result<usize> {
- if !self.1.contains(Rights::READ) {
- return_errno_with_message!(Errno::EBADF, "File is not readable");
- }
- self.0.read(buf)
- }
-
pub fn read_to_end(&self, buf: &mut Vec<u8>) -> Result<usize> {
if !self.1.contains(Rights::READ) {
return_errno_with_message!(Errno::EBADF, "File is not readable");
diff --git a/services/libs/jinux-std/src/fs/file_handle/inode_handle/dyn_cap.rs b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
--- a/services/libs/jinux-std/src/fs/file_handle/inode_handle/dyn_cap.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
@@ -36,13 +36,6 @@ impl InodeHandle<Rights> {
Ok(InodeHandle(self.0, R1::new()))
}
- pub fn read(&self, buf: &mut [u8]) -> Result<usize> {
- if !self.1.contains(Rights::READ) {
- return_errno_with_message!(Errno::EBADF, "File is not readable");
- }
- self.0.read(buf)
- }
-
pub fn read_to_end(&self, buf: &mut Vec<u8>) -> Result<usize> {
if !self.1.contains(Rights::READ) {
return_errno_with_message!(Errno::EBADF, "File is not readable");
diff --git a/services/libs/jinux-std/src/fs/file_handle/inode_handle/dyn_cap.rs b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
--- a/services/libs/jinux-std/src/fs/file_handle/inode_handle/dyn_cap.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
@@ -50,13 +43,6 @@ impl InodeHandle<Rights> {
self.0.read_to_end(buf)
}
- pub fn write(&self, buf: &[u8]) -> Result<usize> {
- if !self.1.contains(Rights::WRITE) {
- return_errno_with_message!(Errno::EBADF, "File is not writable");
- }
- self.0.write(buf)
- }
-
pub fn readdir(&self, visitor: &mut dyn DirentVisitor) -> Result<usize> {
if !self.1.contains(Rights::READ) {
return_errno_with_message!(Errno::EBADF, "File is not readable");
diff --git a/services/libs/jinux-std/src/fs/file_handle/inode_handle/dyn_cap.rs b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
--- a/services/libs/jinux-std/src/fs/file_handle/inode_handle/dyn_cap.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
@@ -50,13 +43,6 @@ impl InodeHandle<Rights> {
self.0.read_to_end(buf)
}
- pub fn write(&self, buf: &[u8]) -> Result<usize> {
- if !self.1.contains(Rights::WRITE) {
- return_errno_with_message!(Errno::EBADF, "File is not writable");
- }
- self.0.write(buf)
- }
-
pub fn readdir(&self, visitor: &mut dyn DirentVisitor) -> Result<usize> {
if !self.1.contains(Rights::READ) {
return_errno_with_message!(Errno::EBADF, "File is not readable");
diff --git a/services/libs/jinux-std/src/fs/file_handle/inode_handle/dyn_cap.rs b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
--- a/services/libs/jinux-std/src/fs/file_handle/inode_handle/dyn_cap.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
@@ -70,3 +56,40 @@ impl Clone for InodeHandle<Rights> {
Self(self.0.clone(), self.1.clone())
}
}
+
+impl FileLike for InodeHandle<Rights> {
+ fn read(&self, buf: &mut [u8]) -> Result<usize> {
+ if !self.1.contains(Rights::READ) {
+ return_errno_with_message!(Errno::EBADF, "File is not readable");
+ }
+ self.0.read(buf)
+ }
+
+ fn write(&self, buf: &[u8]) -> Result<usize> {
+ if !self.1.contains(Rights::WRITE) {
+ return_errno_with_message!(Errno::EBADF, "File is not writable");
+ }
+ self.0.write(buf)
+ }
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ self.dentry().vnode().poll(mask, poller)
+ }
+
+ fn metadata(&self) -> Metadata {
+ self.dentry().vnode().metadata()
+ }
+
+ fn seek(&self, seek_from: SeekFrom) -> Result<usize> {
+ self.0.seek(seek_from)
+ }
+
+ fn clean_for_close(&self) -> Result<()> {
+ // Close does not guarantee that the data has been successfully saved to disk.
+ Ok(())
+ }
+
+ fn as_any_ref(&self) -> &dyn Any {
+ self
+ }
+}
diff --git a/services/libs/jinux-std/src/fs/file_handle/inode_handle/dyn_cap.rs b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
--- a/services/libs/jinux-std/src/fs/file_handle/inode_handle/dyn_cap.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
@@ -70,3 +56,40 @@ impl Clone for InodeHandle<Rights> {
Self(self.0.clone(), self.1.clone())
}
}
+
+impl FileLike for InodeHandle<Rights> {
+ fn read(&self, buf: &mut [u8]) -> Result<usize> {
+ if !self.1.contains(Rights::READ) {
+ return_errno_with_message!(Errno::EBADF, "File is not readable");
+ }
+ self.0.read(buf)
+ }
+
+ fn write(&self, buf: &[u8]) -> Result<usize> {
+ if !self.1.contains(Rights::WRITE) {
+ return_errno_with_message!(Errno::EBADF, "File is not writable");
+ }
+ self.0.write(buf)
+ }
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ self.dentry().vnode().poll(mask, poller)
+ }
+
+ fn metadata(&self) -> Metadata {
+ self.dentry().vnode().metadata()
+ }
+
+ fn seek(&self, seek_from: SeekFrom) -> Result<usize> {
+ self.0.seek(seek_from)
+ }
+
+ fn clean_for_close(&self) -> Result<()> {
+ // Close does not guarantee that the data has been successfully saved to disk.
+ Ok(())
+ }
+
+ fn as_any_ref(&self) -> &dyn Any {
+ self
+ }
+}
diff --git a/services/libs/jinux-std/src/fs/file_handle/inode_handle/mod.rs b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
--- a/services/libs/jinux-std/src/fs/file_handle/inode_handle/mod.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
@@ -3,7 +3,10 @@
mod dyn_cap;
mod static_cap;
-use crate::fs::utils::{AccessMode, Dentry, DirentVisitor, InodeType, SeekFrom, StatusFlags};
+use crate::fs::file_handle::FileLike;
+use crate::fs::utils::{
+ AccessMode, Dentry, DirentVisitor, InodeType, IoEvents, Metadata, Poller, SeekFrom, StatusFlags,
+};
use crate::prelude::*;
use crate::rights::Rights;
diff --git a/services/libs/jinux-std/src/fs/file_handle/inode_handle/mod.rs b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
--- a/services/libs/jinux-std/src/fs/file_handle/inode_handle/mod.rs
+++ b/services/libs/jinux-std/src/fs/inode_handle/mod.rs
@@ -3,7 +3,10 @@
mod dyn_cap;
mod static_cap;
-use crate::fs::utils::{AccessMode, Dentry, DirentVisitor, InodeType, SeekFrom, StatusFlags};
+use crate::fs::file_handle::FileLike;
+use crate::fs::utils::{
+ AccessMode, Dentry, DirentVisitor, InodeType, IoEvents, Metadata, Poller, SeekFrom, StatusFlags,
+};
use crate::prelude::*;
use crate::rights::Rights;
diff --git a/services/libs/jinux-std/src/fs/mod.rs b/services/libs/jinux-std/src/fs/mod.rs
--- a/services/libs/jinux-std/src/fs/mod.rs
+++ b/services/libs/jinux-std/src/fs/mod.rs
@@ -1,7 +1,10 @@
+pub mod epoll;
pub mod file_handle;
pub mod file_table;
pub mod fs_resolver;
pub mod initramfs;
+pub mod inode_handle;
+pub mod pipe;
pub mod procfs;
pub mod ramfs;
pub mod stdio;
diff --git a/services/libs/jinux-std/src/fs/mod.rs b/services/libs/jinux-std/src/fs/mod.rs
--- a/services/libs/jinux-std/src/fs/mod.rs
+++ b/services/libs/jinux-std/src/fs/mod.rs
@@ -1,7 +1,10 @@
+pub mod epoll;
pub mod file_handle;
pub mod file_table;
pub mod fs_resolver;
pub mod initramfs;
+pub mod inode_handle;
+pub mod pipe;
pub mod procfs;
pub mod ramfs;
pub mod stdio;
diff --git /dev/null b/services/libs/jinux-std/src/fs/pipe.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/fs/pipe.rs
@@ -0,0 +1,134 @@
+use crate::events::Observer;
+use crate::prelude::*;
+
+use super::file_handle::FileLike;
+use super::utils::{Consumer, IoEvents, Poller, Producer};
+
+pub struct PipeReader {
+ consumer: Consumer<u8>,
+}
+
+impl PipeReader {
+ pub fn new(consumer: Consumer<u8>) -> Self {
+ Self { consumer }
+ }
+}
+
+impl FileLike for PipeReader {
+ fn read(&self, buf: &mut [u8]) -> Result<usize> {
+ let is_nonblocking = self.consumer.is_nonblocking();
+
+ // Fast path
+ let res = self.consumer.read(buf);
+ if should_io_return(&res, is_nonblocking) {
+ return res;
+ }
+
+ // Slow path
+ let mask = IoEvents::IN;
+ let poller = Poller::new();
+ loop {
+ let res = self.consumer.read(buf);
+ if should_io_return(&res, is_nonblocking) {
+ return res;
+ }
+ let events = self.poll(mask, Some(&poller));
+ if events.is_empty() {
+ poller.wait();
+ }
+ }
+ }
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ self.consumer.poll(mask, poller)
+ }
+
+ fn register_observer(
+ &self,
+ observer: Weak<dyn Observer<IoEvents>>,
+ mask: IoEvents,
+ ) -> Result<()> {
+ self.consumer.register_observer(observer, mask)
+ }
+
+ fn unregister_observer(
+ &self,
+ observer: &Weak<dyn Observer<IoEvents>>,
+ ) -> Result<Weak<dyn Observer<IoEvents>>> {
+ self.consumer.unregister_observer(observer)
+ }
+
+ fn as_any_ref(&self) -> &dyn Any {
+ self
+ }
+}
+
+pub struct PipeWriter {
+ producer: Producer<u8>,
+}
+
+impl PipeWriter {
+ pub fn new(producer: Producer<u8>) -> Self {
+ Self { producer }
+ }
+}
+
+impl FileLike for PipeWriter {
+ fn write(&self, buf: &[u8]) -> Result<usize> {
+ let is_nonblocking = self.producer.is_nonblocking();
+
+ // Fast path
+ let res = self.producer.write(buf);
+ if should_io_return(&res, is_nonblocking) {
+ return res;
+ }
+
+ // Slow path
+ let mask = IoEvents::OUT;
+ let poller = Poller::new();
+ loop {
+ let res = self.producer.write(buf);
+ if should_io_return(&res, is_nonblocking) {
+ return res;
+ }
+ let events = self.poll(mask, Some(&poller));
+ if events.is_empty() {
+ poller.wait();
+ }
+ }
+ }
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ self.producer.poll(mask, poller)
+ }
+
+ fn register_observer(
+ &self,
+ observer: Weak<dyn Observer<IoEvents>>,
+ mask: IoEvents,
+ ) -> Result<()> {
+ self.producer.register_observer(observer, mask)
+ }
+
+ fn unregister_observer(
+ &self,
+ observer: &Weak<dyn Observer<IoEvents>>,
+ ) -> Result<Weak<dyn Observer<IoEvents>>> {
+ self.producer.unregister_observer(observer)
+ }
+
+ fn as_any_ref(&self) -> &dyn Any {
+ self
+ }
+}
+
+fn should_io_return(res: &Result<usize>, is_nonblocking: bool) -> bool {
+ if is_nonblocking {
+ return true;
+ }
+ match res {
+ Ok(_) => true,
+ Err(e) if e.error() == Errno::EAGAIN => false,
+ Err(_) => true,
+ }
+}
diff --git /dev/null b/services/libs/jinux-std/src/fs/pipe.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/fs/pipe.rs
@@ -0,0 +1,134 @@
+use crate::events::Observer;
+use crate::prelude::*;
+
+use super::file_handle::FileLike;
+use super::utils::{Consumer, IoEvents, Poller, Producer};
+
+pub struct PipeReader {
+ consumer: Consumer<u8>,
+}
+
+impl PipeReader {
+ pub fn new(consumer: Consumer<u8>) -> Self {
+ Self { consumer }
+ }
+}
+
+impl FileLike for PipeReader {
+ fn read(&self, buf: &mut [u8]) -> Result<usize> {
+ let is_nonblocking = self.consumer.is_nonblocking();
+
+ // Fast path
+ let res = self.consumer.read(buf);
+ if should_io_return(&res, is_nonblocking) {
+ return res;
+ }
+
+ // Slow path
+ let mask = IoEvents::IN;
+ let poller = Poller::new();
+ loop {
+ let res = self.consumer.read(buf);
+ if should_io_return(&res, is_nonblocking) {
+ return res;
+ }
+ let events = self.poll(mask, Some(&poller));
+ if events.is_empty() {
+ poller.wait();
+ }
+ }
+ }
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ self.consumer.poll(mask, poller)
+ }
+
+ fn register_observer(
+ &self,
+ observer: Weak<dyn Observer<IoEvents>>,
+ mask: IoEvents,
+ ) -> Result<()> {
+ self.consumer.register_observer(observer, mask)
+ }
+
+ fn unregister_observer(
+ &self,
+ observer: &Weak<dyn Observer<IoEvents>>,
+ ) -> Result<Weak<dyn Observer<IoEvents>>> {
+ self.consumer.unregister_observer(observer)
+ }
+
+ fn as_any_ref(&self) -> &dyn Any {
+ self
+ }
+}
+
+pub struct PipeWriter {
+ producer: Producer<u8>,
+}
+
+impl PipeWriter {
+ pub fn new(producer: Producer<u8>) -> Self {
+ Self { producer }
+ }
+}
+
+impl FileLike for PipeWriter {
+ fn write(&self, buf: &[u8]) -> Result<usize> {
+ let is_nonblocking = self.producer.is_nonblocking();
+
+ // Fast path
+ let res = self.producer.write(buf);
+ if should_io_return(&res, is_nonblocking) {
+ return res;
+ }
+
+ // Slow path
+ let mask = IoEvents::OUT;
+ let poller = Poller::new();
+ loop {
+ let res = self.producer.write(buf);
+ if should_io_return(&res, is_nonblocking) {
+ return res;
+ }
+ let events = self.poll(mask, Some(&poller));
+ if events.is_empty() {
+ poller.wait();
+ }
+ }
+ }
+
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ self.producer.poll(mask, poller)
+ }
+
+ fn register_observer(
+ &self,
+ observer: Weak<dyn Observer<IoEvents>>,
+ mask: IoEvents,
+ ) -> Result<()> {
+ self.producer.register_observer(observer, mask)
+ }
+
+ fn unregister_observer(
+ &self,
+ observer: &Weak<dyn Observer<IoEvents>>,
+ ) -> Result<Weak<dyn Observer<IoEvents>>> {
+ self.producer.unregister_observer(observer)
+ }
+
+ fn as_any_ref(&self) -> &dyn Any {
+ self
+ }
+}
+
+fn should_io_return(res: &Result<usize>, is_nonblocking: bool) -> bool {
+ if is_nonblocking {
+ return true;
+ }
+ match res {
+ Ok(_) => true,
+ Err(e) if e.error() == Errno::EAGAIN => false,
+ Err(_) => true,
+ }
+}
diff --git a/services/libs/jinux-std/src/fs/procfs/pid/fd.rs b/services/libs/jinux-std/src/fs/procfs/pid/fd.rs
--- a/services/libs/jinux-std/src/fs/procfs/pid/fd.rs
+++ b/services/libs/jinux-std/src/fs/procfs/pid/fd.rs
@@ -1,6 +1,7 @@
use super::*;
-use crate::fs::file_handle::FileHandle;
+use crate::fs::file_handle::FileLike;
use crate::fs::file_table::FileDescripter;
+use crate::fs::inode_handle::InodeHandle;
/// Represents the inode at `/proc/[pid]/fd`.
pub struct FdDirOps(Arc<Process>);
diff --git a/services/libs/jinux-std/src/fs/procfs/pid/fd.rs b/services/libs/jinux-std/src/fs/procfs/pid/fd.rs
--- a/services/libs/jinux-std/src/fs/procfs/pid/fd.rs
+++ b/services/libs/jinux-std/src/fs/procfs/pid/fd.rs
@@ -1,6 +1,7 @@
use super::*;
-use crate::fs::file_handle::FileHandle;
+use crate::fs::file_handle::FileLike;
use crate::fs::file_table::FileDescripter;
+use crate::fs::inode_handle::InodeHandle;
/// Represents the inode at `/proc/[pid]/fd`.
pub struct FdDirOps(Arc<Process>);
diff --git a/services/libs/jinux-std/src/fs/procfs/pid/fd.rs b/services/libs/jinux-std/src/fs/procfs/pid/fd.rs
--- a/services/libs/jinux-std/src/fs/procfs/pid/fd.rs
+++ b/services/libs/jinux-std/src/fs/procfs/pid/fd.rs
@@ -62,10 +63,10 @@ impl DirOps for FdDirOps {
}
/// Represents the inode at `/proc/[pid]/fd/N`.
-struct FileSymOps(FileHandle);
+struct FileSymOps(Arc<dyn FileLike>);
impl FileSymOps {
- pub fn new_inode(file: FileHandle, parent: Weak<dyn Inode>) -> Arc<dyn Inode> {
+ pub fn new_inode(file: Arc<dyn FileLike>, parent: Weak<dyn Inode>) -> Arc<dyn Inode> {
ProcSymBuilder::new(Self(file))
.parent(parent)
.build()
diff --git a/services/libs/jinux-std/src/fs/procfs/pid/fd.rs b/services/libs/jinux-std/src/fs/procfs/pid/fd.rs
--- a/services/libs/jinux-std/src/fs/procfs/pid/fd.rs
+++ b/services/libs/jinux-std/src/fs/procfs/pid/fd.rs
@@ -62,10 +63,10 @@ impl DirOps for FdDirOps {
}
/// Represents the inode at `/proc/[pid]/fd/N`.
-struct FileSymOps(FileHandle);
+struct FileSymOps(Arc<dyn FileLike>);
impl FileSymOps {
- pub fn new_inode(file: FileHandle, parent: Weak<dyn Inode>) -> Arc<dyn Inode> {
+ pub fn new_inode(file: Arc<dyn FileLike>, parent: Weak<dyn Inode>) -> Arc<dyn Inode> {
ProcSymBuilder::new(Self(file))
.parent(parent)
.build()
diff --git a/services/libs/jinux-std/src/fs/procfs/pid/fd.rs b/services/libs/jinux-std/src/fs/procfs/pid/fd.rs
--- a/services/libs/jinux-std/src/fs/procfs/pid/fd.rs
+++ b/services/libs/jinux-std/src/fs/procfs/pid/fd.rs
@@ -75,13 +76,11 @@ impl FileSymOps {
impl SymOps for FileSymOps {
fn read_link(&self) -> Result<String> {
- let path = if let Some(inode_handle) = self.0.as_inode_handle() {
+ let path = if let Some(inode_handle) = self.0.downcast_ref::<InodeHandle>() {
inode_handle.dentry().abs_path()
- } else if let Some(file) = self.0.as_file() {
- // TODO: get the real path for stdio
- String::from("/dev/tty")
} else {
- unreachable!()
+ // TODO: get the real path for other FileLike object
+ String::from("/dev/tty")
};
Ok(path)
}
diff --git a/services/libs/jinux-std/src/fs/procfs/pid/fd.rs b/services/libs/jinux-std/src/fs/procfs/pid/fd.rs
--- a/services/libs/jinux-std/src/fs/procfs/pid/fd.rs
+++ b/services/libs/jinux-std/src/fs/procfs/pid/fd.rs
@@ -75,13 +76,11 @@ impl FileSymOps {
impl SymOps for FileSymOps {
fn read_link(&self) -> Result<String> {
- let path = if let Some(inode_handle) = self.0.as_inode_handle() {
+ let path = if let Some(inode_handle) = self.0.downcast_ref::<InodeHandle>() {
inode_handle.dentry().abs_path()
- } else if let Some(file) = self.0.as_file() {
- // TODO: get the real path for stdio
- String::from("/dev/tty")
} else {
- unreachable!()
+ // TODO: get the real path for other FileLike object
+ String::from("/dev/tty")
};
Ok(path)
}
diff --git a/services/libs/jinux-std/src/fs/procfs/template/dir.rs b/services/libs/jinux-std/src/fs/procfs/template/dir.rs
--- a/services/libs/jinux-std/src/fs/procfs/template/dir.rs
+++ b/services/libs/jinux-std/src/fs/procfs/template/dir.rs
@@ -2,9 +2,10 @@ use alloc::string::String;
use core::any::Any;
use core::time::Duration;
use jinux_frame::vm::VmFrame;
+use jinux_util::slot_vec::SlotVec;
use crate::fs::utils::{
- DirEntryVec, DirentVisitor, FileSystem, Inode, InodeMode, InodeType, IoctlCmd, Metadata,
+ DirentVisitor, FileSystem, Inode, InodeMode, InodeType, IoctlCmd, Metadata,
};
use crate::prelude::*;
diff --git a/services/libs/jinux-std/src/fs/procfs/template/dir.rs b/services/libs/jinux-std/src/fs/procfs/template/dir.rs
--- a/services/libs/jinux-std/src/fs/procfs/template/dir.rs
+++ b/services/libs/jinux-std/src/fs/procfs/template/dir.rs
@@ -2,9 +2,10 @@ use alloc::string::String;
use core::any::Any;
use core::time::Duration;
use jinux_frame::vm::VmFrame;
+use jinux_util::slot_vec::SlotVec;
use crate::fs::utils::{
- DirEntryVec, DirentVisitor, FileSystem, Inode, InodeMode, InodeType, IoctlCmd, Metadata,
+ DirentVisitor, FileSystem, Inode, InodeMode, InodeType, IoctlCmd, Metadata,
};
use crate::prelude::*;
diff --git a/services/libs/jinux-std/src/fs/procfs/template/dir.rs b/services/libs/jinux-std/src/fs/procfs/template/dir.rs
--- a/services/libs/jinux-std/src/fs/procfs/template/dir.rs
+++ b/services/libs/jinux-std/src/fs/procfs/template/dir.rs
@@ -14,7 +15,7 @@ pub struct ProcDir<D: DirOps> {
inner: D,
this: Weak<ProcDir<D>>,
parent: Option<Weak<dyn Inode>>,
- cached_children: RwLock<DirEntryVec<(String, Arc<dyn Inode>)>>,
+ cached_children: RwLock<SlotVec<(String, Arc<dyn Inode>)>>,
info: ProcInodeInfo,
}
diff --git a/services/libs/jinux-std/src/fs/procfs/template/dir.rs b/services/libs/jinux-std/src/fs/procfs/template/dir.rs
--- a/services/libs/jinux-std/src/fs/procfs/template/dir.rs
+++ b/services/libs/jinux-std/src/fs/procfs/template/dir.rs
@@ -14,7 +15,7 @@ pub struct ProcDir<D: DirOps> {
inner: D,
this: Weak<ProcDir<D>>,
parent: Option<Weak<dyn Inode>>,
- cached_children: RwLock<DirEntryVec<(String, Arc<dyn Inode>)>>,
+ cached_children: RwLock<SlotVec<(String, Arc<dyn Inode>)>>,
info: ProcInodeInfo,
}
diff --git a/services/libs/jinux-std/src/fs/procfs/template/dir.rs b/services/libs/jinux-std/src/fs/procfs/template/dir.rs
--- a/services/libs/jinux-std/src/fs/procfs/template/dir.rs
+++ b/services/libs/jinux-std/src/fs/procfs/template/dir.rs
@@ -38,7 +39,7 @@ impl<D: DirOps> ProcDir<D> {
inner: dir,
this: weak_self.clone(),
parent,
- cached_children: RwLock::new(DirEntryVec::new()),
+ cached_children: RwLock::new(SlotVec::new()),
info,
})
}
diff --git a/services/libs/jinux-std/src/fs/procfs/template/dir.rs b/services/libs/jinux-std/src/fs/procfs/template/dir.rs
--- a/services/libs/jinux-std/src/fs/procfs/template/dir.rs
+++ b/services/libs/jinux-std/src/fs/procfs/template/dir.rs
@@ -38,7 +39,7 @@ impl<D: DirOps> ProcDir<D> {
inner: dir,
this: weak_self.clone(),
parent,
- cached_children: RwLock::new(DirEntryVec::new()),
+ cached_children: RwLock::new(SlotVec::new()),
info,
})
}
diff --git a/services/libs/jinux-std/src/fs/procfs/template/dir.rs b/services/libs/jinux-std/src/fs/procfs/template/dir.rs
--- a/services/libs/jinux-std/src/fs/procfs/template/dir.rs
+++ b/services/libs/jinux-std/src/fs/procfs/template/dir.rs
@@ -51,7 +52,7 @@ impl<D: DirOps> ProcDir<D> {
self.parent.as_ref().and_then(|p| p.upgrade())
}
- pub fn cached_children(&self) -> &RwLock<DirEntryVec<(String, Arc<dyn Inode>)>> {
+ pub fn cached_children(&self) -> &RwLock<SlotVec<(String, Arc<dyn Inode>)>> {
&self.cached_children
}
}
diff --git a/services/libs/jinux-std/src/fs/procfs/template/dir.rs b/services/libs/jinux-std/src/fs/procfs/template/dir.rs
--- a/services/libs/jinux-std/src/fs/procfs/template/dir.rs
+++ b/services/libs/jinux-std/src/fs/procfs/template/dir.rs
@@ -51,7 +52,7 @@ impl<D: DirOps> ProcDir<D> {
self.parent.as_ref().and_then(|p| p.upgrade())
}
- pub fn cached_children(&self) -> &RwLock<DirEntryVec<(String, Arc<dyn Inode>)>> {
+ pub fn cached_children(&self) -> &RwLock<SlotVec<(String, Arc<dyn Inode>)>> {
&self.cached_children
}
}
diff --git a/services/libs/jinux-std/src/fs/procfs/template/dir.rs b/services/libs/jinux-std/src/fs/procfs/template/dir.rs
--- a/services/libs/jinux-std/src/fs/procfs/template/dir.rs
+++ b/services/libs/jinux-std/src/fs/procfs/template/dir.rs
@@ -127,7 +128,7 @@ impl<D: DirOps + 'static> Inode for ProcDir<D> {
self.inner.populate_children(self.this.clone());
let cached_children = self.cached_children.read();
for (idx, (name, child)) in cached_children
- .idxes_and_entries()
+ .idxes_and_items()
.map(|(idx, (name, child))| (idx + 2, (name, child)))
{
if idx < *offset {
diff --git a/services/libs/jinux-std/src/fs/procfs/template/dir.rs b/services/libs/jinux-std/src/fs/procfs/template/dir.rs
--- a/services/libs/jinux-std/src/fs/procfs/template/dir.rs
+++ b/services/libs/jinux-std/src/fs/procfs/template/dir.rs
@@ -127,7 +128,7 @@ impl<D: DirOps + 'static> Inode for ProcDir<D> {
self.inner.populate_children(self.this.clone());
let cached_children = self.cached_children.read();
for (idx, (name, child)) in cached_children
- .idxes_and_entries()
+ .idxes_and_items()
.map(|(idx, (name, child))| (idx + 2, (name, child)))
{
if idx < *offset {
diff --git a/services/libs/jinux-std/src/fs/ramfs/fs.rs b/services/libs/jinux-std/src/fs/ramfs/fs.rs
--- a/services/libs/jinux-std/src/fs/ramfs/fs.rs
+++ b/services/libs/jinux-std/src/fs/ramfs/fs.rs
@@ -5,12 +5,12 @@ use core::any::Any;
use core::sync::atomic::{AtomicUsize, Ordering};
use core::time::Duration;
use jinux_frame::vm::VmFrame;
+use jinux_util::slot_vec::SlotVec;
use spin::{RwLock, RwLockWriteGuard};
use super::*;
use crate::fs::utils::{
- DirEntryVec, DirentVisitor, FileSystem, FsFlags, Inode, InodeMode, InodeType, IoctlCmd,
- Metadata, SuperBlock,
+ DirentVisitor, FileSystem, FsFlags, Inode, InodeMode, InodeType, IoctlCmd, Metadata, SuperBlock,
};
pub struct RamFS {
diff --git a/services/libs/jinux-std/src/fs/ramfs/fs.rs b/services/libs/jinux-std/src/fs/ramfs/fs.rs
--- a/services/libs/jinux-std/src/fs/ramfs/fs.rs
+++ b/services/libs/jinux-std/src/fs/ramfs/fs.rs
@@ -5,12 +5,12 @@ use core::any::Any;
use core::sync::atomic::{AtomicUsize, Ordering};
use core::time::Duration;
use jinux_frame::vm::VmFrame;
+use jinux_util::slot_vec::SlotVec;
use spin::{RwLock, RwLockWriteGuard};
use super::*;
use crate::fs::utils::{
- DirEntryVec, DirentVisitor, FileSystem, FsFlags, Inode, InodeMode, InodeType, IoctlCmd,
- Metadata, SuperBlock,
+ DirentVisitor, FileSystem, FsFlags, Inode, InodeMode, InodeType, IoctlCmd, Metadata, SuperBlock,
};
pub struct RamFS {
diff --git a/services/libs/jinux-std/src/fs/ramfs/fs.rs b/services/libs/jinux-std/src/fs/ramfs/fs.rs
--- a/services/libs/jinux-std/src/fs/ramfs/fs.rs
+++ b/services/libs/jinux-std/src/fs/ramfs/fs.rs
@@ -164,7 +164,7 @@ impl Inner {
}
struct DirEntry {
- children: DirEntryVec<(Str256, Arc<RamInode>)>,
+ children: SlotVec<(Str256, Arc<RamInode>)>,
this: Weak<RamInode>,
parent: Weak<RamInode>,
}
diff --git a/services/libs/jinux-std/src/fs/ramfs/fs.rs b/services/libs/jinux-std/src/fs/ramfs/fs.rs
--- a/services/libs/jinux-std/src/fs/ramfs/fs.rs
+++ b/services/libs/jinux-std/src/fs/ramfs/fs.rs
@@ -164,7 +164,7 @@ impl Inner {
}
struct DirEntry {
- children: DirEntryVec<(Str256, Arc<RamInode>)>,
+ children: SlotVec<(Str256, Arc<RamInode>)>,
this: Weak<RamInode>,
parent: Weak<RamInode>,
}
diff --git a/services/libs/jinux-std/src/fs/ramfs/fs.rs b/services/libs/jinux-std/src/fs/ramfs/fs.rs
--- a/services/libs/jinux-std/src/fs/ramfs/fs.rs
+++ b/services/libs/jinux-std/src/fs/ramfs/fs.rs
@@ -172,7 +172,7 @@ struct DirEntry {
impl DirEntry {
fn new() -> Self {
Self {
- children: DirEntryVec::new(),
+ children: SlotVec::new(),
this: Weak::default(),
parent: Weak::default(),
}
diff --git a/services/libs/jinux-std/src/fs/ramfs/fs.rs b/services/libs/jinux-std/src/fs/ramfs/fs.rs
--- a/services/libs/jinux-std/src/fs/ramfs/fs.rs
+++ b/services/libs/jinux-std/src/fs/ramfs/fs.rs
@@ -172,7 +172,7 @@ struct DirEntry {
impl DirEntry {
fn new() -> Self {
Self {
- children: DirEntryVec::new(),
+ children: SlotVec::new(),
this: Weak::default(),
parent: Weak::default(),
}
diff --git a/services/libs/jinux-std/src/fs/ramfs/fs.rs b/services/libs/jinux-std/src/fs/ramfs/fs.rs
--- a/services/libs/jinux-std/src/fs/ramfs/fs.rs
+++ b/services/libs/jinux-std/src/fs/ramfs/fs.rs
@@ -205,13 +205,13 @@ impl DirEntry {
Some((1, self.parent.upgrade().unwrap()))
} else {
self.children
- .idxes_and_entries()
+ .idxes_and_items()
.find(|(_, (child, _))| child == &Str256::from(name))
.map(|(idx, (_, inode))| (idx + 2, inode.clone()))
}
}
- fn append_entry(&mut self, name: &str, inode: Arc<RamInode>) {
+ fn append_entry(&mut self, name: &str, inode: Arc<RamInode>) -> usize {
self.children.put((Str256::from(name), inode))
}
diff --git a/services/libs/jinux-std/src/fs/ramfs/fs.rs b/services/libs/jinux-std/src/fs/ramfs/fs.rs
--- a/services/libs/jinux-std/src/fs/ramfs/fs.rs
+++ b/services/libs/jinux-std/src/fs/ramfs/fs.rs
@@ -205,13 +205,13 @@ impl DirEntry {
Some((1, self.parent.upgrade().unwrap()))
} else {
self.children
- .idxes_and_entries()
+ .idxes_and_items()
.find(|(_, (child, _))| child == &Str256::from(name))
.map(|(idx, (_, inode))| (idx + 2, inode.clone()))
}
}
- fn append_entry(&mut self, name: &str, inode: Arc<RamInode>) {
+ fn append_entry(&mut self, name: &str, inode: Arc<RamInode>) -> usize {
self.children.put((Str256::from(name), inode))
}
diff --git a/services/libs/jinux-std/src/fs/ramfs/fs.rs b/services/libs/jinux-std/src/fs/ramfs/fs.rs
--- a/services/libs/jinux-std/src/fs/ramfs/fs.rs
+++ b/services/libs/jinux-std/src/fs/ramfs/fs.rs
@@ -255,7 +255,7 @@ impl DirEntry {
// Read the normal child entries.
for (offset, (name, child)) in self
.children
- .idxes_and_entries()
+ .idxes_and_items()
.map(|(offset, (name, child))| (offset + 2, (name, child)))
{
if offset < *idx {
diff --git a/services/libs/jinux-std/src/fs/ramfs/fs.rs b/services/libs/jinux-std/src/fs/ramfs/fs.rs
--- a/services/libs/jinux-std/src/fs/ramfs/fs.rs
+++ b/services/libs/jinux-std/src/fs/ramfs/fs.rs
@@ -255,7 +255,7 @@ impl DirEntry {
// Read the normal child entries.
for (offset, (name, child)) in self
.children
- .idxes_and_entries()
+ .idxes_and_items()
.map(|(offset, (name, child))| (offset + 2, (name, child)))
{
if offset < *idx {
diff --git a/services/libs/jinux-std/src/fs/stdio.rs b/services/libs/jinux-std/src/fs/stdio.rs
--- a/services/libs/jinux-std/src/fs/stdio.rs
+++ b/services/libs/jinux-std/src/fs/stdio.rs
@@ -1,9 +1,9 @@
use crate::prelude::*;
use crate::tty::{get_n_tty, Tty};
-use super::file_handle::File;
+use super::file_handle::FileLike;
use super::file_table::FileDescripter;
-use super::utils::{InodeMode, InodeType, IoEvents, Metadata, SeekFrom};
+use super::utils::{InodeMode, InodeType, IoEvents, Metadata, Poller, SeekFrom};
pub const FD_STDIN: FileDescripter = 0;
pub const FD_STDOUT: FileDescripter = 1;
diff --git a/services/libs/jinux-std/src/fs/stdio.rs b/services/libs/jinux-std/src/fs/stdio.rs
--- a/services/libs/jinux-std/src/fs/stdio.rs
+++ b/services/libs/jinux-std/src/fs/stdio.rs
@@ -1,9 +1,9 @@
use crate::prelude::*;
use crate::tty::{get_n_tty, Tty};
-use super::file_handle::File;
+use super::file_handle::FileLike;
use super::file_table::FileDescripter;
-use super::utils::{InodeMode, InodeType, IoEvents, Metadata, SeekFrom};
+use super::utils::{InodeMode, InodeType, IoEvents, Metadata, Poller, SeekFrom};
pub const FD_STDIN: FileDescripter = 0;
pub const FD_STDOUT: FileDescripter = 1;
diff --git a/services/libs/jinux-std/src/fs/stdio.rs b/services/libs/jinux-std/src/fs/stdio.rs
--- a/services/libs/jinux-std/src/fs/stdio.rs
+++ b/services/libs/jinux-std/src/fs/stdio.rs
@@ -21,10 +21,10 @@ pub struct Stderr {
console: Option<Arc<Tty>>,
}
-impl File for Stdin {
- fn poll(&self) -> IoEvents {
+impl FileLike for Stdin {
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
if let Some(console) = self.console.as_ref() {
- console.poll()
+ console.poll(mask, poller)
} else {
todo!()
}
diff --git a/services/libs/jinux-std/src/fs/stdio.rs b/services/libs/jinux-std/src/fs/stdio.rs
--- a/services/libs/jinux-std/src/fs/stdio.rs
+++ b/services/libs/jinux-std/src/fs/stdio.rs
@@ -21,10 +21,10 @@ pub struct Stderr {
console: Option<Arc<Tty>>,
}
-impl File for Stdin {
- fn poll(&self) -> IoEvents {
+impl FileLike for Stdin {
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
if let Some(console) = self.console.as_ref() {
- console.poll()
+ console.poll(mask, poller)
} else {
todo!()
}
diff --git a/services/libs/jinux-std/src/fs/stdio.rs b/services/libs/jinux-std/src/fs/stdio.rs
--- a/services/libs/jinux-std/src/fs/stdio.rs
+++ b/services/libs/jinux-std/src/fs/stdio.rs
@@ -69,8 +69,12 @@ impl File for Stdin {
rdev: 0,
}
}
+
+ fn as_any_ref(&self) -> &dyn Any {
+ self
+ }
}
-impl File for Stdout {
+impl FileLike for Stdout {
fn ioctl(&self, cmd: super::utils::IoctlCmd, arg: usize) -> Result<i32> {
if let Some(console) = self.console.as_ref() {
console.ioctl(cmd, arg)
diff --git a/services/libs/jinux-std/src/fs/stdio.rs b/services/libs/jinux-std/src/fs/stdio.rs
--- a/services/libs/jinux-std/src/fs/stdio.rs
+++ b/services/libs/jinux-std/src/fs/stdio.rs
@@ -69,8 +69,12 @@ impl File for Stdin {
rdev: 0,
}
}
+
+ fn as_any_ref(&self) -> &dyn Any {
+ self
+ }
}
-impl File for Stdout {
+impl FileLike for Stdout {
fn ioctl(&self, cmd: super::utils::IoctlCmd, arg: usize) -> Result<i32> {
if let Some(console) = self.console.as_ref() {
console.ioctl(cmd, arg)
diff --git a/services/libs/jinux-std/src/fs/stdio.rs b/services/libs/jinux-std/src/fs/stdio.rs
--- a/services/libs/jinux-std/src/fs/stdio.rs
+++ b/services/libs/jinux-std/src/fs/stdio.rs
@@ -110,9 +114,13 @@ impl File for Stdout {
rdev: 0,
}
}
+
+ fn as_any_ref(&self) -> &dyn Any {
+ self
+ }
}
-impl File for Stderr {
+impl FileLike for Stderr {
fn ioctl(&self, cmd: super::utils::IoctlCmd, arg: usize) -> Result<i32> {
if let Some(console) = self.console.as_ref() {
console.ioctl(cmd, arg)
diff --git a/services/libs/jinux-std/src/fs/stdio.rs b/services/libs/jinux-std/src/fs/stdio.rs
--- a/services/libs/jinux-std/src/fs/stdio.rs
+++ b/services/libs/jinux-std/src/fs/stdio.rs
@@ -110,9 +114,13 @@ impl File for Stdout {
rdev: 0,
}
}
+
+ fn as_any_ref(&self) -> &dyn Any {
+ self
+ }
}
-impl File for Stderr {
+impl FileLike for Stderr {
fn ioctl(&self, cmd: super::utils::IoctlCmd, arg: usize) -> Result<i32> {
if let Some(console) = self.console.as_ref() {
console.ioctl(cmd, arg)
diff --git a/services/libs/jinux-std/src/fs/stdio.rs b/services/libs/jinux-std/src/fs/stdio.rs
--- a/services/libs/jinux-std/src/fs/stdio.rs
+++ b/services/libs/jinux-std/src/fs/stdio.rs
@@ -152,6 +160,10 @@ impl File for Stderr {
rdev: 0,
}
}
+
+ fn as_any_ref(&self) -> &dyn Any {
+ self
+ }
}
impl Stdin {
diff --git a/services/libs/jinux-std/src/fs/stdio.rs b/services/libs/jinux-std/src/fs/stdio.rs
--- a/services/libs/jinux-std/src/fs/stdio.rs
+++ b/services/libs/jinux-std/src/fs/stdio.rs
@@ -152,6 +160,10 @@ impl File for Stderr {
rdev: 0,
}
}
+
+ fn as_any_ref(&self) -> &dyn Any {
+ self
+ }
}
impl Stdin {
diff --git /dev/null b/services/libs/jinux-std/src/fs/utils/channel.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/fs/utils/channel.rs
@@ -0,0 +1,347 @@
+use core::sync::atomic::{AtomicBool, AtomicU32, Ordering};
+use jinux_rights_proc::require;
+use ringbuf::{HeapConsumer as HeapRbConsumer, HeapProducer as HeapRbProducer, HeapRb};
+
+use crate::events::Observer;
+use crate::prelude::*;
+use crate::rights::*;
+
+use super::{IoEvents, Pollee, Poller, StatusFlags};
+
+/// A unidirectional communication channel, intended to implement IPC, e.g., pipe,
+/// unix domain sockets, etc.
+pub struct Channel<T> {
+ producer: Producer<T>,
+ consumer: Consumer<T>,
+}
+
+impl<T> Channel<T> {
+ pub fn with_capacity(capacity: usize) -> Result<Self> {
+ Self::with_capacity_and_flags(capacity, StatusFlags::empty())
+ }
+
+ pub fn with_capacity_and_flags(capacity: usize, flags: StatusFlags) -> Result<Self> {
+ let common = Arc::new(Common::with_capacity_and_flags(capacity, flags)?);
+ let producer = Producer(EndPoint::new(common.clone(), WriteOp::new()));
+ let consumer = Consumer(EndPoint::new(common, ReadOp::new()));
+ Ok(Self { producer, consumer })
+ }
+
+ pub fn split(self) -> (Producer<T>, Consumer<T>) {
+ let Self { producer, consumer } = self;
+ (producer, consumer)
+ }
+
+ pub fn producer(&self) -> &Producer<T> {
+ &self.producer
+ }
+
+ pub fn consumer(&self) -> &Consumer<T> {
+ &self.consumer
+ }
+
+ pub fn capacity(&self) -> usize {
+ self.producer.0.common.capacity()
+ }
+}
+
+pub struct Producer<T>(EndPoint<T, WriteOp>);
+
+pub struct Consumer<T>(EndPoint<T, ReadOp>);
+
+macro_rules! impl_common_methods_for_channel {
+ () => {
+ pub fn shutdown(&self) {
+ self.this_end().shutdown()
+ }
+
+ pub fn is_shutdown(&self) -> bool {
+ self.this_end().is_shutdown()
+ }
+
+ pub fn is_peer_shutdown(&self) -> bool {
+ self.peer_end().is_shutdown()
+ }
+
+ pub fn status_flags(&self) -> StatusFlags {
+ self.this_end().status_flags()
+ }
+
+ pub fn set_status_flags(&self, new_flags: StatusFlags) {
+ self.this_end().set_status_flags(new_flags)
+ }
+
+ pub fn is_nonblocking(&self) -> bool {
+ self.this_end()
+ .status_flags()
+ .contains(StatusFlags::O_NONBLOCK)
+ }
+
+ pub fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ self.this_end().pollee.poll(mask, poller)
+ }
+
+ pub fn register_observer(
+ &self,
+ observer: Weak<dyn Observer<IoEvents>>,
+ mask: IoEvents,
+ ) -> Result<()> {
+ self.this_end().pollee.register_observer(observer, mask);
+ Ok(())
+ }
+
+ pub fn unregister_observer(
+ &self,
+ observer: &Weak<dyn Observer<IoEvents>>,
+ ) -> Result<Weak<dyn Observer<IoEvents>>> {
+ self.this_end()
+ .pollee
+ .unregister_observer(observer)
+ .ok_or_else(|| Error::with_message(Errno::ENOENT, "the observer is not registered"))
+ }
+ };
+}
+
+impl<T> Producer<T> {
+ fn this_end(&self) -> &EndPointInner<HeapRbProducer<T>> {
+ &self.0.common.producer
+ }
+
+ fn peer_end(&self) -> &EndPointInner<HeapRbConsumer<T>> {
+ &self.0.common.consumer
+ }
+
+ fn update_pollee(&self) {
+ let this_end = self.this_end();
+ let peer_end = self.peer_end();
+
+ // Update the event of pollee in a critical region so that pollee
+ // always reflects the _true_ state of the underlying ring buffer
+ // regardless of any race conditions.
+ self.0.common.lock_event();
+
+ let rb = this_end.rb();
+ if rb.is_full() {
+ this_end.pollee.del_events(IoEvents::OUT);
+ }
+ if !rb.is_empty() {
+ peer_end.pollee.add_events(IoEvents::IN);
+ }
+ }
+
+ impl_common_methods_for_channel!();
+}
+
+impl<T: Copy> Producer<T> {
+ pub fn write(&self, buf: &[T]) -> Result<usize> {
+ if self.is_shutdown() || self.is_peer_shutdown() {
+ return_errno!(Errno::EPIPE);
+ }
+
+ if buf.len() == 0 {
+ return Ok(0);
+ }
+
+ let written_len = self.0.write(buf);
+
+ self.update_pollee();
+
+ if written_len > 0 {
+ Ok(written_len)
+ } else {
+ return_errno_with_message!(Errno::EAGAIN, "try write later");
+ }
+ }
+}
+
+impl<T> Drop for Producer<T> {
+ fn drop(&mut self) {
+ self.shutdown();
+
+ self.0.common.lock_event();
+
+ // When reading from a channel such as a pipe or a stream socket,
+ // POLLHUP merely indicates that the peer closed its end of the channel.
+ self.peer_end().pollee.add_events(IoEvents::HUP);
+ }
+}
+
+impl<T> Consumer<T> {
+ fn this_end(&self) -> &EndPointInner<HeapRbConsumer<T>> {
+ &self.0.common.consumer
+ }
+
+ fn peer_end(&self) -> &EndPointInner<HeapRbProducer<T>> {
+ &self.0.common.producer
+ }
+
+ fn update_pollee(&self) {
+ let this_end = self.this_end();
+ let peer_end = self.peer_end();
+
+ // Update the event of pollee in a critical region so that pollee
+ // always reflects the _true_ state of the underlying ring buffer
+ // regardless of any race conditions.
+ self.0.common.lock_event();
+
+ let rb = this_end.rb();
+ if rb.is_empty() {
+ this_end.pollee.del_events(IoEvents::IN);
+ }
+ if !rb.is_full() {
+ peer_end.pollee.add_events(IoEvents::OUT);
+ }
+ }
+
+ impl_common_methods_for_channel!();
+}
+
+impl<T: Copy> Consumer<T> {
+ pub fn read(&self, buf: &mut [T]) -> Result<usize> {
+ if self.is_shutdown() {
+ return_errno!(Errno::EPIPE);
+ }
+
+ if buf.len() == 0 {
+ return Ok(0);
+ }
+
+ let read_len = self.0.read(buf);
+
+ self.update_pollee();
+
+ if self.is_peer_shutdown() {
+ return Ok(read_len);
+ }
+
+ if read_len > 0 {
+ Ok(read_len)
+ } else {
+ return_errno_with_message!(Errno::EAGAIN, "try read later");
+ }
+ }
+}
+
+impl<T> Drop for Consumer<T> {
+ fn drop(&mut self) {
+ self.shutdown();
+
+ self.0.common.lock_event();
+
+ // POLLERR is also set for a file descriptor referring to the write end of a pipe
+ // when the read end has been closed.
+ self.peer_end().pollee.add_events(IoEvents::ERR);
+ }
+}
+
+struct EndPoint<T, R: TRights> {
+ common: Arc<Common<T>>,
+ rights: R,
+}
+
+impl<T, R: TRights> EndPoint<T, R> {
+ pub fn new(common: Arc<Common<T>>, rights: R) -> Self {
+ Self { common, rights }
+ }
+}
+
+impl<T: Copy, R: TRights> EndPoint<T, R> {
+ #[require(R > Read)]
+ pub fn read(&self, buf: &mut [T]) -> usize {
+ let mut rb = self.common.consumer.rb();
+ rb.pop_slice(buf)
+ }
+
+ #[require(R > Write)]
+ pub fn write(&self, buf: &[T]) -> usize {
+ let mut rb = self.common.producer.rb();
+ rb.push_slice(buf)
+ }
+}
+
+struct Common<T> {
+ producer: EndPointInner<HeapRbProducer<T>>,
+ consumer: EndPointInner<HeapRbConsumer<T>>,
+ event_lock: Mutex<()>,
+}
+
+impl<T> Common<T> {
+ fn with_capacity_and_flags(capacity: usize, flags: StatusFlags) -> Result<Self> {
+ check_status_flags(flags)?;
+
+ if capacity == 0 {
+ return_errno_with_message!(Errno::EINVAL, "capacity cannot be zero");
+ }
+
+ let rb: HeapRb<T> = HeapRb::new(capacity);
+ let (rb_producer, rb_consumer) = rb.split();
+
+ let producer = EndPointInner::new(rb_producer, IoEvents::OUT, flags);
+ let consumer = EndPointInner::new(rb_consumer, IoEvents::empty(), flags);
+ let event_lock = Mutex::new(());
+
+ Ok(Self {
+ producer,
+ consumer,
+ event_lock,
+ })
+ }
+
+ pub fn lock_event(&self) -> MutexGuard<()> {
+ self.event_lock.lock()
+ }
+
+ pub fn capacity(&self) -> usize {
+ self.producer.rb().capacity()
+ }
+}
+
+struct EndPointInner<T> {
+ rb: Mutex<T>,
+ pollee: Pollee,
+ is_shutdown: AtomicBool,
+ status_flags: AtomicU32,
+}
+
+impl<T> EndPointInner<T> {
+ pub fn new(rb: T, init_events: IoEvents, status_flags: StatusFlags) -> Self {
+ Self {
+ rb: Mutex::new(rb),
+ pollee: Pollee::new(init_events),
+ is_shutdown: AtomicBool::new(false),
+ status_flags: AtomicU32::new(status_flags.bits()),
+ }
+ }
+
+ pub fn rb(&self) -> MutexGuard<T> {
+ self.rb.lock()
+ }
+
+ pub fn is_shutdown(&self) -> bool {
+ self.is_shutdown.load(Ordering::Acquire)
+ }
+
+ pub fn shutdown(&self) {
+ self.is_shutdown.store(true, Ordering::Release)
+ }
+
+ pub fn status_flags(&self) -> StatusFlags {
+ let bits = self.status_flags.load(Ordering::Relaxed);
+ StatusFlags::from_bits(bits).unwrap()
+ }
+
+ pub fn set_status_flags(&self, new_flags: StatusFlags) {
+ self.status_flags.store(new_flags.bits(), Ordering::Relaxed);
+ }
+}
+
+fn check_status_flags(flags: StatusFlags) -> Result<()> {
+ let valid_flags: StatusFlags = StatusFlags::O_NONBLOCK | StatusFlags::O_DIRECT;
+ if !valid_flags.contains(flags) {
+ return_errno_with_message!(Errno::EINVAL, "invalid flags");
+ }
+ if flags.contains(StatusFlags::O_DIRECT) {
+ return_errno_with_message!(Errno::EINVAL, "O_DIRECT is not supported");
+ }
+ Ok(())
+}
diff --git /dev/null b/services/libs/jinux-std/src/fs/utils/channel.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/fs/utils/channel.rs
@@ -0,0 +1,347 @@
+use core::sync::atomic::{AtomicBool, AtomicU32, Ordering};
+use jinux_rights_proc::require;
+use ringbuf::{HeapConsumer as HeapRbConsumer, HeapProducer as HeapRbProducer, HeapRb};
+
+use crate::events::Observer;
+use crate::prelude::*;
+use crate::rights::*;
+
+use super::{IoEvents, Pollee, Poller, StatusFlags};
+
+/// A unidirectional communication channel, intended to implement IPC, e.g., pipe,
+/// unix domain sockets, etc.
+pub struct Channel<T> {
+ producer: Producer<T>,
+ consumer: Consumer<T>,
+}
+
+impl<T> Channel<T> {
+ pub fn with_capacity(capacity: usize) -> Result<Self> {
+ Self::with_capacity_and_flags(capacity, StatusFlags::empty())
+ }
+
+ pub fn with_capacity_and_flags(capacity: usize, flags: StatusFlags) -> Result<Self> {
+ let common = Arc::new(Common::with_capacity_and_flags(capacity, flags)?);
+ let producer = Producer(EndPoint::new(common.clone(), WriteOp::new()));
+ let consumer = Consumer(EndPoint::new(common, ReadOp::new()));
+ Ok(Self { producer, consumer })
+ }
+
+ pub fn split(self) -> (Producer<T>, Consumer<T>) {
+ let Self { producer, consumer } = self;
+ (producer, consumer)
+ }
+
+ pub fn producer(&self) -> &Producer<T> {
+ &self.producer
+ }
+
+ pub fn consumer(&self) -> &Consumer<T> {
+ &self.consumer
+ }
+
+ pub fn capacity(&self) -> usize {
+ self.producer.0.common.capacity()
+ }
+}
+
+pub struct Producer<T>(EndPoint<T, WriteOp>);
+
+pub struct Consumer<T>(EndPoint<T, ReadOp>);
+
+macro_rules! impl_common_methods_for_channel {
+ () => {
+ pub fn shutdown(&self) {
+ self.this_end().shutdown()
+ }
+
+ pub fn is_shutdown(&self) -> bool {
+ self.this_end().is_shutdown()
+ }
+
+ pub fn is_peer_shutdown(&self) -> bool {
+ self.peer_end().is_shutdown()
+ }
+
+ pub fn status_flags(&self) -> StatusFlags {
+ self.this_end().status_flags()
+ }
+
+ pub fn set_status_flags(&self, new_flags: StatusFlags) {
+ self.this_end().set_status_flags(new_flags)
+ }
+
+ pub fn is_nonblocking(&self) -> bool {
+ self.this_end()
+ .status_flags()
+ .contains(StatusFlags::O_NONBLOCK)
+ }
+
+ pub fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ self.this_end().pollee.poll(mask, poller)
+ }
+
+ pub fn register_observer(
+ &self,
+ observer: Weak<dyn Observer<IoEvents>>,
+ mask: IoEvents,
+ ) -> Result<()> {
+ self.this_end().pollee.register_observer(observer, mask);
+ Ok(())
+ }
+
+ pub fn unregister_observer(
+ &self,
+ observer: &Weak<dyn Observer<IoEvents>>,
+ ) -> Result<Weak<dyn Observer<IoEvents>>> {
+ self.this_end()
+ .pollee
+ .unregister_observer(observer)
+ .ok_or_else(|| Error::with_message(Errno::ENOENT, "the observer is not registered"))
+ }
+ };
+}
+
+impl<T> Producer<T> {
+ fn this_end(&self) -> &EndPointInner<HeapRbProducer<T>> {
+ &self.0.common.producer
+ }
+
+ fn peer_end(&self) -> &EndPointInner<HeapRbConsumer<T>> {
+ &self.0.common.consumer
+ }
+
+ fn update_pollee(&self) {
+ let this_end = self.this_end();
+ let peer_end = self.peer_end();
+
+ // Update the event of pollee in a critical region so that pollee
+ // always reflects the _true_ state of the underlying ring buffer
+ // regardless of any race conditions.
+ self.0.common.lock_event();
+
+ let rb = this_end.rb();
+ if rb.is_full() {
+ this_end.pollee.del_events(IoEvents::OUT);
+ }
+ if !rb.is_empty() {
+ peer_end.pollee.add_events(IoEvents::IN);
+ }
+ }
+
+ impl_common_methods_for_channel!();
+}
+
+impl<T: Copy> Producer<T> {
+ pub fn write(&self, buf: &[T]) -> Result<usize> {
+ if self.is_shutdown() || self.is_peer_shutdown() {
+ return_errno!(Errno::EPIPE);
+ }
+
+ if buf.len() == 0 {
+ return Ok(0);
+ }
+
+ let written_len = self.0.write(buf);
+
+ self.update_pollee();
+
+ if written_len > 0 {
+ Ok(written_len)
+ } else {
+ return_errno_with_message!(Errno::EAGAIN, "try write later");
+ }
+ }
+}
+
+impl<T> Drop for Producer<T> {
+ fn drop(&mut self) {
+ self.shutdown();
+
+ self.0.common.lock_event();
+
+ // When reading from a channel such as a pipe or a stream socket,
+ // POLLHUP merely indicates that the peer closed its end of the channel.
+ self.peer_end().pollee.add_events(IoEvents::HUP);
+ }
+}
+
+impl<T> Consumer<T> {
+ fn this_end(&self) -> &EndPointInner<HeapRbConsumer<T>> {
+ &self.0.common.consumer
+ }
+
+ fn peer_end(&self) -> &EndPointInner<HeapRbProducer<T>> {
+ &self.0.common.producer
+ }
+
+ fn update_pollee(&self) {
+ let this_end = self.this_end();
+ let peer_end = self.peer_end();
+
+ // Update the event of pollee in a critical region so that pollee
+ // always reflects the _true_ state of the underlying ring buffer
+ // regardless of any race conditions.
+ self.0.common.lock_event();
+
+ let rb = this_end.rb();
+ if rb.is_empty() {
+ this_end.pollee.del_events(IoEvents::IN);
+ }
+ if !rb.is_full() {
+ peer_end.pollee.add_events(IoEvents::OUT);
+ }
+ }
+
+ impl_common_methods_for_channel!();
+}
+
+impl<T: Copy> Consumer<T> {
+ pub fn read(&self, buf: &mut [T]) -> Result<usize> {
+ if self.is_shutdown() {
+ return_errno!(Errno::EPIPE);
+ }
+
+ if buf.len() == 0 {
+ return Ok(0);
+ }
+
+ let read_len = self.0.read(buf);
+
+ self.update_pollee();
+
+ if self.is_peer_shutdown() {
+ return Ok(read_len);
+ }
+
+ if read_len > 0 {
+ Ok(read_len)
+ } else {
+ return_errno_with_message!(Errno::EAGAIN, "try read later");
+ }
+ }
+}
+
+impl<T> Drop for Consumer<T> {
+ fn drop(&mut self) {
+ self.shutdown();
+
+ self.0.common.lock_event();
+
+ // POLLERR is also set for a file descriptor referring to the write end of a pipe
+ // when the read end has been closed.
+ self.peer_end().pollee.add_events(IoEvents::ERR);
+ }
+}
+
+struct EndPoint<T, R: TRights> {
+ common: Arc<Common<T>>,
+ rights: R,
+}
+
+impl<T, R: TRights> EndPoint<T, R> {
+ pub fn new(common: Arc<Common<T>>, rights: R) -> Self {
+ Self { common, rights }
+ }
+}
+
+impl<T: Copy, R: TRights> EndPoint<T, R> {
+ #[require(R > Read)]
+ pub fn read(&self, buf: &mut [T]) -> usize {
+ let mut rb = self.common.consumer.rb();
+ rb.pop_slice(buf)
+ }
+
+ #[require(R > Write)]
+ pub fn write(&self, buf: &[T]) -> usize {
+ let mut rb = self.common.producer.rb();
+ rb.push_slice(buf)
+ }
+}
+
+struct Common<T> {
+ producer: EndPointInner<HeapRbProducer<T>>,
+ consumer: EndPointInner<HeapRbConsumer<T>>,
+ event_lock: Mutex<()>,
+}
+
+impl<T> Common<T> {
+ fn with_capacity_and_flags(capacity: usize, flags: StatusFlags) -> Result<Self> {
+ check_status_flags(flags)?;
+
+ if capacity == 0 {
+ return_errno_with_message!(Errno::EINVAL, "capacity cannot be zero");
+ }
+
+ let rb: HeapRb<T> = HeapRb::new(capacity);
+ let (rb_producer, rb_consumer) = rb.split();
+
+ let producer = EndPointInner::new(rb_producer, IoEvents::OUT, flags);
+ let consumer = EndPointInner::new(rb_consumer, IoEvents::empty(), flags);
+ let event_lock = Mutex::new(());
+
+ Ok(Self {
+ producer,
+ consumer,
+ event_lock,
+ })
+ }
+
+ pub fn lock_event(&self) -> MutexGuard<()> {
+ self.event_lock.lock()
+ }
+
+ pub fn capacity(&self) -> usize {
+ self.producer.rb().capacity()
+ }
+}
+
+struct EndPointInner<T> {
+ rb: Mutex<T>,
+ pollee: Pollee,
+ is_shutdown: AtomicBool,
+ status_flags: AtomicU32,
+}
+
+impl<T> EndPointInner<T> {
+ pub fn new(rb: T, init_events: IoEvents, status_flags: StatusFlags) -> Self {
+ Self {
+ rb: Mutex::new(rb),
+ pollee: Pollee::new(init_events),
+ is_shutdown: AtomicBool::new(false),
+ status_flags: AtomicU32::new(status_flags.bits()),
+ }
+ }
+
+ pub fn rb(&self) -> MutexGuard<T> {
+ self.rb.lock()
+ }
+
+ pub fn is_shutdown(&self) -> bool {
+ self.is_shutdown.load(Ordering::Acquire)
+ }
+
+ pub fn shutdown(&self) {
+ self.is_shutdown.store(true, Ordering::Release)
+ }
+
+ pub fn status_flags(&self) -> StatusFlags {
+ let bits = self.status_flags.load(Ordering::Relaxed);
+ StatusFlags::from_bits(bits).unwrap()
+ }
+
+ pub fn set_status_flags(&self, new_flags: StatusFlags) {
+ self.status_flags.store(new_flags.bits(), Ordering::Relaxed);
+ }
+}
+
+fn check_status_flags(flags: StatusFlags) -> Result<()> {
+ let valid_flags: StatusFlags = StatusFlags::O_NONBLOCK | StatusFlags::O_DIRECT;
+ if !valid_flags.contains(flags) {
+ return_errno_with_message!(Errno::EINVAL, "invalid flags");
+ }
+ if flags.contains(StatusFlags::O_DIRECT) {
+ return_errno_with_message!(Errno::EINVAL, "O_DIRECT is not supported");
+ }
+ Ok(())
+}
diff --git a/services/libs/jinux-std/src/fs/utils/direntry_vec.rs b/services/libs/jinux-std/src/fs/utils/direntry_vec.rs
--- a/services/libs/jinux-std/src/fs/utils/direntry_vec.rs
+++ b/services/libs/jinux-std/src/fs/utils/direntry_vec.rs
@@ -1,87 +1,7 @@
use super::Inode;
use crate::prelude::*;
-/// DirEntryVec is used to store the entries of a directory.
-/// It can guarantee that the index of one dir entry remains unchanged during
-/// adding or deleting other dir entries of it.
-pub struct DirEntryVec<T> {
- // The slots to store dir entries.
- slots: Vec<Option<T>>,
- // The number of occupied slots.
- // The i-th slot is occupied if `self.slots[i].is_some()`.
- num_occupied: usize,
-}
-
-impl<T> DirEntryVec<T> {
- /// New an empty vec.
- pub fn new() -> Self {
- Self {
- slots: Vec::new(),
- num_occupied: 0,
- }
- }
-
- /// Returns `true` if the vec contains no entries.
- pub fn is_empty(&self) -> bool {
- self.num_occupied == 0
- }
-
- /// Put a dir entry into the vec.
- /// it may be put into an existing empty slot or the back of the vec.
- pub fn put(&mut self, entry: T) {
- if self.num_occupied == self.slots.len() {
- self.slots.push(Some(entry));
- } else {
- let idx = self.slots.iter().position(|x| x.is_none()).unwrap();
- self.slots[idx] = Some(entry);
- }
- self.num_occupied += 1;
- }
-
- /// Removes and returns the entry at position `idx`.
- /// Returns `None` if `idx` is out of bounds or the entry has been removed.
- pub fn remove(&mut self, idx: usize) -> Option<T> {
- if idx >= self.slots.len() {
- return None;
- }
- let mut del_entry = None;
- core::mem::swap(&mut del_entry, &mut self.slots[idx]);
- if del_entry.is_some() {
- debug_assert!(self.num_occupied > 0);
- self.num_occupied -= 1;
- }
- del_entry
- }
-
- /// Put and returns the entry at position `idx`.
- /// Returns `None` if `idx` is out of bounds or the entry has been removed.
- pub fn put_at(&mut self, idx: usize, entry: T) -> Option<T> {
- if idx >= self.slots.len() {
- return None;
- }
- let mut sub_entry = Some(entry);
- core::mem::swap(&mut sub_entry, &mut self.slots[idx]);
- if sub_entry.is_none() {
- self.num_occupied += 1;
- }
- sub_entry
- }
-
- /// Creates an iterator which gives both of the index and the dir entry.
- /// The index may not be continuous.
- pub fn idxes_and_entries(&self) -> impl Iterator<Item = (usize, &'_ T)> {
- self.slots
- .iter()
- .enumerate()
- .filter(|(_, x)| x.is_some())
- .map(|(idx, x)| (idx, x.as_ref().unwrap()))
- }
-
- /// Creates an iterator which gives the dir entry.
- pub fn iter(&self) -> impl Iterator<Item = &'_ T> {
- self.slots.iter().filter_map(|x| x.as_ref())
- }
-}
+use jinux_util::slot_vec::SlotVec;
pub trait DirEntryVecExt {
/// If the entry is not found by `name`, use `f` to get the inode, then put the entry into vec.
diff --git a/services/libs/jinux-std/src/fs/utils/direntry_vec.rs b/services/libs/jinux-std/src/fs/utils/direntry_vec.rs
--- a/services/libs/jinux-std/src/fs/utils/direntry_vec.rs
+++ b/services/libs/jinux-std/src/fs/utils/direntry_vec.rs
@@ -1,87 +1,7 @@
use super::Inode;
use crate::prelude::*;
-/// DirEntryVec is used to store the entries of a directory.
-/// It can guarantee that the index of one dir entry remains unchanged during
-/// adding or deleting other dir entries of it.
-pub struct DirEntryVec<T> {
- // The slots to store dir entries.
- slots: Vec<Option<T>>,
- // The number of occupied slots.
- // The i-th slot is occupied if `self.slots[i].is_some()`.
- num_occupied: usize,
-}
-
-impl<T> DirEntryVec<T> {
- /// New an empty vec.
- pub fn new() -> Self {
- Self {
- slots: Vec::new(),
- num_occupied: 0,
- }
- }
-
- /// Returns `true` if the vec contains no entries.
- pub fn is_empty(&self) -> bool {
- self.num_occupied == 0
- }
-
- /// Put a dir entry into the vec.
- /// it may be put into an existing empty slot or the back of the vec.
- pub fn put(&mut self, entry: T) {
- if self.num_occupied == self.slots.len() {
- self.slots.push(Some(entry));
- } else {
- let idx = self.slots.iter().position(|x| x.is_none()).unwrap();
- self.slots[idx] = Some(entry);
- }
- self.num_occupied += 1;
- }
-
- /// Removes and returns the entry at position `idx`.
- /// Returns `None` if `idx` is out of bounds or the entry has been removed.
- pub fn remove(&mut self, idx: usize) -> Option<T> {
- if idx >= self.slots.len() {
- return None;
- }
- let mut del_entry = None;
- core::mem::swap(&mut del_entry, &mut self.slots[idx]);
- if del_entry.is_some() {
- debug_assert!(self.num_occupied > 0);
- self.num_occupied -= 1;
- }
- del_entry
- }
-
- /// Put and returns the entry at position `idx`.
- /// Returns `None` if `idx` is out of bounds or the entry has been removed.
- pub fn put_at(&mut self, idx: usize, entry: T) -> Option<T> {
- if idx >= self.slots.len() {
- return None;
- }
- let mut sub_entry = Some(entry);
- core::mem::swap(&mut sub_entry, &mut self.slots[idx]);
- if sub_entry.is_none() {
- self.num_occupied += 1;
- }
- sub_entry
- }
-
- /// Creates an iterator which gives both of the index and the dir entry.
- /// The index may not be continuous.
- pub fn idxes_and_entries(&self) -> impl Iterator<Item = (usize, &'_ T)> {
- self.slots
- .iter()
- .enumerate()
- .filter(|(_, x)| x.is_some())
- .map(|(idx, x)| (idx, x.as_ref().unwrap()))
- }
-
- /// Creates an iterator which gives the dir entry.
- pub fn iter(&self) -> impl Iterator<Item = &'_ T> {
- self.slots.iter().filter_map(|x| x.as_ref())
- }
-}
+use jinux_util::slot_vec::SlotVec;
pub trait DirEntryVecExt {
/// If the entry is not found by `name`, use `f` to get the inode, then put the entry into vec.
diff --git a/services/libs/jinux-std/src/fs/utils/direntry_vec.rs b/services/libs/jinux-std/src/fs/utils/direntry_vec.rs
--- a/services/libs/jinux-std/src/fs/utils/direntry_vec.rs
+++ b/services/libs/jinux-std/src/fs/utils/direntry_vec.rs
@@ -92,7 +12,7 @@ pub trait DirEntryVecExt {
fn remove_entry_by_name(&mut self, name: &str) -> Option<(String, Arc<dyn Inode>)>;
}
-impl DirEntryVecExt for DirEntryVec<(String, Arc<dyn Inode>)> {
+impl DirEntryVecExt for SlotVec<(String, Arc<dyn Inode>)> {
fn put_entry_if_not_found(&mut self, name: &str, f: impl Fn() -> Arc<dyn Inode>) {
if self
.iter()
diff --git a/services/libs/jinux-std/src/fs/utils/direntry_vec.rs b/services/libs/jinux-std/src/fs/utils/direntry_vec.rs
--- a/services/libs/jinux-std/src/fs/utils/direntry_vec.rs
+++ b/services/libs/jinux-std/src/fs/utils/direntry_vec.rs
@@ -92,7 +12,7 @@ pub trait DirEntryVecExt {
fn remove_entry_by_name(&mut self, name: &str) -> Option<(String, Arc<dyn Inode>)>;
}
-impl DirEntryVecExt for DirEntryVec<(String, Arc<dyn Inode>)> {
+impl DirEntryVecExt for SlotVec<(String, Arc<dyn Inode>)> {
fn put_entry_if_not_found(&mut self, name: &str, f: impl Fn() -> Arc<dyn Inode>) {
if self
.iter()
diff --git a/services/libs/jinux-std/src/fs/utils/direntry_vec.rs b/services/libs/jinux-std/src/fs/utils/direntry_vec.rs
--- a/services/libs/jinux-std/src/fs/utils/direntry_vec.rs
+++ b/services/libs/jinux-std/src/fs/utils/direntry_vec.rs
@@ -106,7 +26,7 @@ impl DirEntryVecExt for DirEntryVec<(String, Arc<dyn Inode>)> {
fn remove_entry_by_name(&mut self, name: &str) -> Option<(String, Arc<dyn Inode>)> {
let idx = self
- .idxes_and_entries()
+ .idxes_and_items()
.find(|(_, (child_name, _))| child_name == name)
.map(|(idx, _)| idx);
if let Some(idx) = idx {
diff --git a/services/libs/jinux-std/src/fs/utils/direntry_vec.rs b/services/libs/jinux-std/src/fs/utils/direntry_vec.rs
--- a/services/libs/jinux-std/src/fs/utils/direntry_vec.rs
+++ b/services/libs/jinux-std/src/fs/utils/direntry_vec.rs
@@ -106,7 +26,7 @@ impl DirEntryVecExt for DirEntryVec<(String, Arc<dyn Inode>)> {
fn remove_entry_by_name(&mut self, name: &str) -> Option<(String, Arc<dyn Inode>)> {
let idx = self
- .idxes_and_entries()
+ .idxes_and_items()
.find(|(_, (child_name, _))| child_name == name)
.map(|(idx, _)| idx);
if let Some(idx) = idx {
diff --git a/services/libs/jinux-std/src/fs/utils/inode.rs b/services/libs/jinux-std/src/fs/utils/inode.rs
--- a/services/libs/jinux-std/src/fs/utils/inode.rs
+++ b/services/libs/jinux-std/src/fs/utils/inode.rs
@@ -5,7 +5,7 @@ use core::any::Any;
use core::time::Duration;
use jinux_frame::vm::VmFrame;
-use super::{DirentVisitor, FileSystem, IoctlCmd, SuperBlock};
+use super::{DirentVisitor, FileSystem, IoEvents, IoctlCmd, Poller, SuperBlock};
use crate::prelude::*;
#[repr(u32)]
diff --git a/services/libs/jinux-std/src/fs/utils/inode.rs b/services/libs/jinux-std/src/fs/utils/inode.rs
--- a/services/libs/jinux-std/src/fs/utils/inode.rs
+++ b/services/libs/jinux-std/src/fs/utils/inode.rs
@@ -5,7 +5,7 @@ use core::any::Any;
use core::time::Duration;
use jinux_frame::vm::VmFrame;
-use super::{DirentVisitor, FileSystem, IoctlCmd, SuperBlock};
+use super::{DirentVisitor, FileSystem, IoEvents, IoctlCmd, Poller, SuperBlock};
use crate::prelude::*;
#[repr(u32)]
diff --git a/services/libs/jinux-std/src/fs/utils/inode.rs b/services/libs/jinux-std/src/fs/utils/inode.rs
--- a/services/libs/jinux-std/src/fs/utils/inode.rs
+++ b/services/libs/jinux-std/src/fs/utils/inode.rs
@@ -197,6 +197,11 @@ pub trait Inode: Any + Sync + Send {
fn sync(&self) -> Result<()>;
+ fn poll(&self, mask: IoEvents, _poller: Option<&Poller>) -> IoEvents {
+ let events = IoEvents::IN | IoEvents::OUT;
+ events & mask
+ }
+
fn fs(&self) -> Arc<dyn FileSystem>;
fn as_any_ref(&self) -> &dyn Any;
diff --git a/services/libs/jinux-std/src/fs/utils/inode.rs b/services/libs/jinux-std/src/fs/utils/inode.rs
--- a/services/libs/jinux-std/src/fs/utils/inode.rs
+++ b/services/libs/jinux-std/src/fs/utils/inode.rs
@@ -197,6 +197,11 @@ pub trait Inode: Any + Sync + Send {
fn sync(&self) -> Result<()>;
+ fn poll(&self, mask: IoEvents, _poller: Option<&Poller>) -> IoEvents {
+ let events = IoEvents::IN | IoEvents::OUT;
+ events & mask
+ }
+
fn fs(&self) -> Arc<dyn FileSystem>;
fn as_any_ref(&self) -> &dyn Any;
diff --git a/services/libs/jinux-std/src/fs/utils/io_events.rs b/services/libs/jinux-std/src/fs/utils/io_events.rs
--- a/services/libs/jinux-std/src/fs/utils/io_events.rs
+++ b/services/libs/jinux-std/src/fs/utils/io_events.rs
@@ -1,11 +1,23 @@
+use crate::events::{Events, EventsFilter};
+
crate::bitflags! {
pub struct IoEvents: u32 {
- const POLLIN = 0x0001;
- const POLLPRI = 0x0002;
- const POLLOUT = 0x0004;
- const POLLERR = 0x0008;
- const POLLHUP = 0x0010;
- const POLLNVAL = 0x0020;
- const POLLRDHUP = 0x2000;
+ const IN = 0x0001;
+ const PRI = 0x0002;
+ const OUT = 0x0004;
+ const ERR = 0x0008;
+ const HUP = 0x0010;
+ const NVAL = 0x0020;
+ const RDHUP = 0x2000;
+ /// Events that are always polled even without specifying them.
+ const ALWAYS_POLL = Self::ERR.bits | Self::HUP.bits;
+ }
+}
+
+impl Events for IoEvents {}
+
+impl EventsFilter<IoEvents> for IoEvents {
+ fn filter(&self, events: &IoEvents) -> bool {
+ self.intersects(*events)
}
}
diff --git a/services/libs/jinux-std/src/fs/utils/io_events.rs b/services/libs/jinux-std/src/fs/utils/io_events.rs
--- a/services/libs/jinux-std/src/fs/utils/io_events.rs
+++ b/services/libs/jinux-std/src/fs/utils/io_events.rs
@@ -1,11 +1,23 @@
+use crate::events::{Events, EventsFilter};
+
crate::bitflags! {
pub struct IoEvents: u32 {
- const POLLIN = 0x0001;
- const POLLPRI = 0x0002;
- const POLLOUT = 0x0004;
- const POLLERR = 0x0008;
- const POLLHUP = 0x0010;
- const POLLNVAL = 0x0020;
- const POLLRDHUP = 0x2000;
+ const IN = 0x0001;
+ const PRI = 0x0002;
+ const OUT = 0x0004;
+ const ERR = 0x0008;
+ const HUP = 0x0010;
+ const NVAL = 0x0020;
+ const RDHUP = 0x2000;
+ /// Events that are always polled even without specifying them.
+ const ALWAYS_POLL = Self::ERR.bits | Self::HUP.bits;
+ }
+}
+
+impl Events for IoEvents {}
+
+impl EventsFilter<IoEvents> for IoEvents {
+ fn filter(&self, events: &IoEvents) -> bool {
+ self.intersects(*events)
}
}
diff --git a/services/libs/jinux-std/src/fs/utils/mod.rs b/services/libs/jinux-std/src/fs/utils/mod.rs
--- a/services/libs/jinux-std/src/fs/utils/mod.rs
+++ b/services/libs/jinux-std/src/fs/utils/mod.rs
@@ -1,10 +1,11 @@
//! VFS components
pub use access_mode::AccessMode;
+pub use channel::{Channel, Consumer, Producer};
pub use creation_flags::CreationFlags;
pub use dentry_cache::Dentry;
pub use dirent_visitor::DirentVisitor;
-pub use direntry_vec::{DirEntryVec, DirEntryVecExt};
+pub use direntry_vec::DirEntryVecExt;
pub use fcntl::FcntlCmd;
pub use file_creation_mask::FileCreationMask;
pub use fs::{FileSystem, FsFlags, SuperBlock};
diff --git a/services/libs/jinux-std/src/fs/utils/mod.rs b/services/libs/jinux-std/src/fs/utils/mod.rs
--- a/services/libs/jinux-std/src/fs/utils/mod.rs
+++ b/services/libs/jinux-std/src/fs/utils/mod.rs
@@ -1,10 +1,11 @@
//! VFS components
pub use access_mode::AccessMode;
+pub use channel::{Channel, Consumer, Producer};
pub use creation_flags::CreationFlags;
pub use dentry_cache::Dentry;
pub use dirent_visitor::DirentVisitor;
-pub use direntry_vec::{DirEntryVec, DirEntryVecExt};
+pub use direntry_vec::DirEntryVecExt;
pub use fcntl::FcntlCmd;
pub use file_creation_mask::FileCreationMask;
pub use fs::{FileSystem, FsFlags, SuperBlock};
diff --git a/services/libs/jinux-std/src/fs/utils/mod.rs b/services/libs/jinux-std/src/fs/utils/mod.rs
--- a/services/libs/jinux-std/src/fs/utils/mod.rs
+++ b/services/libs/jinux-std/src/fs/utils/mod.rs
@@ -12,11 +13,12 @@ pub use inode::{Inode, InodeMode, InodeType, Metadata};
pub use io_events::IoEvents;
pub use ioctl::IoctlCmd;
pub use page_cache::PageCache;
-pub use poll::{c_nfds, c_pollfd, PollFd};
+pub use poll::{Pollee, Poller};
pub use status_flags::StatusFlags;
pub use vnode::Vnode;
mod access_mode;
+mod channel;
mod creation_flags;
mod dentry_cache;
mod dirent_visitor;
diff --git a/services/libs/jinux-std/src/fs/utils/mod.rs b/services/libs/jinux-std/src/fs/utils/mod.rs
--- a/services/libs/jinux-std/src/fs/utils/mod.rs
+++ b/services/libs/jinux-std/src/fs/utils/mod.rs
@@ -12,11 +13,12 @@ pub use inode::{Inode, InodeMode, InodeType, Metadata};
pub use io_events::IoEvents;
pub use ioctl::IoctlCmd;
pub use page_cache::PageCache;
-pub use poll::{c_nfds, c_pollfd, PollFd};
+pub use poll::{Pollee, Poller};
pub use status_flags::StatusFlags;
pub use vnode::Vnode;
mod access_mode;
+mod channel;
mod creation_flags;
mod dentry_cache;
mod dirent_visitor;
diff --git a/services/libs/jinux-std/src/fs/utils/poll.rs b/services/libs/jinux-std/src/fs/utils/poll.rs
--- a/services/libs/jinux-std/src/fs/utils/poll.rs
+++ b/services/libs/jinux-std/src/fs/utils/poll.rs
@@ -1,46 +1,214 @@
-#![allow(non_camel_case_types)]
-
use super::IoEvents;
-use crate::fs::file_table::FileDescripter;
+use crate::events::{Observer, Subject};
use crate::prelude::*;
-pub type c_nfds = u64;
-// https://github.com/torvalds/linux/blob/master/include/uapi/asm-generic/poll.h
-#[derive(Debug, Clone, Copy, Pod)]
-#[repr(C)]
-pub struct c_pollfd {
- fd: FileDescripter,
- events: i16,
- revents: i16,
+use core::sync::atomic::{AtomicU32, AtomicUsize, Ordering};
+use jinux_frame::sync::WaitQueue;
+use keyable_arc::KeyableWeak;
+
+/// A pollee maintains a set of active events, which can be polled with
+/// pollers or be monitored with observers.
+pub struct Pollee {
+ inner: Arc<PolleeInner>,
+}
+
+struct PolleeInner {
+ // A subject which is monitored with pollers.
+ subject: Subject<IoEvents, IoEvents>,
+ // For efficient manipulation, we use AtomicU32 instead of RwLock<IoEvents>.
+ events: AtomicU32,
+}
+
+impl Pollee {
+ /// Creates a new instance of pollee.
+ pub fn new(init_events: IoEvents) -> Self {
+ let inner = PolleeInner {
+ subject: Subject::new(),
+ events: AtomicU32::new(init_events.bits()),
+ };
+ Self {
+ inner: Arc::new(inner),
+ }
+ }
+
+ /// Returns the current events of the pollee given an event mask.
+ ///
+ /// If no interesting events are polled and a poller is provided, then
+ /// the poller will start monitoring the pollee and receive event
+ /// notification once the pollee gets any interesting events.
+ ///
+ /// This operation is _atomic_ in the sense that either some interesting
+ /// events are returned or the poller is registered (if a poller is provided).
+ pub fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ let mask = mask | IoEvents::ALWAYS_POLL;
+
+ // Fast path: return events immediately
+ let revents = self.events() & mask;
+ if !revents.is_empty() || poller.is_none() {
+ return revents;
+ }
+
+ // Register the provided poller.
+ self.register_poller(poller.unwrap(), mask);
+
+ // It is important to check events again to handle race conditions
+ let revents = self.events() & mask;
+ revents
+ }
+
+ fn register_poller(&self, poller: &Poller, mask: IoEvents) {
+ self.inner
+ .subject
+ .register_observer(poller.observer(), mask);
+ let mut pollees = poller.inner.pollees.lock();
+ pollees.insert(Arc::downgrade(&self.inner).into(), ());
+ }
+
+ /// Register an IoEvents observer.
+ ///
+ /// A registered observer will get notified (through its `on_events` method)
+ /// every time new events specified by the `mask` argument happen on the
+ /// pollee (through the `add_events` method).
+ ///
+ /// If the given observer has already been registered, then its registered
+ /// event mask will be updated.
+ ///
+ /// Note that the observer will always get notified of the events in
+ /// `IoEvents::ALWAYS_POLL` regardless of the value of `mask`.
+ pub fn register_observer(&self, observer: Weak<dyn Observer<IoEvents>>, mask: IoEvents) {
+ let mask = mask | IoEvents::ALWAYS_POLL;
+ self.inner.subject.register_observer(observer, mask);
+ }
+
+ /// Unregister an IoEvents observer.
+ ///
+ /// If such an observer is found, then the registered observer will be
+ /// removed from the pollee and returned as the return value. Otherwise,
+ /// a `None` will be returned.
+ pub fn unregister_observer(
+ &self,
+ observer: &Weak<dyn Observer<IoEvents>>,
+ ) -> Option<Weak<dyn Observer<IoEvents>>> {
+ self.inner.subject.unregister_observer(observer)
+ }
+
+ /// Add some events to the pollee's state.
+ ///
+ /// This method wakes up all registered pollers that are interested in
+ /// the added events.
+ pub fn add_events(&self, events: IoEvents) {
+ self.inner.events.fetch_or(events.bits(), Ordering::Release);
+ self.inner.subject.notify_observers(&events);
+ }
+
+ /// Remove some events from the pollee's state.
+ ///
+ /// This method will not wake up registered pollers even when
+ /// the pollee still has some interesting events to the pollers.
+ pub fn del_events(&self, events: IoEvents) {
+ self.inner
+ .events
+ .fetch_and(!events.bits(), Ordering::Release);
+ }
+
+ /// Reset the pollee's state.
+ ///
+ /// Reset means removing all events on the pollee.
+ pub fn reset_events(&self) {
+ self.inner
+ .events
+ .fetch_and(!IoEvents::all().bits(), Ordering::Release);
+ }
+
+ fn events(&self) -> IoEvents {
+ let event_bits = self.inner.events.load(Ordering::Acquire);
+ IoEvents::from_bits(event_bits).unwrap()
+ }
}
-#[derive(Debug, Clone, Copy)]
-pub struct PollFd {
- pub fd: FileDescripter,
- pub events: IoEvents,
- pub revents: IoEvents,
+/// A poller gets notified when its associated pollees have interesting events.
+pub struct Poller {
+ inner: Arc<PollerInner>,
}
-impl From<c_pollfd> for PollFd {
- fn from(raw: c_pollfd) -> Self {
- let events = IoEvents::from_bits_truncate(raw.events as _);
- let revents = IoEvents::from_bits_truncate(raw.revents as _);
+struct PollerInner {
+ // Use event counter to wait or wake up a poller
+ event_counter: EventCounter,
+ // All pollees that are interesting to this poller
+ pollees: Mutex<BTreeMap<KeyableWeak<PolleeInner>, ()>>,
+}
+
+impl Poller {
+ /// Constructs a new `Poller`.
+ pub fn new() -> Self {
+ let inner = PollerInner {
+ event_counter: EventCounter::new(),
+ pollees: Mutex::new(BTreeMap::new()),
+ };
Self {
- fd: raw.fd,
- events,
- revents,
+ inner: Arc::new(inner),
}
}
+
+ /// Wait until there are any interesting events happen since last `wait`.
+ pub fn wait(&self) {
+ self.inner.event_counter.read();
+ }
+
+ fn observer(&self) -> Weak<dyn Observer<IoEvents>> {
+ Arc::downgrade(&self.inner) as _
+ }
+}
+
+impl Observer<IoEvents> for PollerInner {
+ fn on_events(&self, _events: &IoEvents) {
+ self.event_counter.write();
+ }
}
-impl From<PollFd> for c_pollfd {
- fn from(raw: PollFd) -> Self {
- let events = raw.events.bits() as i16;
- let revents = raw.revents.bits() as i16;
+impl Drop for Poller {
+ fn drop(&mut self) {
+ let mut pollees = self.inner.pollees.lock();
+ if pollees.len() == 0 {
+ return;
+ }
+
+ let self_observer = self.observer();
+ for (weak_pollee, _) in pollees.drain_filter(|_, _| true) {
+ if let Some(pollee) = weak_pollee.upgrade() {
+ pollee.subject.unregister_observer(&self_observer);
+ }
+ }
+ }
+}
+
+/// A counter for wait and wakeup.
+struct EventCounter {
+ counter: AtomicUsize,
+ wait_queue: WaitQueue,
+}
+
+impl EventCounter {
+ pub fn new() -> Self {
Self {
- fd: raw.fd,
- events,
- revents,
+ counter: AtomicUsize::new(0),
+ wait_queue: WaitQueue::new(),
}
}
+
+ pub fn read(&self) -> usize {
+ self.wait_queue.wait_until(|| {
+ let val = self.counter.swap(0, Ordering::Relaxed);
+ if val > 0 {
+ Some(val)
+ } else {
+ None
+ }
+ })
+ }
+
+ pub fn write(&self) {
+ self.counter.fetch_add(1, Ordering::Relaxed);
+ self.wait_queue.wake_one();
+ }
}
diff --git a/services/libs/jinux-std/src/fs/utils/poll.rs b/services/libs/jinux-std/src/fs/utils/poll.rs
--- a/services/libs/jinux-std/src/fs/utils/poll.rs
+++ b/services/libs/jinux-std/src/fs/utils/poll.rs
@@ -1,46 +1,214 @@
-#![allow(non_camel_case_types)]
-
use super::IoEvents;
-use crate::fs::file_table::FileDescripter;
+use crate::events::{Observer, Subject};
use crate::prelude::*;
-pub type c_nfds = u64;
-// https://github.com/torvalds/linux/blob/master/include/uapi/asm-generic/poll.h
-#[derive(Debug, Clone, Copy, Pod)]
-#[repr(C)]
-pub struct c_pollfd {
- fd: FileDescripter,
- events: i16,
- revents: i16,
+use core::sync::atomic::{AtomicU32, AtomicUsize, Ordering};
+use jinux_frame::sync::WaitQueue;
+use keyable_arc::KeyableWeak;
+
+/// A pollee maintains a set of active events, which can be polled with
+/// pollers or be monitored with observers.
+pub struct Pollee {
+ inner: Arc<PolleeInner>,
+}
+
+struct PolleeInner {
+ // A subject which is monitored with pollers.
+ subject: Subject<IoEvents, IoEvents>,
+ // For efficient manipulation, we use AtomicU32 instead of RwLock<IoEvents>.
+ events: AtomicU32,
+}
+
+impl Pollee {
+ /// Creates a new instance of pollee.
+ pub fn new(init_events: IoEvents) -> Self {
+ let inner = PolleeInner {
+ subject: Subject::new(),
+ events: AtomicU32::new(init_events.bits()),
+ };
+ Self {
+ inner: Arc::new(inner),
+ }
+ }
+
+ /// Returns the current events of the pollee given an event mask.
+ ///
+ /// If no interesting events are polled and a poller is provided, then
+ /// the poller will start monitoring the pollee and receive event
+ /// notification once the pollee gets any interesting events.
+ ///
+ /// This operation is _atomic_ in the sense that either some interesting
+ /// events are returned or the poller is registered (if a poller is provided).
+ pub fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ let mask = mask | IoEvents::ALWAYS_POLL;
+
+ // Fast path: return events immediately
+ let revents = self.events() & mask;
+ if !revents.is_empty() || poller.is_none() {
+ return revents;
+ }
+
+ // Register the provided poller.
+ self.register_poller(poller.unwrap(), mask);
+
+ // It is important to check events again to handle race conditions
+ let revents = self.events() & mask;
+ revents
+ }
+
+ fn register_poller(&self, poller: &Poller, mask: IoEvents) {
+ self.inner
+ .subject
+ .register_observer(poller.observer(), mask);
+ let mut pollees = poller.inner.pollees.lock();
+ pollees.insert(Arc::downgrade(&self.inner).into(), ());
+ }
+
+ /// Register an IoEvents observer.
+ ///
+ /// A registered observer will get notified (through its `on_events` method)
+ /// every time new events specified by the `mask` argument happen on the
+ /// pollee (through the `add_events` method).
+ ///
+ /// If the given observer has already been registered, then its registered
+ /// event mask will be updated.
+ ///
+ /// Note that the observer will always get notified of the events in
+ /// `IoEvents::ALWAYS_POLL` regardless of the value of `mask`.
+ pub fn register_observer(&self, observer: Weak<dyn Observer<IoEvents>>, mask: IoEvents) {
+ let mask = mask | IoEvents::ALWAYS_POLL;
+ self.inner.subject.register_observer(observer, mask);
+ }
+
+ /// Unregister an IoEvents observer.
+ ///
+ /// If such an observer is found, then the registered observer will be
+ /// removed from the pollee and returned as the return value. Otherwise,
+ /// a `None` will be returned.
+ pub fn unregister_observer(
+ &self,
+ observer: &Weak<dyn Observer<IoEvents>>,
+ ) -> Option<Weak<dyn Observer<IoEvents>>> {
+ self.inner.subject.unregister_observer(observer)
+ }
+
+ /// Add some events to the pollee's state.
+ ///
+ /// This method wakes up all registered pollers that are interested in
+ /// the added events.
+ pub fn add_events(&self, events: IoEvents) {
+ self.inner.events.fetch_or(events.bits(), Ordering::Release);
+ self.inner.subject.notify_observers(&events);
+ }
+
+ /// Remove some events from the pollee's state.
+ ///
+ /// This method will not wake up registered pollers even when
+ /// the pollee still has some interesting events to the pollers.
+ pub fn del_events(&self, events: IoEvents) {
+ self.inner
+ .events
+ .fetch_and(!events.bits(), Ordering::Release);
+ }
+
+ /// Reset the pollee's state.
+ ///
+ /// Reset means removing all events on the pollee.
+ pub fn reset_events(&self) {
+ self.inner
+ .events
+ .fetch_and(!IoEvents::all().bits(), Ordering::Release);
+ }
+
+ fn events(&self) -> IoEvents {
+ let event_bits = self.inner.events.load(Ordering::Acquire);
+ IoEvents::from_bits(event_bits).unwrap()
+ }
}
-#[derive(Debug, Clone, Copy)]
-pub struct PollFd {
- pub fd: FileDescripter,
- pub events: IoEvents,
- pub revents: IoEvents,
+/// A poller gets notified when its associated pollees have interesting events.
+pub struct Poller {
+ inner: Arc<PollerInner>,
}
-impl From<c_pollfd> for PollFd {
- fn from(raw: c_pollfd) -> Self {
- let events = IoEvents::from_bits_truncate(raw.events as _);
- let revents = IoEvents::from_bits_truncate(raw.revents as _);
+struct PollerInner {
+ // Use event counter to wait or wake up a poller
+ event_counter: EventCounter,
+ // All pollees that are interesting to this poller
+ pollees: Mutex<BTreeMap<KeyableWeak<PolleeInner>, ()>>,
+}
+
+impl Poller {
+ /// Constructs a new `Poller`.
+ pub fn new() -> Self {
+ let inner = PollerInner {
+ event_counter: EventCounter::new(),
+ pollees: Mutex::new(BTreeMap::new()),
+ };
Self {
- fd: raw.fd,
- events,
- revents,
+ inner: Arc::new(inner),
}
}
+
+ /// Wait until there are any interesting events happen since last `wait`.
+ pub fn wait(&self) {
+ self.inner.event_counter.read();
+ }
+
+ fn observer(&self) -> Weak<dyn Observer<IoEvents>> {
+ Arc::downgrade(&self.inner) as _
+ }
+}
+
+impl Observer<IoEvents> for PollerInner {
+ fn on_events(&self, _events: &IoEvents) {
+ self.event_counter.write();
+ }
}
-impl From<PollFd> for c_pollfd {
- fn from(raw: PollFd) -> Self {
- let events = raw.events.bits() as i16;
- let revents = raw.revents.bits() as i16;
+impl Drop for Poller {
+ fn drop(&mut self) {
+ let mut pollees = self.inner.pollees.lock();
+ if pollees.len() == 0 {
+ return;
+ }
+
+ let self_observer = self.observer();
+ for (weak_pollee, _) in pollees.drain_filter(|_, _| true) {
+ if let Some(pollee) = weak_pollee.upgrade() {
+ pollee.subject.unregister_observer(&self_observer);
+ }
+ }
+ }
+}
+
+/// A counter for wait and wakeup.
+struct EventCounter {
+ counter: AtomicUsize,
+ wait_queue: WaitQueue,
+}
+
+impl EventCounter {
+ pub fn new() -> Self {
Self {
- fd: raw.fd,
- events,
- revents,
+ counter: AtomicUsize::new(0),
+ wait_queue: WaitQueue::new(),
}
}
+
+ pub fn read(&self) -> usize {
+ self.wait_queue.wait_until(|| {
+ let val = self.counter.swap(0, Ordering::Relaxed);
+ if val > 0 {
+ Some(val)
+ } else {
+ None
+ }
+ })
+ }
+
+ pub fn write(&self) {
+ self.counter.fetch_add(1, Ordering::Relaxed);
+ self.wait_queue.wake_one();
+ }
}
diff --git a/services/libs/jinux-std/src/fs/utils/vnode.rs b/services/libs/jinux-std/src/fs/utils/vnode.rs
--- a/services/libs/jinux-std/src/fs/utils/vnode.rs
+++ b/services/libs/jinux-std/src/fs/utils/vnode.rs
@@ -1,4 +1,6 @@
-use super::{DirentVisitor, FsFlags, Inode, InodeMode, InodeType, Metadata, PageCache};
+use super::{
+ DirentVisitor, FsFlags, Inode, InodeMode, InodeType, IoEvents, Metadata, PageCache, Poller,
+};
use crate::prelude::*;
use crate::rights::Full;
use crate::vm::vmo::Vmo;
diff --git a/services/libs/jinux-std/src/fs/utils/vnode.rs b/services/libs/jinux-std/src/fs/utils/vnode.rs
--- a/services/libs/jinux-std/src/fs/utils/vnode.rs
+++ b/services/libs/jinux-std/src/fs/utils/vnode.rs
@@ -1,4 +1,6 @@
-use super::{DirentVisitor, FsFlags, Inode, InodeMode, InodeType, Metadata, PageCache};
+use super::{
+ DirentVisitor, FsFlags, Inode, InodeMode, InodeType, IoEvents, Metadata, PageCache, Poller,
+};
use crate::prelude::*;
use crate::rights::Full;
use crate::vm::vmo::Vmo;
diff --git a/services/libs/jinux-std/src/fs/utils/vnode.rs b/services/libs/jinux-std/src/fs/utils/vnode.rs
--- a/services/libs/jinux-std/src/fs/utils/vnode.rs
+++ b/services/libs/jinux-std/src/fs/utils/vnode.rs
@@ -184,6 +186,10 @@ impl Vnode {
self.inner.read().inode.readdir_at(offset, visitor)
}
+ pub fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ self.inner.read().inode.poll(mask, poller)
+ }
+
pub fn metadata(&self) -> Metadata {
self.inner.read().inode.metadata()
}
diff --git a/services/libs/jinux-std/src/fs/utils/vnode.rs b/services/libs/jinux-std/src/fs/utils/vnode.rs
--- a/services/libs/jinux-std/src/fs/utils/vnode.rs
+++ b/services/libs/jinux-std/src/fs/utils/vnode.rs
@@ -184,6 +186,10 @@ impl Vnode {
self.inner.read().inode.readdir_at(offset, visitor)
}
+ pub fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ self.inner.read().inode.poll(mask, poller)
+ }
+
pub fn metadata(&self) -> Metadata {
self.inner.read().inode.metadata()
}
diff --git a/services/libs/jinux-std/src/prelude.rs b/services/libs/jinux-std/src/prelude.rs
--- a/services/libs/jinux-std/src/prelude.rs
+++ b/services/libs/jinux-std/src/prelude.rs
@@ -13,6 +13,7 @@ pub(crate) use alloc::sync::Weak;
pub(crate) use alloc::vec;
pub(crate) use alloc::vec::Vec;
pub(crate) use bitflags::bitflags;
+pub(crate) use core::any::Any;
pub(crate) use core::ffi::CStr;
pub(crate) use jinux_frame::config::PAGE_SIZE;
pub(crate) use jinux_frame::sync::{Mutex, MutexGuard};
diff --git a/services/libs/jinux-std/src/prelude.rs b/services/libs/jinux-std/src/prelude.rs
--- a/services/libs/jinux-std/src/prelude.rs
+++ b/services/libs/jinux-std/src/prelude.rs
@@ -13,6 +13,7 @@ pub(crate) use alloc::sync::Weak;
pub(crate) use alloc::vec;
pub(crate) use alloc::vec::Vec;
pub(crate) use bitflags::bitflags;
+pub(crate) use core::any::Any;
pub(crate) use core::ffi::CStr;
pub(crate) use jinux_frame::config::PAGE_SIZE;
pub(crate) use jinux_frame::sync::{Mutex, MutexGuard};
diff --git a/services/libs/jinux-std/src/process/mod.rs b/services/libs/jinux-std/src/process/mod.rs
--- a/services/libs/jinux-std/src/process/mod.rs
+++ b/services/libs/jinux-std/src/process/mod.rs
@@ -49,8 +49,6 @@ pub struct Process {
root_vmar: Arc<Vmar<Full>>,
/// wait for child status changed
waiting_children: WaitQueue,
- /// wait for io events
- poll_queue: WaitQueue,
// Mutable Part
/// The executable path.
diff --git a/services/libs/jinux-std/src/process/mod.rs b/services/libs/jinux-std/src/process/mod.rs
--- a/services/libs/jinux-std/src/process/mod.rs
+++ b/services/libs/jinux-std/src/process/mod.rs
@@ -49,8 +49,6 @@ pub struct Process {
root_vmar: Arc<Vmar<Full>>,
/// wait for child status changed
waiting_children: WaitQueue,
- /// wait for io events
- poll_queue: WaitQueue,
// Mutable Part
/// The executable path.
diff --git a/services/libs/jinux-std/src/process/mod.rs b/services/libs/jinux-std/src/process/mod.rs
--- a/services/libs/jinux-std/src/process/mod.rs
+++ b/services/libs/jinux-std/src/process/mod.rs
@@ -110,7 +108,6 @@ impl Process {
) -> Self {
let children = BTreeMap::new();
let waiting_children = WaitQueue::new();
- let poll_queue = WaitQueue::new();
let resource_limits = ResourceLimits::default();
Self {
pid,
diff --git a/services/libs/jinux-std/src/process/mod.rs b/services/libs/jinux-std/src/process/mod.rs
--- a/services/libs/jinux-std/src/process/mod.rs
+++ b/services/libs/jinux-std/src/process/mod.rs
@@ -110,7 +108,6 @@ impl Process {
) -> Self {
let children = BTreeMap::new();
let waiting_children = WaitQueue::new();
- let poll_queue = WaitQueue::new();
let resource_limits = ResourceLimits::default();
Self {
pid,
diff --git a/services/libs/jinux-std/src/process/mod.rs b/services/libs/jinux-std/src/process/mod.rs
--- a/services/libs/jinux-std/src/process/mod.rs
+++ b/services/libs/jinux-std/src/process/mod.rs
@@ -119,7 +116,6 @@ impl Process {
user_vm,
root_vmar,
waiting_children,
- poll_queue,
exit_code: AtomicI32::new(0),
status: Mutex::new(ProcessStatus::Runnable),
parent: Mutex::new(parent),
diff --git a/services/libs/jinux-std/src/process/mod.rs b/services/libs/jinux-std/src/process/mod.rs
--- a/services/libs/jinux-std/src/process/mod.rs
+++ b/services/libs/jinux-std/src/process/mod.rs
@@ -119,7 +116,6 @@ impl Process {
user_vm,
root_vmar,
waiting_children,
- poll_queue,
exit_code: AtomicI32::new(0),
status: Mutex::new(ProcessStatus::Runnable),
parent: Mutex::new(parent),
diff --git a/services/libs/jinux-std/src/process/mod.rs b/services/libs/jinux-std/src/process/mod.rs
--- a/services/libs/jinux-std/src/process/mod.rs
+++ b/services/libs/jinux-std/src/process/mod.rs
@@ -138,10 +134,6 @@ impl Process {
&self.waiting_children
}
- pub fn poll_queue(&self) -> &WaitQueue {
- &self.poll_queue
- }
-
/// init a user process and run the process
pub fn spawn_user_process(
executable_path: &str,
diff --git a/services/libs/jinux-std/src/process/mod.rs b/services/libs/jinux-std/src/process/mod.rs
--- a/services/libs/jinux-std/src/process/mod.rs
+++ b/services/libs/jinux-std/src/process/mod.rs
@@ -138,10 +134,6 @@ impl Process {
&self.waiting_children
}
- pub fn poll_queue(&self) -> &WaitQueue {
- &self.poll_queue
- }
-
/// init a user process and run the process
pub fn spawn_user_process(
executable_path: &str,
diff --git a/services/libs/jinux-std/src/process/process_group.rs b/services/libs/jinux-std/src/process/process_group.rs
--- a/services/libs/jinux-std/src/process/process_group.rs
+++ b/services/libs/jinux-std/src/process/process_group.rs
@@ -69,14 +69,6 @@ impl ProcessGroup {
self.inner.lock().pgid
}
- /// Wake up all processes waiting on polling queue
- pub fn wake_all_polling_procs(&self) {
- let inner = self.inner.lock();
- for (_, process) in &inner.processes {
- process.poll_queue().wake_all();
- }
- }
-
/// send kernel signal to all processes in the group
pub fn kernel_signal(&self, signal: KernelSignal) {
for (_, process) in &self.inner.lock().processes {
diff --git a/services/libs/jinux-std/src/process/process_group.rs b/services/libs/jinux-std/src/process/process_group.rs
--- a/services/libs/jinux-std/src/process/process_group.rs
+++ b/services/libs/jinux-std/src/process/process_group.rs
@@ -69,14 +69,6 @@ impl ProcessGroup {
self.inner.lock().pgid
}
- /// Wake up all processes waiting on polling queue
- pub fn wake_all_polling_procs(&self) {
- let inner = self.inner.lock();
- for (_, process) in &inner.processes {
- process.poll_queue().wake_all();
- }
- }
-
/// send kernel signal to all processes in the group
pub fn kernel_signal(&self, signal: KernelSignal) {
for (_, process) in &self.inner.lock().processes {
diff --git a/services/libs/jinux-std/src/process/process_table.rs b/services/libs/jinux-std/src/process/process_table.rs
--- a/services/libs/jinux-std/src/process/process_table.rs
+++ b/services/libs/jinux-std/src/process/process_table.rs
@@ -65,10 +65,10 @@ pub fn pgid_to_process_group(pgid: Pgid) -> Option<Arc<ProcessGroup>> {
}
pub fn register_observer(observer: Weak<dyn Observer<PidEvent>>) {
- PROCESS_TABLE_SUBJECT.register_observer(observer);
+ PROCESS_TABLE_SUBJECT.register_observer(observer, ());
}
-pub fn unregister_observer(observer: Weak<dyn Observer<PidEvent>>) {
+pub fn unregister_observer(observer: &Weak<dyn Observer<PidEvent>>) {
PROCESS_TABLE_SUBJECT.unregister_observer(observer);
}
diff --git a/services/libs/jinux-std/src/process/process_table.rs b/services/libs/jinux-std/src/process/process_table.rs
--- a/services/libs/jinux-std/src/process/process_table.rs
+++ b/services/libs/jinux-std/src/process/process_table.rs
@@ -65,10 +65,10 @@ pub fn pgid_to_process_group(pgid: Pgid) -> Option<Arc<ProcessGroup>> {
}
pub fn register_observer(observer: Weak<dyn Observer<PidEvent>>) {
- PROCESS_TABLE_SUBJECT.register_observer(observer);
+ PROCESS_TABLE_SUBJECT.register_observer(observer, ());
}
-pub fn unregister_observer(observer: Weak<dyn Observer<PidEvent>>) {
+pub fn unregister_observer(observer: &Weak<dyn Observer<PidEvent>>) {
PROCESS_TABLE_SUBJECT.unregister_observer(observer);
}
diff --git a/services/libs/jinux-std/src/syscall/chdir.rs b/services/libs/jinux-std/src/syscall/chdir.rs
--- a/services/libs/jinux-std/src/syscall/chdir.rs
+++ b/services/libs/jinux-std/src/syscall/chdir.rs
@@ -1,4 +1,6 @@
-use crate::fs::{file_table::FileDescripter, fs_resolver::FsPath, utils::InodeType};
+use crate::fs::{
+ file_table::FileDescripter, fs_resolver::FsPath, inode_handle::InodeHandle, utils::InodeType,
+};
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::syscall::constants::MAX_FILENAME_LEN;
diff --git a/services/libs/jinux-std/src/syscall/chdir.rs b/services/libs/jinux-std/src/syscall/chdir.rs
--- a/services/libs/jinux-std/src/syscall/chdir.rs
+++ b/services/libs/jinux-std/src/syscall/chdir.rs
@@ -1,4 +1,6 @@
-use crate::fs::{file_table::FileDescripter, fs_resolver::FsPath, utils::InodeType};
+use crate::fs::{
+ file_table::FileDescripter, fs_resolver::FsPath, inode_handle::InodeHandle, utils::InodeType,
+};
use crate::log_syscall_entry;
use crate::prelude::*;
use crate::syscall::constants::MAX_FILENAME_LEN;
diff --git a/services/libs/jinux-std/src/syscall/chdir.rs b/services/libs/jinux-std/src/syscall/chdir.rs
--- a/services/libs/jinux-std/src/syscall/chdir.rs
+++ b/services/libs/jinux-std/src/syscall/chdir.rs
@@ -38,7 +40,7 @@ pub fn sys_fchdir(fd: FileDescripter) -> Result<SyscallReturn> {
let file_table = current.file_table().lock();
let file = file_table.get_file(fd)?;
let inode_handle = file
- .as_inode_handle()
+ .downcast_ref::<InodeHandle>()
.ok_or(Error::with_message(Errno::EBADE, "not inode"))?;
inode_handle.dentry().clone()
};
diff --git a/services/libs/jinux-std/src/syscall/chdir.rs b/services/libs/jinux-std/src/syscall/chdir.rs
--- a/services/libs/jinux-std/src/syscall/chdir.rs
+++ b/services/libs/jinux-std/src/syscall/chdir.rs
@@ -38,7 +40,7 @@ pub fn sys_fchdir(fd: FileDescripter) -> Result<SyscallReturn> {
let file_table = current.file_table().lock();
let file = file_table.get_file(fd)?;
let inode_handle = file
- .as_inode_handle()
+ .downcast_ref::<InodeHandle>()
.ok_or(Error::with_message(Errno::EBADE, "not inode"))?;
inode_handle.dentry().clone()
};
diff --git /dev/null b/services/libs/jinux-std/src/syscall/epoll.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/syscall/epoll.rs
@@ -0,0 +1,133 @@
+use core::time::Duration;
+
+use crate::fs::epoll::{c_epoll_event, EpollCtl, EpollEvent, EpollFile, EpollFlags};
+use crate::fs::file_table::FileDescripter;
+use crate::fs::utils::CreationFlags;
+use crate::log_syscall_entry;
+use crate::prelude::*;
+use crate::util::{read_val_from_user, write_val_to_user};
+
+use super::SyscallReturn;
+use super::{SYS_EPOLL_CREATE1, SYS_EPOLL_CTL, SYS_EPOLL_WAIT};
+
+pub fn sys_epoll_create(size: i32) -> Result<SyscallReturn> {
+ if size <= 0 {
+ return_errno_with_message!(Errno::EINVAL, "size is not positive");
+ }
+ sys_epoll_create1(0)
+}
+
+pub fn sys_epoll_create1(flags: u32) -> Result<SyscallReturn> {
+ log_syscall_entry!(SYS_EPOLL_CREATE1);
+ debug!("flags = 0x{:x}", flags);
+
+ let close_on_exec = {
+ let flags = CreationFlags::from_bits(flags)
+ .ok_or_else(|| Error::with_message(Errno::EINVAL, "invalid flags"))?;
+ if flags == CreationFlags::empty() {
+ false
+ } else if flags == CreationFlags::O_CLOEXEC {
+ true
+ } else {
+ // Only O_CLOEXEC is valid
+ return_errno_with_message!(Errno::EINVAL, "invalid flags");
+ }
+ };
+
+ let current = current!();
+ let epoll_file: Arc<EpollFile> = EpollFile::new();
+ let mut file_table = current.file_table().lock();
+ let fd = file_table.insert(epoll_file);
+ Ok(SyscallReturn::Return(fd as _))
+}
+
+pub fn sys_epoll_ctl(
+ epfd: FileDescripter,
+ op: i32,
+ fd: FileDescripter,
+ event_addr: Vaddr,
+) -> Result<SyscallReturn> {
+ log_syscall_entry!(SYS_EPOLL_CTL);
+ debug!(
+ "epfd = {}, op = {}, fd = {}, event_addr = 0x{:x}",
+ epfd, op, fd, event_addr
+ );
+
+ const EPOLL_CTL_ADD: i32 = 1;
+ const EPOLL_CTL_DEL: i32 = 2;
+ const EPOLL_CTL_MOD: i32 = 3;
+
+ let cmd = match op {
+ EPOLL_CTL_ADD => {
+ let c_epoll_event = read_val_from_user::<c_epoll_event>(event_addr)?;
+ let event = EpollEvent::from(&c_epoll_event);
+ let flags = EpollFlags::from_bits_truncate(c_epoll_event.events);
+ EpollCtl::Add(fd, event, flags)
+ }
+ EPOLL_CTL_DEL => EpollCtl::Del(fd),
+ EPOLL_CTL_MOD => {
+ let c_epoll_event = read_val_from_user::<c_epoll_event>(event_addr)?;
+ let event = EpollEvent::from(&c_epoll_event);
+ let flags = EpollFlags::from_bits_truncate(c_epoll_event.events);
+ EpollCtl::Mod(fd, event, flags)
+ }
+ _ => return_errno_with_message!(Errno::EINVAL, "invalid op"),
+ };
+
+ let current = current!();
+ let file = {
+ let file_table = current.file_table().lock();
+ file_table.get_file(epfd)?.clone()
+ };
+ let epoll_file = file
+ .downcast_ref::<EpollFile>()
+ .ok_or(Error::with_message(Errno::EINVAL, "not epoll file"))?;
+ epoll_file.control(&cmd)?;
+
+ Ok(SyscallReturn::Return(0 as _))
+}
+
+pub fn sys_epoll_wait(
+ epfd: FileDescripter,
+ events_addr: Vaddr,
+ max_events: i32,
+ timeout: i32,
+) -> Result<SyscallReturn> {
+ log_syscall_entry!(SYS_EPOLL_WAIT);
+
+ let max_events = {
+ if max_events <= 0 {
+ return_errno_with_message!(Errno::EINVAL, "max_events is not positive");
+ }
+ max_events as usize
+ };
+ let timeout = if timeout >= 0 {
+ Some(Duration::from_millis(timeout as _))
+ } else {
+ None
+ };
+ debug!(
+ "epfd = {}, events_addr = 0x{:x}, max_events = {}, timeout = {:?}",
+ epfd, events_addr, max_events, timeout
+ );
+
+ let current = current!();
+ let file = {
+ let file_table = current.file_table().lock();
+ file_table.get_file(epfd)?.clone()
+ };
+ let epoll_file = file
+ .downcast_ref::<EpollFile>()
+ .ok_or(Error::with_message(Errno::EINVAL, "not epoll file"))?;
+ let epoll_events = epoll_file.wait(max_events, timeout.as_ref())?;
+
+ // Write back
+ let mut write_addr = events_addr;
+ for epoll_event in epoll_events.iter() {
+ let c_epoll_event = c_epoll_event::from(epoll_event);
+ write_val_to_user(write_addr, &c_epoll_event)?;
+ write_addr += core::mem::size_of::<c_epoll_event>();
+ }
+
+ Ok(SyscallReturn::Return(epoll_events.len() as _))
+}
diff --git /dev/null b/services/libs/jinux-std/src/syscall/epoll.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/syscall/epoll.rs
@@ -0,0 +1,133 @@
+use core::time::Duration;
+
+use crate::fs::epoll::{c_epoll_event, EpollCtl, EpollEvent, EpollFile, EpollFlags};
+use crate::fs::file_table::FileDescripter;
+use crate::fs::utils::CreationFlags;
+use crate::log_syscall_entry;
+use crate::prelude::*;
+use crate::util::{read_val_from_user, write_val_to_user};
+
+use super::SyscallReturn;
+use super::{SYS_EPOLL_CREATE1, SYS_EPOLL_CTL, SYS_EPOLL_WAIT};
+
+pub fn sys_epoll_create(size: i32) -> Result<SyscallReturn> {
+ if size <= 0 {
+ return_errno_with_message!(Errno::EINVAL, "size is not positive");
+ }
+ sys_epoll_create1(0)
+}
+
+pub fn sys_epoll_create1(flags: u32) -> Result<SyscallReturn> {
+ log_syscall_entry!(SYS_EPOLL_CREATE1);
+ debug!("flags = 0x{:x}", flags);
+
+ let close_on_exec = {
+ let flags = CreationFlags::from_bits(flags)
+ .ok_or_else(|| Error::with_message(Errno::EINVAL, "invalid flags"))?;
+ if flags == CreationFlags::empty() {
+ false
+ } else if flags == CreationFlags::O_CLOEXEC {
+ true
+ } else {
+ // Only O_CLOEXEC is valid
+ return_errno_with_message!(Errno::EINVAL, "invalid flags");
+ }
+ };
+
+ let current = current!();
+ let epoll_file: Arc<EpollFile> = EpollFile::new();
+ let mut file_table = current.file_table().lock();
+ let fd = file_table.insert(epoll_file);
+ Ok(SyscallReturn::Return(fd as _))
+}
+
+pub fn sys_epoll_ctl(
+ epfd: FileDescripter,
+ op: i32,
+ fd: FileDescripter,
+ event_addr: Vaddr,
+) -> Result<SyscallReturn> {
+ log_syscall_entry!(SYS_EPOLL_CTL);
+ debug!(
+ "epfd = {}, op = {}, fd = {}, event_addr = 0x{:x}",
+ epfd, op, fd, event_addr
+ );
+
+ const EPOLL_CTL_ADD: i32 = 1;
+ const EPOLL_CTL_DEL: i32 = 2;
+ const EPOLL_CTL_MOD: i32 = 3;
+
+ let cmd = match op {
+ EPOLL_CTL_ADD => {
+ let c_epoll_event = read_val_from_user::<c_epoll_event>(event_addr)?;
+ let event = EpollEvent::from(&c_epoll_event);
+ let flags = EpollFlags::from_bits_truncate(c_epoll_event.events);
+ EpollCtl::Add(fd, event, flags)
+ }
+ EPOLL_CTL_DEL => EpollCtl::Del(fd),
+ EPOLL_CTL_MOD => {
+ let c_epoll_event = read_val_from_user::<c_epoll_event>(event_addr)?;
+ let event = EpollEvent::from(&c_epoll_event);
+ let flags = EpollFlags::from_bits_truncate(c_epoll_event.events);
+ EpollCtl::Mod(fd, event, flags)
+ }
+ _ => return_errno_with_message!(Errno::EINVAL, "invalid op"),
+ };
+
+ let current = current!();
+ let file = {
+ let file_table = current.file_table().lock();
+ file_table.get_file(epfd)?.clone()
+ };
+ let epoll_file = file
+ .downcast_ref::<EpollFile>()
+ .ok_or(Error::with_message(Errno::EINVAL, "not epoll file"))?;
+ epoll_file.control(&cmd)?;
+
+ Ok(SyscallReturn::Return(0 as _))
+}
+
+pub fn sys_epoll_wait(
+ epfd: FileDescripter,
+ events_addr: Vaddr,
+ max_events: i32,
+ timeout: i32,
+) -> Result<SyscallReturn> {
+ log_syscall_entry!(SYS_EPOLL_WAIT);
+
+ let max_events = {
+ if max_events <= 0 {
+ return_errno_with_message!(Errno::EINVAL, "max_events is not positive");
+ }
+ max_events as usize
+ };
+ let timeout = if timeout >= 0 {
+ Some(Duration::from_millis(timeout as _))
+ } else {
+ None
+ };
+ debug!(
+ "epfd = {}, events_addr = 0x{:x}, max_events = {}, timeout = {:?}",
+ epfd, events_addr, max_events, timeout
+ );
+
+ let current = current!();
+ let file = {
+ let file_table = current.file_table().lock();
+ file_table.get_file(epfd)?.clone()
+ };
+ let epoll_file = file
+ .downcast_ref::<EpollFile>()
+ .ok_or(Error::with_message(Errno::EINVAL, "not epoll file"))?;
+ let epoll_events = epoll_file.wait(max_events, timeout.as_ref())?;
+
+ // Write back
+ let mut write_addr = events_addr;
+ for epoll_event in epoll_events.iter() {
+ let c_epoll_event = c_epoll_event::from(epoll_event);
+ write_val_to_user(write_addr, &c_epoll_event)?;
+ write_addr += core::mem::size_of::<c_epoll_event>();
+ }
+
+ Ok(SyscallReturn::Return(epoll_events.len() as _))
+}
diff --git a/services/libs/jinux-std/src/syscall/fcntl.rs b/services/libs/jinux-std/src/syscall/fcntl.rs
--- a/services/libs/jinux-std/src/syscall/fcntl.rs
+++ b/services/libs/jinux-std/src/syscall/fcntl.rs
@@ -12,8 +12,7 @@ pub fn sys_fcntl(fd: FileDescripter, cmd: i32, arg: u64) -> Result<SyscallReturn
// FIXME: deal with the cloexec flag
let current = current!();
let mut file_table = current.file_table().lock();
- let new_fd = arg as FileDescripter;
- file_table.dup(fd, Some(new_fd))?;
+ let new_fd = file_table.dup(fd, arg as FileDescripter)?;
return Ok(SyscallReturn::Return(new_fd as _));
}
FcntlCmd::F_SETFD => {
diff --git a/services/libs/jinux-std/src/syscall/fcntl.rs b/services/libs/jinux-std/src/syscall/fcntl.rs
--- a/services/libs/jinux-std/src/syscall/fcntl.rs
+++ b/services/libs/jinux-std/src/syscall/fcntl.rs
@@ -12,8 +12,7 @@ pub fn sys_fcntl(fd: FileDescripter, cmd: i32, arg: u64) -> Result<SyscallReturn
// FIXME: deal with the cloexec flag
let current = current!();
let mut file_table = current.file_table().lock();
- let new_fd = arg as FileDescripter;
- file_table.dup(fd, Some(new_fd))?;
+ let new_fd = file_table.dup(fd, arg as FileDescripter)?;
return Ok(SyscallReturn::Return(new_fd as _));
}
FcntlCmd::F_SETFD => {
diff --git a/services/libs/jinux-std/src/syscall/getdents64.rs b/services/libs/jinux-std/src/syscall/getdents64.rs
--- a/services/libs/jinux-std/src/syscall/getdents64.rs
+++ b/services/libs/jinux-std/src/syscall/getdents64.rs
@@ -1,5 +1,6 @@
use crate::fs::{
file_table::FileDescripter,
+ inode_handle::InodeHandle,
utils::{DirentVisitor, InodeType},
};
use crate::log_syscall_entry;
diff --git a/services/libs/jinux-std/src/syscall/getdents64.rs b/services/libs/jinux-std/src/syscall/getdents64.rs
--- a/services/libs/jinux-std/src/syscall/getdents64.rs
+++ b/services/libs/jinux-std/src/syscall/getdents64.rs
@@ -1,5 +1,6 @@
use crate::fs::{
file_table::FileDescripter,
+ inode_handle::InodeHandle,
utils::{DirentVisitor, InodeType},
};
use crate::log_syscall_entry;
diff --git a/services/libs/jinux-std/src/syscall/getdents64.rs b/services/libs/jinux-std/src/syscall/getdents64.rs
--- a/services/libs/jinux-std/src/syscall/getdents64.rs
+++ b/services/libs/jinux-std/src/syscall/getdents64.rs
@@ -27,7 +28,7 @@ pub fn sys_getdents64(
file_table.get_file(fd)?.clone()
};
let inode_handle = file
- .as_inode_handle()
+ .downcast_ref::<InodeHandle>()
.ok_or(Error::with_message(Errno::EBADE, "not inode"))?;
if inode_handle.dentry().inode_type() != InodeType::Dir {
return_errno!(Errno::ENOTDIR);
diff --git a/services/libs/jinux-std/src/syscall/getdents64.rs b/services/libs/jinux-std/src/syscall/getdents64.rs
--- a/services/libs/jinux-std/src/syscall/getdents64.rs
+++ b/services/libs/jinux-std/src/syscall/getdents64.rs
@@ -27,7 +28,7 @@ pub fn sys_getdents64(
file_table.get_file(fd)?.clone()
};
let inode_handle = file
- .as_inode_handle()
+ .downcast_ref::<InodeHandle>()
.ok_or(Error::with_message(Errno::EBADE, "not inode"))?;
if inode_handle.dentry().inode_type() != InodeType::Dir {
return_errno!(Errno::ENOTDIR);
diff --git a/services/libs/jinux-std/src/syscall/ioctl.rs b/services/libs/jinux-std/src/syscall/ioctl.rs
--- a/services/libs/jinux-std/src/syscall/ioctl.rs
+++ b/services/libs/jinux-std/src/syscall/ioctl.rs
@@ -16,6 +16,6 @@ pub fn sys_ioctl(fd: FileDescripter, cmd: u32, arg: Vaddr) -> Result<SyscallRetu
let current = current!();
let file_table = current.file_table().lock();
let file = file_table.get_file(fd)?;
- let res = file.as_file().unwrap().ioctl(ioctl_cmd, arg)?;
+ let res = file.ioctl(ioctl_cmd, arg)?;
return Ok(SyscallReturn::Return(res as _));
}
diff --git a/services/libs/jinux-std/src/syscall/ioctl.rs b/services/libs/jinux-std/src/syscall/ioctl.rs
--- a/services/libs/jinux-std/src/syscall/ioctl.rs
+++ b/services/libs/jinux-std/src/syscall/ioctl.rs
@@ -16,6 +16,6 @@ pub fn sys_ioctl(fd: FileDescripter, cmd: u32, arg: Vaddr) -> Result<SyscallRetu
let current = current!();
let file_table = current.file_table().lock();
let file = file_table.get_file(fd)?;
- let res = file.as_file().unwrap().ioctl(ioctl_cmd, arg)?;
+ let res = file.ioctl(ioctl_cmd, arg)?;
return Ok(SyscallReturn::Return(res as _));
}
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -9,6 +9,7 @@ use crate::syscall::clock_nanosleep::sys_clock_nanosleep;
use crate::syscall::clone::sys_clone;
use crate::syscall::close::sys_close;
use crate::syscall::dup::{sys_dup, sys_dup2};
+use crate::syscall::epoll::{sys_epoll_create, sys_epoll_create1, sys_epoll_ctl, sys_epoll_wait};
use crate::syscall::execve::sys_execve;
use crate::syscall::exit::sys_exit;
use crate::syscall::exit_group::sys_exit_group;
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -9,6 +9,7 @@ use crate::syscall::clock_nanosleep::sys_clock_nanosleep;
use crate::syscall::clone::sys_clone;
use crate::syscall::close::sys_close;
use crate::syscall::dup::{sys_dup, sys_dup2};
+use crate::syscall::epoll::{sys_epoll_create, sys_epoll_create1, sys_epoll_ctl, sys_epoll_wait};
use crate::syscall::execve::sys_execve;
use crate::syscall::exit::sys_exit;
use crate::syscall::exit_group::sys_exit_group;
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -36,6 +37,7 @@ use crate::syscall::mprotect::sys_mprotect;
use crate::syscall::munmap::sys_munmap;
use crate::syscall::open::{sys_open, sys_openat};
use crate::syscall::pause::sys_pause;
+use crate::syscall::pipe::{sys_pipe, sys_pipe2};
use crate::syscall::poll::sys_poll;
use crate::syscall::prctl::sys_prctl;
use crate::syscall::prlimit64::sys_prlimit64;
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -36,6 +37,7 @@ use crate::syscall::mprotect::sys_mprotect;
use crate::syscall::munmap::sys_munmap;
use crate::syscall::open::{sys_open, sys_openat};
use crate::syscall::pause::sys_pause;
+use crate::syscall::pipe::{sys_pipe, sys_pipe2};
use crate::syscall::poll::sys_poll;
use crate::syscall::prctl::sys_prctl;
use crate::syscall::prlimit64::sys_prlimit64;
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -75,6 +77,7 @@ mod clone;
mod close;
mod constants;
mod dup;
+mod epoll;
mod execve;
mod exit;
mod exit_group;
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -75,6 +77,7 @@ mod clone;
mod close;
mod constants;
mod dup;
+mod epoll;
mod execve;
mod exit;
mod exit_group;
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -102,6 +105,7 @@ mod mprotect;
mod munmap;
mod open;
mod pause;
+mod pipe;
mod poll;
mod prctl;
mod pread64;
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -102,6 +105,7 @@ mod mprotect;
mod munmap;
mod open;
mod pause;
+mod pipe;
mod poll;
mod prctl;
mod pread64;
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -181,6 +185,7 @@ define_syscall_nums!(
SYS_PREAD64 = 17,
SYS_WRITEV = 20,
SYS_ACCESS = 21,
+ SYS_PIPE = 22,
SYS_SCHED_YIELD = 24,
SYS_MADVISE = 28,
SYS_DUP = 32,
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -181,6 +185,7 @@ define_syscall_nums!(
SYS_PREAD64 = 17,
SYS_WRITEV = 20,
SYS_ACCESS = 21,
+ SYS_PIPE = 22,
SYS_SCHED_YIELD = 24,
SYS_MADVISE = 28,
SYS_DUP = 32,
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -218,10 +223,13 @@ define_syscall_nums!(
SYS_GETTID = 186,
SYS_TIME = 201,
SYS_FUTEX = 202,
+ SYS_EPOLL_CREATE = 213,
SYS_GETDENTS64 = 217,
SYS_SET_TID_ADDRESS = 218,
SYS_CLOCK_NANOSLEEP = 230,
SYS_EXIT_GROUP = 231,
+ SYS_EPOLL_WAIT = 232,
+ SYS_EPOLL_CTL = 233,
SYS_TGKILL = 234,
SYS_WAITID = 247,
SYS_OPENAT = 257,
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -218,10 +223,13 @@ define_syscall_nums!(
SYS_GETTID = 186,
SYS_TIME = 201,
SYS_FUTEX = 202,
+ SYS_EPOLL_CREATE = 213,
SYS_GETDENTS64 = 217,
SYS_SET_TID_ADDRESS = 218,
SYS_CLOCK_NANOSLEEP = 230,
SYS_EXIT_GROUP = 231,
+ SYS_EPOLL_WAIT = 232,
+ SYS_EPOLL_CTL = 233,
SYS_TGKILL = 234,
SYS_WAITID = 247,
SYS_OPENAT = 257,
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -234,6 +242,8 @@ define_syscall_nums!(
SYS_READLINKAT = 267,
SYS_SET_ROBUST_LIST = 273,
SYS_UTIMENSAT = 280,
+ SYS_EPOLL_CREATE1 = 291,
+ SYS_PIPE2 = 293,
SYS_PRLIMIT64 = 302
);
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -234,6 +242,8 @@ define_syscall_nums!(
SYS_READLINKAT = 267,
SYS_SET_ROBUST_LIST = 273,
SYS_UTIMENSAT = 280,
+ SYS_EPOLL_CREATE1 = 291,
+ SYS_PIPE2 = 293,
SYS_PRLIMIT64 = 302
);
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -313,6 +323,7 @@ pub fn syscall_dispatch(
SYS_PREAD64 => syscall_handler!(4, sys_pread64, args),
SYS_WRITEV => syscall_handler!(3, sys_writev, args),
SYS_ACCESS => syscall_handler!(2, sys_access, args),
+ SYS_PIPE => syscall_handler!(1, sys_pipe, args),
SYS_SCHED_YIELD => syscall_handler!(0, sys_sched_yield),
SYS_MADVISE => syscall_handler!(3, sys_madvise, args),
SYS_DUP => syscall_handler!(1, sys_dup, args),
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -313,6 +323,7 @@ pub fn syscall_dispatch(
SYS_PREAD64 => syscall_handler!(4, sys_pread64, args),
SYS_WRITEV => syscall_handler!(3, sys_writev, args),
SYS_ACCESS => syscall_handler!(2, sys_access, args),
+ SYS_PIPE => syscall_handler!(1, sys_pipe, args),
SYS_SCHED_YIELD => syscall_handler!(0, sys_sched_yield),
SYS_MADVISE => syscall_handler!(3, sys_madvise, args),
SYS_DUP => syscall_handler!(1, sys_dup, args),
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -350,10 +361,13 @@ pub fn syscall_dispatch(
SYS_GETTID => syscall_handler!(0, sys_gettid),
SYS_TIME => syscall_handler!(1, sys_time, args),
SYS_FUTEX => syscall_handler!(6, sys_futex, args),
+ SYS_EPOLL_CREATE => syscall_handler!(1, sys_epoll_create, args),
SYS_GETDENTS64 => syscall_handler!(3, sys_getdents64, args),
SYS_SET_TID_ADDRESS => syscall_handler!(1, sys_set_tid_address, args),
SYS_CLOCK_NANOSLEEP => syscall_handler!(4, sys_clock_nanosleep, args),
SYS_EXIT_GROUP => syscall_handler!(1, sys_exit_group, args),
+ SYS_EPOLL_WAIT => syscall_handler!(4, sys_epoll_wait, args),
+ SYS_EPOLL_CTL => syscall_handler!(4, sys_epoll_ctl, args),
SYS_TGKILL => syscall_handler!(3, sys_tgkill, args),
SYS_WAITID => syscall_handler!(5, sys_waitid, args),
SYS_OPENAT => syscall_handler!(4, sys_openat, args),
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -350,10 +361,13 @@ pub fn syscall_dispatch(
SYS_GETTID => syscall_handler!(0, sys_gettid),
SYS_TIME => syscall_handler!(1, sys_time, args),
SYS_FUTEX => syscall_handler!(6, sys_futex, args),
+ SYS_EPOLL_CREATE => syscall_handler!(1, sys_epoll_create, args),
SYS_GETDENTS64 => syscall_handler!(3, sys_getdents64, args),
SYS_SET_TID_ADDRESS => syscall_handler!(1, sys_set_tid_address, args),
SYS_CLOCK_NANOSLEEP => syscall_handler!(4, sys_clock_nanosleep, args),
SYS_EXIT_GROUP => syscall_handler!(1, sys_exit_group, args),
+ SYS_EPOLL_WAIT => syscall_handler!(4, sys_epoll_wait, args),
+ SYS_EPOLL_CTL => syscall_handler!(4, sys_epoll_ctl, args),
SYS_TGKILL => syscall_handler!(3, sys_tgkill, args),
SYS_WAITID => syscall_handler!(5, sys_waitid, args),
SYS_OPENAT => syscall_handler!(4, sys_openat, args),
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -366,6 +380,8 @@ pub fn syscall_dispatch(
SYS_READLINKAT => syscall_handler!(4, sys_readlinkat, args),
SYS_SET_ROBUST_LIST => syscall_handler!(2, sys_set_robust_list, args),
SYS_UTIMENSAT => syscall_handler!(4, sys_utimensat, args),
+ SYS_EPOLL_CREATE1 => syscall_handler!(1, sys_epoll_create1, args),
+ SYS_PIPE2 => syscall_handler!(2, sys_pipe2, args),
SYS_PRLIMIT64 => syscall_handler!(4, sys_prlimit64, args),
_ => {
error!("Unimplemented syscall number: {}", syscall_number);
diff --git a/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
--- a/services/libs/jinux-std/src/syscall/mod.rs
+++ b/services/libs/jinux-std/src/syscall/mod.rs
@@ -366,6 +380,8 @@ pub fn syscall_dispatch(
SYS_READLINKAT => syscall_handler!(4, sys_readlinkat, args),
SYS_SET_ROBUST_LIST => syscall_handler!(2, sys_set_robust_list, args),
SYS_UTIMENSAT => syscall_handler!(4, sys_utimensat, args),
+ SYS_EPOLL_CREATE1 => syscall_handler!(1, sys_epoll_create1, args),
+ SYS_PIPE2 => syscall_handler!(2, sys_pipe2, args),
SYS_PRLIMIT64 => syscall_handler!(4, sys_prlimit64, args),
_ => {
error!("Unimplemented syscall number: {}", syscall_number);
diff --git a/services/libs/jinux-std/src/syscall/open.rs b/services/libs/jinux-std/src/syscall/open.rs
--- a/services/libs/jinux-std/src/syscall/open.rs
+++ b/services/libs/jinux-std/src/syscall/open.rs
@@ -1,5 +1,5 @@
use crate::fs::{
- file_handle::{File, FileHandle},
+ file_handle::FileLike,
file_table::FileDescripter,
fs_resolver::{FsPath, AT_FDCWD},
};
diff --git a/services/libs/jinux-std/src/syscall/open.rs b/services/libs/jinux-std/src/syscall/open.rs
--- a/services/libs/jinux-std/src/syscall/open.rs
+++ b/services/libs/jinux-std/src/syscall/open.rs
@@ -1,5 +1,5 @@
use crate::fs::{
- file_handle::{File, FileHandle},
+ file_handle::FileLike,
file_table::FileDescripter,
fs_resolver::{FsPath, AT_FDCWD},
};
diff --git a/services/libs/jinux-std/src/syscall/open.rs b/services/libs/jinux-std/src/syscall/open.rs
--- a/services/libs/jinux-std/src/syscall/open.rs
+++ b/services/libs/jinux-std/src/syscall/open.rs
@@ -39,7 +39,7 @@ pub fn sys_openat(
if dirfd == AT_FDCWD && pathname == CString::new("./trace")? {
// Debug use: This file is used for output busybox log
- let trace_file = FileHandle::new_file(Arc::new(BusyBoxTraceFile) as Arc<dyn File>);
+ let trace_file = Arc::new(BusyBoxTraceFile);
let current = current!();
let mut file_table = current.file_table().lock();
let fd = file_table.insert(trace_file);
diff --git a/services/libs/jinux-std/src/syscall/open.rs b/services/libs/jinux-std/src/syscall/open.rs
--- a/services/libs/jinux-std/src/syscall/open.rs
+++ b/services/libs/jinux-std/src/syscall/open.rs
@@ -39,7 +39,7 @@ pub fn sys_openat(
if dirfd == AT_FDCWD && pathname == CString::new("./trace")? {
// Debug use: This file is used for output busybox log
- let trace_file = FileHandle::new_file(Arc::new(BusyBoxTraceFile) as Arc<dyn File>);
+ let trace_file = Arc::new(BusyBoxTraceFile);
let current = current!();
let mut file_table = current.file_table().lock();
let fd = file_table.insert(trace_file);
diff --git a/services/libs/jinux-std/src/syscall/open.rs b/services/libs/jinux-std/src/syscall/open.rs
--- a/services/libs/jinux-std/src/syscall/open.rs
+++ b/services/libs/jinux-std/src/syscall/open.rs
@@ -47,7 +47,7 @@ pub fn sys_openat(
}
if dirfd == AT_FDCWD && pathname == CString::new("/dev/tty")? {
- let tty_file = FileHandle::new_file(get_n_tty().clone() as Arc<dyn File>);
+ let tty_file = get_n_tty().clone();
let current = current!();
let mut file_table = current.file_table().lock();
let fd = file_table.insert(tty_file);
diff --git a/services/libs/jinux-std/src/syscall/open.rs b/services/libs/jinux-std/src/syscall/open.rs
--- a/services/libs/jinux-std/src/syscall/open.rs
+++ b/services/libs/jinux-std/src/syscall/open.rs
@@ -47,7 +47,7 @@ pub fn sys_openat(
}
if dirfd == AT_FDCWD && pathname == CString::new("/dev/tty")? {
- let tty_file = FileHandle::new_file(get_n_tty().clone() as Arc<dyn File>);
+ let tty_file = get_n_tty().clone();
let current = current!();
let mut file_table = current.file_table().lock();
let fd = file_table.insert(tty_file);
diff --git a/services/libs/jinux-std/src/syscall/open.rs b/services/libs/jinux-std/src/syscall/open.rs
--- a/services/libs/jinux-std/src/syscall/open.rs
+++ b/services/libs/jinux-std/src/syscall/open.rs
@@ -60,7 +60,7 @@ pub fn sys_openat(
let pathname = pathname.to_string_lossy();
let fs_path = FsPath::new(dirfd, pathname.as_ref())?;
let inode_handle = current.fs().read().open(&fs_path, flags, mode)?;
- FileHandle::new_inode_handle(inode_handle)
+ Arc::new(inode_handle)
};
let mut file_table = current.file_table().lock();
let fd = file_table.insert(file_handle);
diff --git a/services/libs/jinux-std/src/syscall/open.rs b/services/libs/jinux-std/src/syscall/open.rs
--- a/services/libs/jinux-std/src/syscall/open.rs
+++ b/services/libs/jinux-std/src/syscall/open.rs
@@ -60,7 +60,7 @@ pub fn sys_openat(
let pathname = pathname.to_string_lossy();
let fs_path = FsPath::new(dirfd, pathname.as_ref())?;
let inode_handle = current.fs().read().open(&fs_path, flags, mode)?;
- FileHandle::new_inode_handle(inode_handle)
+ Arc::new(inode_handle)
};
let mut file_table = current.file_table().lock();
let fd = file_table.insert(file_handle);
diff --git a/services/libs/jinux-std/src/syscall/open.rs b/services/libs/jinux-std/src/syscall/open.rs
--- a/services/libs/jinux-std/src/syscall/open.rs
+++ b/services/libs/jinux-std/src/syscall/open.rs
@@ -74,9 +74,13 @@ pub fn sys_open(pathname_addr: Vaddr, flags: u32, mode: u16) -> Result<SyscallRe
/// File for output busybox ash log.
struct BusyBoxTraceFile;
-impl File for BusyBoxTraceFile {
+impl FileLike for BusyBoxTraceFile {
fn write(&self, buf: &[u8]) -> Result<usize> {
debug!("ASH TRACE: {}", core::str::from_utf8(buf)?);
Ok(buf.len())
}
+
+ fn as_any_ref(&self) -> &dyn Any {
+ self
+ }
}
diff --git a/services/libs/jinux-std/src/syscall/open.rs b/services/libs/jinux-std/src/syscall/open.rs
--- a/services/libs/jinux-std/src/syscall/open.rs
+++ b/services/libs/jinux-std/src/syscall/open.rs
@@ -74,9 +74,13 @@ pub fn sys_open(pathname_addr: Vaddr, flags: u32, mode: u16) -> Result<SyscallRe
/// File for output busybox ash log.
struct BusyBoxTraceFile;
-impl File for BusyBoxTraceFile {
+impl FileLike for BusyBoxTraceFile {
fn write(&self, buf: &[u8]) -> Result<usize> {
debug!("ASH TRACE: {}", core::str::from_utf8(buf)?);
Ok(buf.len())
}
+
+ fn as_any_ref(&self) -> &dyn Any {
+ self
+ }
}
diff --git /dev/null b/services/libs/jinux-std/src/syscall/pipe.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/syscall/pipe.rs
@@ -0,0 +1,47 @@
+use crate::fs::file_table::FileDescripter;
+use crate::fs::pipe::{PipeReader, PipeWriter};
+use crate::fs::utils::{Channel, StatusFlags};
+use crate::log_syscall_entry;
+use crate::prelude::*;
+use crate::util::{read_val_from_user, write_val_to_user};
+
+use super::SyscallReturn;
+use super::SYS_PIPE2;
+
+pub fn sys_pipe2(fds: Vaddr, flags: u32) -> Result<SyscallReturn> {
+ log_syscall_entry!(SYS_PIPE2);
+ debug!("flags: {:?}", flags);
+
+ let mut pipe_fds = read_val_from_user::<PipeFds>(fds)?;
+ let (reader, writer) = {
+ let (producer, consumer) = Channel::with_capacity_and_flags(
+ PIPE_BUF_SIZE,
+ StatusFlags::from_bits_truncate(flags),
+ )?
+ .split();
+ (PipeReader::new(consumer), PipeWriter::new(producer))
+ };
+ let pipe_reader = Arc::new(reader);
+ let pipe_writer = Arc::new(writer);
+
+ let current = current!();
+ let mut file_table = current.file_table().lock();
+ pipe_fds.reader_fd = file_table.insert(pipe_reader);
+ pipe_fds.writer_fd = file_table.insert(pipe_writer);
+ write_val_to_user(fds, &pipe_fds)?;
+
+ Ok(SyscallReturn::Return(0))
+}
+
+pub fn sys_pipe(fds: Vaddr) -> Result<SyscallReturn> {
+ self::sys_pipe2(fds, 0)
+}
+
+#[derive(Debug, Clone, Copy, Pod)]
+#[repr(C)]
+struct PipeFds {
+ reader_fd: FileDescripter,
+ writer_fd: FileDescripter,
+}
+
+const PIPE_BUF_SIZE: usize = 1024 * 1024;
diff --git /dev/null b/services/libs/jinux-std/src/syscall/pipe.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-std/src/syscall/pipe.rs
@@ -0,0 +1,47 @@
+use crate::fs::file_table::FileDescripter;
+use crate::fs::pipe::{PipeReader, PipeWriter};
+use crate::fs::utils::{Channel, StatusFlags};
+use crate::log_syscall_entry;
+use crate::prelude::*;
+use crate::util::{read_val_from_user, write_val_to_user};
+
+use super::SyscallReturn;
+use super::SYS_PIPE2;
+
+pub fn sys_pipe2(fds: Vaddr, flags: u32) -> Result<SyscallReturn> {
+ log_syscall_entry!(SYS_PIPE2);
+ debug!("flags: {:?}", flags);
+
+ let mut pipe_fds = read_val_from_user::<PipeFds>(fds)?;
+ let (reader, writer) = {
+ let (producer, consumer) = Channel::with_capacity_and_flags(
+ PIPE_BUF_SIZE,
+ StatusFlags::from_bits_truncate(flags),
+ )?
+ .split();
+ (PipeReader::new(consumer), PipeWriter::new(producer))
+ };
+ let pipe_reader = Arc::new(reader);
+ let pipe_writer = Arc::new(writer);
+
+ let current = current!();
+ let mut file_table = current.file_table().lock();
+ pipe_fds.reader_fd = file_table.insert(pipe_reader);
+ pipe_fds.writer_fd = file_table.insert(pipe_writer);
+ write_val_to_user(fds, &pipe_fds)?;
+
+ Ok(SyscallReturn::Return(0))
+}
+
+pub fn sys_pipe(fds: Vaddr) -> Result<SyscallReturn> {
+ self::sys_pipe2(fds, 0)
+}
+
+#[derive(Debug, Clone, Copy, Pod)]
+#[repr(C)]
+struct PipeFds {
+ reader_fd: FileDescripter,
+ writer_fd: FileDescripter,
+}
+
+const PIPE_BUF_SIZE: usize = 1024 * 1024;
diff --git a/services/libs/jinux-std/src/syscall/poll.rs b/services/libs/jinux-std/src/syscall/poll.rs
--- a/services/libs/jinux-std/src/syscall/poll.rs
+++ b/services/libs/jinux-std/src/syscall/poll.rs
@@ -1,65 +1,161 @@
+use core::cell::Cell;
use core::time::Duration;
-use crate::fs::utils::{c_pollfd, PollFd};
+use crate::fs::file_table::FileDescripter;
+use crate::fs::utils::{IoEvents, Poller};
use crate::log_syscall_entry;
+use crate::prelude::*;
use crate::util::{read_val_from_user, write_val_to_user};
-use crate::{fs::utils::c_nfds, prelude::*};
use super::SyscallReturn;
use super::SYS_POLL;
-pub fn sys_poll(fds: Vaddr, nfds: c_nfds, timeout: i32) -> Result<SyscallReturn> {
+pub fn sys_poll(fds: Vaddr, nfds: u64, timeout: i32) -> Result<SyscallReturn> {
log_syscall_entry!(SYS_POLL);
- let mut read_addr = fds;
- let mut pollfds = Vec::with_capacity(nfds as _);
- for _ in 0..nfds {
- let c_poll_fd = read_val_from_user::<c_pollfd>(read_addr)?;
- let poll_fd = PollFd::from(c_poll_fd);
- pollfds.push(poll_fd);
- // FIXME: do we need to respect align of c_pollfd here?
- read_addr += core::mem::size_of::<c_pollfd>();
- }
- let timeout = if timeout == 0 {
- None
- } else {
+ let poll_fds = {
+ let mut read_addr = fds;
+ let mut poll_fds = Vec::with_capacity(nfds as _);
+ for _ in 0..nfds {
+ let c_poll_fd = read_val_from_user::<c_pollfd>(read_addr)?;
+ let poll_fd = PollFd::from(c_poll_fd);
+ // Always clear the revents fields first
+ poll_fd.revents().set(IoEvents::empty());
+ poll_fds.push(poll_fd);
+ // FIXME: do we need to respect align of c_pollfd here?
+ read_addr += core::mem::size_of::<c_pollfd>();
+ }
+ poll_fds
+ };
+ let timeout = if timeout >= 0 {
Some(Duration::from_millis(timeout as _))
+ } else {
+ None
};
debug!(
"poll_fds = {:?}, nfds = {}, timeout = {:?}",
- pollfds, nfds, timeout
+ poll_fds, nfds, timeout
);
- let current = current!();
- // FIXME: respect timeout parameter
- let ready_files = current.poll_queue().wait_until(|| {
- let mut ready_files = 0;
- for pollfd in &mut pollfds {
- let file_table = current.file_table().lock();
- let file = file_table.get_file(pollfd.fd);
- match file {
- Err(_) => return Some(Err(Error::new(Errno::EBADF))),
- Ok(file) => {
- let file_events = file.as_file().unwrap().poll();
- let polled_events = pollfd.events.intersection(file_events);
- if !polled_events.is_empty() {
- ready_files += 1;
- pollfd.revents |= polled_events;
- }
- }
- }
- }
- if ready_files > 0 {
- return Some(Ok(ready_files));
- } else {
- return None;
- }
- })?;
+
+ let num_revents = do_poll(&poll_fds, timeout)?;
+
+ // Write back
let mut write_addr = fds;
- for pollfd in pollfds {
+ for pollfd in poll_fds {
let c_poll_fd = c_pollfd::from(pollfd);
write_val_to_user(write_addr, &c_poll_fd)?;
// FIXME: do we need to respect align of c_pollfd here?
write_addr += core::mem::size_of::<c_pollfd>();
}
- Ok(SyscallReturn::Return(ready_files))
+
+ Ok(SyscallReturn::Return(num_revents as _))
+}
+
+fn do_poll(poll_fds: &[PollFd], timeout: Option<Duration>) -> Result<usize> {
+ // The main loop of polling
+ let poller = Poller::new();
+ loop {
+ let mut num_revents = 0;
+
+ for poll_fd in poll_fds {
+ // Skip poll_fd if it is not given a fd
+ let fd = match poll_fd.fd() {
+ Some(fd) => fd,
+ None => continue,
+ };
+
+ // Poll the file
+ let current = current!();
+ let file = {
+ let file_table = current.file_table().lock();
+ file_table.get_file(fd)?.clone()
+ };
+ let need_poller = if num_revents == 0 {
+ Some(&poller)
+ } else {
+ None
+ };
+ let revents = file.poll(poll_fd.events(), need_poller);
+ if !revents.is_empty() {
+ poll_fd.revents().set(revents);
+ num_revents += 1;
+ }
+ }
+
+ if num_revents > 0 {
+ return Ok(num_revents);
+ }
+
+ // Return immediately if specifying a timeout of zero
+ if timeout.is_some() && timeout.as_ref().unwrap().is_zero() {
+ return Ok(0);
+ }
+
+ // FIXME: respect timeout parameter
+ poller.wait();
+ }
+}
+
+// https://github.com/torvalds/linux/blob/master/include/uapi/asm-generic/poll.h
+#[derive(Debug, Clone, Copy, Pod)]
+#[repr(C)]
+pub struct c_pollfd {
+ fd: i32,
+ events: i16,
+ revents: i16,
+}
+
+#[derive(Debug, Clone)]
+pub struct PollFd {
+ fd: Option<FileDescripter>,
+ events: IoEvents,
+ revents: Cell<IoEvents>,
+}
+
+impl PollFd {
+ pub fn fd(&self) -> Option<FileDescripter> {
+ self.fd
+ }
+
+ pub fn events(&self) -> IoEvents {
+ self.events
+ }
+
+ pub fn revents(&self) -> &Cell<IoEvents> {
+ &self.revents
+ }
+}
+
+impl From<c_pollfd> for PollFd {
+ fn from(raw: c_pollfd) -> Self {
+ let fd = if raw.fd >= 0 {
+ Some(raw.fd as FileDescripter)
+ } else {
+ None
+ };
+ let events = IoEvents::from_bits_truncate(raw.events as _);
+ let revents = Cell::new(IoEvents::from_bits_truncate(raw.revents as _));
+ Self {
+ fd,
+ events,
+ revents,
+ }
+ }
+}
+
+impl From<PollFd> for c_pollfd {
+ fn from(raw: PollFd) -> Self {
+ let fd = if let Some(fd) = raw.fd() {
+ fd as i32
+ } else {
+ -1
+ };
+ let events = raw.events().bits() as i16;
+ let revents = raw.revents().get().bits() as i16;
+ Self {
+ fd,
+ events,
+ revents,
+ }
+ }
}
diff --git a/services/libs/jinux-std/src/syscall/poll.rs b/services/libs/jinux-std/src/syscall/poll.rs
--- a/services/libs/jinux-std/src/syscall/poll.rs
+++ b/services/libs/jinux-std/src/syscall/poll.rs
@@ -1,65 +1,161 @@
+use core::cell::Cell;
use core::time::Duration;
-use crate::fs::utils::{c_pollfd, PollFd};
+use crate::fs::file_table::FileDescripter;
+use crate::fs::utils::{IoEvents, Poller};
use crate::log_syscall_entry;
+use crate::prelude::*;
use crate::util::{read_val_from_user, write_val_to_user};
-use crate::{fs::utils::c_nfds, prelude::*};
use super::SyscallReturn;
use super::SYS_POLL;
-pub fn sys_poll(fds: Vaddr, nfds: c_nfds, timeout: i32) -> Result<SyscallReturn> {
+pub fn sys_poll(fds: Vaddr, nfds: u64, timeout: i32) -> Result<SyscallReturn> {
log_syscall_entry!(SYS_POLL);
- let mut read_addr = fds;
- let mut pollfds = Vec::with_capacity(nfds as _);
- for _ in 0..nfds {
- let c_poll_fd = read_val_from_user::<c_pollfd>(read_addr)?;
- let poll_fd = PollFd::from(c_poll_fd);
- pollfds.push(poll_fd);
- // FIXME: do we need to respect align of c_pollfd here?
- read_addr += core::mem::size_of::<c_pollfd>();
- }
- let timeout = if timeout == 0 {
- None
- } else {
+ let poll_fds = {
+ let mut read_addr = fds;
+ let mut poll_fds = Vec::with_capacity(nfds as _);
+ for _ in 0..nfds {
+ let c_poll_fd = read_val_from_user::<c_pollfd>(read_addr)?;
+ let poll_fd = PollFd::from(c_poll_fd);
+ // Always clear the revents fields first
+ poll_fd.revents().set(IoEvents::empty());
+ poll_fds.push(poll_fd);
+ // FIXME: do we need to respect align of c_pollfd here?
+ read_addr += core::mem::size_of::<c_pollfd>();
+ }
+ poll_fds
+ };
+ let timeout = if timeout >= 0 {
Some(Duration::from_millis(timeout as _))
+ } else {
+ None
};
debug!(
"poll_fds = {:?}, nfds = {}, timeout = {:?}",
- pollfds, nfds, timeout
+ poll_fds, nfds, timeout
);
- let current = current!();
- // FIXME: respect timeout parameter
- let ready_files = current.poll_queue().wait_until(|| {
- let mut ready_files = 0;
- for pollfd in &mut pollfds {
- let file_table = current.file_table().lock();
- let file = file_table.get_file(pollfd.fd);
- match file {
- Err(_) => return Some(Err(Error::new(Errno::EBADF))),
- Ok(file) => {
- let file_events = file.as_file().unwrap().poll();
- let polled_events = pollfd.events.intersection(file_events);
- if !polled_events.is_empty() {
- ready_files += 1;
- pollfd.revents |= polled_events;
- }
- }
- }
- }
- if ready_files > 0 {
- return Some(Ok(ready_files));
- } else {
- return None;
- }
- })?;
+
+ let num_revents = do_poll(&poll_fds, timeout)?;
+
+ // Write back
let mut write_addr = fds;
- for pollfd in pollfds {
+ for pollfd in poll_fds {
let c_poll_fd = c_pollfd::from(pollfd);
write_val_to_user(write_addr, &c_poll_fd)?;
// FIXME: do we need to respect align of c_pollfd here?
write_addr += core::mem::size_of::<c_pollfd>();
}
- Ok(SyscallReturn::Return(ready_files))
+
+ Ok(SyscallReturn::Return(num_revents as _))
+}
+
+fn do_poll(poll_fds: &[PollFd], timeout: Option<Duration>) -> Result<usize> {
+ // The main loop of polling
+ let poller = Poller::new();
+ loop {
+ let mut num_revents = 0;
+
+ for poll_fd in poll_fds {
+ // Skip poll_fd if it is not given a fd
+ let fd = match poll_fd.fd() {
+ Some(fd) => fd,
+ None => continue,
+ };
+
+ // Poll the file
+ let current = current!();
+ let file = {
+ let file_table = current.file_table().lock();
+ file_table.get_file(fd)?.clone()
+ };
+ let need_poller = if num_revents == 0 {
+ Some(&poller)
+ } else {
+ None
+ };
+ let revents = file.poll(poll_fd.events(), need_poller);
+ if !revents.is_empty() {
+ poll_fd.revents().set(revents);
+ num_revents += 1;
+ }
+ }
+
+ if num_revents > 0 {
+ return Ok(num_revents);
+ }
+
+ // Return immediately if specifying a timeout of zero
+ if timeout.is_some() && timeout.as_ref().unwrap().is_zero() {
+ return Ok(0);
+ }
+
+ // FIXME: respect timeout parameter
+ poller.wait();
+ }
+}
+
+// https://github.com/torvalds/linux/blob/master/include/uapi/asm-generic/poll.h
+#[derive(Debug, Clone, Copy, Pod)]
+#[repr(C)]
+pub struct c_pollfd {
+ fd: i32,
+ events: i16,
+ revents: i16,
+}
+
+#[derive(Debug, Clone)]
+pub struct PollFd {
+ fd: Option<FileDescripter>,
+ events: IoEvents,
+ revents: Cell<IoEvents>,
+}
+
+impl PollFd {
+ pub fn fd(&self) -> Option<FileDescripter> {
+ self.fd
+ }
+
+ pub fn events(&self) -> IoEvents {
+ self.events
+ }
+
+ pub fn revents(&self) -> &Cell<IoEvents> {
+ &self.revents
+ }
+}
+
+impl From<c_pollfd> for PollFd {
+ fn from(raw: c_pollfd) -> Self {
+ let fd = if raw.fd >= 0 {
+ Some(raw.fd as FileDescripter)
+ } else {
+ None
+ };
+ let events = IoEvents::from_bits_truncate(raw.events as _);
+ let revents = Cell::new(IoEvents::from_bits_truncate(raw.revents as _));
+ Self {
+ fd,
+ events,
+ revents,
+ }
+ }
+}
+
+impl From<PollFd> for c_pollfd {
+ fn from(raw: PollFd) -> Self {
+ let fd = if let Some(fd) = raw.fd() {
+ fd as i32
+ } else {
+ -1
+ };
+ let events = raw.events().bits() as i16;
+ let revents = raw.revents().get().bits() as i16;
+ Self {
+ fd,
+ events,
+ revents,
+ }
+ }
}
diff --git a/services/libs/jinux-std/src/tty/line_discipline.rs b/services/libs/jinux-std/src/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/tty/line_discipline.rs
@@ -1,11 +1,10 @@
-use crate::fs::utils::IoEvents;
+use crate::fs::utils::{IoEvents, Pollee, Poller};
use crate::process::signal::constants::{SIGINT, SIGQUIT};
use crate::{
prelude::*,
process::{process_table, signal::signals::kernel::KernelSignal, Pgid},
};
-use jinux_frame::sync::WaitQueue;
-use ringbuffer::{ConstGenericRingBuffer, RingBuffer, RingBufferRead, RingBufferWrite};
+use ringbuf::{ring_buffer::RbBase, Rb, StaticRb};
use super::termio::{KernelTermios, CC_C_CHAR};
diff --git a/services/libs/jinux-std/src/tty/line_discipline.rs b/services/libs/jinux-std/src/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/tty/line_discipline.rs
@@ -1,11 +1,10 @@
-use crate::fs::utils::IoEvents;
+use crate::fs::utils::{IoEvents, Pollee, Poller};
use crate::process::signal::constants::{SIGINT, SIGQUIT};
use crate::{
prelude::*,
process::{process_table, signal::signals::kernel::KernelSignal, Pgid},
};
-use jinux_frame::sync::WaitQueue;
-use ringbuffer::{ConstGenericRingBuffer, RingBuffer, RingBufferRead, RingBufferWrite};
+use ringbuf::{ring_buffer::RbBase, Rb, StaticRb};
use super::termio::{KernelTermios, CC_C_CHAR};
diff --git a/services/libs/jinux-std/src/tty/line_discipline.rs b/services/libs/jinux-std/src/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/tty/line_discipline.rs
@@ -18,40 +17,39 @@ pub struct LineDiscipline {
/// current line
current_line: RwLock<CurrentLine>,
/// The read buffer
- read_buffer: Mutex<ConstGenericRingBuffer<u8, BUFFER_CAPACITY>>,
+ read_buffer: Mutex<StaticRb<u8, BUFFER_CAPACITY>>,
/// The foreground process group
foreground: RwLock<Option<Pgid>>,
/// termios
termios: RwLock<KernelTermios>,
- /// wait until self is readable
- read_wait_queue: WaitQueue,
+ /// Pollee
+ pollee: Pollee,
}
-#[derive(Debug)]
pub struct CurrentLine {
- buffer: ConstGenericRingBuffer<u8, BUFFER_CAPACITY>,
+ buffer: StaticRb<u8, BUFFER_CAPACITY>,
}
impl CurrentLine {
pub fn new() -> Self {
Self {
- buffer: ConstGenericRingBuffer::new(),
+ buffer: StaticRb::default(),
}
}
/// read all bytes inside current line and clear current line
pub fn drain(&mut self) -> Vec<u8> {
- self.buffer.drain().collect()
+ self.buffer.pop_iter().collect()
}
pub fn push_char(&mut self, char: u8) {
// What should we do if line is full?
debug_assert!(!self.is_full());
- self.buffer.push(char);
+ self.buffer.push_overwrite(char);
}
pub fn backspace(&mut self) {
- self.buffer.dequeue();
+ self.buffer.pop();
}
pub fn is_full(&self) -> bool {
diff --git a/services/libs/jinux-std/src/tty/line_discipline.rs b/services/libs/jinux-std/src/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/tty/line_discipline.rs
@@ -18,40 +17,39 @@ pub struct LineDiscipline {
/// current line
current_line: RwLock<CurrentLine>,
/// The read buffer
- read_buffer: Mutex<ConstGenericRingBuffer<u8, BUFFER_CAPACITY>>,
+ read_buffer: Mutex<StaticRb<u8, BUFFER_CAPACITY>>,
/// The foreground process group
foreground: RwLock<Option<Pgid>>,
/// termios
termios: RwLock<KernelTermios>,
- /// wait until self is readable
- read_wait_queue: WaitQueue,
+ /// Pollee
+ pollee: Pollee,
}
-#[derive(Debug)]
pub struct CurrentLine {
- buffer: ConstGenericRingBuffer<u8, BUFFER_CAPACITY>,
+ buffer: StaticRb<u8, BUFFER_CAPACITY>,
}
impl CurrentLine {
pub fn new() -> Self {
Self {
- buffer: ConstGenericRingBuffer::new(),
+ buffer: StaticRb::default(),
}
}
/// read all bytes inside current line and clear current line
pub fn drain(&mut self) -> Vec<u8> {
- self.buffer.drain().collect()
+ self.buffer.pop_iter().collect()
}
pub fn push_char(&mut self, char: u8) {
// What should we do if line is full?
debug_assert!(!self.is_full());
- self.buffer.push(char);
+ self.buffer.push_overwrite(char);
}
pub fn backspace(&mut self) {
- self.buffer.dequeue();
+ self.buffer.pop();
}
pub fn is_full(&self) -> bool {
diff --git a/services/libs/jinux-std/src/tty/line_discipline.rs b/services/libs/jinux-std/src/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/tty/line_discipline.rs
@@ -68,10 +66,10 @@ impl LineDiscipline {
pub fn new() -> Self {
Self {
current_line: RwLock::new(CurrentLine::new()),
- read_buffer: Mutex::new(ConstGenericRingBuffer::new()),
+ read_buffer: Mutex::new(StaticRb::default()),
foreground: RwLock::new(None),
termios: RwLock::new(KernelTermios::default()),
- read_wait_queue: WaitQueue::new(),
+ pollee: Pollee::new(IoEvents::empty()),
}
}
diff --git a/services/libs/jinux-std/src/tty/line_discipline.rs b/services/libs/jinux-std/src/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/tty/line_discipline.rs
@@ -68,10 +66,10 @@ impl LineDiscipline {
pub fn new() -> Self {
Self {
current_line: RwLock::new(CurrentLine::new()),
- read_buffer: Mutex::new(ConstGenericRingBuffer::new()),
+ read_buffer: Mutex::new(StaticRb::default()),
foreground: RwLock::new(None),
termios: RwLock::new(KernelTermios::default()),
- read_wait_queue: WaitQueue::new(),
+ pollee: Pollee::new(IoEvents::empty()),
}
}
diff --git a/services/libs/jinux-std/src/tty/line_discipline.rs b/services/libs/jinux-std/src/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/tty/line_discipline.rs
@@ -118,7 +116,7 @@ impl LineDiscipline {
current_line.push_char(item);
let current_line_chars = current_line.drain();
for char in current_line_chars {
- self.read_buffer.lock().push(char);
+ self.read_buffer.lock().push_overwrite(char);
}
} else if item >= 0x20 && item < 0x7f {
// printable character
diff --git a/services/libs/jinux-std/src/tty/line_discipline.rs b/services/libs/jinux-std/src/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/tty/line_discipline.rs
@@ -118,7 +116,7 @@ impl LineDiscipline {
current_line.push_char(item);
let current_line_chars = current_line.drain();
for char in current_line_chars {
- self.read_buffer.lock().push(char);
+ self.read_buffer.lock().push_overwrite(char);
}
} else if item >= 0x20 && item < 0x7f {
// printable character
diff --git a/services/libs/jinux-std/src/tty/line_discipline.rs b/services/libs/jinux-std/src/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/tty/line_discipline.rs
@@ -126,7 +124,7 @@ impl LineDiscipline {
}
} else {
// raw mode
- self.read_buffer.lock().push(item);
+ self.read_buffer.lock().push_overwrite(item);
// debug!("push char: {}", char::from(item))
}
diff --git a/services/libs/jinux-std/src/tty/line_discipline.rs b/services/libs/jinux-std/src/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/tty/line_discipline.rs
@@ -126,7 +124,7 @@ impl LineDiscipline {
}
} else {
// raw mode
- self.read_buffer.lock().push(item);
+ self.read_buffer.lock().push_overwrite(item);
// debug!("push char: {}", char::from(item))
}
diff --git a/services/libs/jinux-std/src/tty/line_discipline.rs b/services/libs/jinux-std/src/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/tty/line_discipline.rs
@@ -135,13 +133,13 @@ impl LineDiscipline {
}
if self.is_readable() {
- self.read_wait_queue.wake_all();
+ self.pollee.add_events(IoEvents::IN);
}
}
/// whether self is readable
fn is_readable(&self) -> bool {
- self.read_buffer.lock().len() > 0
+ !self.read_buffer.lock().is_empty()
}
// TODO: respect output flags
diff --git a/services/libs/jinux-std/src/tty/line_discipline.rs b/services/libs/jinux-std/src/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/tty/line_discipline.rs
@@ -135,13 +133,13 @@ impl LineDiscipline {
}
if self.is_readable() {
- self.read_wait_queue.wake_all();
+ self.pollee.add_events(IoEvents::IN);
}
}
/// whether self is readable
fn is_readable(&self) -> bool {
- self.read_buffer.lock().len() > 0
+ !self.read_buffer.lock().is_empty()
}
// TODO: respect output flags
diff --git a/services/libs/jinux-std/src/tty/line_discipline.rs b/services/libs/jinux-std/src/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/tty/line_discipline.rs
@@ -170,58 +168,84 @@ impl LineDiscipline {
/// read all bytes buffered to dst, return the actual read length.
pub fn read(&self, dst: &mut [u8]) -> Result<usize> {
- let termios = self.termios.read();
- let vmin = *termios.get_special_char(CC_C_CHAR::VMIN);
- let vtime = *termios.get_special_char(CC_C_CHAR::VTIME);
- drop(termios);
- let read_len: usize = self.read_wait_queue.wait_until(|| {
- // if current process does not belong to foreground process group,
- // block until current process become foreground.
- if !self.current_belongs_to_foreground() {
- warn!("current process does not belong to foreground process group");
- return None;
+ let mut poller = None;
+ loop {
+ let res = self.try_read(dst);
+ match res {
+ Ok(read_len) => {
+ return Ok(read_len);
+ }
+ Err(e) => {
+ if e.error() != Errno::EAGAIN {
+ return Err(e);
+ }
+ }
+ }
+
+ // Wait for read event
+ let need_poller = if poller.is_none() {
+ poller = Some(Poller::new());
+ poller.as_ref()
+ } else {
+ None
+ };
+ let revents = self.pollee.poll(IoEvents::IN, need_poller);
+ if revents.is_empty() {
+ poller.as_ref().unwrap().wait();
}
+ }
+ }
+
+ pub fn try_read(&self, dst: &mut [u8]) -> Result<usize> {
+ if !self.current_belongs_to_foreground() {
+ return_errno!(Errno::EAGAIN);
+ }
+
+ let (vmin, vtime) = {
+ let termios = self.termios.read();
+ let vmin = *termios.get_special_char(CC_C_CHAR::VMIN);
+ let vtime = *termios.get_special_char(CC_C_CHAR::VTIME);
+ (vmin, vtime)
+ };
+ let read_len = {
let len = self.read_buffer.lock().len();
let max_read_len = len.min(dst.len());
if vmin == 0 && vtime == 0 {
// poll read
- return self.poll_read(dst);
- }
- if vmin > 0 && vtime == 0 {
+ self.poll_read(dst)
+ } else if vmin > 0 && vtime == 0 {
// block read
- return self.block_read(dst, vmin);
- }
- if vmin == 0 && vtime > 0 {
+ self.block_read(dst, vmin)?
+ } else if vmin == 0 && vtime > 0 {
todo!()
- }
- if vmin > 0 && vtime > 0 {
+ } else if vmin > 0 && vtime > 0 {
todo!()
+ } else {
+ unreachable!()
}
- unreachable!()
- });
+ };
+ if !self.is_readable() {
+ self.pollee.del_events(IoEvents::IN);
+ }
Ok(read_len)
}
- pub fn poll(&self) -> IoEvents {
- if self.is_empty() {
- IoEvents::empty()
- } else {
- IoEvents::POLLIN
- }
+ pub fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ self.pollee.poll(mask, poller)
}
/// returns immediately with the lesser of the number of bytes available or the number of bytes requested.
/// If no bytes are available, completes immediately, returning 0.
- fn poll_read(&self, dst: &mut [u8]) -> Option<usize> {
+ fn poll_read(&self, dst: &mut [u8]) -> usize {
let mut buffer = self.read_buffer.lock();
let len = buffer.len();
let max_read_len = len.min(dst.len());
if max_read_len == 0 {
- return Some(0);
+ return 0;
}
let mut read_len = 0;
for i in 0..max_read_len {
- if let Some(next_char) = buffer.dequeue() {
+ if let Some(next_char) = buffer.pop() {
if self.termios.read().is_canonical_mode() {
// canonical mode, read until meet new line
if meet_new_line(next_char, &self.termios.read()) {
diff --git a/services/libs/jinux-std/src/tty/line_discipline.rs b/services/libs/jinux-std/src/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/tty/line_discipline.rs
@@ -170,58 +168,84 @@ impl LineDiscipline {
/// read all bytes buffered to dst, return the actual read length.
pub fn read(&self, dst: &mut [u8]) -> Result<usize> {
- let termios = self.termios.read();
- let vmin = *termios.get_special_char(CC_C_CHAR::VMIN);
- let vtime = *termios.get_special_char(CC_C_CHAR::VTIME);
- drop(termios);
- let read_len: usize = self.read_wait_queue.wait_until(|| {
- // if current process does not belong to foreground process group,
- // block until current process become foreground.
- if !self.current_belongs_to_foreground() {
- warn!("current process does not belong to foreground process group");
- return None;
+ let mut poller = None;
+ loop {
+ let res = self.try_read(dst);
+ match res {
+ Ok(read_len) => {
+ return Ok(read_len);
+ }
+ Err(e) => {
+ if e.error() != Errno::EAGAIN {
+ return Err(e);
+ }
+ }
+ }
+
+ // Wait for read event
+ let need_poller = if poller.is_none() {
+ poller = Some(Poller::new());
+ poller.as_ref()
+ } else {
+ None
+ };
+ let revents = self.pollee.poll(IoEvents::IN, need_poller);
+ if revents.is_empty() {
+ poller.as_ref().unwrap().wait();
}
+ }
+ }
+
+ pub fn try_read(&self, dst: &mut [u8]) -> Result<usize> {
+ if !self.current_belongs_to_foreground() {
+ return_errno!(Errno::EAGAIN);
+ }
+
+ let (vmin, vtime) = {
+ let termios = self.termios.read();
+ let vmin = *termios.get_special_char(CC_C_CHAR::VMIN);
+ let vtime = *termios.get_special_char(CC_C_CHAR::VTIME);
+ (vmin, vtime)
+ };
+ let read_len = {
let len = self.read_buffer.lock().len();
let max_read_len = len.min(dst.len());
if vmin == 0 && vtime == 0 {
// poll read
- return self.poll_read(dst);
- }
- if vmin > 0 && vtime == 0 {
+ self.poll_read(dst)
+ } else if vmin > 0 && vtime == 0 {
// block read
- return self.block_read(dst, vmin);
- }
- if vmin == 0 && vtime > 0 {
+ self.block_read(dst, vmin)?
+ } else if vmin == 0 && vtime > 0 {
todo!()
- }
- if vmin > 0 && vtime > 0 {
+ } else if vmin > 0 && vtime > 0 {
todo!()
+ } else {
+ unreachable!()
}
- unreachable!()
- });
+ };
+ if !self.is_readable() {
+ self.pollee.del_events(IoEvents::IN);
+ }
Ok(read_len)
}
- pub fn poll(&self) -> IoEvents {
- if self.is_empty() {
- IoEvents::empty()
- } else {
- IoEvents::POLLIN
- }
+ pub fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ self.pollee.poll(mask, poller)
}
/// returns immediately with the lesser of the number of bytes available or the number of bytes requested.
/// If no bytes are available, completes immediately, returning 0.
- fn poll_read(&self, dst: &mut [u8]) -> Option<usize> {
+ fn poll_read(&self, dst: &mut [u8]) -> usize {
let mut buffer = self.read_buffer.lock();
let len = buffer.len();
let max_read_len = len.min(dst.len());
if max_read_len == 0 {
- return Some(0);
+ return 0;
}
let mut read_len = 0;
for i in 0..max_read_len {
- if let Some(next_char) = buffer.dequeue() {
+ if let Some(next_char) = buffer.pop() {
if self.termios.read().is_canonical_mode() {
// canonical mode, read until meet new line
if meet_new_line(next_char, &self.termios.read()) {
diff --git a/services/libs/jinux-std/src/tty/line_discipline.rs b/services/libs/jinux-std/src/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/tty/line_discipline.rs
@@ -245,18 +269,18 @@ impl LineDiscipline {
}
}
- Some(read_len)
+ read_len
}
// The read() blocks until the lesser of the number of bytes requested or
// MIN bytes are available, and returns the lesser of the two values.
- pub fn block_read(&self, dst: &mut [u8], vmin: u8) -> Option<usize> {
+ pub fn block_read(&self, dst: &mut [u8], vmin: u8) -> Result<usize> {
let min_read_len = (vmin as usize).min(dst.len());
let buffer_len = self.read_buffer.lock().len();
if buffer_len < min_read_len {
- return None;
+ return_errno!(Errno::EAGAIN);
}
- return self.poll_read(&mut dst[..min_read_len]);
+ Ok(self.poll_read(&mut dst[..min_read_len]))
}
/// write bytes to buffer, if flush to console, then write the content to console
diff --git a/services/libs/jinux-std/src/tty/line_discipline.rs b/services/libs/jinux-std/src/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/tty/line_discipline.rs
@@ -245,18 +269,18 @@ impl LineDiscipline {
}
}
- Some(read_len)
+ read_len
}
// The read() blocks until the lesser of the number of bytes requested or
// MIN bytes are available, and returns the lesser of the two values.
- pub fn block_read(&self, dst: &mut [u8], vmin: u8) -> Option<usize> {
+ pub fn block_read(&self, dst: &mut [u8], vmin: u8) -> Result<usize> {
let min_read_len = (vmin as usize).min(dst.len());
let buffer_len = self.read_buffer.lock().len();
if buffer_len < min_read_len {
- return None;
+ return_errno!(Errno::EAGAIN);
}
- return self.poll_read(&mut dst[..min_read_len]);
+ Ok(self.poll_read(&mut dst[..min_read_len]))
}
/// write bytes to buffer, if flush to console, then write the content to console
diff --git a/services/libs/jinux-std/src/tty/line_discipline.rs b/services/libs/jinux-std/src/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/tty/line_discipline.rs
@@ -283,7 +307,7 @@ impl LineDiscipline {
*self.foreground.write() = Some(fg_pgid);
// Some background processes may be waiting on the wait queue, when set_fg, the background processes may be able to read.
if self.is_readable() {
- self.read_wait_queue.wake_all();
+ self.pollee.add_events(IoEvents::IN);
}
}
diff --git a/services/libs/jinux-std/src/tty/line_discipline.rs b/services/libs/jinux-std/src/tty/line_discipline.rs
--- a/services/libs/jinux-std/src/tty/line_discipline.rs
+++ b/services/libs/jinux-std/src/tty/line_discipline.rs
@@ -283,7 +307,7 @@ impl LineDiscipline {
*self.foreground.write() = Some(fg_pgid);
// Some background processes may be waiting on the wait queue, when set_fg, the background processes may be able to read.
if self.is_readable() {
- self.read_wait_queue.wake_all();
+ self.pollee.add_events(IoEvents::IN);
}
}
diff --git a/services/libs/jinux-std/src/tty/mod.rs b/services/libs/jinux-std/src/tty/mod.rs
--- a/services/libs/jinux-std/src/tty/mod.rs
+++ b/services/libs/jinux-std/src/tty/mod.rs
@@ -1,9 +1,12 @@
use self::line_discipline::LineDiscipline;
use crate::driver::tty::TtyDriver;
use crate::fs::utils::{InodeMode, InodeType, IoEvents, Metadata};
-use crate::fs::{file_handle::File, utils::IoctlCmd};
+use crate::fs::{
+ file_handle::FileLike,
+ utils::{IoctlCmd, Poller},
+};
use crate::prelude::*;
-use crate::process::{process_table, Pgid};
+use crate::process::Pgid;
use crate::util::{read_val_from_user, write_val_to_user};
pub mod line_discipline;
diff --git a/services/libs/jinux-std/src/tty/mod.rs b/services/libs/jinux-std/src/tty/mod.rs
--- a/services/libs/jinux-std/src/tty/mod.rs
+++ b/services/libs/jinux-std/src/tty/mod.rs
@@ -1,9 +1,12 @@
use self::line_discipline::LineDiscipline;
use crate::driver::tty::TtyDriver;
use crate::fs::utils::{InodeMode, InodeType, IoEvents, Metadata};
-use crate::fs::{file_handle::File, utils::IoctlCmd};
+use crate::fs::{
+ file_handle::FileLike,
+ utils::{IoctlCmd, Poller},
+};
use crate::prelude::*;
-use crate::process::{process_table, Pgid};
+use crate::process::Pgid;
use crate::util::{read_val_from_user, write_val_to_user};
pub mod line_discipline;
diff --git a/services/libs/jinux-std/src/tty/mod.rs b/services/libs/jinux-std/src/tty/mod.rs
--- a/services/libs/jinux-std/src/tty/mod.rs
+++ b/services/libs/jinux-std/src/tty/mod.rs
@@ -43,23 +46,12 @@ impl Tty {
*self.driver.lock() = driver;
}
- /// Wake up foreground process group that wait on IO events.
- /// This function should be called when the interrupt handler of IO events is called.
- fn wake_fg_proc_grp(&self) {
- if let Some(fg_pgid) = self.ldisc.get_fg() {
- if let Some(fg_proc_grp) = process_table::pgid_to_process_group(fg_pgid) {
- fg_proc_grp.wake_all_polling_procs();
- }
- }
- }
-
pub fn receive_char(&self, item: u8) {
self.ldisc.push_char(item);
- self.wake_fg_proc_grp();
}
}
-impl File for Tty {
+impl FileLike for Tty {
fn read(&self, buf: &mut [u8]) -> Result<usize> {
self.ldisc.read(buf)
}
diff --git a/services/libs/jinux-std/src/tty/mod.rs b/services/libs/jinux-std/src/tty/mod.rs
--- a/services/libs/jinux-std/src/tty/mod.rs
+++ b/services/libs/jinux-std/src/tty/mod.rs
@@ -43,23 +46,12 @@ impl Tty {
*self.driver.lock() = driver;
}
- /// Wake up foreground process group that wait on IO events.
- /// This function should be called when the interrupt handler of IO events is called.
- fn wake_fg_proc_grp(&self) {
- if let Some(fg_pgid) = self.ldisc.get_fg() {
- if let Some(fg_proc_grp) = process_table::pgid_to_process_group(fg_pgid) {
- fg_proc_grp.wake_all_polling_procs();
- }
- }
- }
-
pub fn receive_char(&self, item: u8) {
self.ldisc.push_char(item);
- self.wake_fg_proc_grp();
}
}
-impl File for Tty {
+impl FileLike for Tty {
fn read(&self, buf: &mut [u8]) -> Result<usize> {
self.ldisc.read(buf)
}
diff --git a/services/libs/jinux-std/src/tty/mod.rs b/services/libs/jinux-std/src/tty/mod.rs
--- a/services/libs/jinux-std/src/tty/mod.rs
+++ b/services/libs/jinux-std/src/tty/mod.rs
@@ -73,8 +65,8 @@ impl File for Tty {
Ok(buf.len())
}
- fn poll(&self) -> IoEvents {
- self.ldisc.poll()
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ self.ldisc.poll(mask, poller)
}
fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
diff --git a/services/libs/jinux-std/src/tty/mod.rs b/services/libs/jinux-std/src/tty/mod.rs
--- a/services/libs/jinux-std/src/tty/mod.rs
+++ b/services/libs/jinux-std/src/tty/mod.rs
@@ -73,8 +65,8 @@ impl File for Tty {
Ok(buf.len())
}
- fn poll(&self) -> IoEvents {
- self.ldisc.poll()
+ fn poll(&self, mask: IoEvents, poller: Option<&Poller>) -> IoEvents {
+ self.ldisc.poll(mask, poller)
}
fn ioctl(&self, cmd: IoctlCmd, arg: usize) -> Result<i32> {
diff --git a/services/libs/jinux-std/src/tty/mod.rs b/services/libs/jinux-std/src/tty/mod.rs
--- a/services/libs/jinux-std/src/tty/mod.rs
+++ b/services/libs/jinux-std/src/tty/mod.rs
@@ -137,6 +129,10 @@ impl File for Tty {
rdev: 0,
}
}
+
+ fn as_any_ref(&self) -> &dyn Any {
+ self
+ }
}
/// FIXME: should we maintain a static console?
diff --git a/services/libs/jinux-std/src/tty/mod.rs b/services/libs/jinux-std/src/tty/mod.rs
--- a/services/libs/jinux-std/src/tty/mod.rs
+++ b/services/libs/jinux-std/src/tty/mod.rs
@@ -137,6 +129,10 @@ impl File for Tty {
rdev: 0,
}
}
+
+ fn as_any_ref(&self) -> &dyn Any {
+ self
+ }
}
/// FIXME: should we maintain a static console?
diff --git a/services/libs/jinux-util/src/lib.rs b/services/libs/jinux-util/src/lib.rs
--- a/services/libs/jinux-util/src/lib.rs
+++ b/services/libs/jinux-util/src/lib.rs
@@ -2,5 +2,8 @@
#![no_std]
#![forbid(unsafe_code)]
+extern crate alloc;
+
pub mod frame_ptr;
+pub mod slot_vec;
pub mod union_read_ptr;
diff --git a/services/libs/jinux-util/src/lib.rs b/services/libs/jinux-util/src/lib.rs
--- a/services/libs/jinux-util/src/lib.rs
+++ b/services/libs/jinux-util/src/lib.rs
@@ -2,5 +2,8 @@
#![no_std]
#![forbid(unsafe_code)]
+extern crate alloc;
+
pub mod frame_ptr;
+pub mod slot_vec;
pub mod union_read_ptr;
diff --git /dev/null b/services/libs/jinux-util/src/slot_vec.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-util/src/slot_vec.rs
@@ -0,0 +1,119 @@
+use alloc::vec::Vec;
+
+/// SlotVec is the variant of Vector.
+/// It guarantees that the index of one item remains unchanged during adding
+/// or deleting other items of the vector.
+pub struct SlotVec<T> {
+ // The slots to store items.
+ slots: Vec<Option<T>>,
+ // The number of occupied slots.
+ // The i-th slot is occupied if `self.slots[i].is_some()`.
+ num_occupied: usize,
+}
+
+impl<T> SlotVec<T> {
+ /// New an empty vector.
+ pub fn new() -> Self {
+ Self {
+ slots: Vec::new(),
+ num_occupied: 0,
+ }
+ }
+
+ /// Return `true` if the vector contains no items.
+ pub fn is_empty(&self) -> bool {
+ self.num_occupied == 0
+ }
+
+ /// Return the number of items.
+ pub fn len(&self) -> usize {
+ self.num_occupied
+ }
+
+ /// Return the number of slots.
+ pub fn slots_len(&self) -> usize {
+ self.slots.len()
+ }
+
+ /// Get the item at position `idx`.
+ ///
+ /// Return `None` if `idx` is out of bounds or the item is not exist.
+ pub fn get(&self, idx: usize) -> Option<&T> {
+ if idx >= self.slots.len() {
+ return None;
+ }
+ self.slots[idx].as_ref()
+ }
+
+ /// Put an item into the vector.
+ /// It may be put into any existing empty slots or the back of the vector.
+ ///
+ /// Return the index of the inserted item.
+ pub fn put(&mut self, entry: T) -> usize {
+ let idx = if self.num_occupied == self.slots.len() {
+ self.slots.push(Some(entry));
+ self.slots.len() - 1
+ } else {
+ let idx = self.slots.iter().position(|x| x.is_none()).unwrap();
+ self.slots[idx] = Some(entry);
+ idx
+ };
+ self.num_occupied += 1;
+ idx
+ }
+
+ /// Put and return the item at position `idx`.
+ ///
+ /// Return `None` if the item is not exist.
+ pub fn put_at(&mut self, idx: usize, item: T) -> Option<T> {
+ if idx >= self.slots.len() {
+ self.slots.resize_with(idx + 1, Default::default);
+ }
+ let mut sub_item = Some(item);
+ core::mem::swap(&mut sub_item, &mut self.slots[idx]);
+ if sub_item.is_none() {
+ self.num_occupied += 1;
+ }
+ sub_item
+ }
+
+ /// Remove and return the item at position `idx`.
+ ///
+ /// Return `None` if `idx` is out of bounds or the item has been removed.
+ pub fn remove(&mut self, idx: usize) -> Option<T> {
+ if idx >= self.slots.len() {
+ return None;
+ }
+ let mut del_item = None;
+ core::mem::swap(&mut del_item, &mut self.slots[idx]);
+ if del_item.is_some() {
+ debug_assert!(self.num_occupied > 0);
+ self.num_occupied -= 1;
+ }
+ del_item
+ }
+
+ /// Create an iterator which gives both of the index and the item.
+ /// The index may not be continuous.
+ pub fn idxes_and_items(&self) -> impl Iterator<Item = (usize, &'_ T)> {
+ self.slots
+ .iter()
+ .enumerate()
+ .filter(|(_, x)| x.is_some())
+ .map(|(idx, x)| (idx, x.as_ref().unwrap()))
+ }
+
+ /// Create an iterator which just gives the item.
+ pub fn iter(&self) -> impl Iterator<Item = &'_ T> {
+ self.slots.iter().filter_map(|x| x.as_ref())
+ }
+}
+
+impl<T: Clone> Clone for SlotVec<T> {
+ fn clone(&self) -> Self {
+ Self {
+ slots: self.slots.clone(),
+ num_occupied: self.num_occupied.clone(),
+ }
+ }
+}
diff --git /dev/null b/services/libs/jinux-util/src/slot_vec.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/jinux-util/src/slot_vec.rs
@@ -0,0 +1,119 @@
+use alloc::vec::Vec;
+
+/// SlotVec is the variant of Vector.
+/// It guarantees that the index of one item remains unchanged during adding
+/// or deleting other items of the vector.
+pub struct SlotVec<T> {
+ // The slots to store items.
+ slots: Vec<Option<T>>,
+ // The number of occupied slots.
+ // The i-th slot is occupied if `self.slots[i].is_some()`.
+ num_occupied: usize,
+}
+
+impl<T> SlotVec<T> {
+ /// New an empty vector.
+ pub fn new() -> Self {
+ Self {
+ slots: Vec::new(),
+ num_occupied: 0,
+ }
+ }
+
+ /// Return `true` if the vector contains no items.
+ pub fn is_empty(&self) -> bool {
+ self.num_occupied == 0
+ }
+
+ /// Return the number of items.
+ pub fn len(&self) -> usize {
+ self.num_occupied
+ }
+
+ /// Return the number of slots.
+ pub fn slots_len(&self) -> usize {
+ self.slots.len()
+ }
+
+ /// Get the item at position `idx`.
+ ///
+ /// Return `None` if `idx` is out of bounds or the item is not exist.
+ pub fn get(&self, idx: usize) -> Option<&T> {
+ if idx >= self.slots.len() {
+ return None;
+ }
+ self.slots[idx].as_ref()
+ }
+
+ /// Put an item into the vector.
+ /// It may be put into any existing empty slots or the back of the vector.
+ ///
+ /// Return the index of the inserted item.
+ pub fn put(&mut self, entry: T) -> usize {
+ let idx = if self.num_occupied == self.slots.len() {
+ self.slots.push(Some(entry));
+ self.slots.len() - 1
+ } else {
+ let idx = self.slots.iter().position(|x| x.is_none()).unwrap();
+ self.slots[idx] = Some(entry);
+ idx
+ };
+ self.num_occupied += 1;
+ idx
+ }
+
+ /// Put and return the item at position `idx`.
+ ///
+ /// Return `None` if the item is not exist.
+ pub fn put_at(&mut self, idx: usize, item: T) -> Option<T> {
+ if idx >= self.slots.len() {
+ self.slots.resize_with(idx + 1, Default::default);
+ }
+ let mut sub_item = Some(item);
+ core::mem::swap(&mut sub_item, &mut self.slots[idx]);
+ if sub_item.is_none() {
+ self.num_occupied += 1;
+ }
+ sub_item
+ }
+
+ /// Remove and return the item at position `idx`.
+ ///
+ /// Return `None` if `idx` is out of bounds or the item has been removed.
+ pub fn remove(&mut self, idx: usize) -> Option<T> {
+ if idx >= self.slots.len() {
+ return None;
+ }
+ let mut del_item = None;
+ core::mem::swap(&mut del_item, &mut self.slots[idx]);
+ if del_item.is_some() {
+ debug_assert!(self.num_occupied > 0);
+ self.num_occupied -= 1;
+ }
+ del_item
+ }
+
+ /// Create an iterator which gives both of the index and the item.
+ /// The index may not be continuous.
+ pub fn idxes_and_items(&self) -> impl Iterator<Item = (usize, &'_ T)> {
+ self.slots
+ .iter()
+ .enumerate()
+ .filter(|(_, x)| x.is_some())
+ .map(|(idx, x)| (idx, x.as_ref().unwrap()))
+ }
+
+ /// Create an iterator which just gives the item.
+ pub fn iter(&self) -> impl Iterator<Item = &'_ T> {
+ self.slots.iter().filter_map(|x| x.as_ref())
+ }
+}
+
+impl<T: Clone> Clone for SlotVec<T> {
+ fn clone(&self) -> Self {
+ Self {
+ slots: self.slots.clone(),
+ num_occupied: self.num_occupied.clone(),
+ }
+ }
+}
diff --git /dev/null b/services/libs/keyable-arc/Cargo.toml
new file mode 100644
--- /dev/null
+++ b/services/libs/keyable-arc/Cargo.toml
@@ -0,0 +1,9 @@
+[package]
+name = "keyable-arc"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+
diff --git /dev/null b/services/libs/keyable-arc/Cargo.toml
new file mode 100644
--- /dev/null
+++ b/services/libs/keyable-arc/Cargo.toml
@@ -0,0 +1,9 @@
+[package]
+name = "keyable-arc"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
+
diff --git /dev/null b/services/libs/keyable-arc/src/lib.rs
new file mode 100644
--- /dev/null
+++ b/services/libs/keyable-arc/src/lib.rs
@@ -0,0 +1,362 @@
+//! Same as the standard `Arc`, except that it can be used as the key type of a hash table.
+//!
+//! # Motivation
+//!
+//! A type `K` is _keyable_ if it can be used as the key type for a hash map. Specifically,
+//! according to the document of `std::collections::HashMap`, the type `K` must satisfy
+//! the following properties.
+//!
+//! 1. It implements the `Eq` and `Hash` traits.
+//! 2. The two values of `k1` and `k2` of type `K` equal to each other,
+//! if and only if their hash values equal to each other.
+//! 3. The hashes of a value of `k` of type `K` cannot change while it
+//! is in a map.
+//!
+//! Sometimes we want to use `Arc<T>` as the key type for a hash map but cannot do so
+//! since `T` does not satisfy the properties above. For example, a lot of types
+//! do not or cannot implemennt the `Eq` trait. This is when `KeyableArc<T>` can come
+//! to your aid.
+//!
+//! # Overview
+//!
+//! For any type `T`, `KeyableArc<T>` satisfies all the properties to be keyable.
+//! This can be achieved easily and efficiently as we can simply use the address
+//! of the data (of `T` type) of a `KeyableArc<T>` object in the heap to determine the
+//! equality and hash of the `KeyableArc<T>` object. As the address won't change for
+//! an immutable `KeyableArc<T>` object, the hash and equality also stay the same.
+//!
+//! This crate is `#[no_std]` compatible, but requires the `alloc` crate.
+//!
+//! # Usage
+//!
+//! Here is a basic example to how that `KeyableArc<T>` is keyable even when `T`
+//! is not.
+//!
+//! ```rust
+//! use std::collections::HashMap;
+//! use std::sync::Arc;
+//! use keyable_arc::KeyableArc;
+//!
+//! struct Dummy; // Does not implement Eq and Hash
+//!
+//! let map: HashMap<KeyableArc<Dummy>, String> = HashMap::new();
+//! ```
+//!
+//! `KeyableArc` is a reference counter-based smart pointer, just like `Arc`.
+//! So you can use `KeyableArc` the same way you would use `Arc`.
+//!
+//! ```rust
+//! use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
+//! use keyable_arc::KeyableArc;
+//!
+//! let key_arc0 = KeyableArc::new(AtomicU64::new(0));
+//! let key_arc1 = key_arc0.clone();
+//! assert!(key_arc0.load(Relaxed) == 0 && key_arc1.load(Relaxed) == 0);
+//!
+//! key_arc0.fetch_add(1, Relaxed);
+//! assert!(key_arc0.load(Relaxed) == 1 && key_arc1.load(Relaxed) == 1);
+//! ```
+//!
+//! # Differences from `Arc<T>`
+//!
+//! Notice how `KeyableArc` differs from standard smart pointers in determining equality?
+//! Two `KeyableArc` objects are considered different even when their data have the same
+//! value.
+//!
+//! ```rust
+//! use keyable_arc::KeyableArc;
+//!
+//! let key_arc0 = KeyableArc::new(0);
+//! let key_arc1 = key_arc0.clone();
+//! assert!(key_arc0 == key_arc1);
+//! assert!(*key_arc0 == *key_arc1);
+//!
+//! let key_arc1 = KeyableArc::new(0);
+//! assert!(key_arc0 != key_arc1);
+//! assert!(*key_arc0 == *key_arc1);
+//! ```
+//!
+//! `KeyableArc<T>` is simply a wrapper of `Arc<T>. So converting between them
+//! through the `From` and `Into` traits is zero cost.
+//!
+//! ```rust
+//! use std::sync::Arc;
+//! use keyable_arc::KeyableArc;
+//!
+//! let key_arc: KeyableArc<u32> = Arc::new(0).into();
+//! let arc: Arc<u32> = KeyableArc::new(0).into();
+//! ```
+//!
+//! # The weak version
+//!
+//! `KeyableWeak<T>` is the weak version of `KeyableArc<T>`, just like `Weak<T>` is
+//! that of `Arc<T>`. And of course, `KeyableWeak<T>` is also _keyable_ for any
+//! type `T`.
+
+// TODO: Add `KeyableBox<T>` or other keyable versions of smart pointers.
+// If this is needed in the future, this crate should be renamed to `keyable`.
+
+// TODO: Add the missing methods offered by `Arc` or `Weak` but not their
+// keyable counterparts.
+
+#![cfg_attr(not(test), no_std)]
+#![feature(coerce_unsized)]
+#![feature(unsize)]
+#![forbid(unsafe_code)]
+
+extern crate alloc;
+
+use alloc::sync::{Arc, Weak};
+use core::borrow::Borrow;
+use core::cmp::Ordering;
+use core::convert::AsRef;
+use core::fmt;
+use core::hash::{Hash, Hasher};
+use core::marker::Unsize;
+use core::ops::{CoerceUnsized, Deref};
+
+/// Same as the standard `Arc`, except that it can be used as the key type of a hash table.
+#[repr(transparent)]
+pub struct KeyableArc<T: ?Sized>(Arc<T>);
+
+impl<T> KeyableArc<T> {
+ /// Constructs a new instance of `KeyableArc<T>`.
+ #[inline]
+ pub fn new(data: T) -> Self {
+ Self(Arc::new(data))
+ }
+}
+
+impl<T: ?Sized> KeyableArc<T> {
+ /// Returns a raw pointer to the object `T` pointed to by this `KeyableArc<T>`.
+ #[inline]
+ pub fn as_ptr(this: &Self) -> *const T {
+ Arc::as_ptr(&this.0)
+ }
+
+ /// Creates a new `KeyableWeak` pointer to this allocation.
+ pub fn downgrade(this: &Self) -> KeyableWeak<T> {
+ Arc::downgrade(&this.0).into()
+ }
+}
+
+impl<T: ?Sized> Deref for KeyableArc<T> {
+ type Target = T;
+
+ #[inline]
+ fn deref(&self) -> &T {
+ &*self.0
+ }
+}
+
+impl<T: ?Sized> AsRef<T> for KeyableArc<T> {
+ #[inline]
+ fn as_ref(&self) -> &T {
+ &**self
+ }
+}
+
+impl<T: ?Sized> Borrow<T> for KeyableArc<T> {
+ #[inline]
+ fn borrow(&self) -> &T {
+ &**self
+ }
+}
+
+impl<T: ?Sized> From<Arc<T>> for KeyableArc<T> {
+ #[inline]
+ fn from(arc: Arc<T>) -> Self {
+ Self(arc)
+ }
+}
+
+impl<T: ?Sized> Into<Arc<T>> for KeyableArc<T> {
+ #[inline]
+ fn into(self) -> Arc<T> {
+ self.0
+ }
+}
+
+impl<T: ?Sized> PartialEq for KeyableArc<T> {
+ fn eq(&self, other: &Self) -> bool {
+ Arc::as_ptr(&self.0) == Arc::as_ptr(&other.0)
+ }
+}
+
+impl<T: ?Sized> Eq for KeyableArc<T> {}
+
+impl<T: ?Sized> PartialOrd for KeyableArc<T> {
+ fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+ Some(Arc::as_ptr(&self.0).cmp(&Arc::as_ptr(&other.0)))
+ }
+}
+
+impl<T: ?Sized> Ord for KeyableArc<T> {
+ fn cmp(&self, other: &Self) -> Ordering {
+ Arc::as_ptr(&self.0).cmp(&Arc::as_ptr(&other.0))
+ }
+}
+
+impl<T: ?Sized> Hash for KeyableArc<T> {
+ fn hash<H: Hasher>(&self, s: &mut H) {
+ Arc::as_ptr(&self.0).hash(s)
+ }
+}
+
+impl<T: ?Sized> Clone for KeyableArc<T> {
+ fn clone(&self) -> Self {
+ Self(self.0.clone())
+ }
+}
+
+impl<T: ?Sized + fmt::Debug> fmt::Debug for KeyableArc<T> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ fmt::Debug::fmt(&**self, f)
+ }
+}
+
+//=========================================================
+// The weak version
+//=========================================================
+
+/// The weak counterpart of `KeyableArc<T>`, similar to `Weak<T>`.
+///
+/// `KeyableWeak<T>` is also _keyable_ for any type `T` just like
+/// `KeyableArc<T>`.
+#[repr(transparent)]
+pub struct KeyableWeak<T: ?Sized>(Weak<T>);
+
+impl<T> KeyableWeak<T> {
+ /// Constructs a new `KeyableWeak<T>`, without allocating any memory.
+ /// Calling `upgrade` on the return value always gives `None`.
+ #[inline]
+ pub fn new() -> Self {
+ Self(Weak::new())
+ }
+
+ /// Returns a raw pointer to the object `T` pointed to by this `KeyableWeak<T>`.
+ ///
+ /// The pointer is valid only if there are some strong references.
+ /// The pointer may be dangling, unaligned or even null otherwise.
+ #[inline]
+ pub fn as_ptr(&self) -> *const T {
+ self.0.as_ptr()
+ }
+}
+
+impl<T: ?Sized> KeyableWeak<T> {
+ /// Attempts to upgrade the Weak pointer to an Arc,
+ /// delaying dropping of the inner value if successful.
+ ///
+ /// Returns None if the inner value has since been dropped.
+ #[inline]
+ pub fn upgrade(&self) -> Option<KeyableArc<T>> {
+ self.0.upgrade().map(|arc| arc.into())
+ }
+
+ /// Gets the number of strong pointers pointing to this allocation.
+ #[inline]
+ pub fn strong_count(&self) -> usize {
+ self.0.strong_count()
+ }
+
+ /// Gets the number of weak pointers pointing to this allocation.
+ #[inline]
+ pub fn weak_count(&self) -> usize {
+ self.0.weak_count()
+ }
+}
+
+impl<T: ?Sized> PartialEq for KeyableWeak<T> {
+ fn eq(&self, other: &Self) -> bool {
+ self.0.as_ptr() == other.0.as_ptr()
+ }
+}
+
+impl<T: ?Sized> Eq for KeyableWeak<T> {}
+
+impl<T: ?Sized> PartialOrd for KeyableWeak<T> {
+ fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+ Some(self.0.as_ptr().cmp(&other.0.as_ptr()))
+ }
+}
+
+impl<T: ?Sized> Ord for KeyableWeak<T> {
+ fn cmp(&self, other: &Self) -> Ordering {
+ self.0.as_ptr().cmp(&other.0.as_ptr())
+ }
+}
+
+impl<T: ?Sized> Hash for KeyableWeak<T> {
+ fn hash<H: Hasher>(&self, s: &mut H) {
+ self.0.as_ptr().hash(s)
+ }
+}
+
+impl<T: ?Sized> From<Weak<T>> for KeyableWeak<T> {
+ #[inline]
+ fn from(weak: Weak<T>) -> Self {
+ Self(weak)
+ }
+}
+
+impl<T: ?Sized> Into<Weak<T>> for KeyableWeak<T> {
+ #[inline]
+ fn into(self) -> Weak<T> {
+ self.0
+ }
+}
+
+impl<T: ?Sized + fmt::Debug> fmt::Debug for KeyableWeak<T> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "(KeyableWeak)")
+ }
+}
+
+// Enabling type coercing, e.g., converting from `KeyableArc<T>` to `KeyableArc<dyn S>`,
+// where `T` implements `S`.
+impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<KeyableArc<U>> for KeyableArc<T> {}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn downgrade_and_upgrade() {
+ let arc = KeyableArc::new(1);
+ let weak = KeyableArc::downgrade(&arc);
+ assert!(arc.clone() == weak.upgrade().unwrap());
+ assert!(weak == KeyableArc::downgrade(&arc));
+ }
+
+ #[test]
+ fn debug_format() {
+ println!("{:?}", KeyableArc::new(1u32));
+ println!("{:?}", KeyableWeak::<u32>::new());
+ }
+
+ #[test]
+ fn use_as_key() {
+ use std::collections::HashMap;
+
+ let mut map: HashMap<KeyableArc<u32>, u32> = HashMap::new();
+ let key = KeyableArc::new(1);
+ let val = 1;
+ map.insert(key.clone(), val);
+ assert!(map.get(&key) == Some(&val));
+ assert!(map.remove(&key) == Some(val));
+ assert!(map.keys().count() == 0);
+ }
+
+ #[test]
+ fn as_trait_object() {
+ trait DummyTrait {}
+ struct DummyStruct;
+ impl DummyTrait for DummyStruct {}
+
+ let arc_struct = KeyableArc::new(DummyStruct);
+ let arc_dyn0: KeyableArc<dyn DummyTrait> = arc_struct.clone();
+ let arc_dyn1: KeyableArc<dyn DummyTrait> = arc_struct.clone();
+ assert!(arc_dyn0 == arc_dyn1);
+ }
+}
|
2023-04-20T03:46:19Z
|
25c4f0f2bcaa0bc8c650b0f4ee7b0d78e2a836b2
|
|
asterinas/asterinas
|
diff --git a/.gitattributes b/.gitattributes
--- a/.gitattributes
+++ b/.gitattributes
@@ -1,10 +1,10 @@
-src/apps/hello_world/hello_world filter=lfs diff=lfs merge=lfs -text
-src/apps/fork/fork filter=lfs diff=lfs merge=lfs -text
-src/apps/hello_c/hello filter=lfs diff=lfs merge=lfs -text
-src/apps/execve/execve filter=lfs diff=lfs merge=lfs -text
-src/apps/execve/hello filter=lfs diff=lfs merge=lfs -text
-src/apps/fork_c/fork filter=lfs diff=lfs merge=lfs -text
-src/apps/signal_c/signal_test filter=lfs diff=lfs merge=lfs -text
-src/apps/busybox/busybox filter=lfs diff=lfs merge=lfs -text
-src/apps/pthread/pthread_test filter=lfs diff=lfs merge=lfs -text
-src/apps/hello_pie/hello filter=lfs diff=lfs merge=lfs -text
+regression/apps/hello_world/hello_world filter=lfs diff=lfs merge=lfs -text
+regression/apps/fork/fork filter=lfs diff=lfs merge=lfs -text
+regression/apps/hello_c/hello filter=lfs diff=lfs merge=lfs -text
+regression/apps/execve/execve filter=lfs diff=lfs merge=lfs -text
+regression/apps/execve/hello filter=lfs diff=lfs merge=lfs -text
+regression/apps/fork_c/fork filter=lfs diff=lfs merge=lfs -text
+regression/apps/signal_c/signal_test filter=lfs diff=lfs merge=lfs -text
+regression/apps/busybox/busybox filter=lfs diff=lfs merge=lfs -text
+regression/apps/pthread/pthread_test filter=lfs diff=lfs merge=lfs -text
+regression/apps/hello_pie/hello filter=lfs diff=lfs merge=lfs -text
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -1,6 +1,6 @@
.PHONY: all build clean docs fmt run setup test tools
-all: build test
+all: build
setup:
@rustup component add rust-src
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -9,28 +9,28 @@ setup:
@cargo install mdbook
build:
- @make --no-print-directory -C src/ramdisk
- @cd src && cargo kbuild
+ @make --no-print-directory -C regression/ramdisk
+ @cargo kbuild
tools:
- @cd src/services/comp-sys && cargo install --path cargo-component
+ @cd services/libs/comp-sys && cargo install --path cargo-component
run: build
- @cd src && cargo krun
+ @cargo krun
test: build
- @cd src && cargo ktest
+ @cargo ktest
docs:
- @cd src && cargo doc # Build Rust docs
+ @cargo doc # Build Rust docs
@echo "" # Add a blank line
@cd docs && mdbook build # Build mdBook
check:
- @cd src && cargo fmt --check # Check Rust format issues
- @cd src && cargo clippy # Check common programming mistakes
+ @cargo fmt --check # Check Rust format issues
+ @cargo clippy # Check common programming mistakes
clean:
- @cd src && cargo clean
+ @cargo clean
@cd docs && mdbook clean
- @make --no-print-directory -C src/ramdisk clean
+ @make --no-print-directory -C regression/ramdisk clean
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -23,16 +23,16 @@ As a zero-cost, least-privilege OS, Jinux provides the best of both worlds: the
## How to build and test
While most code is written in Rust, the project-scope build process is governed
-by Makefile.
+by Makefile. The following commands are intended for use on an Ubuntu server that has installed qemu-system-x86_64.
-Before downloading source code, install and init Git LFS since the project manage binaries with Git LFS.
+### Preparation
+Before downloading source code, install and init Git LFS since the project manages binaries with Git LFS.
```bash
# 1. install git-lfs
-brew install git-lfs # for mac
-apt install git-lfs # for ubuntu
+apt install git-lfs
# 2. init git-lfs for current user
-git lfs install --skip-repo # for mac & ubuntu
+git lfs install --skip-repo
```
Then, download source codes as normal.
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -46,22 +46,29 @@ all developmennt tools are installed.
make setup
```
-Then, install some standalone tools (e.g., `cargo-component`) under the project directory.
-``` bash
-make tools
+### build
+Then, we can build the project.
+```bash
+make build
```
-Set environmental variables to enable `cargo` find installed tools.
+If everything goes well, then we can run the OS.
```bash
-export PATH=`pwd`/src/target/bin:${PATH}
+make run
```
-Then, we can build and test the project.
+### Test
+We can run unit tests and integration tests if building succeeds.
```bash
-make
+make test
```
-If everything goes well, then we can run the OS.
+If we want to check access control policy among components, install some standalone tools (e.g., `cargo-component`), and set environmental variables to enable `cargo` find installed tools under the project directory.
+``` bash
+make tools
+export PATH=`pwd`/target/bin:${PATH}
+```
+Then we can use the tool to check access control policy.
```bash
-make run
+cargo component-check
```
|
[
"115"
] | null |
888853a6de752e97c6f94fff83c00594be42929f
|
Reorganize the codebase for cleanness
To make the codebase more clean and understandable, I propose to do the following changes:
* Rename `tests` to `test`, which indicates that the directory contains various types of testing code, including unit tests, user programs, and possibly LTP tests
* Rename `apps` to `test/apps`
* In the future, add LTP tests to `test`
* Put `ramdisk` under `test` because its content is only intended for testing
* Create a `framework/libs` and move every dir (except `jinux-frame`) to the new dir
* Rename `jinux-boot` to `boot` to make the name consistent with other dirs like `services` and `framework`
* Move `services/comp-sys` to `services/libs/comp-sys`
* Move `src/*` to the project root dir
* [Optional] Rename `src/src` to `src/kernel`
|
asterinas__asterinas-183
| 183
|
diff --git a/.gitattributes b/.gitattributes
--- a/.gitattributes
+++ b/.gitattributes
@@ -1,10 +1,10 @@
-src/apps/hello_world/hello_world filter=lfs diff=lfs merge=lfs -text
-src/apps/fork/fork filter=lfs diff=lfs merge=lfs -text
-src/apps/hello_c/hello filter=lfs diff=lfs merge=lfs -text
-src/apps/execve/execve filter=lfs diff=lfs merge=lfs -text
-src/apps/execve/hello filter=lfs diff=lfs merge=lfs -text
-src/apps/fork_c/fork filter=lfs diff=lfs merge=lfs -text
-src/apps/signal_c/signal_test filter=lfs diff=lfs merge=lfs -text
-src/apps/busybox/busybox filter=lfs diff=lfs merge=lfs -text
-src/apps/pthread/pthread_test filter=lfs diff=lfs merge=lfs -text
-src/apps/hello_pie/hello filter=lfs diff=lfs merge=lfs -text
+regression/apps/hello_world/hello_world filter=lfs diff=lfs merge=lfs -text
+regression/apps/fork/fork filter=lfs diff=lfs merge=lfs -text
+regression/apps/hello_c/hello filter=lfs diff=lfs merge=lfs -text
+regression/apps/execve/execve filter=lfs diff=lfs merge=lfs -text
+regression/apps/execve/hello filter=lfs diff=lfs merge=lfs -text
+regression/apps/fork_c/fork filter=lfs diff=lfs merge=lfs -text
+regression/apps/signal_c/signal_test filter=lfs diff=lfs merge=lfs -text
+regression/apps/busybox/busybox filter=lfs diff=lfs merge=lfs -text
+regression/apps/pthread/pthread_test filter=lfs diff=lfs merge=lfs -text
+regression/apps/hello_pie/hello filter=lfs diff=lfs merge=lfs -text
diff --git a/.gitignore b/.gitignore
--- a/.gitignore
+++ b/.gitignore
@@ -13,8 +13,8 @@ target/
**/.DS_Store
# Ramdisk file
-src/ramdisk/initramfs/
-src/ramdisk/build/
+regression/ramdisk/initramfs/
+regression/ramdisk/build/
# qemu log file
qemu.log
diff --git a/.gitignore b/.gitignore
--- a/.gitignore
+++ b/.gitignore
@@ -13,8 +13,8 @@ target/
**/.DS_Store
# Ramdisk file
-src/ramdisk/initramfs/
-src/ramdisk/build/
+regression/ramdisk/initramfs/
+regression/ramdisk/build/
# qemu log file
qemu.log
diff --git a/src/Cargo.toml b/Cargo.toml
--- a/src/Cargo.toml
+++ b/Cargo.toml
@@ -3,11 +3,15 @@ name = "jinux"
version = "0.1.0"
edition = "2021"
+[[bin]]
+name = "jinux"
+path = "kernel/main.rs"
+
[dependencies]
limine = "0.1.10"
jinux-frame = { path = "framework/jinux-frame" }
jinux-std = { path = "services/libs/jinux-std" }
-component = { path = "services/comp-sys/component" }
+component = { path = "services/libs/comp-sys/component" }
[dev-dependencies]
x86_64 = "0.14.2"
diff --git a/src/Cargo.toml b/Cargo.toml
--- a/src/Cargo.toml
+++ b/Cargo.toml
@@ -3,11 +3,15 @@ name = "jinux"
version = "0.1.0"
edition = "2021"
+[[bin]]
+name = "jinux"
+path = "kernel/main.rs"
+
[dependencies]
limine = "0.1.10"
jinux-frame = { path = "framework/jinux-frame" }
jinux-std = { path = "services/libs/jinux-std" }
-component = { path = "services/comp-sys/component" }
+component = { path = "services/libs/comp-sys/component" }
[dev-dependencies]
x86_64 = "0.14.2"
diff --git a/src/Cargo.toml b/Cargo.toml
--- a/src/Cargo.toml
+++ b/Cargo.toml
@@ -33,4 +37,4 @@ members = [
"services/libs/cpio-decoder",
]
-exclude = ["services/comp-sys/controlled", "services/comp-sys/cargo-component"]
+exclude = ["services/libs/comp-sys/controlled", "services/libs/comp-sys/cargo-component"]
diff --git a/src/Cargo.toml b/Cargo.toml
--- a/src/Cargo.toml
+++ b/Cargo.toml
@@ -33,4 +37,4 @@ members = [
"services/libs/cpio-decoder",
]
-exclude = ["services/comp-sys/controlled", "services/comp-sys/cargo-component"]
+exclude = ["services/libs/comp-sys/controlled", "services/libs/comp-sys/cargo-component"]
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -1,6 +1,6 @@
.PHONY: all build clean docs fmt run setup test tools
-all: build test
+all: build
setup:
@rustup component add rust-src
diff --git a/Makefile b/Makefile
--- a/Makefile
+++ b/Makefile
@@ -9,28 +9,28 @@ setup:
@cargo install mdbook
build:
- @make --no-print-directory -C src/ramdisk
- @cd src && cargo kbuild
+ @make --no-print-directory -C regression/ramdisk
+ @cargo kbuild
tools:
- @cd src/services/comp-sys && cargo install --path cargo-component
+ @cd services/libs/comp-sys && cargo install --path cargo-component
run: build
- @cd src && cargo krun
+ @cargo krun
test: build
- @cd src && cargo ktest
+ @cargo ktest
docs:
- @cd src && cargo doc # Build Rust docs
+ @cargo doc # Build Rust docs
@echo "" # Add a blank line
@cd docs && mdbook build # Build mdBook
check:
- @cd src && cargo fmt --check # Check Rust format issues
- @cd src && cargo clippy # Check common programming mistakes
+ @cargo fmt --check # Check Rust format issues
+ @cargo clippy # Check common programming mistakes
clean:
- @cd src && cargo clean
+ @cargo clean
@cd docs && mdbook clean
- @make --no-print-directory -C src/ramdisk clean
+ @make --no-print-directory -C regression/ramdisk clean
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -23,16 +23,16 @@ As a zero-cost, least-privilege OS, Jinux provides the best of both worlds: the
## How to build and test
While most code is written in Rust, the project-scope build process is governed
-by Makefile.
+by Makefile. The following commands are intended for use on an Ubuntu server that has installed qemu-system-x86_64.
-Before downloading source code, install and init Git LFS since the project manage binaries with Git LFS.
+### Preparation
+Before downloading source code, install and init Git LFS since the project manages binaries with Git LFS.
```bash
# 1. install git-lfs
-brew install git-lfs # for mac
-apt install git-lfs # for ubuntu
+apt install git-lfs
# 2. init git-lfs for current user
-git lfs install --skip-repo # for mac & ubuntu
+git lfs install --skip-repo
```
Then, download source codes as normal.
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -46,22 +46,29 @@ all developmennt tools are installed.
make setup
```
-Then, install some standalone tools (e.g., `cargo-component`) under the project directory.
-``` bash
-make tools
+### build
+Then, we can build the project.
+```bash
+make build
```
-Set environmental variables to enable `cargo` find installed tools.
+If everything goes well, then we can run the OS.
```bash
-export PATH=`pwd`/src/target/bin:${PATH}
+make run
```
-Then, we can build and test the project.
+### Test
+We can run unit tests and integration tests if building succeeds.
```bash
-make
+make test
```
-If everything goes well, then we can run the OS.
+If we want to check access control policy among components, install some standalone tools (e.g., `cargo-component`), and set environmental variables to enable `cargo` find installed tools under the project directory.
+``` bash
+make tools
+export PATH=`pwd`/target/bin:${PATH}
+```
+Then we can use the tool to check access control policy.
```bash
-make run
+cargo component-check
```
diff --git a/src/boot/limine/scripts/limine-build.sh b/boot/limine/scripts/limine-build.sh
--- a/src/boot/limine/scripts/limine-build.sh
+++ b/boot/limine/scripts/limine-build.sh
@@ -25,7 +25,7 @@ cp target/limine/limine-cd.bin target/iso_root
cp target/limine/limine-cd-efi.bin target/iso_root
# Copy ramdisk
-cp ramdisk/build/ramdisk.cpio target/iso_root
+cp regression/ramdisk/build/ramdisk.cpio target/iso_root
xorriso -as mkisofs \
-b limine-cd.bin \
diff --git a/src/boot/limine/scripts/limine-build.sh b/boot/limine/scripts/limine-build.sh
--- a/src/boot/limine/scripts/limine-build.sh
+++ b/boot/limine/scripts/limine-build.sh
@@ -25,7 +25,7 @@ cp target/limine/limine-cd.bin target/iso_root
cp target/limine/limine-cd-efi.bin target/iso_root
# Copy ramdisk
-cp ramdisk/build/ramdisk.cpio target/iso_root
+cp regression/ramdisk/build/ramdisk.cpio target/iso_root
xorriso -as mkisofs \
-b limine-cd.bin \
diff --git a/src/framework/jinux-frame/Cargo.toml b/framework/jinux-frame/Cargo.toml
--- a/src/framework/jinux-frame/Cargo.toml
+++ b/framework/jinux-frame/Cargo.toml
@@ -12,7 +12,7 @@ spin = "0.9.4"
volatile = { version = "0.4.5", features = ["unstable"] }
buddy_system_allocator = "0.9.0"
pod = { git = "https://github.com/jinzhao-dev/pod", rev = "7fa2ed2" }
-align_ext = { path = "../align_ext" }
+align_ext = { path = "../libs/align_ext" }
intrusive-collections = "0.9.5"
log = "0.4"
lazy_static = { version = "1.0", features = ["spin_no_std"] }
diff --git a/src/framework/jinux-frame/Cargo.toml b/framework/jinux-frame/Cargo.toml
--- a/src/framework/jinux-frame/Cargo.toml
+++ b/framework/jinux-frame/Cargo.toml
@@ -12,7 +12,7 @@ spin = "0.9.4"
volatile = { version = "0.4.5", features = ["unstable"] }
buddy_system_allocator = "0.9.0"
pod = { git = "https://github.com/jinzhao-dev/pod", rev = "7fa2ed2" }
-align_ext = { path = "../align_ext" }
+align_ext = { path = "../libs/align_ext" }
intrusive-collections = "0.9.5"
log = "0.4"
lazy_static = { version = "1.0", features = ["spin_no_std"] }
diff --git /dev/null b/regression/apps/hello_c/hello
new file mode 100644
--- /dev/null
+++ b/regression/apps/hello_c/hello
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:dda5a7d6081cc2252056375d0550731ef2fd24789aa5f17da189a36bf78c588d
+size 871896
diff --git /dev/null b/regression/apps/hello_c/hello
new file mode 100644
--- /dev/null
+++ b/regression/apps/hello_c/hello
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:dda5a7d6081cc2252056375d0550731ef2fd24789aa5f17da189a36bf78c588d
+size 871896
diff --git a/src/services/comps/block/Cargo.toml b/services/comps/block/Cargo.toml
--- a/src/services/comps/block/Cargo.toml
+++ b/services/comps/block/Cargo.toml
@@ -12,7 +12,7 @@ jinux-frame = { path = "../../../framework/jinux-frame" }
jinux-pci = { path = "../pci" }
jinux-virtio = { path = "../virtio" }
jinux-util = { path = "../../libs/jinux-util" }
-component = { path = "../../comp-sys/component" }
+component = { path = "../../libs/comp-sys/component" }
log = "0.4"
[features]
diff --git a/src/services/comps/block/Cargo.toml b/services/comps/block/Cargo.toml
--- a/src/services/comps/block/Cargo.toml
+++ b/services/comps/block/Cargo.toml
@@ -12,7 +12,7 @@ jinux-frame = { path = "../../../framework/jinux-frame" }
jinux-pci = { path = "../pci" }
jinux-virtio = { path = "../virtio" }
jinux-util = { path = "../../libs/jinux-util" }
-component = { path = "../../comp-sys/component" }
+component = { path = "../../libs/comp-sys/component" }
log = "0.4"
[features]
diff --git a/src/services/comps/framebuffer/Cargo.toml b/services/comps/framebuffer/Cargo.toml
--- a/src/services/comps/framebuffer/Cargo.toml
+++ b/services/comps/framebuffer/Cargo.toml
@@ -7,7 +7,7 @@ edition = "2021"
[dependencies]
jinux-frame = { path = "../../../framework/jinux-frame" }
-component = { path = "../../comp-sys/component" }
+component = { path = "../../libs/comp-sys/component" }
log = "0.4"
spin = "0.9.4"
font8x8 = { version = "0.2.5", default-features = false, features = [
diff --git a/src/services/comps/framebuffer/Cargo.toml b/services/comps/framebuffer/Cargo.toml
--- a/src/services/comps/framebuffer/Cargo.toml
+++ b/services/comps/framebuffer/Cargo.toml
@@ -7,7 +7,7 @@ edition = "2021"
[dependencies]
jinux-frame = { path = "../../../framework/jinux-frame" }
-component = { path = "../../comp-sys/component" }
+component = { path = "../../libs/comp-sys/component" }
log = "0.4"
spin = "0.9.4"
font8x8 = { version = "0.2.5", default-features = false, features = [
diff --git a/src/services/comps/input/Cargo.toml b/services/comps/input/Cargo.toml
--- a/src/services/comps/input/Cargo.toml
+++ b/services/comps/input/Cargo.toml
@@ -12,7 +12,7 @@ jinux-frame = { path = "../../../framework/jinux-frame" }
jinux-pci = { path = "../pci" }
jinux-virtio = { path = "../virtio" }
jinux-util = { path = "../../libs/jinux-util" }
-component = { path = "../../comp-sys/component" }
+component = { path = "../../libs/comp-sys/component" }
virtio-input-decoder = "0.1.4"
log = "0.4"
diff --git a/src/services/comps/input/Cargo.toml b/services/comps/input/Cargo.toml
--- a/src/services/comps/input/Cargo.toml
+++ b/services/comps/input/Cargo.toml
@@ -12,7 +12,7 @@ jinux-frame = { path = "../../../framework/jinux-frame" }
jinux-pci = { path = "../pci" }
jinux-virtio = { path = "../virtio" }
jinux-util = { path = "../../libs/jinux-util" }
-component = { path = "../../comp-sys/component" }
+component = { path = "../../libs/comp-sys/component" }
virtio-input-decoder = "0.1.4"
log = "0.4"
diff --git a/src/services/comps/pci/Cargo.toml b/services/comps/pci/Cargo.toml
--- a/src/services/comps/pci/Cargo.toml
+++ b/services/comps/pci/Cargo.toml
@@ -11,7 +11,7 @@ spin = "0.9.4"
jinux-frame = { path = "../../../framework/jinux-frame" }
jinux-util = { path = "../../libs/jinux-util" }
pod = { git = "https://github.com/jinzhao-dev/pod", rev = "7fa2ed2" }
-component = { path = "../../comp-sys/component" }
+component = { path = "../../libs/comp-sys/component" }
log = "0.4"
[dependencies.lazy_static]
diff --git a/src/services/comps/pci/Cargo.toml b/services/comps/pci/Cargo.toml
--- a/src/services/comps/pci/Cargo.toml
+++ b/services/comps/pci/Cargo.toml
@@ -11,7 +11,7 @@ spin = "0.9.4"
jinux-frame = { path = "../../../framework/jinux-frame" }
jinux-util = { path = "../../libs/jinux-util" }
pod = { git = "https://github.com/jinzhao-dev/pod", rev = "7fa2ed2" }
-component = { path = "../../comp-sys/component" }
+component = { path = "../../libs/comp-sys/component" }
log = "0.4"
[dependencies.lazy_static]
diff --git a/src/services/comps/time/Cargo.toml b/services/comps/time/Cargo.toml
--- a/src/services/comps/time/Cargo.toml
+++ b/services/comps/time/Cargo.toml
@@ -7,7 +7,7 @@ edition = "2021"
[dependencies]
jinux-frame = { path = "../../../framework/jinux-frame" }
-component = { path = "../../comp-sys/component" }
+component = { path = "../../libs/comp-sys/component" }
log = "0.4"
spin = "0.9.4"
diff --git a/src/services/comps/time/Cargo.toml b/services/comps/time/Cargo.toml
--- a/src/services/comps/time/Cargo.toml
+++ b/services/comps/time/Cargo.toml
@@ -7,7 +7,7 @@ edition = "2021"
[dependencies]
jinux-frame = { path = "../../../framework/jinux-frame" }
-component = { path = "../../comp-sys/component" }
+component = { path = "../../libs/comp-sys/component" }
log = "0.4"
spin = "0.9.4"
diff --git a/src/services/comps/virtio/Cargo.toml b/services/comps/virtio/Cargo.toml
--- a/src/services/comps/virtio/Cargo.toml
+++ b/services/comps/virtio/Cargo.toml
@@ -12,7 +12,7 @@ jinux-frame = { path = "../../../framework/jinux-frame" }
jinux-pci = { path = "../pci" }
jinux-util = { path = "../../libs/jinux-util" }
pod = { git = "https://github.com/jinzhao-dev/pod", rev = "7fa2ed2" }
-component = { path = "../../comp-sys/component" }
+component = { path = "../../libs/comp-sys/component" }
log = "0.4"
[features]
diff --git a/src/services/comps/virtio/Cargo.toml b/services/comps/virtio/Cargo.toml
--- a/src/services/comps/virtio/Cargo.toml
+++ b/services/comps/virtio/Cargo.toml
@@ -12,7 +12,7 @@ jinux-frame = { path = "../../../framework/jinux-frame" }
jinux-pci = { path = "../pci" }
jinux-util = { path = "../../libs/jinux-util" }
pod = { git = "https://github.com/jinzhao-dev/pod", rev = "7fa2ed2" }
-component = { path = "../../comp-sys/component" }
+component = { path = "../../libs/comp-sys/component" }
log = "0.4"
[features]
diff --git a/src/services/libs/jinux-std/Cargo.toml b/services/libs/jinux-std/Cargo.toml
--- a/src/services/libs/jinux-std/Cargo.toml
+++ b/services/libs/jinux-std/Cargo.toml
@@ -7,12 +7,12 @@ edition = "2021"
[dependencies]
jinux-frame = { path = "../../../framework/jinux-frame" }
-align_ext = { path = "../../../framework/align_ext" }
+align_ext = { path = "../../../framework/libs/align_ext" }
pod = { git = "https://github.com/jinzhao-dev/pod", rev = "7fa2ed2" }
jinux-input = { path = "../../comps/input" }
jinux-block = { path = "../../comps/block" }
jinux-time = { path = "../../comps/time" }
-controlled = { path = "../../comp-sys/controlled" }
+controlled = { path = "../../libs/comp-sys/controlled" }
typeflags = { path = "../typeflags" }
typeflags-util = { path = "../typeflags-util" }
jinux-rights-proc = { path = "../jinux-rights-proc" }
diff --git a/src/services/libs/jinux-std/Cargo.toml b/services/libs/jinux-std/Cargo.toml
--- a/src/services/libs/jinux-std/Cargo.toml
+++ b/services/libs/jinux-std/Cargo.toml
@@ -7,12 +7,12 @@ edition = "2021"
[dependencies]
jinux-frame = { path = "../../../framework/jinux-frame" }
-align_ext = { path = "../../../framework/align_ext" }
+align_ext = { path = "../../../framework/libs/align_ext" }
pod = { git = "https://github.com/jinzhao-dev/pod", rev = "7fa2ed2" }
jinux-input = { path = "../../comps/input" }
jinux-block = { path = "../../comps/block" }
jinux-time = { path = "../../comps/time" }
-controlled = { path = "../../comp-sys/controlled" }
+controlled = { path = "../../libs/comp-sys/controlled" }
typeflags = { path = "../typeflags" }
typeflags-util = { path = "../typeflags-util" }
jinux-rights-proc = { path = "../jinux-rights-proc" }
diff --git a/src/services/libs/jinux-std/src/lib.rs b/services/libs/jinux-std/src/lib.rs
--- a/src/services/libs/jinux-std/src/lib.rs
+++ b/services/libs/jinux-std/src/lib.rs
@@ -79,7 +79,7 @@ fn init_thread() {
}
fn read_ramdisk_content() -> &'static [u8] {
- include_bytes!("../../../../ramdisk/build/ramdisk.cpio")
+ include_bytes!("../../../../regression/ramdisk/build/ramdisk.cpio")
}
/// first process never return
diff --git a/src/services/libs/jinux-std/src/lib.rs b/services/libs/jinux-std/src/lib.rs
--- a/src/services/libs/jinux-std/src/lib.rs
+++ b/services/libs/jinux-std/src/lib.rs
@@ -79,7 +79,7 @@ fn init_thread() {
}
fn read_ramdisk_content() -> &'static [u8] {
- include_bytes!("../../../../ramdisk/build/ramdisk.cpio")
+ include_bytes!("../../../../regression/ramdisk/build/ramdisk.cpio")
}
/// first process never return
|
2023-04-10T03:22:03Z
|
888853a6de752e97c6f94fff83c00594be42929f
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.