version
stringclasses 3
values | pull_number
int64 928
1.28k
| problem_statement
stringclasses 3
values | test_patch
stringclasses 3
values | instance_id
stringclasses 3
values | created_at
stringclasses 3
values | base_commit
stringclasses 3
values | repo
stringclasses 1
value | issue_numbers
sequencelengths 1
1
| patch
stringclasses 3
values | hints_text
stringclasses 3
values | environment_setup_commit
stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
0.8
| 1,279
|
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
|
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);
+ }
+}
|
asterinas__asterinas-1279
|
2024-09-02T06:56:20Z
|
963874471284ed014b76d268d933b6d13073c2cc
|
asterinas/asterinas
|
[
"1274"
] |
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>>>;
|
The bug introduced in this commit: https://github.com/asterinas/asterinas/commit/d15b4d9115cf33490245c06a93928995765f0d3f#r146080074
A potential fix: #497
|
963874471284ed014b76d268d933b6d13073c2cc
|
0.4
| 928
|
[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.
|
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)
+ ))
+ );
}
|
asterinas__asterinas-928
|
2024-06-12T07:29:38Z
|
e210e68920481c911f62f03ade0a780f96e48e24
|
asterinas/asterinas
|
[
"906"
] |
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
@@ -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/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/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
@@ -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
@@ -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
@@ -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/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
@@ -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_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
@@ -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);
|
e210e68920481c911f62f03ade0a780f96e48e24
|
|
0.7
| 1,159
|
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! -->
|
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
@@ -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/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/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
@@ -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);
};
|
asterinas__asterinas-1159
|
2024-08-13T11:21:28Z
|
c2a83427520f8263a8eb2c36edacdba261ad5cae
|
asterinas/asterinas
|
[
"975"
] |
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/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
@@ -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.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/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
@@ -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_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/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/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/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/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/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/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/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/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/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/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
@@ -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/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
@@ -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/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/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
@@ -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.
|
c2a83427520f8263a8eb2c36edacdba261ad5cae
|
README.md exists but content is empty.
- Downloads last month
- 1