repo
stringclasses 1
value | pull_number
int64 183
1.37k
| instance_id
stringlengths 24
25
| issue_numbers
listlengths 1
1
| base_commit
stringlengths 40
40
| patch
stringlengths 1.17k
285k
| test_patch
stringlengths 600
27.2k
| problem_statement
stringlengths 100
10.3k
| hints_text
stringclasses 7
values | created_at
stringlengths 20
20
| version
stringclasses 7
values | environment_setup_commit
stringclasses 7
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
asterinas/asterinas
| 1,369
|
asterinas__asterinas-1369
|
[
"919"
] |
ae4ac384713e63232b74915593ebdef680049d31
|
diff --git a/kernel/src/vm/vmar/mod.rs b/kernel/src/vm/vmar/mod.rs
index f691a40453..4cdd850def 100644
--- 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::{
@@ -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);
@@ -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)
}
@@ -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());
}
@@ -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
index b5d818e668..87ed53d484 100644
--- 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_};
@@ -224,7 +225,7 @@ impl VmMapping {
match cursor.query().unwrap() {
VmItem::Mapped {
- va: _,
+ va,
frame,
mut prop,
} if is_write => {
@@ -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;
@@ -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
index 6bea920ae0..bfe2cafec6 100644
--- 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
index a02f490dff..9a643ee1d9 100644
--- 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
index 9bb1e2cc62..a8294c38da 100644
--- 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
index 134cd112a0..f39d9daf57 100644
--- 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::{
@@ -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/tlb.rs b/ostd/src/mm/tlb.rs
new file mode 100644
index 0000000000..4ec58e091e
--- /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
index 78109d9b8e..3c55d6c3bd 100644
--- 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,
};
@@ -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<()>,
@@ -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(()),
}
}
@@ -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`.
@@ -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()),
}
})?)
}
@@ -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.
@@ -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<'_, '_> {
@@ -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.
@@ -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();
}
}
@@ -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;
@@ -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.
@@ -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/page_table/test.rs b/ostd/src/mm/page_table/test.rs
index 834289a910..6acb5bc22b 100644
--- 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();
@@ -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!(
@@ -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);
|
[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
|
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
|
0.8
|
ae4ac384713e63232b74915593ebdef680049d31
|
asterinas/asterinas
| 1,362
|
asterinas__asterinas-1362
|
[
"964"
] |
f7932595125a0bba8230b5f8d3b110c687d6f3b2
|
diff --git a/Makefile b/Makefile
index 55e0f3885f..b820be36b7 100644
--- 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
@@ -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.
@@ -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)"
@@ -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
index a2c6a915ce..fc8abb4c8e 100644
--- 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
index d21a19b6de..5c79ad7eb5 100644
--- 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/profile.md b/docs/src/osdk/reference/commands/profile.md
new file mode 100644
index 0000000000..c2ec6afbc1
--- /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
index 049ac5984a..7729adb3d4 100644
--- 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
index 681d6b55b0..c50b84b429 100644
--- 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",
@@ -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"
@@ -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"
@@ -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"
@@ -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"
@@ -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",
@@ -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"
@@ -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"
@@ -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"
@@ -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"
@@ -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"
@@ -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"
@@ -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"
@@ -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"
@@ -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"
@@ -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"
@@ -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"
@@ -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"
@@ -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"
@@ -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"
@@ -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"
@@ -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"
@@ -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"
@@ -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
index 5001dabcee..2b00eb81aa 100644
--- 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
index ba052e3621..0692a1a6da 100644
--- 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},
@@ -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) => {
@@ -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);
}
@@ -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")]
@@ -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
index 46247abedd..a80f9c289f 100644
--- 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
index 22f6b074c7..875bf4a657 100644
--- 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 a/osdk/src/commands/profile.rs b/osdk/src/commands/profile.rs
new file mode 100644
index 0000000000..587a645de3
--- /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
index e751956c8f..223f9ddf60 100644
--- 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(
@@ -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 {
@@ -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},
};
@@ -121,7 +165,7 @@ mod vsc {
path::Path,
};
- use super::gdb;
+ use super::{gdb, GdbServerArgs};
const VSC_DIR: &str = ".vscode";
@@ -170,6 +214,7 @@ mod vsc {
}
}
}
+
impl Drop for VscLaunchConfig {
fn drop(&mut self) {
// remove generated files
@@ -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
index 1dfdeaa17f..41260a993b 100644
--- 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
index 693f68e9cc..716286abf0 100644
--- 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();
@@ -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 {
@@ -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() {
|
[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`.
|
2024-09-21T13:48:03Z
|
0.8
|
ae4ac384713e63232b74915593ebdef680049d31
|
|
asterinas/asterinas
| 1,328
|
asterinas__asterinas-1328
|
[
"1244"
] |
42e28763c59202486af4298d5305e5c5e5ab9b54
|
diff --git a/kernel/src/lib.rs b/kernel/src/lib.rs
index c8f1e1bb7c..42390338cb 100644
--- 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();
@@ -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
index 29a23f07fe..f6233f314f 100644
--- 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,
@@ -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! {
@@ -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();
@@ -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,
@@ -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)
@@ -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(
@@ -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
index 8580e49fc3..c0fedd853a 100644
--- 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) {
@@ -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
index 3ed3f5e4b9..29cfaf63f2 100644
--- 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,
@@ -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.
///
@@ -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
index b7ae0d6762..c2467fbfd3 100644
--- 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::{
@@ -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},
};
@@ -72,7 +72,7 @@ impl PosixThreadBuilder {
self
}
- pub fn build(self) -> Arc<Thread> {
+ pub fn build(self) -> Arc<Task> {
let Self {
tid,
user_space,
@@ -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
index 64a1d9d852..7143a7b6dc 100644
--- 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.
@@ -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
index 49f70f55f2..2cef30b227 100644
--- 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;
@@ -22,7 +22,7 @@ use crate::{
events::Observer,
prelude::*,
process::signal::constants::SIGCONT,
- thread::Tid,
+ thread::{Thread, Tid},
time::{clocks::ProfClock, Timer, TimerManager},
};
@@ -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>>,
@@ -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
}
@@ -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.
@@ -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
index 012da12257..eac3cbb680 100644
--- 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},
};
@@ -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/thread_table.rs b/kernel/src/process/posix_thread/thread_table.rs
new file mode 100644
index 0000000000..fc8f1e88da
--- /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
index f645221e64..5f296b6949 100644
--- 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> {
@@ -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(),
@@ -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
index 68381cf6c2..b8dc35da39 100644
--- 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,
@@ -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,
};
@@ -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;
@@ -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
@@ -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,
@@ -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,
@@ -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();
@@ -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();
}
@@ -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 {
@@ -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()
}
@@ -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()) {
@@ -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
index f003752639..f9e686ff89 100644
--- 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
index 668c340bc6..3dfe35d79e 100644
--- 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! {
@@ -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
index c4a6031df9..725e2dc966 100644
--- 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
index 48917479f9..d8c1805a14 100644
--- 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
index b9fbcb888e..5e28a98799 100644
--- 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
index b51f992c99..18f67c1471 100644
--- 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
index fbe453d1a5..9d96c90976 100644
--- 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
index cc7e5df39f..d682d4cc82 100644
--- 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
index 297567aaaf..5723e36bb8 100644
--- 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},
@@ -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
index 461e22827a..e613ceccfb 100644
--- 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
}
@@ -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() {
@@ -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
index cb7249fe75..43f27d59f2 100644
--- 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;
@@ -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>,
@@ -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),
@@ -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) {
@@ -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.
@@ -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
index d7b6ed3c45..ee8b120d8e 100644
--- 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()
@@ -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();
}
@@ -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 b/kernel/src/thread/thread_table.rs
deleted file mode 100644
index 8f92a33403..0000000000
--- 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
index 173af08f99..0a38c2944b 100644
--- 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,
};
@@ -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>,
}
@@ -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,
@@ -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.
@@ -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
index c1a5b467de..6b9425d371 100644
--- 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,
};
@@ -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 {
@@ -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) {
@@ -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/ostd/src/task/mod.rs b/ostd/src/task/mod.rs
index 253caf09a2..e99da2ba7f 100644
--- 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() {
@@ -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)
}
@@ -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]
|
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
index 23618110b8..7c7c9f4348 100644
--- 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) {
|
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
```
|
2024-09-12T06:03:09Z
|
0.8
|
ae4ac384713e63232b74915593ebdef680049d31
|
|
asterinas/asterinas
| 1,159
|
asterinas__asterinas-1159
|
[
"975"
] |
c2a83427520f8263a8eb2c36edacdba261ad5cae
|
diff --git a/.github/workflows/benchmark_asterinas.yml b/.github/workflows/benchmark_asterinas.yml
index acdd3f0461..718e61be3b 100644
--- 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
index a6f2dcdc65..32f3c8b46e 100644
--- 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
@@ -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
@@ -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 }}
@@ -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
index d89b5ebbc4..af23d7b1f2 100644
--- 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
index edf500ce53..a70a63a84f 100644
--- 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
index 117acb1d2e..57ad547f93 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -153,6 +153,7 @@ dependencies = [
"ascii",
"aster-block",
"aster-console",
+ "aster-framebuffer",
"aster-input",
"aster-network",
"aster-rights",
@@ -166,6 +167,7 @@ dependencies = [
"bytemuck",
"bytemuck_derive",
"cfg-if",
+ "component",
"controlled",
"core2",
"cpio-decoder",
@@ -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"
@@ -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",
@@ -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",
@@ -1119,9 +1117,6 @@ dependencies = [
[[package]]
name = "ostd-test"
version = "0.1.0"
-dependencies = [
- "owo-colors",
-]
[[package]]
name = "owo-colors"
@@ -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
index 26ab93e796..64ffc7e587 100644
--- 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",
@@ -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
index ba1b5572ae..f442c589ea 100644
--- 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
index 8b85e848fa..227088ff9a 100644
--- 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 \
@@ -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
@@ -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
index 26832d32e8..41c4e203fc 100644
--- 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
index d825b72ace..f840de52c3 100644
--- 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
index bcaffe19b5..8adc70fdd9 100644
--- 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
index da180fe146..e66756912b 100644
--- 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
index 294caedc92..acfdfa2055 100644
--- 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
index 74c60a4c10..aeceb262e9 100644
--- 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
index 8ceec4a481..5351b489a8 100644
--- 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 b/kernel/aster-nix/Cargo.toml
deleted file mode 100644
index 219b372561..0000000000
--- 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 b/kernel/aster-nix/src/lib.rs
deleted file mode 100644
index 72ea970ee7..0000000000
--- 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
index 7cf1eed61c..1a86f898d0 100644
--- 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/arch/mod.rs b/kernel/src/arch/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/arch/mod.rs
rename to kernel/src/arch/mod.rs
diff --git a/kernel/aster-nix/src/arch/x86/cpu.rs b/kernel/src/arch/x86/cpu.rs
similarity index 100%
rename from kernel/aster-nix/src/arch/x86/cpu.rs
rename to kernel/src/arch/x86/cpu.rs
diff --git a/kernel/aster-nix/src/arch/x86/mod.rs b/kernel/src/arch/x86/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/arch/x86/mod.rs
rename to kernel/src/arch/x86/mod.rs
diff --git a/kernel/aster-nix/src/arch/x86/signal.rs b/kernel/src/arch/x86/signal.rs
similarity index 100%
rename from kernel/aster-nix/src/arch/x86/signal.rs
rename to kernel/src/arch/x86/signal.rs
diff --git a/kernel/aster-nix/src/console.rs b/kernel/src/console.rs
similarity index 100%
rename from kernel/aster-nix/src/console.rs
rename to kernel/src/console.rs
diff --git a/kernel/aster-nix/src/context.rs b/kernel/src/context.rs
similarity index 100%
rename from kernel/aster-nix/src/context.rs
rename to kernel/src/context.rs
diff --git a/kernel/aster-nix/src/cpu.rs b/kernel/src/cpu.rs
similarity index 100%
rename from kernel/aster-nix/src/cpu.rs
rename to kernel/src/cpu.rs
diff --git a/kernel/aster-nix/src/device/mod.rs b/kernel/src/device/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/device/mod.rs
rename to kernel/src/device/mod.rs
diff --git a/kernel/aster-nix/src/device/null.rs b/kernel/src/device/null.rs
similarity index 100%
rename from kernel/aster-nix/src/device/null.rs
rename to kernel/src/device/null.rs
diff --git a/kernel/aster-nix/src/device/pty/mod.rs b/kernel/src/device/pty/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/device/pty/mod.rs
rename to kernel/src/device/pty/mod.rs
diff --git a/kernel/aster-nix/src/device/pty/pty.rs b/kernel/src/device/pty/pty.rs
similarity index 100%
rename from kernel/aster-nix/src/device/pty/pty.rs
rename to kernel/src/device/pty/pty.rs
diff --git a/kernel/aster-nix/src/device/random.rs b/kernel/src/device/random.rs
similarity index 100%
rename from kernel/aster-nix/src/device/random.rs
rename to kernel/src/device/random.rs
diff --git a/kernel/aster-nix/src/device/tdxguest/mod.rs b/kernel/src/device/tdxguest/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/device/tdxguest/mod.rs
rename to kernel/src/device/tdxguest/mod.rs
diff --git a/kernel/aster-nix/src/device/tty/device.rs b/kernel/src/device/tty/device.rs
similarity index 100%
rename from kernel/aster-nix/src/device/tty/device.rs
rename to kernel/src/device/tty/device.rs
diff --git a/kernel/aster-nix/src/device/tty/driver.rs b/kernel/src/device/tty/driver.rs
similarity index 100%
rename from kernel/aster-nix/src/device/tty/driver.rs
rename to kernel/src/device/tty/driver.rs
diff --git a/kernel/aster-nix/src/device/tty/line_discipline.rs b/kernel/src/device/tty/line_discipline.rs
similarity index 100%
rename from kernel/aster-nix/src/device/tty/line_discipline.rs
rename to kernel/src/device/tty/line_discipline.rs
diff --git a/kernel/aster-nix/src/device/tty/mod.rs b/kernel/src/device/tty/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/device/tty/mod.rs
rename to kernel/src/device/tty/mod.rs
diff --git a/kernel/aster-nix/src/device/tty/termio.rs b/kernel/src/device/tty/termio.rs
similarity index 100%
rename from kernel/aster-nix/src/device/tty/termio.rs
rename to kernel/src/device/tty/termio.rs
diff --git a/kernel/aster-nix/src/device/urandom.rs b/kernel/src/device/urandom.rs
similarity index 100%
rename from kernel/aster-nix/src/device/urandom.rs
rename to kernel/src/device/urandom.rs
diff --git a/kernel/aster-nix/src/device/zero.rs b/kernel/src/device/zero.rs
similarity index 100%
rename from kernel/aster-nix/src/device/zero.rs
rename to kernel/src/device/zero.rs
diff --git a/kernel/aster-nix/src/driver/mod.rs b/kernel/src/driver/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/driver/mod.rs
rename to kernel/src/driver/mod.rs
diff --git a/kernel/aster-nix/src/error.rs b/kernel/src/error.rs
similarity index 100%
rename from kernel/aster-nix/src/error.rs
rename to kernel/src/error.rs
diff --git a/kernel/aster-nix/src/events/events.rs b/kernel/src/events/events.rs
similarity index 100%
rename from kernel/aster-nix/src/events/events.rs
rename to kernel/src/events/events.rs
diff --git a/kernel/aster-nix/src/events/io_events.rs b/kernel/src/events/io_events.rs
similarity index 100%
rename from kernel/aster-nix/src/events/io_events.rs
rename to kernel/src/events/io_events.rs
diff --git a/kernel/aster-nix/src/events/mod.rs b/kernel/src/events/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/events/mod.rs
rename to kernel/src/events/mod.rs
diff --git a/kernel/aster-nix/src/events/observer.rs b/kernel/src/events/observer.rs
similarity index 100%
rename from kernel/aster-nix/src/events/observer.rs
rename to kernel/src/events/observer.rs
diff --git a/kernel/aster-nix/src/events/subject.rs b/kernel/src/events/subject.rs
similarity index 100%
rename from kernel/aster-nix/src/events/subject.rs
rename to kernel/src/events/subject.rs
diff --git a/kernel/aster-nix/src/fs/device.rs b/kernel/src/fs/device.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/device.rs
rename to kernel/src/fs/device.rs
diff --git a/kernel/aster-nix/src/fs/devpts/mod.rs b/kernel/src/fs/devpts/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/devpts/mod.rs
rename to kernel/src/fs/devpts/mod.rs
diff --git a/kernel/aster-nix/src/fs/devpts/ptmx.rs b/kernel/src/fs/devpts/ptmx.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/devpts/ptmx.rs
rename to kernel/src/fs/devpts/ptmx.rs
diff --git a/kernel/aster-nix/src/fs/devpts/slave.rs b/kernel/src/fs/devpts/slave.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/devpts/slave.rs
rename to kernel/src/fs/devpts/slave.rs
diff --git a/kernel/aster-nix/src/fs/epoll/epoll_file.rs b/kernel/src/fs/epoll/epoll_file.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/epoll/epoll_file.rs
rename to kernel/src/fs/epoll/epoll_file.rs
diff --git a/kernel/aster-nix/src/fs/epoll/mod.rs b/kernel/src/fs/epoll/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/epoll/mod.rs
rename to kernel/src/fs/epoll/mod.rs
diff --git a/kernel/aster-nix/src/fs/exfat/bitmap.rs b/kernel/src/fs/exfat/bitmap.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/exfat/bitmap.rs
rename to kernel/src/fs/exfat/bitmap.rs
diff --git a/kernel/aster-nix/src/fs/exfat/constants.rs b/kernel/src/fs/exfat/constants.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/exfat/constants.rs
rename to kernel/src/fs/exfat/constants.rs
diff --git a/kernel/aster-nix/src/fs/exfat/dentry.rs b/kernel/src/fs/exfat/dentry.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/exfat/dentry.rs
rename to kernel/src/fs/exfat/dentry.rs
diff --git a/kernel/aster-nix/src/fs/exfat/fat.rs b/kernel/src/fs/exfat/fat.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/exfat/fat.rs
rename to kernel/src/fs/exfat/fat.rs
diff --git a/kernel/aster-nix/src/fs/exfat/fs.rs b/kernel/src/fs/exfat/fs.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/exfat/fs.rs
rename to kernel/src/fs/exfat/fs.rs
diff --git a/kernel/aster-nix/src/fs/exfat/inode.rs b/kernel/src/fs/exfat/inode.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/exfat/inode.rs
rename to kernel/src/fs/exfat/inode.rs
diff --git a/kernel/aster-nix/src/fs/exfat/mod.rs b/kernel/src/fs/exfat/mod.rs
similarity index 99%
rename from kernel/aster-nix/src/fs/exfat/mod.rs
rename to kernel/src/fs/exfat/mod.rs
index fb2a770091..b748f32a2d 100644
--- 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 {
@@ -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()
);
@@ -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()
);
@@ -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/super_block.rs b/kernel/src/fs/exfat/super_block.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/exfat/super_block.rs
rename to kernel/src/fs/exfat/super_block.rs
diff --git a/kernel/aster-nix/src/fs/exfat/upcase_table.rs b/kernel/src/fs/exfat/upcase_table.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/exfat/upcase_table.rs
rename to kernel/src/fs/exfat/upcase_table.rs
diff --git a/kernel/aster-nix/src/fs/exfat/utils.rs b/kernel/src/fs/exfat/utils.rs
similarity index 98%
rename from kernel/aster-nix/src/fs/exfat/utils.rs
rename to kernel/src/fs/exfat/utils.rs
index 3eb2355afe..41e41979af 100644
--- 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())
}
@@ -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/ext2/block_group.rs b/kernel/src/fs/ext2/block_group.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/ext2/block_group.rs
rename to kernel/src/fs/ext2/block_group.rs
diff --git a/kernel/aster-nix/src/fs/ext2/block_ptr.rs b/kernel/src/fs/ext2/block_ptr.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/ext2/block_ptr.rs
rename to kernel/src/fs/ext2/block_ptr.rs
diff --git a/kernel/aster-nix/src/fs/ext2/blocks_hole.rs b/kernel/src/fs/ext2/blocks_hole.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/ext2/blocks_hole.rs
rename to kernel/src/fs/ext2/blocks_hole.rs
diff --git a/kernel/aster-nix/src/fs/ext2/dir.rs b/kernel/src/fs/ext2/dir.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/ext2/dir.rs
rename to kernel/src/fs/ext2/dir.rs
diff --git a/kernel/aster-nix/src/fs/ext2/fs.rs b/kernel/src/fs/ext2/fs.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/ext2/fs.rs
rename to kernel/src/fs/ext2/fs.rs
diff --git a/kernel/aster-nix/src/fs/ext2/impl_for_vfs/fs.rs b/kernel/src/fs/ext2/impl_for_vfs/fs.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/ext2/impl_for_vfs/fs.rs
rename to kernel/src/fs/ext2/impl_for_vfs/fs.rs
diff --git a/kernel/aster-nix/src/fs/ext2/impl_for_vfs/inode.rs b/kernel/src/fs/ext2/impl_for_vfs/inode.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/ext2/impl_for_vfs/inode.rs
rename to kernel/src/fs/ext2/impl_for_vfs/inode.rs
diff --git a/kernel/aster-nix/src/fs/ext2/impl_for_vfs/mod.rs b/kernel/src/fs/ext2/impl_for_vfs/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/ext2/impl_for_vfs/mod.rs
rename to kernel/src/fs/ext2/impl_for_vfs/mod.rs
diff --git a/kernel/aster-nix/src/fs/ext2/indirect_block_cache.rs b/kernel/src/fs/ext2/indirect_block_cache.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/ext2/indirect_block_cache.rs
rename to kernel/src/fs/ext2/indirect_block_cache.rs
diff --git a/kernel/aster-nix/src/fs/ext2/inode.rs b/kernel/src/fs/ext2/inode.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/ext2/inode.rs
rename to kernel/src/fs/ext2/inode.rs
diff --git a/kernel/aster-nix/src/fs/ext2/mod.rs b/kernel/src/fs/ext2/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/ext2/mod.rs
rename to kernel/src/fs/ext2/mod.rs
diff --git a/kernel/aster-nix/src/fs/ext2/prelude.rs b/kernel/src/fs/ext2/prelude.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/ext2/prelude.rs
rename to kernel/src/fs/ext2/prelude.rs
diff --git a/kernel/aster-nix/src/fs/ext2/super_block.rs b/kernel/src/fs/ext2/super_block.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/ext2/super_block.rs
rename to kernel/src/fs/ext2/super_block.rs
diff --git a/kernel/aster-nix/src/fs/ext2/utils.rs b/kernel/src/fs/ext2/utils.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/ext2/utils.rs
rename to kernel/src/fs/ext2/utils.rs
diff --git a/kernel/aster-nix/src/fs/file_handle.rs b/kernel/src/fs/file_handle.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/file_handle.rs
rename to kernel/src/fs/file_handle.rs
diff --git a/kernel/aster-nix/src/fs/file_table.rs b/kernel/src/fs/file_table.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/file_table.rs
rename to kernel/src/fs/file_table.rs
diff --git a/kernel/aster-nix/src/fs/fs_resolver.rs b/kernel/src/fs/fs_resolver.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/fs_resolver.rs
rename to kernel/src/fs/fs_resolver.rs
diff --git a/kernel/aster-nix/src/fs/inode_handle/dyn_cap.rs b/kernel/src/fs/inode_handle/dyn_cap.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/inode_handle/dyn_cap.rs
rename to kernel/src/fs/inode_handle/dyn_cap.rs
diff --git a/kernel/aster-nix/src/fs/inode_handle/mod.rs b/kernel/src/fs/inode_handle/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/inode_handle/mod.rs
rename to kernel/src/fs/inode_handle/mod.rs
diff --git a/kernel/aster-nix/src/fs/inode_handle/static_cap.rs b/kernel/src/fs/inode_handle/static_cap.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/inode_handle/static_cap.rs
rename to kernel/src/fs/inode_handle/static_cap.rs
diff --git a/kernel/aster-nix/src/fs/mod.rs b/kernel/src/fs/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/mod.rs
rename to kernel/src/fs/mod.rs
diff --git a/kernel/aster-nix/src/fs/named_pipe.rs b/kernel/src/fs/named_pipe.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/named_pipe.rs
rename to kernel/src/fs/named_pipe.rs
diff --git a/kernel/aster-nix/src/fs/path/dentry.rs b/kernel/src/fs/path/dentry.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/path/dentry.rs
rename to kernel/src/fs/path/dentry.rs
diff --git a/kernel/aster-nix/src/fs/path/mod.rs b/kernel/src/fs/path/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/path/mod.rs
rename to kernel/src/fs/path/mod.rs
diff --git a/kernel/aster-nix/src/fs/path/mount.rs b/kernel/src/fs/path/mount.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/path/mount.rs
rename to kernel/src/fs/path/mount.rs
diff --git a/kernel/aster-nix/src/fs/pipe.rs b/kernel/src/fs/pipe.rs
similarity index 99%
rename from kernel/aster-nix/src/fs/pipe.rs
rename to kernel/src/fs/pipe.rs
index 2340437729..ee676475c3 100644
--- 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);
@@ -350,7 +350,7 @@ mod test {
Errno::EPIPE
);
},
- |reader| drop(reader),
+ drop,
Ordering::WriteThenRead,
);
}
diff --git a/kernel/aster-nix/src/fs/procfs/filesystems.rs b/kernel/src/fs/procfs/filesystems.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/procfs/filesystems.rs
rename to kernel/src/fs/procfs/filesystems.rs
diff --git a/kernel/aster-nix/src/fs/procfs/meminfo.rs b/kernel/src/fs/procfs/meminfo.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/procfs/meminfo.rs
rename to kernel/src/fs/procfs/meminfo.rs
diff --git a/kernel/aster-nix/src/fs/procfs/mod.rs b/kernel/src/fs/procfs/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/procfs/mod.rs
rename to kernel/src/fs/procfs/mod.rs
diff --git a/kernel/aster-nix/src/fs/procfs/pid/cmdline.rs b/kernel/src/fs/procfs/pid/cmdline.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/procfs/pid/cmdline.rs
rename to kernel/src/fs/procfs/pid/cmdline.rs
diff --git a/kernel/aster-nix/src/fs/procfs/pid/comm.rs b/kernel/src/fs/procfs/pid/comm.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/procfs/pid/comm.rs
rename to kernel/src/fs/procfs/pid/comm.rs
diff --git a/kernel/aster-nix/src/fs/procfs/pid/exe.rs b/kernel/src/fs/procfs/pid/exe.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/procfs/pid/exe.rs
rename to kernel/src/fs/procfs/pid/exe.rs
diff --git a/kernel/aster-nix/src/fs/procfs/pid/fd.rs b/kernel/src/fs/procfs/pid/fd.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/procfs/pid/fd.rs
rename to kernel/src/fs/procfs/pid/fd.rs
diff --git a/kernel/aster-nix/src/fs/procfs/pid/mod.rs b/kernel/src/fs/procfs/pid/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/procfs/pid/mod.rs
rename to kernel/src/fs/procfs/pid/mod.rs
diff --git a/kernel/aster-nix/src/fs/procfs/self_.rs b/kernel/src/fs/procfs/self_.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/procfs/self_.rs
rename to kernel/src/fs/procfs/self_.rs
diff --git a/kernel/aster-nix/src/fs/procfs/sys/kernel/cap_last_cap.rs b/kernel/src/fs/procfs/sys/kernel/cap_last_cap.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/procfs/sys/kernel/cap_last_cap.rs
rename to kernel/src/fs/procfs/sys/kernel/cap_last_cap.rs
diff --git a/kernel/aster-nix/src/fs/procfs/sys/kernel/mod.rs b/kernel/src/fs/procfs/sys/kernel/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/procfs/sys/kernel/mod.rs
rename to kernel/src/fs/procfs/sys/kernel/mod.rs
diff --git a/kernel/aster-nix/src/fs/procfs/sys/mod.rs b/kernel/src/fs/procfs/sys/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/procfs/sys/mod.rs
rename to kernel/src/fs/procfs/sys/mod.rs
diff --git a/kernel/aster-nix/src/fs/procfs/template/builder.rs b/kernel/src/fs/procfs/template/builder.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/procfs/template/builder.rs
rename to kernel/src/fs/procfs/template/builder.rs
diff --git a/kernel/aster-nix/src/fs/procfs/template/dir.rs b/kernel/src/fs/procfs/template/dir.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/procfs/template/dir.rs
rename to kernel/src/fs/procfs/template/dir.rs
diff --git a/kernel/aster-nix/src/fs/procfs/template/file.rs b/kernel/src/fs/procfs/template/file.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/procfs/template/file.rs
rename to kernel/src/fs/procfs/template/file.rs
diff --git a/kernel/aster-nix/src/fs/procfs/template/mod.rs b/kernel/src/fs/procfs/template/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/procfs/template/mod.rs
rename to kernel/src/fs/procfs/template/mod.rs
diff --git a/kernel/aster-nix/src/fs/procfs/template/sym.rs b/kernel/src/fs/procfs/template/sym.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/procfs/template/sym.rs
rename to kernel/src/fs/procfs/template/sym.rs
diff --git a/kernel/aster-nix/src/fs/ramfs/fs.rs b/kernel/src/fs/ramfs/fs.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/ramfs/fs.rs
rename to kernel/src/fs/ramfs/fs.rs
diff --git a/kernel/aster-nix/src/fs/ramfs/mod.rs b/kernel/src/fs/ramfs/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/ramfs/mod.rs
rename to kernel/src/fs/ramfs/mod.rs
diff --git a/kernel/aster-nix/src/fs/rootfs.rs b/kernel/src/fs/rootfs.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/rootfs.rs
rename to kernel/src/fs/rootfs.rs
diff --git a/kernel/aster-nix/src/fs/utils/access_mode.rs b/kernel/src/fs/utils/access_mode.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/utils/access_mode.rs
rename to kernel/src/fs/utils/access_mode.rs
diff --git a/kernel/aster-nix/src/fs/utils/channel.rs b/kernel/src/fs/utils/channel.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/utils/channel.rs
rename to kernel/src/fs/utils/channel.rs
diff --git a/kernel/aster-nix/src/fs/utils/creation_flags.rs b/kernel/src/fs/utils/creation_flags.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/utils/creation_flags.rs
rename to kernel/src/fs/utils/creation_flags.rs
diff --git a/kernel/aster-nix/src/fs/utils/dirent_visitor.rs b/kernel/src/fs/utils/dirent_visitor.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/utils/dirent_visitor.rs
rename to kernel/src/fs/utils/dirent_visitor.rs
diff --git a/kernel/aster-nix/src/fs/utils/direntry_vec.rs b/kernel/src/fs/utils/direntry_vec.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/utils/direntry_vec.rs
rename to kernel/src/fs/utils/direntry_vec.rs
diff --git a/kernel/aster-nix/src/fs/utils/falloc_mode.rs b/kernel/src/fs/utils/falloc_mode.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/utils/falloc_mode.rs
rename to kernel/src/fs/utils/falloc_mode.rs
diff --git a/kernel/aster-nix/src/fs/utils/file_creation_mask.rs b/kernel/src/fs/utils/file_creation_mask.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/utils/file_creation_mask.rs
rename to kernel/src/fs/utils/file_creation_mask.rs
diff --git a/kernel/aster-nix/src/fs/utils/flock.rs b/kernel/src/fs/utils/flock.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/utils/flock.rs
rename to kernel/src/fs/utils/flock.rs
diff --git a/kernel/aster-nix/src/fs/utils/fs.rs b/kernel/src/fs/utils/fs.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/utils/fs.rs
rename to kernel/src/fs/utils/fs.rs
diff --git a/kernel/aster-nix/src/fs/utils/inode.rs b/kernel/src/fs/utils/inode.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/utils/inode.rs
rename to kernel/src/fs/utils/inode.rs
diff --git a/kernel/aster-nix/src/fs/utils/ioctl.rs b/kernel/src/fs/utils/ioctl.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/utils/ioctl.rs
rename to kernel/src/fs/utils/ioctl.rs
diff --git a/kernel/aster-nix/src/fs/utils/mod.rs b/kernel/src/fs/utils/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/utils/mod.rs
rename to kernel/src/fs/utils/mod.rs
diff --git a/kernel/aster-nix/src/fs/utils/page_cache.rs b/kernel/src/fs/utils/page_cache.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/utils/page_cache.rs
rename to kernel/src/fs/utils/page_cache.rs
diff --git a/kernel/aster-nix/src/fs/utils/range_lock/builder.rs b/kernel/src/fs/utils/range_lock/builder.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/utils/range_lock/builder.rs
rename to kernel/src/fs/utils/range_lock/builder.rs
diff --git a/kernel/aster-nix/src/fs/utils/range_lock/mod.rs b/kernel/src/fs/utils/range_lock/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/utils/range_lock/mod.rs
rename to kernel/src/fs/utils/range_lock/mod.rs
diff --git a/kernel/aster-nix/src/fs/utils/range_lock/range.rs b/kernel/src/fs/utils/range_lock/range.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/utils/range_lock/range.rs
rename to kernel/src/fs/utils/range_lock/range.rs
diff --git a/kernel/aster-nix/src/fs/utils/status_flags.rs b/kernel/src/fs/utils/status_flags.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/utils/status_flags.rs
rename to kernel/src/fs/utils/status_flags.rs
diff --git a/kernel/aster-nix/src/ipc/mod.rs b/kernel/src/ipc/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/ipc/mod.rs
rename to kernel/src/ipc/mod.rs
diff --git a/kernel/aster-nix/src/ipc/semaphore/mod.rs b/kernel/src/ipc/semaphore/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/ipc/semaphore/mod.rs
rename to kernel/src/ipc/semaphore/mod.rs
diff --git a/kernel/aster-nix/src/ipc/semaphore/posix/mod.rs b/kernel/src/ipc/semaphore/posix/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/ipc/semaphore/posix/mod.rs
rename to kernel/src/ipc/semaphore/posix/mod.rs
diff --git a/kernel/aster-nix/src/ipc/semaphore/system_v/mod.rs b/kernel/src/ipc/semaphore/system_v/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/ipc/semaphore/system_v/mod.rs
rename to kernel/src/ipc/semaphore/system_v/mod.rs
diff --git a/kernel/aster-nix/src/ipc/semaphore/system_v/sem.rs b/kernel/src/ipc/semaphore/system_v/sem.rs
similarity index 100%
rename from kernel/aster-nix/src/ipc/semaphore/system_v/sem.rs
rename to kernel/src/ipc/semaphore/system_v/sem.rs
diff --git a/kernel/aster-nix/src/ipc/semaphore/system_v/sem_set.rs b/kernel/src/ipc/semaphore/system_v/sem_set.rs
similarity index 100%
rename from kernel/aster-nix/src/ipc/semaphore/system_v/sem_set.rs
rename to kernel/src/ipc/semaphore/system_v/sem_set.rs
diff --git a/kernel/src/lib.rs b/kernel/src/lib.rs
index dd59f76b09..96e14678ff 100644
--- 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/net/iface/any_socket.rs b/kernel/src/net/iface/any_socket.rs
similarity index 100%
rename from kernel/aster-nix/src/net/iface/any_socket.rs
rename to kernel/src/net/iface/any_socket.rs
diff --git a/kernel/aster-nix/src/net/iface/common.rs b/kernel/src/net/iface/common.rs
similarity index 100%
rename from kernel/aster-nix/src/net/iface/common.rs
rename to kernel/src/net/iface/common.rs
diff --git a/kernel/aster-nix/src/net/iface/loopback.rs b/kernel/src/net/iface/loopback.rs
similarity index 100%
rename from kernel/aster-nix/src/net/iface/loopback.rs
rename to kernel/src/net/iface/loopback.rs
diff --git a/kernel/aster-nix/src/net/iface/mod.rs b/kernel/src/net/iface/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/net/iface/mod.rs
rename to kernel/src/net/iface/mod.rs
diff --git a/kernel/aster-nix/src/net/iface/time.rs b/kernel/src/net/iface/time.rs
similarity index 100%
rename from kernel/aster-nix/src/net/iface/time.rs
rename to kernel/src/net/iface/time.rs
diff --git a/kernel/aster-nix/src/net/iface/util.rs b/kernel/src/net/iface/util.rs
similarity index 100%
rename from kernel/aster-nix/src/net/iface/util.rs
rename to kernel/src/net/iface/util.rs
diff --git a/kernel/aster-nix/src/net/iface/virtio.rs b/kernel/src/net/iface/virtio.rs
similarity index 100%
rename from kernel/aster-nix/src/net/iface/virtio.rs
rename to kernel/src/net/iface/virtio.rs
diff --git a/kernel/aster-nix/src/net/mod.rs b/kernel/src/net/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/net/mod.rs
rename to kernel/src/net/mod.rs
diff --git a/kernel/aster-nix/src/net/socket/ip/addr.rs b/kernel/src/net/socket/ip/addr.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/ip/addr.rs
rename to kernel/src/net/socket/ip/addr.rs
diff --git a/kernel/aster-nix/src/net/socket/ip/common.rs b/kernel/src/net/socket/ip/common.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/ip/common.rs
rename to kernel/src/net/socket/ip/common.rs
diff --git a/kernel/aster-nix/src/net/socket/ip/datagram/bound.rs b/kernel/src/net/socket/ip/datagram/bound.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/ip/datagram/bound.rs
rename to kernel/src/net/socket/ip/datagram/bound.rs
diff --git a/kernel/aster-nix/src/net/socket/ip/datagram/mod.rs b/kernel/src/net/socket/ip/datagram/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/ip/datagram/mod.rs
rename to kernel/src/net/socket/ip/datagram/mod.rs
diff --git a/kernel/aster-nix/src/net/socket/ip/datagram/unbound.rs b/kernel/src/net/socket/ip/datagram/unbound.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/ip/datagram/unbound.rs
rename to kernel/src/net/socket/ip/datagram/unbound.rs
diff --git a/kernel/aster-nix/src/net/socket/ip/mod.rs b/kernel/src/net/socket/ip/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/ip/mod.rs
rename to kernel/src/net/socket/ip/mod.rs
diff --git a/kernel/aster-nix/src/net/socket/ip/stream/connected.rs b/kernel/src/net/socket/ip/stream/connected.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/ip/stream/connected.rs
rename to kernel/src/net/socket/ip/stream/connected.rs
diff --git a/kernel/aster-nix/src/net/socket/ip/stream/connecting.rs b/kernel/src/net/socket/ip/stream/connecting.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/ip/stream/connecting.rs
rename to kernel/src/net/socket/ip/stream/connecting.rs
diff --git a/kernel/aster-nix/src/net/socket/ip/stream/init.rs b/kernel/src/net/socket/ip/stream/init.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/ip/stream/init.rs
rename to kernel/src/net/socket/ip/stream/init.rs
diff --git a/kernel/aster-nix/src/net/socket/ip/stream/listen.rs b/kernel/src/net/socket/ip/stream/listen.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/ip/stream/listen.rs
rename to kernel/src/net/socket/ip/stream/listen.rs
diff --git a/kernel/aster-nix/src/net/socket/ip/stream/mod.rs b/kernel/src/net/socket/ip/stream/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/ip/stream/mod.rs
rename to kernel/src/net/socket/ip/stream/mod.rs
diff --git a/kernel/aster-nix/src/net/socket/ip/stream/options.rs b/kernel/src/net/socket/ip/stream/options.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/ip/stream/options.rs
rename to kernel/src/net/socket/ip/stream/options.rs
diff --git a/kernel/aster-nix/src/net/socket/ip/stream/util.rs b/kernel/src/net/socket/ip/stream/util.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/ip/stream/util.rs
rename to kernel/src/net/socket/ip/stream/util.rs
diff --git a/kernel/aster-nix/src/net/socket/mod.rs b/kernel/src/net/socket/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/mod.rs
rename to kernel/src/net/socket/mod.rs
diff --git a/kernel/aster-nix/src/net/socket/options/macros.rs b/kernel/src/net/socket/options/macros.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/options/macros.rs
rename to kernel/src/net/socket/options/macros.rs
diff --git a/kernel/aster-nix/src/net/socket/options/mod.rs b/kernel/src/net/socket/options/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/options/mod.rs
rename to kernel/src/net/socket/options/mod.rs
diff --git a/kernel/aster-nix/src/net/socket/unix/addr.rs b/kernel/src/net/socket/unix/addr.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/unix/addr.rs
rename to kernel/src/net/socket/unix/addr.rs
diff --git a/kernel/aster-nix/src/net/socket/unix/mod.rs b/kernel/src/net/socket/unix/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/unix/mod.rs
rename to kernel/src/net/socket/unix/mod.rs
diff --git a/kernel/aster-nix/src/net/socket/unix/stream/connected.rs b/kernel/src/net/socket/unix/stream/connected.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/unix/stream/connected.rs
rename to kernel/src/net/socket/unix/stream/connected.rs
diff --git a/kernel/aster-nix/src/net/socket/unix/stream/init.rs b/kernel/src/net/socket/unix/stream/init.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/unix/stream/init.rs
rename to kernel/src/net/socket/unix/stream/init.rs
diff --git a/kernel/aster-nix/src/net/socket/unix/stream/listener.rs b/kernel/src/net/socket/unix/stream/listener.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/unix/stream/listener.rs
rename to kernel/src/net/socket/unix/stream/listener.rs
diff --git a/kernel/aster-nix/src/net/socket/unix/stream/mod.rs b/kernel/src/net/socket/unix/stream/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/unix/stream/mod.rs
rename to kernel/src/net/socket/unix/stream/mod.rs
diff --git a/kernel/aster-nix/src/net/socket/unix/stream/socket.rs b/kernel/src/net/socket/unix/stream/socket.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/unix/stream/socket.rs
rename to kernel/src/net/socket/unix/stream/socket.rs
diff --git a/kernel/aster-nix/src/net/socket/util/message_header.rs b/kernel/src/net/socket/util/message_header.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/util/message_header.rs
rename to kernel/src/net/socket/util/message_header.rs
diff --git a/kernel/aster-nix/src/net/socket/util/mod.rs b/kernel/src/net/socket/util/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/util/mod.rs
rename to kernel/src/net/socket/util/mod.rs
diff --git a/kernel/aster-nix/src/net/socket/util/options.rs b/kernel/src/net/socket/util/options.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/util/options.rs
rename to kernel/src/net/socket/util/options.rs
diff --git a/kernel/aster-nix/src/net/socket/util/send_recv_flags.rs b/kernel/src/net/socket/util/send_recv_flags.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/util/send_recv_flags.rs
rename to kernel/src/net/socket/util/send_recv_flags.rs
diff --git a/kernel/aster-nix/src/net/socket/util/shutdown_cmd.rs b/kernel/src/net/socket/util/shutdown_cmd.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/util/shutdown_cmd.rs
rename to kernel/src/net/socket/util/shutdown_cmd.rs
diff --git a/kernel/aster-nix/src/net/socket/util/socket_addr.rs b/kernel/src/net/socket/util/socket_addr.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/util/socket_addr.rs
rename to kernel/src/net/socket/util/socket_addr.rs
diff --git a/kernel/aster-nix/src/net/socket/vsock/addr.rs b/kernel/src/net/socket/vsock/addr.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/vsock/addr.rs
rename to kernel/src/net/socket/vsock/addr.rs
diff --git a/kernel/aster-nix/src/net/socket/vsock/common.rs b/kernel/src/net/socket/vsock/common.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/vsock/common.rs
rename to kernel/src/net/socket/vsock/common.rs
diff --git a/kernel/aster-nix/src/net/socket/vsock/mod.rs b/kernel/src/net/socket/vsock/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/vsock/mod.rs
rename to kernel/src/net/socket/vsock/mod.rs
diff --git a/kernel/aster-nix/src/net/socket/vsock/stream/connected.rs b/kernel/src/net/socket/vsock/stream/connected.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/vsock/stream/connected.rs
rename to kernel/src/net/socket/vsock/stream/connected.rs
diff --git a/kernel/aster-nix/src/net/socket/vsock/stream/connecting.rs b/kernel/src/net/socket/vsock/stream/connecting.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/vsock/stream/connecting.rs
rename to kernel/src/net/socket/vsock/stream/connecting.rs
diff --git a/kernel/aster-nix/src/net/socket/vsock/stream/init.rs b/kernel/src/net/socket/vsock/stream/init.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/vsock/stream/init.rs
rename to kernel/src/net/socket/vsock/stream/init.rs
diff --git a/kernel/aster-nix/src/net/socket/vsock/stream/listen.rs b/kernel/src/net/socket/vsock/stream/listen.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/vsock/stream/listen.rs
rename to kernel/src/net/socket/vsock/stream/listen.rs
diff --git a/kernel/aster-nix/src/net/socket/vsock/stream/mod.rs b/kernel/src/net/socket/vsock/stream/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/vsock/stream/mod.rs
rename to kernel/src/net/socket/vsock/stream/mod.rs
diff --git a/kernel/aster-nix/src/net/socket/vsock/stream/socket.rs b/kernel/src/net/socket/vsock/stream/socket.rs
similarity index 100%
rename from kernel/aster-nix/src/net/socket/vsock/stream/socket.rs
rename to kernel/src/net/socket/vsock/stream/socket.rs
diff --git a/kernel/aster-nix/src/prelude.rs b/kernel/src/prelude.rs
similarity index 100%
rename from kernel/aster-nix/src/prelude.rs
rename to kernel/src/prelude.rs
diff --git a/kernel/aster-nix/src/process/clone.rs b/kernel/src/process/clone.rs
similarity index 100%
rename from kernel/aster-nix/src/process/clone.rs
rename to kernel/src/process/clone.rs
diff --git a/kernel/aster-nix/src/process/credentials/c_types.rs b/kernel/src/process/credentials/c_types.rs
similarity index 100%
rename from kernel/aster-nix/src/process/credentials/c_types.rs
rename to kernel/src/process/credentials/c_types.rs
diff --git a/kernel/aster-nix/src/process/credentials/capabilities.rs b/kernel/src/process/credentials/capabilities.rs
similarity index 100%
rename from kernel/aster-nix/src/process/credentials/capabilities.rs
rename to kernel/src/process/credentials/capabilities.rs
diff --git a/kernel/aster-nix/src/process/credentials/credentials_.rs b/kernel/src/process/credentials/credentials_.rs
similarity index 100%
rename from kernel/aster-nix/src/process/credentials/credentials_.rs
rename to kernel/src/process/credentials/credentials_.rs
diff --git a/kernel/aster-nix/src/process/credentials/group.rs b/kernel/src/process/credentials/group.rs
similarity index 100%
rename from kernel/aster-nix/src/process/credentials/group.rs
rename to kernel/src/process/credentials/group.rs
diff --git a/kernel/aster-nix/src/process/credentials/mod.rs b/kernel/src/process/credentials/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/process/credentials/mod.rs
rename to kernel/src/process/credentials/mod.rs
diff --git a/kernel/aster-nix/src/process/credentials/static_cap.rs b/kernel/src/process/credentials/static_cap.rs
similarity index 100%
rename from kernel/aster-nix/src/process/credentials/static_cap.rs
rename to kernel/src/process/credentials/static_cap.rs
diff --git a/kernel/aster-nix/src/process/credentials/user.rs b/kernel/src/process/credentials/user.rs
similarity index 100%
rename from kernel/aster-nix/src/process/credentials/user.rs
rename to kernel/src/process/credentials/user.rs
diff --git a/kernel/aster-nix/src/process/exit.rs b/kernel/src/process/exit.rs
similarity index 100%
rename from kernel/aster-nix/src/process/exit.rs
rename to kernel/src/process/exit.rs
diff --git a/kernel/aster-nix/src/process/kill.rs b/kernel/src/process/kill.rs
similarity index 100%
rename from kernel/aster-nix/src/process/kill.rs
rename to kernel/src/process/kill.rs
diff --git a/kernel/aster-nix/src/process/mod.rs b/kernel/src/process/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/process/mod.rs
rename to kernel/src/process/mod.rs
diff --git a/kernel/aster-nix/src/process/posix_thread/builder.rs b/kernel/src/process/posix_thread/builder.rs
similarity index 100%
rename from kernel/aster-nix/src/process/posix_thread/builder.rs
rename to kernel/src/process/posix_thread/builder.rs
diff --git a/kernel/aster-nix/src/process/posix_thread/exit.rs b/kernel/src/process/posix_thread/exit.rs
similarity index 100%
rename from kernel/aster-nix/src/process/posix_thread/exit.rs
rename to kernel/src/process/posix_thread/exit.rs
diff --git a/kernel/aster-nix/src/process/posix_thread/futex.rs b/kernel/src/process/posix_thread/futex.rs
similarity index 100%
rename from kernel/aster-nix/src/process/posix_thread/futex.rs
rename to kernel/src/process/posix_thread/futex.rs
diff --git a/kernel/aster-nix/src/process/posix_thread/mod.rs b/kernel/src/process/posix_thread/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/process/posix_thread/mod.rs
rename to kernel/src/process/posix_thread/mod.rs
diff --git a/kernel/aster-nix/src/process/posix_thread/name.rs b/kernel/src/process/posix_thread/name.rs
similarity index 100%
rename from kernel/aster-nix/src/process/posix_thread/name.rs
rename to kernel/src/process/posix_thread/name.rs
diff --git a/kernel/aster-nix/src/process/posix_thread/posix_thread_ext.rs b/kernel/src/process/posix_thread/posix_thread_ext.rs
similarity index 100%
rename from kernel/aster-nix/src/process/posix_thread/posix_thread_ext.rs
rename to kernel/src/process/posix_thread/posix_thread_ext.rs
diff --git a/kernel/aster-nix/src/process/posix_thread/robust_list.rs b/kernel/src/process/posix_thread/robust_list.rs
similarity index 100%
rename from kernel/aster-nix/src/process/posix_thread/robust_list.rs
rename to kernel/src/process/posix_thread/robust_list.rs
diff --git a/kernel/aster-nix/src/process/process/builder.rs b/kernel/src/process/process/builder.rs
similarity index 100%
rename from kernel/aster-nix/src/process/process/builder.rs
rename to kernel/src/process/process/builder.rs
diff --git a/kernel/aster-nix/src/process/process/job_control.rs b/kernel/src/process/process/job_control.rs
similarity index 100%
rename from kernel/aster-nix/src/process/process/job_control.rs
rename to kernel/src/process/process/job_control.rs
diff --git a/kernel/aster-nix/src/process/process/mod.rs b/kernel/src/process/process/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/process/process/mod.rs
rename to kernel/src/process/process/mod.rs
diff --git a/kernel/aster-nix/src/process/process/process_group.rs b/kernel/src/process/process/process_group.rs
similarity index 100%
rename from kernel/aster-nix/src/process/process/process_group.rs
rename to kernel/src/process/process/process_group.rs
diff --git a/kernel/aster-nix/src/process/process/session.rs b/kernel/src/process/process/session.rs
similarity index 100%
rename from kernel/aster-nix/src/process/process/session.rs
rename to kernel/src/process/process/session.rs
diff --git a/kernel/aster-nix/src/process/process/terminal.rs b/kernel/src/process/process/terminal.rs
similarity index 100%
rename from kernel/aster-nix/src/process/process/terminal.rs
rename to kernel/src/process/process/terminal.rs
diff --git a/kernel/aster-nix/src/process/process/timer_manager.rs b/kernel/src/process/process/timer_manager.rs
similarity index 100%
rename from kernel/aster-nix/src/process/process/timer_manager.rs
rename to kernel/src/process/process/timer_manager.rs
diff --git a/kernel/aster-nix/src/process/process_filter.rs b/kernel/src/process/process_filter.rs
similarity index 100%
rename from kernel/aster-nix/src/process/process_filter.rs
rename to kernel/src/process/process_filter.rs
diff --git a/kernel/aster-nix/src/process/process_table.rs b/kernel/src/process/process_table.rs
similarity index 100%
rename from kernel/aster-nix/src/process/process_table.rs
rename to kernel/src/process/process_table.rs
diff --git a/kernel/aster-nix/src/process/process_vm/heap.rs b/kernel/src/process/process_vm/heap.rs
similarity index 100%
rename from kernel/aster-nix/src/process/process_vm/heap.rs
rename to kernel/src/process/process_vm/heap.rs
diff --git a/kernel/aster-nix/src/process/process_vm/init_stack/aux_vec.rs b/kernel/src/process/process_vm/init_stack/aux_vec.rs
similarity index 100%
rename from kernel/aster-nix/src/process/process_vm/init_stack/aux_vec.rs
rename to kernel/src/process/process_vm/init_stack/aux_vec.rs
diff --git a/kernel/aster-nix/src/process/process_vm/init_stack/mod.rs b/kernel/src/process/process_vm/init_stack/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/process/process_vm/init_stack/mod.rs
rename to kernel/src/process/process_vm/init_stack/mod.rs
diff --git a/kernel/aster-nix/src/process/process_vm/mod.rs b/kernel/src/process/process_vm/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/process/process_vm/mod.rs
rename to kernel/src/process/process_vm/mod.rs
diff --git a/kernel/aster-nix/src/process/program_loader/elf/elf_file.rs b/kernel/src/process/program_loader/elf/elf_file.rs
similarity index 100%
rename from kernel/aster-nix/src/process/program_loader/elf/elf_file.rs
rename to kernel/src/process/program_loader/elf/elf_file.rs
diff --git a/kernel/aster-nix/src/process/program_loader/elf/load_elf.rs b/kernel/src/process/program_loader/elf/load_elf.rs
similarity index 100%
rename from kernel/aster-nix/src/process/program_loader/elf/load_elf.rs
rename to kernel/src/process/program_loader/elf/load_elf.rs
diff --git a/kernel/aster-nix/src/process/program_loader/elf/mod.rs b/kernel/src/process/program_loader/elf/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/process/program_loader/elf/mod.rs
rename to kernel/src/process/program_loader/elf/mod.rs
diff --git a/kernel/aster-nix/src/process/program_loader/mod.rs b/kernel/src/process/program_loader/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/process/program_loader/mod.rs
rename to kernel/src/process/program_loader/mod.rs
diff --git a/kernel/aster-nix/src/process/program_loader/shebang.rs b/kernel/src/process/program_loader/shebang.rs
similarity index 100%
rename from kernel/aster-nix/src/process/program_loader/shebang.rs
rename to kernel/src/process/program_loader/shebang.rs
diff --git a/kernel/aster-nix/src/process/rlimit.rs b/kernel/src/process/rlimit.rs
similarity index 100%
rename from kernel/aster-nix/src/process/rlimit.rs
rename to kernel/src/process/rlimit.rs
diff --git a/kernel/aster-nix/src/process/signal/c_types.rs b/kernel/src/process/signal/c_types.rs
similarity index 100%
rename from kernel/aster-nix/src/process/signal/c_types.rs
rename to kernel/src/process/signal/c_types.rs
diff --git a/kernel/aster-nix/src/process/signal/constants.rs b/kernel/src/process/signal/constants.rs
similarity index 100%
rename from kernel/aster-nix/src/process/signal/constants.rs
rename to kernel/src/process/signal/constants.rs
diff --git a/kernel/aster-nix/src/process/signal/events.rs b/kernel/src/process/signal/events.rs
similarity index 100%
rename from kernel/aster-nix/src/process/signal/events.rs
rename to kernel/src/process/signal/events.rs
diff --git a/kernel/aster-nix/src/process/signal/mod.rs b/kernel/src/process/signal/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/process/signal/mod.rs
rename to kernel/src/process/signal/mod.rs
diff --git a/kernel/aster-nix/src/process/signal/pauser.rs b/kernel/src/process/signal/pauser.rs
similarity index 100%
rename from kernel/aster-nix/src/process/signal/pauser.rs
rename to kernel/src/process/signal/pauser.rs
diff --git a/kernel/aster-nix/src/process/signal/poll.rs b/kernel/src/process/signal/poll.rs
similarity index 100%
rename from kernel/aster-nix/src/process/signal/poll.rs
rename to kernel/src/process/signal/poll.rs
diff --git a/kernel/aster-nix/src/process/signal/sig_action.rs b/kernel/src/process/signal/sig_action.rs
similarity index 100%
rename from kernel/aster-nix/src/process/signal/sig_action.rs
rename to kernel/src/process/signal/sig_action.rs
diff --git a/kernel/aster-nix/src/process/signal/sig_disposition.rs b/kernel/src/process/signal/sig_disposition.rs
similarity index 100%
rename from kernel/aster-nix/src/process/signal/sig_disposition.rs
rename to kernel/src/process/signal/sig_disposition.rs
diff --git a/kernel/aster-nix/src/process/signal/sig_mask.rs b/kernel/src/process/signal/sig_mask.rs
similarity index 100%
rename from kernel/aster-nix/src/process/signal/sig_mask.rs
rename to kernel/src/process/signal/sig_mask.rs
diff --git a/kernel/aster-nix/src/process/signal/sig_num.rs b/kernel/src/process/signal/sig_num.rs
similarity index 100%
rename from kernel/aster-nix/src/process/signal/sig_num.rs
rename to kernel/src/process/signal/sig_num.rs
diff --git a/kernel/aster-nix/src/process/signal/sig_queues.rs b/kernel/src/process/signal/sig_queues.rs
similarity index 100%
rename from kernel/aster-nix/src/process/signal/sig_queues.rs
rename to kernel/src/process/signal/sig_queues.rs
diff --git a/kernel/aster-nix/src/process/signal/sig_stack.rs b/kernel/src/process/signal/sig_stack.rs
similarity index 100%
rename from kernel/aster-nix/src/process/signal/sig_stack.rs
rename to kernel/src/process/signal/sig_stack.rs
diff --git a/kernel/aster-nix/src/process/signal/signals/fault.rs b/kernel/src/process/signal/signals/fault.rs
similarity index 100%
rename from kernel/aster-nix/src/process/signal/signals/fault.rs
rename to kernel/src/process/signal/signals/fault.rs
diff --git a/kernel/aster-nix/src/process/signal/signals/kernel.rs b/kernel/src/process/signal/signals/kernel.rs
similarity index 100%
rename from kernel/aster-nix/src/process/signal/signals/kernel.rs
rename to kernel/src/process/signal/signals/kernel.rs
diff --git a/kernel/aster-nix/src/process/signal/signals/mod.rs b/kernel/src/process/signal/signals/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/process/signal/signals/mod.rs
rename to kernel/src/process/signal/signals/mod.rs
diff --git a/kernel/aster-nix/src/process/signal/signals/user.rs b/kernel/src/process/signal/signals/user.rs
similarity index 100%
rename from kernel/aster-nix/src/process/signal/signals/user.rs
rename to kernel/src/process/signal/signals/user.rs
diff --git a/kernel/aster-nix/src/process/status.rs b/kernel/src/process/status.rs
similarity index 100%
rename from kernel/aster-nix/src/process/status.rs
rename to kernel/src/process/status.rs
diff --git a/kernel/aster-nix/src/process/sync/condvar.rs b/kernel/src/process/sync/condvar.rs
similarity index 98%
rename from kernel/aster-nix/src/process/sync/condvar.rs
rename to kernel/src/process/sync/condvar.rs
index 2f18bc2cec..45ec27e039 100644
--- 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);
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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/process/sync/mod.rs b/kernel/src/process/sync/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/process/sync/mod.rs
rename to kernel/src/process/sync/mod.rs
diff --git a/kernel/aster-nix/src/process/term_status.rs b/kernel/src/process/term_status.rs
similarity index 100%
rename from kernel/aster-nix/src/process/term_status.rs
rename to kernel/src/process/term_status.rs
diff --git a/kernel/aster-nix/src/process/wait.rs b/kernel/src/process/wait.rs
similarity index 100%
rename from kernel/aster-nix/src/process/wait.rs
rename to kernel/src/process/wait.rs
diff --git a/kernel/aster-nix/src/sched/mod.rs b/kernel/src/sched/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/sched/mod.rs
rename to kernel/src/sched/mod.rs
diff --git a/kernel/aster-nix/src/sched/nice.rs b/kernel/src/sched/nice.rs
similarity index 100%
rename from kernel/aster-nix/src/sched/nice.rs
rename to kernel/src/sched/nice.rs
diff --git a/kernel/aster-nix/src/sched/priority_scheduler.rs b/kernel/src/sched/priority_scheduler.rs
similarity index 100%
rename from kernel/aster-nix/src/sched/priority_scheduler.rs
rename to kernel/src/sched/priority_scheduler.rs
diff --git a/kernel/aster-nix/src/softirq_id.rs b/kernel/src/softirq_id.rs
similarity index 100%
rename from kernel/aster-nix/src/softirq_id.rs
rename to kernel/src/softirq_id.rs
diff --git a/kernel/aster-nix/src/syscall/accept.rs b/kernel/src/syscall/accept.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/accept.rs
rename to kernel/src/syscall/accept.rs
diff --git a/kernel/aster-nix/src/syscall/access.rs b/kernel/src/syscall/access.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/access.rs
rename to kernel/src/syscall/access.rs
diff --git a/kernel/aster-nix/src/syscall/alarm.rs b/kernel/src/syscall/alarm.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/alarm.rs
rename to kernel/src/syscall/alarm.rs
diff --git a/kernel/aster-nix/src/syscall/arch/mod.rs b/kernel/src/syscall/arch/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/arch/mod.rs
rename to kernel/src/syscall/arch/mod.rs
diff --git a/kernel/aster-nix/src/syscall/arch/x86.rs b/kernel/src/syscall/arch/x86.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/arch/x86.rs
rename to kernel/src/syscall/arch/x86.rs
diff --git a/kernel/aster-nix/src/syscall/arch_prctl.rs b/kernel/src/syscall/arch_prctl.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/arch_prctl.rs
rename to kernel/src/syscall/arch_prctl.rs
diff --git a/kernel/aster-nix/src/syscall/bind.rs b/kernel/src/syscall/bind.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/bind.rs
rename to kernel/src/syscall/bind.rs
diff --git a/kernel/aster-nix/src/syscall/brk.rs b/kernel/src/syscall/brk.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/brk.rs
rename to kernel/src/syscall/brk.rs
diff --git a/kernel/aster-nix/src/syscall/capget.rs b/kernel/src/syscall/capget.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/capget.rs
rename to kernel/src/syscall/capget.rs
diff --git a/kernel/aster-nix/src/syscall/capset.rs b/kernel/src/syscall/capset.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/capset.rs
rename to kernel/src/syscall/capset.rs
diff --git a/kernel/aster-nix/src/syscall/chdir.rs b/kernel/src/syscall/chdir.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/chdir.rs
rename to kernel/src/syscall/chdir.rs
diff --git a/kernel/aster-nix/src/syscall/chmod.rs b/kernel/src/syscall/chmod.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/chmod.rs
rename to kernel/src/syscall/chmod.rs
diff --git a/kernel/aster-nix/src/syscall/chown.rs b/kernel/src/syscall/chown.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/chown.rs
rename to kernel/src/syscall/chown.rs
diff --git a/kernel/aster-nix/src/syscall/chroot.rs b/kernel/src/syscall/chroot.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/chroot.rs
rename to kernel/src/syscall/chroot.rs
diff --git a/kernel/aster-nix/src/syscall/clock_gettime.rs b/kernel/src/syscall/clock_gettime.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/clock_gettime.rs
rename to kernel/src/syscall/clock_gettime.rs
diff --git a/kernel/aster-nix/src/syscall/clone.rs b/kernel/src/syscall/clone.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/clone.rs
rename to kernel/src/syscall/clone.rs
diff --git a/kernel/aster-nix/src/syscall/close.rs b/kernel/src/syscall/close.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/close.rs
rename to kernel/src/syscall/close.rs
diff --git a/kernel/aster-nix/src/syscall/connect.rs b/kernel/src/syscall/connect.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/connect.rs
rename to kernel/src/syscall/connect.rs
diff --git a/kernel/aster-nix/src/syscall/constants.rs b/kernel/src/syscall/constants.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/constants.rs
rename to kernel/src/syscall/constants.rs
diff --git a/kernel/aster-nix/src/syscall/dup.rs b/kernel/src/syscall/dup.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/dup.rs
rename to kernel/src/syscall/dup.rs
diff --git a/kernel/aster-nix/src/syscall/epoll.rs b/kernel/src/syscall/epoll.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/epoll.rs
rename to kernel/src/syscall/epoll.rs
diff --git a/kernel/aster-nix/src/syscall/eventfd.rs b/kernel/src/syscall/eventfd.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/eventfd.rs
rename to kernel/src/syscall/eventfd.rs
diff --git a/kernel/aster-nix/src/syscall/execve.rs b/kernel/src/syscall/execve.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/execve.rs
rename to kernel/src/syscall/execve.rs
diff --git a/kernel/aster-nix/src/syscall/exit.rs b/kernel/src/syscall/exit.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/exit.rs
rename to kernel/src/syscall/exit.rs
diff --git a/kernel/aster-nix/src/syscall/exit_group.rs b/kernel/src/syscall/exit_group.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/exit_group.rs
rename to kernel/src/syscall/exit_group.rs
diff --git a/kernel/aster-nix/src/syscall/fallocate.rs b/kernel/src/syscall/fallocate.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/fallocate.rs
rename to kernel/src/syscall/fallocate.rs
diff --git a/kernel/aster-nix/src/syscall/fcntl.rs b/kernel/src/syscall/fcntl.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/fcntl.rs
rename to kernel/src/syscall/fcntl.rs
diff --git a/kernel/aster-nix/src/syscall/flock.rs b/kernel/src/syscall/flock.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/flock.rs
rename to kernel/src/syscall/flock.rs
diff --git a/kernel/aster-nix/src/syscall/fork.rs b/kernel/src/syscall/fork.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/fork.rs
rename to kernel/src/syscall/fork.rs
diff --git a/kernel/aster-nix/src/syscall/fsync.rs b/kernel/src/syscall/fsync.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/fsync.rs
rename to kernel/src/syscall/fsync.rs
diff --git a/kernel/aster-nix/src/syscall/futex.rs b/kernel/src/syscall/futex.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/futex.rs
rename to kernel/src/syscall/futex.rs
diff --git a/kernel/aster-nix/src/syscall/getcwd.rs b/kernel/src/syscall/getcwd.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/getcwd.rs
rename to kernel/src/syscall/getcwd.rs
diff --git a/kernel/aster-nix/src/syscall/getdents64.rs b/kernel/src/syscall/getdents64.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/getdents64.rs
rename to kernel/src/syscall/getdents64.rs
diff --git a/kernel/aster-nix/src/syscall/getegid.rs b/kernel/src/syscall/getegid.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/getegid.rs
rename to kernel/src/syscall/getegid.rs
diff --git a/kernel/aster-nix/src/syscall/geteuid.rs b/kernel/src/syscall/geteuid.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/geteuid.rs
rename to kernel/src/syscall/geteuid.rs
diff --git a/kernel/aster-nix/src/syscall/getgid.rs b/kernel/src/syscall/getgid.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/getgid.rs
rename to kernel/src/syscall/getgid.rs
diff --git a/kernel/aster-nix/src/syscall/getgroups.rs b/kernel/src/syscall/getgroups.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/getgroups.rs
rename to kernel/src/syscall/getgroups.rs
diff --git a/kernel/aster-nix/src/syscall/getpeername.rs b/kernel/src/syscall/getpeername.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/getpeername.rs
rename to kernel/src/syscall/getpeername.rs
diff --git a/kernel/aster-nix/src/syscall/getpgrp.rs b/kernel/src/syscall/getpgrp.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/getpgrp.rs
rename to kernel/src/syscall/getpgrp.rs
diff --git a/kernel/aster-nix/src/syscall/getpid.rs b/kernel/src/syscall/getpid.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/getpid.rs
rename to kernel/src/syscall/getpid.rs
diff --git a/kernel/aster-nix/src/syscall/getppid.rs b/kernel/src/syscall/getppid.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/getppid.rs
rename to kernel/src/syscall/getppid.rs
diff --git a/kernel/aster-nix/src/syscall/getrandom.rs b/kernel/src/syscall/getrandom.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/getrandom.rs
rename to kernel/src/syscall/getrandom.rs
diff --git a/kernel/aster-nix/src/syscall/getresgid.rs b/kernel/src/syscall/getresgid.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/getresgid.rs
rename to kernel/src/syscall/getresgid.rs
diff --git a/kernel/aster-nix/src/syscall/getresuid.rs b/kernel/src/syscall/getresuid.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/getresuid.rs
rename to kernel/src/syscall/getresuid.rs
diff --git a/kernel/aster-nix/src/syscall/getrusage.rs b/kernel/src/syscall/getrusage.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/getrusage.rs
rename to kernel/src/syscall/getrusage.rs
diff --git a/kernel/aster-nix/src/syscall/getsid.rs b/kernel/src/syscall/getsid.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/getsid.rs
rename to kernel/src/syscall/getsid.rs
diff --git a/kernel/aster-nix/src/syscall/getsockname.rs b/kernel/src/syscall/getsockname.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/getsockname.rs
rename to kernel/src/syscall/getsockname.rs
diff --git a/kernel/aster-nix/src/syscall/getsockopt.rs b/kernel/src/syscall/getsockopt.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/getsockopt.rs
rename to kernel/src/syscall/getsockopt.rs
diff --git a/kernel/aster-nix/src/syscall/gettid.rs b/kernel/src/syscall/gettid.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/gettid.rs
rename to kernel/src/syscall/gettid.rs
diff --git a/kernel/aster-nix/src/syscall/gettimeofday.rs b/kernel/src/syscall/gettimeofday.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/gettimeofday.rs
rename to kernel/src/syscall/gettimeofday.rs
diff --git a/kernel/aster-nix/src/syscall/getuid.rs b/kernel/src/syscall/getuid.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/getuid.rs
rename to kernel/src/syscall/getuid.rs
diff --git a/kernel/aster-nix/src/syscall/ioctl.rs b/kernel/src/syscall/ioctl.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/ioctl.rs
rename to kernel/src/syscall/ioctl.rs
diff --git a/kernel/aster-nix/src/syscall/kill.rs b/kernel/src/syscall/kill.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/kill.rs
rename to kernel/src/syscall/kill.rs
diff --git a/kernel/aster-nix/src/syscall/link.rs b/kernel/src/syscall/link.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/link.rs
rename to kernel/src/syscall/link.rs
diff --git a/kernel/aster-nix/src/syscall/listen.rs b/kernel/src/syscall/listen.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/listen.rs
rename to kernel/src/syscall/listen.rs
diff --git a/kernel/aster-nix/src/syscall/lseek.rs b/kernel/src/syscall/lseek.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/lseek.rs
rename to kernel/src/syscall/lseek.rs
diff --git a/kernel/aster-nix/src/syscall/madvise.rs b/kernel/src/syscall/madvise.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/madvise.rs
rename to kernel/src/syscall/madvise.rs
diff --git a/kernel/aster-nix/src/syscall/mkdir.rs b/kernel/src/syscall/mkdir.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/mkdir.rs
rename to kernel/src/syscall/mkdir.rs
diff --git a/kernel/aster-nix/src/syscall/mknod.rs b/kernel/src/syscall/mknod.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/mknod.rs
rename to kernel/src/syscall/mknod.rs
diff --git a/kernel/aster-nix/src/syscall/mmap.rs b/kernel/src/syscall/mmap.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/mmap.rs
rename to kernel/src/syscall/mmap.rs
diff --git a/kernel/aster-nix/src/syscall/mod.rs b/kernel/src/syscall/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/mod.rs
rename to kernel/src/syscall/mod.rs
diff --git a/kernel/aster-nix/src/syscall/mount.rs b/kernel/src/syscall/mount.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/mount.rs
rename to kernel/src/syscall/mount.rs
diff --git a/kernel/aster-nix/src/syscall/mprotect.rs b/kernel/src/syscall/mprotect.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/mprotect.rs
rename to kernel/src/syscall/mprotect.rs
diff --git a/kernel/aster-nix/src/syscall/msync.rs b/kernel/src/syscall/msync.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/msync.rs
rename to kernel/src/syscall/msync.rs
diff --git a/kernel/aster-nix/src/syscall/munmap.rs b/kernel/src/syscall/munmap.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/munmap.rs
rename to kernel/src/syscall/munmap.rs
diff --git a/kernel/aster-nix/src/syscall/nanosleep.rs b/kernel/src/syscall/nanosleep.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/nanosleep.rs
rename to kernel/src/syscall/nanosleep.rs
diff --git a/kernel/aster-nix/src/syscall/open.rs b/kernel/src/syscall/open.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/open.rs
rename to kernel/src/syscall/open.rs
diff --git a/kernel/aster-nix/src/syscall/pause.rs b/kernel/src/syscall/pause.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/pause.rs
rename to kernel/src/syscall/pause.rs
diff --git a/kernel/aster-nix/src/syscall/pipe.rs b/kernel/src/syscall/pipe.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/pipe.rs
rename to kernel/src/syscall/pipe.rs
diff --git a/kernel/aster-nix/src/syscall/poll.rs b/kernel/src/syscall/poll.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/poll.rs
rename to kernel/src/syscall/poll.rs
diff --git a/kernel/aster-nix/src/syscall/prctl.rs b/kernel/src/syscall/prctl.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/prctl.rs
rename to kernel/src/syscall/prctl.rs
diff --git a/kernel/aster-nix/src/syscall/pread64.rs b/kernel/src/syscall/pread64.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/pread64.rs
rename to kernel/src/syscall/pread64.rs
diff --git a/kernel/aster-nix/src/syscall/preadv.rs b/kernel/src/syscall/preadv.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/preadv.rs
rename to kernel/src/syscall/preadv.rs
diff --git a/kernel/aster-nix/src/syscall/prlimit64.rs b/kernel/src/syscall/prlimit64.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/prlimit64.rs
rename to kernel/src/syscall/prlimit64.rs
diff --git a/kernel/aster-nix/src/syscall/pselect6.rs b/kernel/src/syscall/pselect6.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/pselect6.rs
rename to kernel/src/syscall/pselect6.rs
diff --git a/kernel/aster-nix/src/syscall/pwrite64.rs b/kernel/src/syscall/pwrite64.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/pwrite64.rs
rename to kernel/src/syscall/pwrite64.rs
diff --git a/kernel/aster-nix/src/syscall/pwritev.rs b/kernel/src/syscall/pwritev.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/pwritev.rs
rename to kernel/src/syscall/pwritev.rs
diff --git a/kernel/aster-nix/src/syscall/read.rs b/kernel/src/syscall/read.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/read.rs
rename to kernel/src/syscall/read.rs
diff --git a/kernel/aster-nix/src/syscall/readlink.rs b/kernel/src/syscall/readlink.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/readlink.rs
rename to kernel/src/syscall/readlink.rs
diff --git a/kernel/aster-nix/src/syscall/recvfrom.rs b/kernel/src/syscall/recvfrom.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/recvfrom.rs
rename to kernel/src/syscall/recvfrom.rs
diff --git a/kernel/aster-nix/src/syscall/recvmsg.rs b/kernel/src/syscall/recvmsg.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/recvmsg.rs
rename to kernel/src/syscall/recvmsg.rs
diff --git a/kernel/aster-nix/src/syscall/rename.rs b/kernel/src/syscall/rename.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/rename.rs
rename to kernel/src/syscall/rename.rs
diff --git a/kernel/aster-nix/src/syscall/rmdir.rs b/kernel/src/syscall/rmdir.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/rmdir.rs
rename to kernel/src/syscall/rmdir.rs
diff --git a/kernel/aster-nix/src/syscall/rt_sigaction.rs b/kernel/src/syscall/rt_sigaction.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/rt_sigaction.rs
rename to kernel/src/syscall/rt_sigaction.rs
diff --git a/kernel/aster-nix/src/syscall/rt_sigpending.rs b/kernel/src/syscall/rt_sigpending.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/rt_sigpending.rs
rename to kernel/src/syscall/rt_sigpending.rs
diff --git a/kernel/aster-nix/src/syscall/rt_sigprocmask.rs b/kernel/src/syscall/rt_sigprocmask.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/rt_sigprocmask.rs
rename to kernel/src/syscall/rt_sigprocmask.rs
diff --git a/kernel/aster-nix/src/syscall/rt_sigreturn.rs b/kernel/src/syscall/rt_sigreturn.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/rt_sigreturn.rs
rename to kernel/src/syscall/rt_sigreturn.rs
diff --git a/kernel/aster-nix/src/syscall/rt_sigsuspend.rs b/kernel/src/syscall/rt_sigsuspend.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/rt_sigsuspend.rs
rename to kernel/src/syscall/rt_sigsuspend.rs
diff --git a/kernel/aster-nix/src/syscall/sched_getaffinity.rs b/kernel/src/syscall/sched_getaffinity.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/sched_getaffinity.rs
rename to kernel/src/syscall/sched_getaffinity.rs
diff --git a/kernel/aster-nix/src/syscall/sched_yield.rs b/kernel/src/syscall/sched_yield.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/sched_yield.rs
rename to kernel/src/syscall/sched_yield.rs
diff --git a/kernel/aster-nix/src/syscall/select.rs b/kernel/src/syscall/select.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/select.rs
rename to kernel/src/syscall/select.rs
diff --git a/kernel/aster-nix/src/syscall/semctl.rs b/kernel/src/syscall/semctl.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/semctl.rs
rename to kernel/src/syscall/semctl.rs
diff --git a/kernel/aster-nix/src/syscall/semget.rs b/kernel/src/syscall/semget.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/semget.rs
rename to kernel/src/syscall/semget.rs
diff --git a/kernel/aster-nix/src/syscall/semop.rs b/kernel/src/syscall/semop.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/semop.rs
rename to kernel/src/syscall/semop.rs
diff --git a/kernel/aster-nix/src/syscall/sendfile.rs b/kernel/src/syscall/sendfile.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/sendfile.rs
rename to kernel/src/syscall/sendfile.rs
diff --git a/kernel/aster-nix/src/syscall/sendmsg.rs b/kernel/src/syscall/sendmsg.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/sendmsg.rs
rename to kernel/src/syscall/sendmsg.rs
diff --git a/kernel/aster-nix/src/syscall/sendto.rs b/kernel/src/syscall/sendto.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/sendto.rs
rename to kernel/src/syscall/sendto.rs
diff --git a/kernel/aster-nix/src/syscall/set_get_priority.rs b/kernel/src/syscall/set_get_priority.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/set_get_priority.rs
rename to kernel/src/syscall/set_get_priority.rs
diff --git a/kernel/aster-nix/src/syscall/set_robust_list.rs b/kernel/src/syscall/set_robust_list.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/set_robust_list.rs
rename to kernel/src/syscall/set_robust_list.rs
diff --git a/kernel/aster-nix/src/syscall/set_tid_address.rs b/kernel/src/syscall/set_tid_address.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/set_tid_address.rs
rename to kernel/src/syscall/set_tid_address.rs
diff --git a/kernel/aster-nix/src/syscall/setfsgid.rs b/kernel/src/syscall/setfsgid.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/setfsgid.rs
rename to kernel/src/syscall/setfsgid.rs
diff --git a/kernel/aster-nix/src/syscall/setfsuid.rs b/kernel/src/syscall/setfsuid.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/setfsuid.rs
rename to kernel/src/syscall/setfsuid.rs
diff --git a/kernel/aster-nix/src/syscall/setgid.rs b/kernel/src/syscall/setgid.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/setgid.rs
rename to kernel/src/syscall/setgid.rs
diff --git a/kernel/aster-nix/src/syscall/setgroups.rs b/kernel/src/syscall/setgroups.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/setgroups.rs
rename to kernel/src/syscall/setgroups.rs
diff --git a/kernel/aster-nix/src/syscall/setitimer.rs b/kernel/src/syscall/setitimer.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/setitimer.rs
rename to kernel/src/syscall/setitimer.rs
diff --git a/kernel/aster-nix/src/syscall/setpgid.rs b/kernel/src/syscall/setpgid.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/setpgid.rs
rename to kernel/src/syscall/setpgid.rs
diff --git a/kernel/aster-nix/src/syscall/setregid.rs b/kernel/src/syscall/setregid.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/setregid.rs
rename to kernel/src/syscall/setregid.rs
diff --git a/kernel/aster-nix/src/syscall/setresgid.rs b/kernel/src/syscall/setresgid.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/setresgid.rs
rename to kernel/src/syscall/setresgid.rs
diff --git a/kernel/aster-nix/src/syscall/setresuid.rs b/kernel/src/syscall/setresuid.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/setresuid.rs
rename to kernel/src/syscall/setresuid.rs
diff --git a/kernel/aster-nix/src/syscall/setreuid.rs b/kernel/src/syscall/setreuid.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/setreuid.rs
rename to kernel/src/syscall/setreuid.rs
diff --git a/kernel/aster-nix/src/syscall/setsid.rs b/kernel/src/syscall/setsid.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/setsid.rs
rename to kernel/src/syscall/setsid.rs
diff --git a/kernel/aster-nix/src/syscall/setsockopt.rs b/kernel/src/syscall/setsockopt.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/setsockopt.rs
rename to kernel/src/syscall/setsockopt.rs
diff --git a/kernel/aster-nix/src/syscall/setuid.rs b/kernel/src/syscall/setuid.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/setuid.rs
rename to kernel/src/syscall/setuid.rs
diff --git a/kernel/aster-nix/src/syscall/shutdown.rs b/kernel/src/syscall/shutdown.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/shutdown.rs
rename to kernel/src/syscall/shutdown.rs
diff --git a/kernel/aster-nix/src/syscall/sigaltstack.rs b/kernel/src/syscall/sigaltstack.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/sigaltstack.rs
rename to kernel/src/syscall/sigaltstack.rs
diff --git a/kernel/aster-nix/src/syscall/socket.rs b/kernel/src/syscall/socket.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/socket.rs
rename to kernel/src/syscall/socket.rs
diff --git a/kernel/aster-nix/src/syscall/socketpair.rs b/kernel/src/syscall/socketpair.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/socketpair.rs
rename to kernel/src/syscall/socketpair.rs
diff --git a/kernel/aster-nix/src/syscall/stat.rs b/kernel/src/syscall/stat.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/stat.rs
rename to kernel/src/syscall/stat.rs
diff --git a/kernel/aster-nix/src/syscall/statfs.rs b/kernel/src/syscall/statfs.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/statfs.rs
rename to kernel/src/syscall/statfs.rs
diff --git a/kernel/aster-nix/src/syscall/symlink.rs b/kernel/src/syscall/symlink.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/symlink.rs
rename to kernel/src/syscall/symlink.rs
diff --git a/kernel/aster-nix/src/syscall/sync.rs b/kernel/src/syscall/sync.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/sync.rs
rename to kernel/src/syscall/sync.rs
diff --git a/kernel/aster-nix/src/syscall/tgkill.rs b/kernel/src/syscall/tgkill.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/tgkill.rs
rename to kernel/src/syscall/tgkill.rs
diff --git a/kernel/aster-nix/src/syscall/time.rs b/kernel/src/syscall/time.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/time.rs
rename to kernel/src/syscall/time.rs
diff --git a/kernel/aster-nix/src/syscall/timer_create.rs b/kernel/src/syscall/timer_create.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/timer_create.rs
rename to kernel/src/syscall/timer_create.rs
diff --git a/kernel/aster-nix/src/syscall/timer_settime.rs b/kernel/src/syscall/timer_settime.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/timer_settime.rs
rename to kernel/src/syscall/timer_settime.rs
diff --git a/kernel/aster-nix/src/syscall/truncate.rs b/kernel/src/syscall/truncate.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/truncate.rs
rename to kernel/src/syscall/truncate.rs
diff --git a/kernel/aster-nix/src/syscall/umask.rs b/kernel/src/syscall/umask.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/umask.rs
rename to kernel/src/syscall/umask.rs
diff --git a/kernel/aster-nix/src/syscall/umount.rs b/kernel/src/syscall/umount.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/umount.rs
rename to kernel/src/syscall/umount.rs
diff --git a/kernel/aster-nix/src/syscall/uname.rs b/kernel/src/syscall/uname.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/uname.rs
rename to kernel/src/syscall/uname.rs
diff --git a/kernel/aster-nix/src/syscall/unlink.rs b/kernel/src/syscall/unlink.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/unlink.rs
rename to kernel/src/syscall/unlink.rs
diff --git a/kernel/aster-nix/src/syscall/utimens.rs b/kernel/src/syscall/utimens.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/utimens.rs
rename to kernel/src/syscall/utimens.rs
diff --git a/kernel/aster-nix/src/syscall/wait4.rs b/kernel/src/syscall/wait4.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/wait4.rs
rename to kernel/src/syscall/wait4.rs
diff --git a/kernel/aster-nix/src/syscall/waitid.rs b/kernel/src/syscall/waitid.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/waitid.rs
rename to kernel/src/syscall/waitid.rs
diff --git a/kernel/aster-nix/src/syscall/write.rs b/kernel/src/syscall/write.rs
similarity index 100%
rename from kernel/aster-nix/src/syscall/write.rs
rename to kernel/src/syscall/write.rs
diff --git a/kernel/aster-nix/src/taskless.rs b/kernel/src/taskless.rs
similarity index 98%
rename from kernel/aster-nix/src/taskless.rs
rename to kernel/src/taskless.rs
index fc3f668945..a5b8f89eb1 100644
--- 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 {
@@ -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/thread/exception.rs b/kernel/src/thread/exception.rs
similarity index 100%
rename from kernel/aster-nix/src/thread/exception.rs
rename to kernel/src/thread/exception.rs
diff --git a/kernel/aster-nix/src/thread/kernel_thread.rs b/kernel/src/thread/kernel_thread.rs
similarity index 100%
rename from kernel/aster-nix/src/thread/kernel_thread.rs
rename to kernel/src/thread/kernel_thread.rs
diff --git a/kernel/aster-nix/src/thread/mod.rs b/kernel/src/thread/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/thread/mod.rs
rename to kernel/src/thread/mod.rs
diff --git a/kernel/aster-nix/src/thread/status.rs b/kernel/src/thread/status.rs
similarity index 100%
rename from kernel/aster-nix/src/thread/status.rs
rename to kernel/src/thread/status.rs
diff --git a/kernel/aster-nix/src/thread/task.rs b/kernel/src/thread/task.rs
similarity index 100%
rename from kernel/aster-nix/src/thread/task.rs
rename to kernel/src/thread/task.rs
diff --git a/kernel/aster-nix/src/thread/thread_table.rs b/kernel/src/thread/thread_table.rs
similarity index 100%
rename from kernel/aster-nix/src/thread/thread_table.rs
rename to kernel/src/thread/thread_table.rs
diff --git a/kernel/aster-nix/src/thread/work_queue/mod.rs b/kernel/src/thread/work_queue/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/thread/work_queue/mod.rs
rename to kernel/src/thread/work_queue/mod.rs
diff --git a/kernel/aster-nix/src/thread/work_queue/simple_scheduler.rs b/kernel/src/thread/work_queue/simple_scheduler.rs
similarity index 100%
rename from kernel/aster-nix/src/thread/work_queue/simple_scheduler.rs
rename to kernel/src/thread/work_queue/simple_scheduler.rs
diff --git a/kernel/aster-nix/src/thread/work_queue/work_item.rs b/kernel/src/thread/work_queue/work_item.rs
similarity index 100%
rename from kernel/aster-nix/src/thread/work_queue/work_item.rs
rename to kernel/src/thread/work_queue/work_item.rs
diff --git a/kernel/aster-nix/src/thread/work_queue/worker.rs b/kernel/src/thread/work_queue/worker.rs
similarity index 100%
rename from kernel/aster-nix/src/thread/work_queue/worker.rs
rename to kernel/src/thread/work_queue/worker.rs
diff --git a/kernel/aster-nix/src/thread/work_queue/worker_pool.rs b/kernel/src/thread/work_queue/worker_pool.rs
similarity index 100%
rename from kernel/aster-nix/src/thread/work_queue/worker_pool.rs
rename to kernel/src/thread/work_queue/worker_pool.rs
diff --git a/kernel/aster-nix/src/time/clocks/cpu_clock.rs b/kernel/src/time/clocks/cpu_clock.rs
similarity index 100%
rename from kernel/aster-nix/src/time/clocks/cpu_clock.rs
rename to kernel/src/time/clocks/cpu_clock.rs
diff --git a/kernel/aster-nix/src/time/clocks/mod.rs b/kernel/src/time/clocks/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/time/clocks/mod.rs
rename to kernel/src/time/clocks/mod.rs
diff --git a/kernel/aster-nix/src/time/clocks/system_wide.rs b/kernel/src/time/clocks/system_wide.rs
similarity index 100%
rename from kernel/aster-nix/src/time/clocks/system_wide.rs
rename to kernel/src/time/clocks/system_wide.rs
diff --git a/kernel/aster-nix/src/time/core/mod.rs b/kernel/src/time/core/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/time/core/mod.rs
rename to kernel/src/time/core/mod.rs
diff --git a/kernel/aster-nix/src/time/core/timer.rs b/kernel/src/time/core/timer.rs
similarity index 100%
rename from kernel/aster-nix/src/time/core/timer.rs
rename to kernel/src/time/core/timer.rs
diff --git a/kernel/aster-nix/src/time/mod.rs b/kernel/src/time/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/time/mod.rs
rename to kernel/src/time/mod.rs
diff --git a/kernel/aster-nix/src/time/softirq.rs b/kernel/src/time/softirq.rs
similarity index 100%
rename from kernel/aster-nix/src/time/softirq.rs
rename to kernel/src/time/softirq.rs
diff --git a/kernel/aster-nix/src/time/system_time.rs b/kernel/src/time/system_time.rs
similarity index 100%
rename from kernel/aster-nix/src/time/system_time.rs
rename to kernel/src/time/system_time.rs
diff --git a/kernel/aster-nix/src/time/wait.rs b/kernel/src/time/wait.rs
similarity index 100%
rename from kernel/aster-nix/src/time/wait.rs
rename to kernel/src/time/wait.rs
diff --git a/kernel/aster-nix/src/util/iovec.rs b/kernel/src/util/iovec.rs
similarity index 100%
rename from kernel/aster-nix/src/util/iovec.rs
rename to kernel/src/util/iovec.rs
diff --git a/kernel/aster-nix/src/util/mod.rs b/kernel/src/util/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/util/mod.rs
rename to kernel/src/util/mod.rs
diff --git a/kernel/aster-nix/src/util/net/addr/family.rs b/kernel/src/util/net/addr/family.rs
similarity index 100%
rename from kernel/aster-nix/src/util/net/addr/family.rs
rename to kernel/src/util/net/addr/family.rs
diff --git a/kernel/aster-nix/src/util/net/addr/ip.rs b/kernel/src/util/net/addr/ip.rs
similarity index 100%
rename from kernel/aster-nix/src/util/net/addr/ip.rs
rename to kernel/src/util/net/addr/ip.rs
diff --git a/kernel/aster-nix/src/util/net/addr/mod.rs b/kernel/src/util/net/addr/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/util/net/addr/mod.rs
rename to kernel/src/util/net/addr/mod.rs
diff --git a/kernel/aster-nix/src/util/net/addr/unix.rs b/kernel/src/util/net/addr/unix.rs
similarity index 100%
rename from kernel/aster-nix/src/util/net/addr/unix.rs
rename to kernel/src/util/net/addr/unix.rs
diff --git a/kernel/aster-nix/src/util/net/addr/vsock.rs b/kernel/src/util/net/addr/vsock.rs
similarity index 100%
rename from kernel/aster-nix/src/util/net/addr/vsock.rs
rename to kernel/src/util/net/addr/vsock.rs
diff --git a/kernel/aster-nix/src/util/net/mod.rs b/kernel/src/util/net/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/util/net/mod.rs
rename to kernel/src/util/net/mod.rs
diff --git a/kernel/aster-nix/src/util/net/options/mod.rs b/kernel/src/util/net/options/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/util/net/options/mod.rs
rename to kernel/src/util/net/options/mod.rs
diff --git a/kernel/aster-nix/src/util/net/options/socket.rs b/kernel/src/util/net/options/socket.rs
similarity index 100%
rename from kernel/aster-nix/src/util/net/options/socket.rs
rename to kernel/src/util/net/options/socket.rs
diff --git a/kernel/aster-nix/src/util/net/options/tcp.rs b/kernel/src/util/net/options/tcp.rs
similarity index 100%
rename from kernel/aster-nix/src/util/net/options/tcp.rs
rename to kernel/src/util/net/options/tcp.rs
diff --git a/kernel/aster-nix/src/util/net/options/utils.rs b/kernel/src/util/net/options/utils.rs
similarity index 100%
rename from kernel/aster-nix/src/util/net/options/utils.rs
rename to kernel/src/util/net/options/utils.rs
diff --git a/kernel/aster-nix/src/util/net/socket.rs b/kernel/src/util/net/socket.rs
similarity index 100%
rename from kernel/aster-nix/src/util/net/socket.rs
rename to kernel/src/util/net/socket.rs
diff --git a/kernel/aster-nix/src/util/random.rs b/kernel/src/util/random.rs
similarity index 100%
rename from kernel/aster-nix/src/util/random.rs
rename to kernel/src/util/random.rs
diff --git a/kernel/aster-nix/src/vdso.rs b/kernel/src/vdso.rs
similarity index 100%
rename from kernel/aster-nix/src/vdso.rs
rename to kernel/src/vdso.rs
diff --git a/kernel/aster-nix/src/vm/mod.rs b/kernel/src/vm/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/vm/mod.rs
rename to kernel/src/vm/mod.rs
diff --git a/kernel/aster-nix/src/vm/page_fault_handler.rs b/kernel/src/vm/page_fault_handler.rs
similarity index 100%
rename from kernel/aster-nix/src/vm/page_fault_handler.rs
rename to kernel/src/vm/page_fault_handler.rs
diff --git a/kernel/aster-nix/src/vm/perms.rs b/kernel/src/vm/perms.rs
similarity index 100%
rename from kernel/aster-nix/src/vm/perms.rs
rename to kernel/src/vm/perms.rs
diff --git a/kernel/aster-nix/src/vm/util.rs b/kernel/src/vm/util.rs
similarity index 100%
rename from kernel/aster-nix/src/vm/util.rs
rename to kernel/src/vm/util.rs
diff --git a/kernel/aster-nix/src/vm/vmar/dyn_cap.rs b/kernel/src/vm/vmar/dyn_cap.rs
similarity index 100%
rename from kernel/aster-nix/src/vm/vmar/dyn_cap.rs
rename to kernel/src/vm/vmar/dyn_cap.rs
diff --git a/kernel/aster-nix/src/vm/vmar/interval.rs b/kernel/src/vm/vmar/interval.rs
similarity index 100%
rename from kernel/aster-nix/src/vm/vmar/interval.rs
rename to kernel/src/vm/vmar/interval.rs
diff --git a/kernel/aster-nix/src/vm/vmar/mod.rs b/kernel/src/vm/vmar/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/vm/vmar/mod.rs
rename to kernel/src/vm/vmar/mod.rs
diff --git a/kernel/aster-nix/src/vm/vmar/options.rs b/kernel/src/vm/vmar/options.rs
similarity index 99%
rename from kernel/aster-nix/src/vm/vmar/options.rs
rename to kernel/src/vm/vmar/options.rs
index 95f9cd4d15..8af45336f8 100644
--- 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/kernel/aster-nix/src/vm/vmar/static_cap.rs b/kernel/src/vm/vmar/static_cap.rs
similarity index 100%
rename from kernel/aster-nix/src/vm/vmar/static_cap.rs
rename to kernel/src/vm/vmar/static_cap.rs
diff --git a/kernel/aster-nix/src/vm/vmar/vm_mapping.rs b/kernel/src/vm/vmar/vm_mapping.rs
similarity index 100%
rename from kernel/aster-nix/src/vm/vmar/vm_mapping.rs
rename to kernel/src/vm/vmar/vm_mapping.rs
diff --git a/kernel/aster-nix/src/vm/vmo/dyn_cap.rs b/kernel/src/vm/vmo/dyn_cap.rs
similarity index 100%
rename from kernel/aster-nix/src/vm/vmo/dyn_cap.rs
rename to kernel/src/vm/vmo/dyn_cap.rs
diff --git a/kernel/aster-nix/src/vm/vmo/mod.rs b/kernel/src/vm/vmo/mod.rs
similarity index 100%
rename from kernel/aster-nix/src/vm/vmo/mod.rs
rename to kernel/src/vm/vmo/mod.rs
diff --git a/kernel/aster-nix/src/vm/vmo/options.rs b/kernel/src/vm/vmo/options.rs
similarity index 100%
rename from kernel/aster-nix/src/vm/vmo/options.rs
rename to kernel/src/vm/vmo/options.rs
diff --git a/kernel/aster-nix/src/vm/vmo/pager.rs b/kernel/src/vm/vmo/pager.rs
similarity index 100%
rename from kernel/aster-nix/src/vm/vmo/pager.rs
rename to kernel/src/vm/vmo/pager.rs
diff --git a/kernel/aster-nix/src/vm/vmo/static_cap.rs b/kernel/src/vm/vmo/static_cap.rs
similarity index 100%
rename from kernel/aster-nix/src/vm/vmo/static_cap.rs
rename to kernel/src/vm/vmo/static_cap.rs
diff --git a/osdk/Cargo.lock b/osdk/Cargo.lock
index 4eefec4c61..6ee3668a08 100644
--- 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
index 7fbcb3abf5..00f4f978ad 100644
--- 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
index 4f1b727ae3..f7a4820526 100644
--- 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,
@@ -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();
@@ -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);
@@ -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 = {
@@ -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
index 33e29b80d6..ba052e3621 100644
--- 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
index 10d9073079..29194b0f2f 100644
--- 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
index 8252402b2b..7f680b214e 100644
--- 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
index 0e279b933d..22f6b074c7 100644
--- 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()) {
@@ -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
index bb5486add9..c92050d16a 100644
--- 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
index 2cb750e63a..287461003f 100644
--- 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
index b266c8f593..1dfdeaa17f 100644
--- 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
index c1d357cf0d..e232964a9e 100644
--- 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
index 93466626b9..869d75a182 100644
--- 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::*;
///
@@ -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
index 627c674aa5..2bd462f25b 100644
--- 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.
@@ -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
index 215d57e4e5..4d25097733 100644
--- 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();
@@ -114,6 +119,7 @@ mod test {
use crate::prelude::*;
#[ktest]
+ #[allow(clippy::eq_op)]
fn trivial_assertion() {
assert_eq!(0, 0);
}
@@ -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
index 56d9828add..00dd6f961d 100644
--- 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
index 1b92799e81..3ddeeac4bb 100644
--- 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));
}
}
@@ -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
index 2aa6011706..56ca700c05 100644
--- 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
index 9604232a2f..8bf1cc93d7 100644
--- 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);
};
@@ -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
index ecf828d2bc..410fcb63c6 100755
--- 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"
@@ -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})
@@ -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
@@ -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/.github/workflows/test_asterinas.yml b/.github/workflows/test_asterinas.yml
index 5e299f64c9..1a4d1f4060 100644
--- 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
@@ -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
@@ -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
@@ -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,
@@ -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
index 97b1a83d41..1125ba8d68 100644
--- 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
index e07e53358a..71b1d3617a 100644
--- 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 }}"
@@ -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)
@@ -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
@@ -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/kernel/aster-nix/src/fs/utils/random_test.rs b/kernel/src/fs/utils/random_test.rs
similarity index 100%
rename from kernel/aster-nix/src/fs/utils/random_test.rs
rename to kernel/src/fs/utils/random_test.rs
diff --git a/osdk/src/commands/test.rs b/osdk/src/commands/test.rs
index e3d0865e86..327ebd476a 100644
--- 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,
},
@@ -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");
@@ -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/test-kernel/Cargo.toml b/osdk/test-kernel/Cargo.toml
new file mode 100644
index 0000000000..c2e1bac1b4
--- /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
similarity index 57%
rename from ostd/libs/ostd-test/src/runner.rs
rename to osdk/test-kernel/src/lib.rs
index 1fc16fd00f..164ce20ce3 100644
--- 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`
@@ -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()
@@ -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
@@ -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()));
}
}
@@ -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,
@@ -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
similarity index 98%
rename from ostd/libs/ostd-test/src/path.rs
rename to osdk/test-kernel/src/path.rs
index 434acb49be..b6a973e711 100644
--- 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");
@@ -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");
@@ -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");
@@ -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] = &[
@@ -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)));
@@ -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
similarity index 97%
rename from ostd/libs/ostd-test/src/tree.rs
rename to osdk/test-kernel/src/tree.rs
index 3d908fd9aa..a822a776a6 100644
--- 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,
@@ -250,7 +250,7 @@ mod tests {
}};
}
- #[test]
+ #[ktest]
fn test_tree_iter() {
let tree = gen_test_case!();
let mut iter = tree.iter();
@@ -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() {
@@ -285,7 +285,7 @@ mod tests {
}
}
- #[test]
+ #[ktest]
fn test_module_iter() {
let tree = gen_test_case!();
let mut collection = Vec::<&KtestItem>::new();
@@ -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
index a8fc07f1d0..a5cd52cd9d 100644
--- 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
index 9fbfde5115..b7d9235425 100644
--- 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-test/Cargo.toml b/ostd/libs/ostd-test/Cargo.toml
index 82d4bcacf7..5b8e6f9492 100644
--- 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
index 3ec04c6085..b4fd65d595 100644
--- 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]`
@@ -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.
@@ -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};
@@ -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>),
@@ -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,
}
@@ -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>),
@@ -153,6 +141,7 @@ impl KtestItem {
}
}
+ /// Get the information of the test.
pub fn info(&self) -> &KtestItemInfo {
&self.info
}
@@ -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 }
}
}
@@ -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 }
+}
|
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! -->
|
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
|
0.7
|
c2a83427520f8263a8eb2c36edacdba261ad5cae
|
asterinas/asterinas
| 1,158
|
asterinas__asterinas-1158
|
[
"1264"
] |
c68302f7007225fa47f22a1085a8c59dcdae2ad4
|
diff --git a/kernel/src/sched/priority_scheduler.rs b/kernel/src/sched/priority_scheduler.rs
index b2aaecdad6..dc33bd12f1 100644
--- 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
index 963b44dd9f..4cc8bb99ba 100644
--- 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
index c3fd6dd0b7..c12167b0ee 100644
--- 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
index af91f2e647..b46f55b957 100644
--- 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();
@@ -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
index 6fc0a6ff7c..3ced68bcaf 100644
--- 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
@@ -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();
@@ -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 {
@@ -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 {
@@ -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/ostd/src/arch/x86/boot/smp.rs b/ostd/src/arch/x86/boot/smp.rs
index 5a2596e01c..55df785205 100644
--- 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() {
@@ -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() {
@@ -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
index f4cb86548f..e3dbd329a8 100644
--- 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
index 855bc83c41..e06370d584 100644
--- 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();
@@ -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();
@@ -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();
@@ -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(),));
@@ -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,
@@ -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
index 11475f0c21..21cd13b916 100644
--- 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
index 8838357d12..a6fdc060c5 100644
--- 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;
@@ -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);
});
@@ -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);
@@ -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);
@@ -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
index 6c4af14292..ef722663e1 100644
--- 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
index bd98f8d7c7..309ec68d0e 100644
--- 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;
@@ -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);
@@ -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);
@@ -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
index 79b6d971b2..745668ab73 100644
--- 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;
@@ -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
index bc41dc1ffe..dc01236865 100644
--- 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
index a9075d17ee..111b434a61 100644
--- 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);
}
}
}
@@ -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
index c74c087c1f..9c4004df91 100644
--- 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
index 75b1bdb9de..f9b6d0fafe 100644
--- 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 {
@@ -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>
@@ -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
@@ -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.
- }
}
}
}
@@ -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.
@@ -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
@@ -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());
@@ -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.
@@ -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);
@@ -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!(),
};
@@ -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.
@@ -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
index e54afc420b..9bb1e2cc62 100644
--- 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
index 37e54ca74d..134cd112a0 100644
--- 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.
@@ -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()
@@ -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.
@@ -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
@@ -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]:,
@@ -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 {
@@ -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,
@@ -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
}
}
@@ -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!();
}
}
@@ -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!();
}
}
@@ -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.
@@ -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
index ae0c6b95cb..2bf24e3565 100644
--- 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,
};
@@ -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(()),
}
}
@@ -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,
@@ -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();
@@ -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(()),
}
}
@@ -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.
@@ -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;
@@ -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.
@@ -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/smp.rs b/ostd/src/smp.rs
new file mode 100644
index 0000000000..910bb564a1
--- /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
index a8e9bd8d96..1aa88c6e1d 100644
--- 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/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
index fcb2feb3b5..23618110b8 100644
--- 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 = {
|
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
|
2024-08-13T09:28:07Z
|
0.8
|
ae4ac384713e63232b74915593ebdef680049d31
|
|
asterinas/asterinas
| 1,138
|
asterinas__asterinas-1138
|
[
"1135"
] |
6414111cc57b42db2bae1a0c8b01b85c3830a3b3
|
diff --git a/osdk/src/commands/new/mod.rs b/osdk/src/commands/new/mod.rs
index 1c5c386004..7d4b9b0a4a 100644
--- 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
index ed909baaf0..4a7fbc1fda 100644
--- 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]
@@ -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");
+}
|
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.
|
2024-08-08T01:38:09Z
|
0.6
|
6414111cc57b42db2bae1a0c8b01b85c3830a3b3
|
|
asterinas/asterinas
| 1,125
|
asterinas__asterinas-1125
|
[
"1106"
] |
d04111079cb8edf03d9a58b2bd88d4af4b11543a
|
diff --git a/kernel/aster-nix/src/prelude.rs b/kernel/aster-nix/src/prelude.rs
index dfff76268f..44357e6dd8 100644
--- 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
index b0afbdac69..c701a5a7f7 100644
--- 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
index 362d52df96..0b3a0ff468 100644
--- 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,
@@ -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
index 14bd44fa9e..64ac8f82a0 100644
--- 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,
@@ -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
index 349c9eb0e0..cb7249fe75 100644
--- 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
index a9f4fbf5a1..930978127a 100644
--- 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};
@@ -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)?;
@@ -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()
@@ -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)?;
@@ -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
index 57087f86ef..2803d19538 100644
--- 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
index 2d629aa63b..0ff06dc44c 100644
--- 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/ostd/src/arch/x86/cpu/local.rs b/ostd/src/arch/x86/cpu/local.rs
index 325d692d2e..b5a6473271 100644
--- 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
index 1693e0a8c6..3e9b3c36de 100644
--- 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
index dc0ce89582..5ccc58f657 100644
--- 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")]
@@ -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
@@ -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
index a40b417e7c..05b9384519 100644
--- 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 b/ostd/src/cpu/cpu_local.rs
deleted file mode 100644
index e72ed1ffcd..0000000000
--- 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 a/ostd/src/cpu/local/cell.rs b/ostd/src/cpu/local/cell.rs
new file mode 100644
index 0000000000..97c6ceca6a
--- /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 a/ostd/src/cpu/local/cpu_local.rs b/ostd/src/cpu/local/cpu_local.rs
new file mode 100644
index 0000000000..37724d2717
--- /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 a/ostd/src/cpu/local/mod.rs b/ostd/src/cpu/local/mod.rs
new file mode 100644
index 0000000000..6e9c7b16f1
--- /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/cpu/local/single_instr.rs b/ostd/src/cpu/local/single_instr.rs
new file mode 100644
index 0000000000..1ac436c0b2
--- /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
index fa73c96ced..17289230c7 100644
--- 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")]{
@@ -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);
@@ -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
index eee80a8a21..f99bb07ecb 100644
--- 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)]
@@ -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.
///
@@ -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
index a37672eb37..f9f556d65e 100644
--- 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
index 54d3de1e8c..c82bcab4da 100644
--- 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;
@@ -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)]
{
@@ -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
index c8951d109d..2eb81b7996 100644
--- 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
index 430c5733a6..81cd950e80 100644
--- 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
//
@@ -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
index bfae2f3b37..61b76cd957 100644
--- 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
index ee28a3ae53..4bbad8c5e8 100644
--- 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
index 71acd5ffcb..4588b6732b 100644
--- 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
@@ -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();
@@ -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
@@ -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]
@@ -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: () }
}
@@ -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
index e18b079954..638591b3f5 100644
--- 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};
@@ -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,
@@ -41,6 +41,7 @@ pub trait TaskContextApi {
fn stack_pointer(&self) -> usize;
}
+#[derive(Debug)]
pub struct KernelStack {
segment: Segment,
has_guard_page: bool,
@@ -121,6 +122,7 @@ pub struct Task {
link: LinkedListAtomicLink,
priority: Priority,
// TODO: add multiprocessor support
+ #[allow(dead_code)]
cpu_affinity: CpuSet,
}
@@ -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
index d61bd2b23a..3f359f7021 100644
--- 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();
@@ -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
index df08a08d41..3d9a136c1a 100644
--- 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.
///
@@ -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.
@@ -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.
@@ -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
index 2628ed4449..d52b224f09 100644
--- 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>,
@@ -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.
@@ -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,
}
@@ -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/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
index 52dde2534b..21f60b1b6e 100644
--- 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
index 94e2207f16..3ec04c6085 100644
--- 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 {
@@ -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(())
|
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! -->
|
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
|
0.6
|
6414111cc57b42db2bae1a0c8b01b85c3830a3b3
|
asterinas/asterinas
| 1,098
|
asterinas__asterinas-1098
|
[
"819"
] |
e83e1fc01ba38ad2a405d7d710ec7258fb664f60
|
diff --git a/kernel/aster-nix/src/net/iface/any_socket.rs b/kernel/aster-nix/src/net/iface/any_socket.rs
index 912c7e99e1..a95f0c04e2 100644
--- 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(
@@ -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
@@ -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)
@@ -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
index 787669245b..23bafa8f2d 100644
--- 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},
@@ -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::*;
@@ -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,
}
@@ -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()
}
@@ -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 {
@@ -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)
}
@@ -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 {
@@ -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
index d90b746d94..47149a0e38 100644
--- 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
index 5edfa2ebee..785bc5a03d 100644
--- 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
index 4fc9f4bfd4..e8869bcb23 100644
--- 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
index afb4527c43..6ac2b91226 100644
--- 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.
///
@@ -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
index 3503a9afee..2aca5c52b5 100644
--- 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>>,
}
@@ -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
index 8f103a4044..81c1df5185 100644
--- 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 {
@@ -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) => {
@@ -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
index ef63ce1561..d7bdc593c0 100644
--- 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,
@@ -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",
@@ -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
index 9491891655..301a90bde7 100644
--- 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
index d4b8671e9b..6889fe1a01 100644
--- 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
index 384f7d179d..d8247cecee 100644
--- 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()
|
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.
|
2024-07-26T01:51:02Z
|
0.6
|
6414111cc57b42db2bae1a0c8b01b85c3830a3b3
|
|
asterinas/asterinas
| 1,073
|
asterinas__asterinas-1073
|
[
"1069"
] |
5aa28eae7e14594bbe68827114443b31002bf742
|
diff --git a/osdk/src/base_crate/x86_64.ld.template b/osdk/src/base_crate/x86_64.ld.template
index 18539eb1fa..0682ed20d6 100644
--- 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/ostd/src/arch/x86/cpu/local.rs b/ostd/src/arch/x86/cpu/local.rs
new file mode 100644
index 0000000000..325d692d2e
--- /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
similarity index 95%
rename from ostd/src/arch/x86/cpu.rs
rename to ostd/src/arch/x86/cpu/mod.rs
index 7692d472b1..636fc41613 100644
--- 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},
@@ -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};
@@ -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
index ef3f96c502..71beac6a50 100644
--- 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},
};
@@ -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.
///
@@ -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;
@@ -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.
@@ -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
@@ -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
index abc7e57733..83a9e42d68 100644
--- 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
index d3dcd60d69..a4bdc385bb 100644
--- 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,
@@ -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
index c6dfb9932c..71acd5ffcb 100644
--- 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>>,
@@ -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/.github/workflows/test_asterinas.yml b/.github/workflows/test_asterinas.yml
index 4147c50999..5fb1678a85 100644
--- 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
|
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`.
|
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
|
0.6
|
6414111cc57b42db2bae1a0c8b01b85c3830a3b3
|
asterinas/asterinas
| 1,026
|
asterinas__asterinas-1026
|
[
"681"
] |
94eba6d85eb9e62ddd904c1132d556b808cc3174
|
diff --git a/kernel/aster-nix/src/vm/vmar/vm_mapping.rs b/kernel/aster-nix/src/vm/vmar/vm_mapping.rs
index 6119c96d60..bdec0e5b95 100644
--- 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::{
@@ -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)?;
@@ -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;
@@ -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(())
}
@@ -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(())
}
@@ -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/ostd/src/mm/frame/frame_vec.rs b/ostd/src/mm/frame/frame_vec.rs
deleted file mode 100644
index e37e84e56e..0000000000
--- 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
index 62a035288f..6a880af26b 100644
--- 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::{
@@ -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
index a5006a6bac..4bd3f627b9 100644
--- 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},
@@ -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 {
@@ -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
index aeab21d261..d93adc33e3 100644
--- 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
index e923f5d027..d3dcd60d69 100644
--- 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
///
@@ -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
index ab7f995a04..3d6485ae15 100644
--- 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};
@@ -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
index d24df70738..a5b2338003 100644
--- 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,
@@ -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]:,
{
@@ -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));
}
@@ -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 {
@@ -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),
});
@@ -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),
@@ -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 {
@@ -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.
@@ -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()
}
}
@@ -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
@@ -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`].
@@ -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());
@@ -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);
@@ -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);
@@ -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
index 3b68869290..118f76de92 100644
--- 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,
};
@@ -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;
@@ -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.
@@ -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,
@@ -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 {
@@ -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.
@@ -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>();
@@ -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;
@@ -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,
@@ -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>,
@@ -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),
@@ -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> {
@@ -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,
@@ -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 = {
@@ -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 b/ostd/src/mm/space.rs
deleted file mode 100644
index 548348f763..0000000000
--- 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/vm_space.rs b/ostd/src/mm/vm_space.rs
new file mode 100644
index 0000000000..72c799eea1
--- /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
index c66baa29fe..eaf54478ab 100755
--- 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"
|
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
index 889779f7b7..52dde2534b 100644
--- 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};
@@ -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.
@@ -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 = {
|
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.
|
2024-07-04T11:40:07Z
|
0.6
|
6414111cc57b42db2bae1a0c8b01b85c3830a3b3
|
|
asterinas/asterinas
| 1,018
|
asterinas__asterinas-1018
|
[
"1009"
] |
8a9c012249d36c54712030c41388d20a608939f5
|
diff --git a/.github/workflows/publish_api_docs.yml b/.github/workflows/publish_api_docs.yml
deleted file mode 100644
index 64c59ef4b5..0000000000
--- 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 b/.github/workflows/publish_osdk.yml
deleted file mode 100644
index 62a5580b49..0000000000
--- 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 a/.github/workflows/publish_osdk_and_ostd.yml b/.github/workflows/publish_osdk_and_ostd.yml
new file mode 100644
index 0000000000..c9e4d2e520
--- /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
index c70d7b0c6d..79dc2328da 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -84,7 +84,6 @@ dependencies = [
"lazy_static",
"log",
"ostd",
- "pod",
"spin 0.9.8",
"static_assertions",
]
@@ -141,7 +140,6 @@ dependencies = [
"int-to-c-enum",
"log",
"ostd",
- "pod",
"ringbuf",
"smoltcp",
"spin 0.9.8",
@@ -185,7 +183,6 @@ dependencies = [
"lru",
"ostd",
"paste",
- "pod",
"rand",
"ringbuf",
"smoltcp",
@@ -238,7 +235,6 @@ dependencies = [
"aster-rights-proc",
"inherit-methods-macro",
"ostd",
- "pod",
"typeflags-util",
]
@@ -261,7 +257,6 @@ dependencies = [
"int-to-c-enum",
"log",
"ostd",
- "pod",
"smoltcp",
"spin 0.9.8",
"typeflags-util",
@@ -277,7 +272,7 @@ dependencies = [
"component",
"id-alloc",
"ostd",
- "x86_64",
+ "x86_64 0.14.11",
]
[[package]]
@@ -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",
]
@@ -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"
@@ -891,7 +879,7 @@ dependencies = [
"uart_16550",
"uefi",
"uefi-services",
- "x86_64",
+ "x86_64 0.14.11",
"xmas-elf 0.8.0",
]
@@ -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",
]
@@ -1094,7 +1082,6 @@ dependencies = [
"inherit-methods-macro",
"int-to-c-enum",
"intrusive-collections",
- "ktest",
"lazy_static",
"linux-boot-params",
"log",
@@ -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",
@@ -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",
@@ -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"
@@ -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"
@@ -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"
@@ -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"
@@ -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]]
@@ -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]]
@@ -1723,7 +1726,7 @@ checksum = "2781db97787217ad2a2845c396a5efe286f87467a5810836db6d74926e94a385"
dependencies = [
"bit_field",
"bitflags 1.3.2",
- "raw-cpuid",
+ "raw-cpuid 10.7.0",
]
[[package]]
@@ -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
index 9e47daa492..26ab93e796 100644
--- 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
index 0a02b8043d..56134ff5af 100644
--- 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
index 7cd55ee321..9912a4ba91 100644
--- 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
index b2651c6b42..f5b52453e9 100644
--- 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" }
@@ -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
index b6b2572111..3bb49ce1bf 100644
--- 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;
@@ -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
index eb422c463a..78225709c9 100644
--- 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
index 701b8ed91d..dfff76268f 100644
--- 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
index b2f39c9c45..5981cd165f 100644
--- 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},
};
@@ -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
index aba58e03ac..38a727a35a 100644
--- 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
index a25258bba9..bd45365f9f 100644
--- 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
index 1db2adbc7c..c1f9b70134 100644
--- 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
index 95af96b158..e0c8770f6b 100644
--- 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
index 300817379d..6065f2397c 100644
--- 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
index 1da353f3d4..f57c9d2052 100644
--- 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
index c4fd2204c8..845fc26b28 100644
--- 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
index 5c19dfa882..e5378f1248 100644
--- 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
index 9763a7738e..3347c8c8b8 100644
--- 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
index fce5c64e60..8c28d23146 100644
--- 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
index 18faf8a184..e0970a8051 100644
--- 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
index 05d24ef1cb..49079e2747 100644
--- 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
index e42a53e985..2823eaee18 100644
--- 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
index aa2fe3874b..278d89265e 100644
--- 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
index 2294fbb0ec..ca888a8cd2 100644
--- 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
index 8c1331f7b1..f2ce56f1d3 100644
--- 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
index 3536c20c50..44fbc9a7fb 100644
--- 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
index d66f37a6df..339e60c66b 100644
--- 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
index c8a167668f..4a45f4a2bd 100644
--- 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
index 71bf7a2391..a6b601ee08 100644
--- 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
index a6e8b2e292..a3b022ba05 100644
--- 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
index 321d5a74a0..7b6454e016 100644
--- 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
index dd9bde819f..0444a9f5d4 100644
--- 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
index 3e811630c0..30d3b2e538 100644
--- 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
index 09656d0c60..98443d32f8 100644
--- 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
index c235a57aa7..badab5b61a 100644
--- 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
index 977ade064e..f0dda6359f 100644
--- 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
index bc321cd7f8..1c5c386004 100644
--- 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) {
@@ -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
index 1f1e4b855f..2d629aa63b 100644
--- 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/ostd/Cargo.toml b/ostd/Cargo.toml
index bacfdf3d6d..b788274f1c 100644
--- 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
index fb2d163eda..bbb8c99c72 100644
--- 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
index 1ccca34600..6a5bffc1c8 100644
--- 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
index 3b4b3459ba..a6942acaf3 100644
--- 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
index 23b0f633e9..621829afb7 100644
--- 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"
@@ -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
index cc6d9946fb..816b8e0585 100644
--- 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
index 3020e43883..93466626b9 100644
--- 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]
@@ -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]
@@ -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]
@@ -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/src/arch/x86/cpu.rs b/ostd/src/arch/x86/cpu.rs
index da7beea74d..5fbd567481 100644
--- 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},
@@ -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
}
@@ -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
index 4da92c8d20..ba2fbeb4fe 100644
--- 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::{
@@ -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
index 521db1a092..907b770f14 100644
--- 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
index 93d38baf7e..774a61deed 100644
--- 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
index 669e5fda0c..7604f9035b 100644
--- 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
index 63f84e9fa2..76f7d3032c 100644
--- 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
index 249204fecb..9a17cd4310 100644
--- 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
index e4db96a25a..abc7e57733 100644
--- 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};
@@ -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
index 869315d752..e923f5d027 100644
--- 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,
@@ -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
index 0fc7487dc7..3b68869290 100644
--- 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
index bb24724039..d9e4cb1fbc 100644
--- 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
index a5fe3dfd0a..1b92799e81 100644
--- 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() {
|
diff --git a/osdk/tests/util/mod.rs b/osdk/tests/util/mod.rs
index 98ac7b614c..4f947ba48c 100644
--- 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/libs/ktest/Cargo.toml b/ostd/libs/ostd-test/Cargo.toml
similarity index 54%
rename from ostd/libs/ktest/Cargo.toml
rename to ostd/libs/ostd-test/Cargo.toml
index db397f1ada..82d4bcacf7 100644
--- 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
similarity index 92%
rename from ostd/libs/ktest/src/lib.rs
rename to ostd/libs/ostd-test/src/lib.rs
index f193a7ac6f..94e2207f16 100644
--- 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
//!
@@ -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/libs/ktest/src/path.rs b/ostd/libs/ostd-test/src/path.rs
similarity index 100%
rename from ostd/libs/ktest/src/path.rs
rename to ostd/libs/ostd-test/src/path.rs
diff --git a/ostd/libs/ktest/src/runner.rs b/ostd/libs/ostd-test/src/runner.rs
similarity index 100%
rename from ostd/libs/ktest/src/runner.rs
rename to ostd/libs/ostd-test/src/runner.rs
diff --git a/ostd/libs/ktest/src/tree.rs b/ostd/libs/ostd-test/src/tree.rs
similarity index 100%
rename from ostd/libs/ktest/src/tree.rs
rename to ostd/libs/ostd-test/src/tree.rs
|
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`
|
2024-07-03T08:57:04Z
|
0.6
|
6414111cc57b42db2bae1a0c8b01b85c3830a3b3
|
|
asterinas/asterinas
| 954
|
asterinas__asterinas-954
|
[
"871"
] |
cd2b305fa890bca9c4374ccd83c9ccb24bf8dda3
|
diff --git a/docs/src/ostd/a-100-line-kernel.md b/docs/src/ostd/a-100-line-kernel.md
index 3962907a02..7cfa3bed60 100644
--- 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.
@@ -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
index 4c96985542..977ade064e 100644
--- 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
index 2fa4e61acd..9387dc507a 100644
--- 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
index 676c44d009..3061c071b7 100644
--- 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,
@@ -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();
@@ -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");
@@ -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 a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines.rs b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines.rs
new file mode 100644
index 0000000000..9c41a6f980
--- /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 a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/hello.S b/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/hello.S
new file mode 100644
index 0000000000..140432d095
--- /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 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
new file mode 100644
index 0000000000..889779f7b7
--- /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!(),
+ }
+}
|
"[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;
```
|
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
|
0.5
|
cd2b305fa890bca9c4374ccd83c9ccb24bf8dda3
|
asterinas/asterinas
| 567
|
asterinas__asterinas-567
|
[
"555"
] |
5fb8a9f7e558977a8027eec32565a2de6b87636b
|
diff --git a/.github/workflows/license_check.yml b/.github/workflows/license_check.yml
new file mode 100644
index 0000000000..29fd6bb2f0
--- /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 a/.licenserc.yaml b/.licenserc.yaml
new file mode 100644
index 0000000000..297579edba
--- /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
index ec7f5b34cc..d937389fd3 100644
--- 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
index 0c2017fb8b..cff89a754b 100644
--- 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
index 2c243b413c..bd52ba4417 100644
--- 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
index 4150e70b51..cf758ec163 100644
--- 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
index 1e94c0d644..d2df419919 100644
--- 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
index ee4347c673..b23ebf0ebd 100644
--- 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
index e7acd3ca26..fcdbde1be0 100644
--- 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
index 3a27a515fb..227a135464 100644
--- 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
index 3eb8334535..3819aff46b 100644
--- 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
index ff8f9b191f..a5e358a8d1 100644
--- 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
index 826f59d869..a66f005fb1 100644
--- 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
index 3bacaae656..492f40cefa 100644
--- 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
index 8916169186..fef7662045 100644
--- 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
index 42d329f4d1..e5c60c90bf 100644
--- 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
index 9499ac3f29..d588d790ab 100644
--- 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
index 8e628e9958..30ae618a10 100644
--- 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
index d98548167f..4aa2c3cd26 100644
--- 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
index df08aef4c3..a98c0667e6 100644
--- 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
index 7f984b78ea..a40e3a072b 100644
--- 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
index d584d69fbc..d670bc29fc 100644
--- 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
index 7e310d919d..ef8e55a382 100644
--- 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
index 2a54aa670f..0640178458 100644
--- 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
index 8c7e0130c7..02575ecfd6 100644
--- 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
index afc9e10dc5..70e047f2d7 100644
--- 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
index 8c41e0889d..6a6eed745d 100644
--- 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
index f0addb37ae..36b3e74456 100644
--- 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
index be4ecf4415..7847499f10 100644
--- 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
index bf30afed81..da31bf41fe 100644
--- 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
index 76ae1d1ee0..ea578dff84 100644
--- 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
index 008c9ec8ec..4af2b96602 100644
--- 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
index fbe04eaa03..719c8ee59f 100644
--- 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
index f6cd07aa0f..41acea5820 100644
--- 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
index 1386d7a0d2..2b53b00275 100644
--- 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
index 5d0dc6db43..ed27662381 100644
--- 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
index 34a8d9bcbd..00b66265bd 100644
--- 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
index 5d8fd7bfe1..db93a97ffe 100644
--- 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
index 463b91dce6..1d506ab2f4 100644
--- 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
index 81441e5e3d..437e21e89e 100644
--- 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
index cc4ba75125..44d78c3ffc 100644
--- 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
index aee24d1f3b..4f3bccc9ea 100644
--- 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
index 69fce02ffa..2f830ee54b 100644
--- 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
index f68dff1b09..b8158dd21b 100644
--- 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
index ac2fcdd243..10fa73f397 100644
--- 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
index 6afdc118ab..0e92fa6cc6 100644
--- 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
index daf3b965da..38ddac64b3 100644
--- 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
index 03e2e69738..1dd0a5fbac 100644
--- 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
index 4c58bd7401..f55f43e386 100644
--- 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
index 24e5ef3473..3654081ec5 100644
--- 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
index b487d8f07d..9082f69417 100644
--- 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
index 63628e74f9..3cceb0354f 100644
--- 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
index e162da67eb..5305afc160 100644
--- 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
index b1c5f36ec9..dea1beb1f1 100644
--- 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
index 7750238624..9965837ea1 100644
--- 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
index 110fdad690..ba19c64fd1 100644
--- 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
index c767d742d7..46cc56d185 100644
--- 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
index d4497b5474..9552a86f44 100644
--- 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
index 416ade6c83..145e2c156b 100644
--- 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
index d0a3193ef2..0f164f29ce 100644
--- 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
index 4b94bf6b3b..96a6ec9813 100644
--- 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
index fa6676d10e..bd859950b6 100644
--- 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
index 6ad3cb3de8..55c2e0a22a 100644
--- 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
index 9486c22598..01468fcea0 100644
--- 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
index 8e5f0b868a..7b2316dcea 100644
--- 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
index 57d8a06649..b3786a44cb 100644
--- 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
index bc93334ac2..c7c196faac 100644
--- 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
index 85656935c5..3c6c5d34d2 100644
--- 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
index 23b37ea10a..cbe24ad2b6 100644
--- 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
index 1e64144d57..74a740203a 100644
--- 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
index 360ba8ddb0..6bc7fffbab 100644
--- 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
index a39913fb34..d694bfa7ae 100644
--- 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
index 97775de01d..7ea176fcf2 100644
--- 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
index 7e8cbe46ba..ac0797474b 100644
--- 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
index 46078ac42f..f08cf2003a 100644
--- 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
index 5981c83dcb..833ae871c5 100644
--- 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
index 0d042e2c74..991d006170 100644
--- 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
index 4f05e9ae23..ebd821c847 100644
--- 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
index 6a577c4a3a..8f895d14b4 100644
--- 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
index d2bd40cda4..90034ae738 100644
--- 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
index 40185cffda..260d14df33 100644
--- 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
index 4456f19f15..1520392168 100644
--- 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
index a8d5bae7b6..0b7f5d6a6a 100644
--- 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
index 551528d7d6..dcccd0a7d0 100644
--- 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
index 2b945b6da7..43e53ac107 100644
--- 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
index 0f23b5b061..97851566b8 100644
--- 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
index 0c86e31c35..e4717e64b0 100644
--- 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
index 9b89bc6c4f..d351464d3d 100644
--- 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
index d5b1738f47..0c94155a99 100644
--- 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
index 265372801c..9d171a5386 100644
--- 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
index 872de9788e..e49dbabc74 100644
--- 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
index f78aadfa50..6f5f5c084d 100644
--- 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
index 4f13e4055d..d611e17bf0 100644
--- 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
index 35855adf9c..abd5bcebd4 100644
--- 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
index 34fb73e459..f1b1c82a6c 100644
--- 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
index 081c39718c..1d1bbaa299 100644
--- 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
index f252defb71..1f71e01967 100644
--- 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
index 7776f6cd49..6bbd67be77 100644
--- 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
index bdd36c1797..6aaed0245a 100644
--- 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
index d89f970e9b..566d4238d7 100644
--- 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
index 14dcbc47a5..67c5c99862 100644
--- 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
index d4d9b8d0b5..af0922a436 100644
--- 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
index 89a3df99bb..9db926ef8d 100644
--- 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
index f3078beb94..f9692e86ce 100644
--- 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/linux-bzimage/boot-params/src/lib.rs b/framework/libs/linux-bzimage/boot-params/src/lib.rs
index 8d23876dc0..4cd390a87e 100644
--- 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
index b62c925afd..34ee01ec4f 100644
--- 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
index 9e7870000c..babb18cb67 100644
--- 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
index 16c83bef1b..740c5e15ea 100644
--- 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
index af5b57d4b7..66d4b53118 100644
--- 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
index 74ad42675c..386f991ebd 100644
--- 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
index 6f43a3d85c..158c92ee9d 100644
--- 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
index 7e90322691..bb972ea708 100644
--- 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
index aeeaa8cb57..33a414e25b 100644
--- 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
index b458b50553..8637161325 100644
--- 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
index d1022586a7..d3acbf7044 100644
--- 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
index b11559c7a9..68f92fa361 100644
--- 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
index 627019f3e7..d1e34bdac3 100644
--- 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
index 7a0f18fd55..89db788405 100644
--- 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
index 32a48f1ec3..199f9b3993 100644
--- 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
index 504063a71a..131e44a01e 100644
--- 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
index 29d47f6242..9d75959d53 100644
--- 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
index d500efeeae..350f28c348 100644
--- 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
index 1eaf81a83d..c9884c97af 100644
--- 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
index 2d0d54e25a..77de60dfd8 100644
--- 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
index dba18d0729..fb47221104 100644
--- 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
index 68cd6e29b5..6b32e65c7e 100644
--- 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
index 409e34f352..fc99b71aa7 100644
--- 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
index 7ccc418a9e..f3477110d3 100644
--- 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
index bbb7737d2a..6e7a577d7b 100644
--- 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
index 64da749303..7d17163dbd 100644
--- 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
index 5f70f66350..9f616d2847 100644
--- 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
index d393e1212e..bf39ea0bf8 100644
--- 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
index a7bda5d968..45bd90a0f0 100644
--- 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
index 014411efd2..4402eac96f 100644
--- 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
index 238cf33ab7..00cb44cdff 100644
--- 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
index d818c62861..3bdfa103dc 100644
--- 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
index d393e1212e..bf39ea0bf8 100644
--- 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
index dfbfc2efc8..47dd6246b2 100644
--- 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
index d6dcb9e580..e299341f1d 100644
--- 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
index d7f033f7e2..f77edde9cc 100644
--- 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
index 05ff449d2d..c603a781ad 100644
--- 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
index 5deb4f724b..e2eb146a91 100644
--- 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
index 238cf33ab7..00cb44cdff 100644
--- 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
index 3cf6c075a6..b18b834834 100644
--- 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
index 05ff449d2d..c603a781ad 100644
--- 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
index a54c79b969..da57117ce2 100644
--- 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
index 23b5388b33..9d47b8d7f4 100644
--- 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
index 0441cc00bc..73e66f53c1 100644
--- 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
index b4fa0b258e..91996bd8c2 100644
--- 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
index a290bf3f27..8302ed0dd3 100644
--- 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
index 1709914768..49c2be8763 100644
--- 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
index 2ad81b8de7..0f5ce5cf04 100644
--- 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
index 435097d97d..12bb8c991d 100644
--- 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
index 041ab1f06f..0befa4ee2e 100644
--- 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
index f2ca1c9ccb..064b769dd3 100644
--- 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
index 2eef3474a6..8f1ee0ae68 100644
--- 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/pty/Makefile b/regression/apps/pty/Makefile
index 05ff449d2d..c603a781ad 100644
--- 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
index 220d2f3eb3..2ef2e04ffa 100644
--- 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
index f2b54367a5..2e1e19d5a1 100644
--- 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
index 432272b5d7..0dfbc0f10c 100755
--- 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
index 9e8145891a..3b00757e26 100755
--- 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/shell_cmd.sh b/regression/apps/scripts/shell_cmd.sh
index 7136d793ac..49d6ab2c47 100755
--- 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
index d393e1212e..bf39ea0bf8 100644
--- 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/runner/src/gdb.rs b/runner/src/gdb.rs
index 209680b4b7..1985d002c5 100644
--- 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
index 3e8e9b1041..f92a18b6db 100644
--- 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
index da68453ad0..fb7c0255b1 100644
--- 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
index f2051d99bc..46f7dd6273 100644
--- 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
index 78be09ff36..f3141d8398 100644
--- 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
index dbdc2a7b99..f3ee10acd5 100644
--- 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
index a193cfd336..13eb6c96e9 100644
--- 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
index 6bc00e4d2d..447a79a852 100644
--- 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
index 409907417b..723f9c3902 100644
--- 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
index dca1f8ff2f..77dc3c68ab 100644
--- 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
index d0403e9c43..749a8b15d4 100644
--- 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
index 431856d1f7..c223cd9944 100644
--- 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
index 05c8820b75..221e69cc57 100644
--- 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
index 3edf755095..815a1e8221 100644
--- 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
index 0769b40fb6..e0322c2736 100644
--- 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
index b2d2b9c447..118a8d94e3 100644
--- 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
index 04ea774669..9e4af881ec 100644
--- 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
index b688d42355..a3a003e8f1 100644
--- 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
index 9c165d56bb..1f81930b1e 100644
--- 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
index a6dc47b6c4..92ed6476a3 100644
--- 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
index d44fc34a8c..97a68eec5e 100644
--- 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
index 6ff7cf7d6e..5e0613087f 100644
--- 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
index 8473d1cce0..5e508c3ac1 100644
--- 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
index f4e2373195..411bcb9f8a 100644
--- 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
index d791f7e33c..85276b0114 100644
--- 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
index b322d6a33e..b5a8fce11a 100644
--- 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
index f447d0f900..e5a345fc62 100644
--- 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
index eea3e13600..011acd0059 100644
--- 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
index a8e00cd5c2..5c2defdbc4 100644
--- 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
index 0fb980d5b3..a819e3b042 100644
--- 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
index d8ba25912f..aa2b1da8f9 100644
--- 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
index c1179ab369..2294fbb0ec 100644
--- 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
index b88f1c3d3c..7940c44381 100644
--- 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
index 6b5e896716..34d70b56be 100644
--- 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
index 50c5c3a4ca..092d139e95 100644
--- 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
index 60f2dce266..eca2e0a521 100644
--- 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
index e4d21dc8bb..82c88715de 100644
--- 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
index cc3a56f117..71bf7a2391 100644
--- 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
index 13bb42c18b..d26453ff33 100644
--- 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
index 82ee9f27df..e4f90dcf1f 100644
--- 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
index 46e083b86f..28a1ef1e13 100644
--- 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
index f8a4c6a7a9..e360c99230 100644
--- 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
index 6d72489665..f3af5ebb5a 100644
--- 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
index f67f1f0976..019da9d96e 100644
--- 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
index 5e37120f00..eb6dadaeba 100644
--- 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
index 4fd80e8c75..a7eb1964b0 100644
--- 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
index baeb093acb..b5dc34d405 100644
--- 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
index 3ca7d27e20..86c4ef58b7 100644
--- 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
index 6cf791a9f5..eb48870da8 100644
--- 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
index a423539b50..3d7fcd513e 100644
--- 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
index e7e929bff9..9c92045516 100644
--- 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
index d42995e2fa..9368b59327 100644
--- 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
index 79d1248d29..add0439d5f 100644
--- 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
index 7137a64edf..81426c621c 100644
--- 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
index 8ee323a677..45655f692e 100644
--- 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
index 748edb3ecc..e10cc948b0 100644
--- 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
index 4ed22a5e20..74f13e32ab 100644
--- 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
index 6a493d8dab..ba50ebace2 100644
--- 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
index e5f8afb799..b0f76d7a0e 100644
--- 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
index 8801680db3..951dd1084b 100644
--- 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
index 29ace51903..63117009cd 100644
--- 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
index 1aea18dadb..dfb1f53940 100644
--- 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
index b7074e719c..d9f256e201 100644
--- 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
index 687ecb762b..82828d02c7 100644
--- 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
index e3b695cd97..f72c8fa02a 100644
--- 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
index 2ef474470a..750803b5e2 100644
--- 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
index e23d819cdc..8d2b1346da 100644
--- 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
index 1c4ff51abf..0ca220e335 100644
--- 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
index 7f8111f344..029bddafdd 100644
--- 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
index b977e5f87d..51a625d351 100644
--- 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
index 6f2052b49a..dc5c11fa0d 100644
--- 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
index f5bbd4c00c..376fe1eda4 100644
--- 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
index d93928f5dc..1f45b4370f 100644
--- 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
index 99f75ff862..4af0873749 100644
--- 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
index 398d86adc9..1d23120697 100644
--- 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
index 6bb34fbfd1..1f0b29b793 100644
--- 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
index 5282766780..8fe9d06fda 100644
--- 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
index 66ae3bfc90..c4fbbed750 100644
--- 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
index 1941328dfa..1d85f6b64d 100644
--- 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
index da924b651a..3214eced1e 100644
--- 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
index 5f60bcdb28..5ca1faefe1 100644
--- 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
index 45b47c0a9f..4113fc7cb3 100644
--- 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
index e65f431940..691314f704 100644
--- 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
index fd4ae92123..83d936a3b9 100644
--- 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
index 249746aab0..311217dbb7 100644
--- 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
index 61bdf58d5e..ca79ada0e6 100644
--- 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
index ff7774871a..b1c107c249 100644
--- 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
index 6fc487b7a6..716389edcd 100644
--- 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
index 631b96ee09..8b8c2cde9b 100644
--- 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
index 8d28703194..cd41c9d2ab 100644
--- 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
index 8bc4c71bd7..23e0156fd5 100644
--- 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
index a3eeb0a0ce..df48d5fdec 100644
--- 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
index 776eec7dfa..b98b032ef2 100644
--- 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
index f554f46213..3e62d1b00a 100644
--- 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
index e84dba0a22..695edfab00 100644
--- 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
index 1744f4815e..77e2ac0cba 100644
--- 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
index 644e8d170f..52bf23673b 100644
--- 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
index d7992ca49a..6ccf69c793 100644
--- 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
index f1fec834a4..4a9e4c17cf 100644
--- 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
index 20b1e3533b..7b906a7f92 100644
--- 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
index 22a9f42f91..016f137465 100644
--- 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
index 49c9dc004b..335757b04d 100644
--- 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
index da4548e2ae..bb4987b53f 100644
--- 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
index a046a7655a..0fa34b3f79 100644
--- 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
index 60263a6acd..560db8c30b 100644
--- 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
index 251c623122..22076b9ad6 100644
--- 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
index ad810575c6..5312f26009 100644
--- 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
index d15fa01a88..3eb4e5163a 100644
--- 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
index 289438e0a4..68e22496d7 100644
--- 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
index 8a2f17cadd..7a6ab7c499 100644
--- 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
index 9bf41b31c3..c407cf701c 100644
--- 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
index ea61135800..b3afaca680 100644
--- 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
index cbf76ba378..29cf2529b3 100644
--- 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
index 722953cafd..164bd76a4d 100644
--- 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
index dc6bfe1d50..d6e69014a7 100644
--- 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
index a4c3d8c6e6..21cf04717f 100644
--- 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
index 2bd2642ce4..d47b215741 100644
--- 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
index 45c4b6b7ab..43ac243b8a 100644
--- 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
index 2a2e9d98f3..42e54bb903 100644
--- 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
index f06a5d8691..033d52dabe 100644
--- 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
index 01143dc471..e611503703 100644
--- 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
index 0901c544b3..4503dcfa34 100644
--- 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
index f5595834ca..e71fc4ffcf 100644
--- 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
index 044a6bfdf7..6cef1b12f2 100644
--- 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
index e685ab1db9..2e2876b81a 100644
--- 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
index 2645c332bd..f2d124b948 100644
--- 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
index a58704a868..44063f9af1 100644
--- 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
index fbd5e9eb01..21e3aac3f7 100644
--- 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
index 01890a4466..8bee94f164 100644
--- 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
index 0d40e18fcf..cfb66e2f8e 100644
--- 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
index 92a7013cd3..bdd40c8708 100644
--- 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
index d7aced038e..fe6b08e167 100644
--- 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
index d4dd1acac0..b693a24e9e 100644
--- 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
index aa49034ff9..252a6083fa 100644
--- 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
index bf368dd371..52ac4d1b77 100644
--- 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
index e1ee83a5f2..d359110d28 100644
--- 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
index 0e18ff42a0..c1261a7189 100644
--- 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
index 9f8ee372c4..6ec2352fa4 100644
--- 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
index 261035cf8f..6f06da6f03 100644
--- 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
index 102a7d8180..9ea1cabf0b 100644
--- 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
index 1f66a3f507..b6cf51ac68 100644
--- 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
index a5d5d299e2..c70a8f6173 100644
--- 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
index d97e3ff47f..9a1ff54f51 100644
--- 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
index c2d33b4d1c..ec0f7f29eb 100644
--- 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
index bc3d238005..8f8cfbfe4e 100644
--- 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
index 01b6b7ff27..c78bb6e92c 100644
--- 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
index e99a9c1e37..db633feb4f 100644
--- 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
index c37b1c0f3c..1f22ba9a96 100644
--- 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
index 2d92a02fd9..b629664ae1 100644
--- 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
index c1f73a9079..c81b4a3216 100644
--- 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
index 3cbb682459..8b8f66103e 100644
--- 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
index d4f4b5e50f..d470e5e314 100644
--- 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
index 0d54d2de80..698dbf54ad 100644
--- 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
index f4d611b3f0..f7e2602224 100644
--- 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
index 9071fd3786..30e9c8b67f 100644
--- 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
index cc6c341243..748c5ca559 100644
--- 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
index c406eb52c3..4f3650a48c 100644
--- 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
index 52fd78f7b0..ca5d91ff0c 100644
--- 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
index 5eb6390b0e..1ecc7a950b 100644
--- 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
index cf76c1473d..7478fe95ed 100644
--- 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
index 68afa53184..20c4d48930 100644
--- 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
index a8f36077b1..e7fe906deb 100644
--- 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
index 81fa84f9e8..8eecdb4f4d 100644
--- 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
index b9b92c27d9..80fadb52a0 100644
--- 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
index 538603340e..d40e7e0169 100644
--- 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
index 9ca391e71e..0e3b0ea774 100644
--- 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
index 6edd777585..ad3251112b 100644
--- 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
index 9a0d6c5bdc..82f639dbce 100644
--- 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
index f5e162a356..158182d398 100644
--- 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
index 07e9848a33..37945db687 100644
--- 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
index a10e8db706..34f81cda50 100644
--- 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
index 20da64981b..cb45df21d9 100644
--- 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
index 4bd5658954..9c3e23cc34 100644
--- 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
index ef96eb1017..ddadb36778 100644
--- 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
index 5507dace7b..6cb075ce13 100644
--- 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
index 1259f3f3f0..7f7e4094da 100644
--- 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
index 4679efe926..fa18fef202 100644
--- 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
index b8a945ed85..6cc4347e61 100644
--- 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
index 8003bfbf42..035ceb4f1d 100644
--- 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
index f4b5057e2a..5116d26cc7 100644
--- 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
index 7bbe124485..01caa00db9 100644
--- 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
index d5af056c65..5fda59fa6d 100644
--- 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
index 6ec2981788..6cde240486 100644
--- 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
index 9a69d5752b..3c656bec44 100644
--- 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
index 66ce097d16..bb3ce62448 100644
--- 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
index 94d66b319a..bcca5dc5ad 100644
--- 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
index a3f4c494ba..d558d9bf5e 100644
--- 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
index d5d216c34e..84b1782f62 100644
--- 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
index 468b7aa7e0..d38634caab 100644
--- 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
index 7dff106e40..ba27374e12 100644
--- 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
index 228c8f1f4f..e125cbd90a 100644
--- 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
index 499f93d038..af1e43e63f 100644
--- 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
index 3dce8da1d5..3605525686 100644
--- 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
index f1cc047cbb..6be5b846f7 100644
--- 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
index 20ebdd39f4..35dbc0e758 100644
--- 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
index c1456e1f5b..e779e48372 100644
--- 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
index 784525ac20..3aa7cb8200 100644
--- 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
index 3c8b0f7d72..cbf95a0299 100644
--- 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
index 15f4a94afc..47d39dda7b 100644
--- 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
index 9c4593e1a0..240ac2a6f9 100644
--- 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
index 37b472609f..a741825ad5 100644
--- 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
index 950479d582..cd73cda955 100644
--- 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
index c277c895af..3c2e03ab1e 100644
--- 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
index 6cb0f075b6..118c9c83f0 100644
--- 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
index 937f2e75a5..3203e3102f 100644
--- 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
index f644eb2ca4..26510b6618 100644
--- 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
index 4758832ee2..d0565f13fa 100644
--- 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
index 76a48accbf..f93c764d74 100644
--- 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
index 9b687ea8a1..544fa82ce2 100644
--- 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
index b7ce816798..374080df97 100644
--- 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
index 799af8113c..586c8080a4 100644
--- 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
index cdd17f7540..abe7ad9d17 100644
--- 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
index 15f77042a1..07f2094c3c 100644
--- 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
index 40d56e149e..423080be32 100644
--- 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
index 6b172d0616..4c2b96d9ee 100644
--- 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
index 5e0e512618..05bb10f224 100644
--- 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
index 99e4d45724..f57eba0ce2 100644
--- 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
index b6cf2d58ea..bfa1437c37 100644
--- 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
index 4523c1d98f..235ad706cb 100644
--- 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
index 5977afcf9f..b0756329b5 100644
--- 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
index 17cc3b505c..203691769a 100644
--- 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
index c94a4a7e06..5a0ce97a3c 100644
--- 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
index ec49a746d2..93630a2191 100644
--- 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
index 528033a251..f32b3298aa 100644
--- 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
index fffaa12ad0..8bf5025e6c 100644
--- 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
index a78992ea0b..e26f398183 100644
--- 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
index b1ca852959..4994c50918 100644
--- 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
index c94f0336d1..d7254a2fb5 100644
--- 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
index fc9d9f2402..c13c18f062 100644
--- 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
index 3061664ad1..d7c5bc076d 100644
--- 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
index 5523af8eb7..a7ad69e008 100644
--- 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
index e919774e85..80d600ab6f 100644
--- 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
index b4e36b47e7..a936243ae2 100644
--- 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
index fac3921353..8be2f326a4 100644
--- 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
index b15e8579d8..b60968dcb2 100644
--- 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
index b1eb00a160..2a14eb0d10 100644
--- 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
index aca5c09395..b5d3039937 100644
--- 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
index bbd1fe402c..fbd21fe1a1 100644
--- 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
index 3fcbaf0478..30729377e0 100644
--- 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
index 1e31934e7e..4038e945b8 100644
--- 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
index 31d491ea86..28dfda1ca8 100644
--- 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
index 58d04434e5..f464f9965c 100644
--- 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
index c959e33e6c..e8842b8c96 100644
--- 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
index ee29e73c0d..bbf0b24c8d 100644
--- 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
index 8a85b28613..0f980491f6 100644
--- 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
index 7b718a60ae..1d7ba72388 100644
--- 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
index 319de710b0..56985461a3 100644
--- 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
index 3ee51eeb69..01b419e0fd 100644
--- 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
index 2ea24c37a7..7df17147d1 100644
--- 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
index 56178967cc..47835f26f2 100644
--- 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
index 610d24186a..6b5d424613 100644
--- 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
index 6c2f8d7020..e2d142c9f8 100644
--- 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
index c2ae6b6f50..0a62b9ec71 100644
--- 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
index f93b4e653b..b91ea082d0 100644
--- 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
index 721644c3de..d527425b41 100644
--- 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
index 13990c609b..f9f0d4fc02 100644
--- 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
index f0689af7ee..1f37d459c8 100644
--- 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
index 180e22fa0f..1b56ffdcc8 100644
--- 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
index 76d6f5bb84..a47109bbb6 100644
--- 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
index 7bd70a11ad..49fb4a7786 100644
--- 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
index 6d478a4c54..dd56e419fd 100644
--- 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
index 6f8e04ef59..3b9223a431 100644
--- 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
index 36c1be8576..128d232d18 100644
--- 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
index 954b473d78..66af78772b 100644
--- 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
index d37e284602..10003807fc 100644
--- 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
index 491b7fc6a7..575c59952b 100644
--- 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
index f8f2193eda..b98ea48dab 100644
--- 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
index e739bae54d..e309239c11 100644
--- 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
index fad21485b9..54ef4b542d 100644
--- 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
index 27c438b4d4..7bcbe03e03 100644
--- 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
index 786bfb022b..4f1759500d 100644
--- 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
index df3d96f3ce..dd522eb321 100644
--- 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
index 8f57012213..5478ac1004 100644
--- 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
index 973163d72e..93d90dc710 100644
--- 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
index 4833cc042f..2c89df5c48 100644
--- 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
index 5ab582f6ed..25b5568279 100644
--- 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
index ac0d1b8827..32bef2c92d 100644
--- 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
index 6ec5da219b..1a56f13c49 100644
--- 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
index f12ba29e38..55ba051124 100644
--- 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
index dbba1dad88..59bf2a924d 100644
--- 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
index 2dd766d145..008de71926 100644
--- 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
index 2441d55675..c3398a3ab6 100644
--- 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
index cda168e79e..8008c4c79b 100644
--- 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
index ef7346faae..2f28362403 100644
--- 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
index c39356707c..e1b9ad181f 100644
--- 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
index c74e6f6e31..567632e494 100644
--- 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
index d448b97a7b..f566555292 100644
--- 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
index ddeb243f48..8a81c2ecae 100644
--- 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
index 3bae9a713d..534bd52d8c 100644
--- 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
index 277fa78a5b..ca0bc9b87f 100644
--- 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
index b98e07461a..16129fa85f 100644
--- 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
index e8f9f28626..cac1244942 100644
--- 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
index 8bfc763836..5cd77a70bb 100644
--- 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
index eeb946bbb8..847303a3bb 100644
--- 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
index 9acf79c01c..77e028b63b 100644
--- 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
index 36e8636c34..758820e051 100644
--- 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
index a8b730cdaf..eb215e431f 100644
--- 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
index 8c35b4cdea..b95b1a3a9e 100644
--- 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
index 0eccd29df2..23e0b6e486 100644
--- 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
index 90612db888..a662eee8de 100644
--- 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
index 40a315f2c1..d9aa56f734 100644
--- 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
index bf7b23f45d..85a930ac22 100644
--- 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
index d1c0a609b9..137e599c84 100644
--- 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
index aa300819fe..3fbb0ec3e7 100644
--- 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
index e64679937c..c8259af478 100644
--- 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
index c9bfd09e7f..dcad0b29e1 100644
--- 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
index f009294332..6ab14fcfba 100644
--- 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
index 7dc19d9903..e2fc86fef3 100644
--- 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
index dbaa13240b..f5cbf39168 100644
--- 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
index c63a701bfb..7d5a184425 100644
--- 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
index 643020113f..54cf034a2b 100644
--- 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
index 1941370c4e..6715246475 100644
--- 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
index 28366239f1..1e9d0c1f03 100644
--- 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
index 1b46d11974..06a1325907 100644
--- 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
index f1dd60c14d..82a9c9b6a3 100644
--- 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
index 07cd6b6879..65b970e92e 100644
--- 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
index a96d1d391f..20feeb8e35 100644
--- 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
index 6cfaba6c60..f26762bd47 100644
--- 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
index b3d612cc43..4358e692ba 100644
--- 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
index 60df03be06..eec44d3386 100644
--- 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
index b927988c99..d5d9bb9b91 100644
--- 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
index 6a690c54af..bab26771d7 100644
--- 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
index be39fb5b3d..aaa0fe91af 100644
--- 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
index c321170c74..5a73f2fc14 100644
--- 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
index c715b3d4b9..8a438e3ef8 100644
--- 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
index 856161045a..ceefd0974c 100644
--- 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
index 59e5facf81..6135e4342c 100644
--- 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
index 4e55e7b69a..390578cb77 100644
--- 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
index d8470f75b3..963b44dd9f 100644
--- 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
index 919a5318d1..ba308618e7 100644
--- 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
index 3ba850ed88..d60ee3335f 100644
--- 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
index 462864cd12..b3040fa5de 100644
--- 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
index f9c8682ed3..513c9e0613 100644
--- 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
index bca7a387b0..21ad5b4183 100644
--- 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
index 210358bc8e..62f6f8a6ff 100644
--- 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
index db88aa74eb..0df1aea948 100644
--- 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
index 15a6078c84..394d343a38 100644
--- 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
index cf66b4a63a..8dcc2f1992 100644
--- 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
index 7e627e8cd2..aebdc8e88f 100644
--- 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
index 426e5c1232..ebf608714c 100644
--- 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
index cd776f7394..6a09a1100e 100644
--- 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
index 986d58794b..6464854e77 100644
--- 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
index 242b9a17fa..7b577b225c 100644
--- 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
index 28b205c30e..b4d623ab53 100644
--- 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
index 6e79c68e40..9686637d86 100644
--- 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
index 5422358834..fdb2c69c25 100644
--- 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
index 138dcbe386..59fa7cd76a 100644
--- 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
index ced1b01df5..3b17738f4f 100644
--- 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
index df0ae43cf0..18fe069016 100644
--- 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
index 248ac40a7d..1b3fe9bc8b 100644
--- 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
index b1c4bd9528..22be8143a5 100644
--- 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
index 0ee957d5ea..c7ee7ce4b5 100644
--- 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
index b84b2ccd9e..67bad9b249 100644
--- 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
index 88e559cc4b..22d84483e5 100644
--- 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
index d3893c3509..da25e31ce0 100644
--- 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
index b728b4e185..7824a92f50 100644
--- 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
index 08e7158d9d..ab863321cd 100644
--- 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
index 0b9b9e99e7..c3de639da3 100644
--- 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
index 2938b084b2..6569cf5ab2 100644
--- 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
index 783f59b225..3777fe45c1 100644
--- 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
index 8d86bb25cb..93fe585a83 100644
--- 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
index 3fc35f5060..5b38e6bbbf 100644
--- 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
index 9e902c990e..a215429db8 100644
--- 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
index 707b2ea89e..d0d1a078f7 100644
--- 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
index 6382901bd3..05268a661b 100644
--- 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
index fab8a69a27..1890a189bb 100644
--- 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
index 4a378237b1..43bc66f0d9 100644
--- 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
index 9f7feace1c..96a1254d89 100644
--- 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/component-macro/src/init_comp.rs b/services/libs/comp-sys/component-macro/src/init_comp.rs
index 4f3f6624d2..6137428a68 100644
--- 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
index 5fb3c8f2bf..0f777958b4 100644
--- 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
index 931f27196d..f775271814 100644
--- 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
index c019bde45c..1bffe3a69c 100644
--- 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/controlled/src/lib.rs b/services/libs/comp-sys/controlled/src/lib.rs
index a047e8b07e..d4f313dce6 100644
--- 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
index 39efbae8f6..61147e2bc4 100644
--- 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
index fa2924f3fb..9955c83afa 100644
--- 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/int-to-c-enum/derive/src/lib.rs b/services/libs/int-to-c-enum/derive/src/lib.rs
index a9793d2ff6..4fb34c2803 100644
--- 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
index b3a58ec49f..39b9264dba 100644
--- 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/keyable-arc/src/lib.rs b/services/libs/keyable-arc/src/lib.rs
index c96b710930..a1761a26f1 100644
--- 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
index a9f0afe554..77c7524e15 100644
--- 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
index dc9743bcb9..c6cf57dfcf 100644
--- 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
index 3f579c7706..c0a5d5ffa3 100644
--- 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
index 4b1445514b..5a67ae84dd 100644
--- 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
index 07b8a7404a..f3e7ff6070 100644
--- 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
index 66b19330a4..aba553ae08 100644
--- 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
index 4e21c92cb5..062eac1ef4 100644
--- 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
index 2b1fd4089d..d7d1c4acd9 100644
--- 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
index f11eb3dcb8..4037dd79f2 100644
--- 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
index 0d4366f38e..0d42eab1a3 100644
--- 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
index fcc9d53d8f..7313b17866 100644
--- 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
index 854e16da2a..23dc6af729 100755
--- 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
index 8af048e769..efaa556ee6 100644
--- 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
index 92af52d14c..a7e3334281 100755
--- 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/framework/libs/ktest-proc-macro/src/lib.rs b/framework/libs/ktest-proc-macro/src/lib.rs
index 30fb919e99..6edbcdbbd6 100644
--- 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
index 7ba5795027..e6a2d04d0f 100644
--- 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
index e62aa5eb0d..434acb49be 100644
--- 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
index 1f60ba962f..9711811f20 100644
--- 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
index 913ebe0a52..3a99e60ba4 100644
--- 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/pthread/pthread_test.c b/regression/apps/pthread/pthread_test.c
index 138e59b574..1c601b456b 100644
--- 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/scripts/run_regression_test.sh b/regression/apps/scripts/run_regression_test.sh
index 1dbba14741..57d87ae152 100755
--- 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/signal_test.c b/regression/apps/signal_c/signal_test.c
index 8d800feef3..1193173b04 100644
--- 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
index 7187429001..e31292967f 100644
--- 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
index acca28e15d..60b047e940 100644
--- 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
index d66c8562ce..3d2d75e519 100755
--- 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/services/libs/comp-sys/cargo-component/tests/duplicate_lib_name.rs b/services/libs/comp-sys/cargo-component/tests/duplicate_lib_name.rs
index 985ec2b4fe..ccc3c0fc8c 100644
--- 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
index e9ed461e5f..9c36b614ba 100644
--- 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
index 8707dedf65..c8d00d103f 100644
--- 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
index 79504c9682..678d688dc7 100644
--- 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
index 6ef8c6ee2e..3724d455e0 100644
--- 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
index d11d9626e1..3b5e2ca3f4 100644
--- 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
index 58802fe10a..4126bc6320 100644
--- 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
index 0875097625..66c9b41811 100644
--- 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
index 10ff955828..03ee5d5123 100644
--- 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
index 2bb2e5c42f..42cdb72f91 100644
--- 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
index eb87b21754..304060cc9b 100644
--- 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
index 64c7c8b136..92ea589798 100644
--- 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
index 871f73959b..805611d153 100644
--- 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
index b3ede6712d..2f6f615230 100644
--- 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)]
|
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
```
|
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
|
0.3
|
5fb8a9f7e558977a8027eec32565a2de6b87636b
|
asterinas/asterinas
| 561
|
asterinas__asterinas-561
|
[
"551"
] |
6dbf5d560deafea0dcec228e4cb2d5e53c756174
|
diff --git a/.cargo/config.toml b/.cargo/config.toml
index c353f95051..0b4b26d967 100644
--- 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
index d05eb6a071..30f72a3c84 100644
--- 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
index 29a8c03c1d..745d9711f1 100644
--- 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
@@ -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/COPYRIGHT b/COPYRIGHT
index ec66a4219d..1bfe4d99ea 100644
--- 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
index 67e48cc9f9..591a040cf6 100644
--- 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"
@@ -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",
@@ -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"
@@ -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",
@@ -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",
@@ -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",
]
@@ -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",
@@ -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
index 5d86a8379c..895bc690be 100644
--- 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
@@ -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",
@@ -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",
@@ -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
index 3f5a396ad9..91183d0331 100644
--- 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
index c4e5f2cbd7..485b26467a 100644
--- 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
@@ -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
index 1128e92a52..a0d5783ab8 100644
--- 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.**
@@ -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
@@ -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
```
@@ -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.)
@@ -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
index df176c1db6..0c2017fb8b 100644
--- 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
index 501530b428..bbba0f9432 100644
--- 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
index 99f5875342..feb3db7264 100644
--- 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
index 5f3ab2fa99..d370fb5433 100644
--- 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:
@@ -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).
@@ -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
index e5fd82c6ae..b6797dcf42 100644
--- 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
index b07173c8cc..476b053a8a 100644
--- 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_.
@@ -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.
@@ -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
index fd341d04dc..06150ae840 100644
--- 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
index b85e420922..d69aa19e8d 100644
--- 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
@@ -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,
@@ -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
index 3873c81619..e3e856b9b3 100644
--- 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.
@@ -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
@@ -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
@@ -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);
@@ -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;
@@ -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).
///
@@ -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;
@@ -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
index 31ee67d5e4..604a9ee7e1 100644
--- 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
similarity index 79%
rename from framework/jinux-frame/Cargo.toml
rename to framework/aster-frame/Cargo.toml
index ad99cea1b3..827dfcef25 100644
--- 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"
@@ -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
similarity index 96%
rename from framework/jinux-frame/build.rs
rename to framework/aster-frame/build.rs
index c8d65f3dc7..6bd57bc3bc 100644
--- 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/mod.rs b/framework/aster-frame/src/arch/mod.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/mod.rs
rename to framework/aster-frame/src/arch/mod.rs
diff --git a/framework/jinux-frame/src/arch/x86/boot/boot.S b/framework/aster-frame/src/arch/x86/boot/boot.S
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/boot/boot.S
rename to framework/aster-frame/src/arch/x86/boot/boot.S
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
similarity index 99%
rename from framework/jinux-frame/src/arch/x86/boot/linux_boot/boot_params.rs
rename to framework/aster-frame/src/arch/x86/boot/linux_boot/boot_params.rs
index 5150a19afc..b4a07971c8 100644
--- 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
similarity index 99%
rename from framework/jinux-frame/src/arch/x86/boot/linux_boot/mod.rs
rename to framework/aster-frame/src/arch/x86/boot/linux_boot/mod.rs
index fb932305d9..1967faa996 100644
--- 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
similarity index 82%
rename from framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/Cargo.toml
rename to framework/aster-frame/src/arch/x86/boot/linux_boot/setup/Cargo.toml
index 019b0c64cc..41ba76b240 100644
--- 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/build.rs b/framework/aster-frame/src/arch/x86/boot/linux_boot/setup/build.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/build.rs
rename to framework/aster-frame/src/arch/x86/boot/linux_boot/setup/build.rs
diff --git a/framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/linker.ld b/framework/aster-frame/src/arch/x86/boot/linux_boot/setup/linker.ld
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/linker.ld
rename to framework/aster-frame/src/arch/x86/boot/linux_boot/setup/linker.ld
diff --git a/framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/src/boot_params.rs b/framework/aster-frame/src/arch/x86/boot/linux_boot/setup/src/boot_params.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/src/boot_params.rs
rename to framework/aster-frame/src/arch/x86/boot/linux_boot/setup/src/boot_params.rs
diff --git a/framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/src/console.rs b/framework/aster-frame/src/arch/x86/boot/linux_boot/setup/src/console.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/src/console.rs
rename to framework/aster-frame/src/arch/x86/boot/linux_boot/setup/src/console.rs
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
similarity index 95%
rename from framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/src/header.S
rename to framework/aster-frame/src/arch/x86/boot/linux_boot/setup/src/header.S
index ab47ecbcb2..563a15e508 100644
--- 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
similarity index 98%
rename from framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/src/loader.rs
rename to framework/aster-frame/src/arch/x86/boot/linux_boot/setup/src/loader.rs
index d22eec0986..2f515c2025 100644
--- 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
similarity index 90%
rename from framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/src/main.rs
rename to framework/aster-frame/src/arch/x86/boot/linux_boot/setup/src/main.rs
index 22b98a187d..aa621aa655 100644
--- 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");
@@ -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/x86_64-i386_protected_mode.json b/framework/aster-frame/src/arch/x86/boot/linux_boot/setup/x86_64-i386_protected_mode.json
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/boot/linux_boot/setup/x86_64-i386_protected_mode.json
rename to framework/aster-frame/src/arch/x86/boot/linux_boot/setup/x86_64-i386_protected_mode.json
diff --git a/framework/jinux-frame/src/arch/x86/boot/mod.rs b/framework/aster-frame/src/arch/x86/boot/mod.rs
similarity index 81%
rename from framework/jinux-frame/src/arch/x86/boot/mod.rs
rename to framework/aster-frame/src/arch/x86/boot/mod.rs
index 584e07d5fd..ee4347c673 100644
--- 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
@@ -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/header.S b/framework/aster-frame/src/arch/x86/boot/multiboot/header.S
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/boot/multiboot/header.S
rename to framework/aster-frame/src/arch/x86/boot/multiboot/header.S
diff --git a/framework/jinux-frame/src/arch/x86/boot/multiboot/mod.rs b/framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs
similarity index 99%
rename from framework/jinux-frame/src/arch/x86/boot/multiboot/mod.rs
rename to framework/aster-frame/src/arch/x86/boot/multiboot/mod.rs
index 45a1582b45..3a27a515fb 100644
--- 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/header.S b/framework/aster-frame/src/arch/x86/boot/multiboot2/header.S
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/boot/multiboot2/header.S
rename to framework/aster-frame/src/arch/x86/boot/multiboot2/header.S
diff --git a/framework/jinux-frame/src/arch/x86/boot/multiboot2/mod.rs b/framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs
similarity index 99%
rename from framework/jinux-frame/src/arch/x86/boot/multiboot2/mod.rs
rename to framework/aster-frame/src/arch/x86/boot/multiboot2/mod.rs
index dda8fa31e3..ff8f9b191f 100644
--- 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/console.rs b/framework/aster-frame/src/arch/x86/console.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/console.rs
rename to framework/aster-frame/src/arch/x86/console.rs
diff --git a/framework/jinux-frame/src/arch/x86/cpu.rs b/framework/aster-frame/src/arch/x86/cpu.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/cpu.rs
rename to framework/aster-frame/src/arch/x86/cpu.rs
diff --git a/framework/jinux-frame/src/arch/x86/device/cmos.rs b/framework/aster-frame/src/arch/x86/device/cmos.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/device/cmos.rs
rename to framework/aster-frame/src/arch/x86/device/cmos.rs
diff --git a/framework/jinux-frame/src/arch/x86/device/io_port.rs b/framework/aster-frame/src/arch/x86/device/io_port.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/device/io_port.rs
rename to framework/aster-frame/src/arch/x86/device/io_port.rs
diff --git a/framework/jinux-frame/src/arch/x86/device/mod.rs b/framework/aster-frame/src/arch/x86/device/mod.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/device/mod.rs
rename to framework/aster-frame/src/arch/x86/device/mod.rs
diff --git a/framework/jinux-frame/src/arch/x86/device/serial.rs b/framework/aster-frame/src/arch/x86/device/serial.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/device/serial.rs
rename to framework/aster-frame/src/arch/x86/device/serial.rs
diff --git a/framework/jinux-frame/src/arch/x86/iommu/context_table.rs b/framework/aster-frame/src/arch/x86/iommu/context_table.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/iommu/context_table.rs
rename to framework/aster-frame/src/arch/x86/iommu/context_table.rs
diff --git a/framework/jinux-frame/src/arch/x86/iommu/fault.rs b/framework/aster-frame/src/arch/x86/iommu/fault.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/iommu/fault.rs
rename to framework/aster-frame/src/arch/x86/iommu/fault.rs
diff --git a/framework/jinux-frame/src/arch/x86/iommu/mod.rs b/framework/aster-frame/src/arch/x86/iommu/mod.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/iommu/mod.rs
rename to framework/aster-frame/src/arch/x86/iommu/mod.rs
diff --git a/framework/jinux-frame/src/arch/x86/iommu/remapping.rs b/framework/aster-frame/src/arch/x86/iommu/remapping.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/iommu/remapping.rs
rename to framework/aster-frame/src/arch/x86/iommu/remapping.rs
diff --git a/framework/jinux-frame/src/arch/x86/iommu/second_stage.rs b/framework/aster-frame/src/arch/x86/iommu/second_stage.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/iommu/second_stage.rs
rename to framework/aster-frame/src/arch/x86/iommu/second_stage.rs
diff --git a/framework/jinux-frame/src/arch/x86/irq.rs b/framework/aster-frame/src/arch/x86/irq.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/irq.rs
rename to framework/aster-frame/src/arch/x86/irq.rs
diff --git a/framework/jinux-frame/src/arch/x86/kernel/acpi/dmar.rs b/framework/aster-frame/src/arch/x86/kernel/acpi/dmar.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/kernel/acpi/dmar.rs
rename to framework/aster-frame/src/arch/x86/kernel/acpi/dmar.rs
diff --git a/framework/jinux-frame/src/arch/x86/kernel/acpi/mod.rs b/framework/aster-frame/src/arch/x86/kernel/acpi/mod.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/kernel/acpi/mod.rs
rename to framework/aster-frame/src/arch/x86/kernel/acpi/mod.rs
diff --git a/framework/jinux-frame/src/arch/x86/kernel/acpi/remapping.rs b/framework/aster-frame/src/arch/x86/kernel/acpi/remapping.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/kernel/acpi/remapping.rs
rename to framework/aster-frame/src/arch/x86/kernel/acpi/remapping.rs
diff --git a/framework/jinux-frame/src/arch/x86/kernel/apic/ioapic.rs b/framework/aster-frame/src/arch/x86/kernel/apic/ioapic.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/kernel/apic/ioapic.rs
rename to framework/aster-frame/src/arch/x86/kernel/apic/ioapic.rs
diff --git a/framework/jinux-frame/src/arch/x86/kernel/apic/mod.rs b/framework/aster-frame/src/arch/x86/kernel/apic/mod.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/kernel/apic/mod.rs
rename to framework/aster-frame/src/arch/x86/kernel/apic/mod.rs
diff --git a/framework/jinux-frame/src/arch/x86/kernel/apic/x2apic.rs b/framework/aster-frame/src/arch/x86/kernel/apic/x2apic.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/kernel/apic/x2apic.rs
rename to framework/aster-frame/src/arch/x86/kernel/apic/x2apic.rs
diff --git a/framework/jinux-frame/src/arch/x86/kernel/apic/xapic.rs b/framework/aster-frame/src/arch/x86/kernel/apic/xapic.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/kernel/apic/xapic.rs
rename to framework/aster-frame/src/arch/x86/kernel/apic/xapic.rs
diff --git a/framework/jinux-frame/src/arch/x86/kernel/mod.rs b/framework/aster-frame/src/arch/x86/kernel/mod.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/kernel/mod.rs
rename to framework/aster-frame/src/arch/x86/kernel/mod.rs
diff --git a/framework/jinux-frame/src/arch/x86/kernel/pic.rs b/framework/aster-frame/src/arch/x86/kernel/pic.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/kernel/pic.rs
rename to framework/aster-frame/src/arch/x86/kernel/pic.rs
diff --git a/framework/jinux-frame/src/arch/x86/kernel/tsc.rs b/framework/aster-frame/src/arch/x86/kernel/tsc.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/kernel/tsc.rs
rename to framework/aster-frame/src/arch/x86/kernel/tsc.rs
diff --git a/framework/jinux-frame/src/arch/x86/linker.ld b/framework/aster-frame/src/arch/x86/linker.ld
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/linker.ld
rename to framework/aster-frame/src/arch/x86/linker.ld
diff --git a/framework/jinux-frame/src/arch/x86/mm/mod.rs b/framework/aster-frame/src/arch/x86/mm/mod.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/mm/mod.rs
rename to framework/aster-frame/src/arch/x86/mm/mod.rs
diff --git a/framework/jinux-frame/src/arch/x86/mod.rs b/framework/aster-frame/src/arch/x86/mod.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/mod.rs
rename to framework/aster-frame/src/arch/x86/mod.rs
diff --git a/framework/jinux-frame/src/arch/x86/pci.rs b/framework/aster-frame/src/arch/x86/pci.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/pci.rs
rename to framework/aster-frame/src/arch/x86/pci.rs
diff --git a/framework/jinux-frame/src/arch/x86/qemu.rs b/framework/aster-frame/src/arch/x86/qemu.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/qemu.rs
rename to framework/aster-frame/src/arch/x86/qemu.rs
diff --git a/framework/jinux-frame/src/arch/x86/tdx_guest.rs b/framework/aster-frame/src/arch/x86/tdx_guest.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/tdx_guest.rs
rename to framework/aster-frame/src/arch/x86/tdx_guest.rs
diff --git a/framework/jinux-frame/src/arch/x86/timer/apic.rs b/framework/aster-frame/src/arch/x86/timer/apic.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/timer/apic.rs
rename to framework/aster-frame/src/arch/x86/timer/apic.rs
diff --git a/framework/jinux-frame/src/arch/x86/timer/hpet.rs b/framework/aster-frame/src/arch/x86/timer/hpet.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/timer/hpet.rs
rename to framework/aster-frame/src/arch/x86/timer/hpet.rs
diff --git a/framework/jinux-frame/src/arch/x86/timer/mod.rs b/framework/aster-frame/src/arch/x86/timer/mod.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/timer/mod.rs
rename to framework/aster-frame/src/arch/x86/timer/mod.rs
diff --git a/framework/jinux-frame/src/arch/x86/timer/pit.rs b/framework/aster-frame/src/arch/x86/timer/pit.rs
similarity index 100%
rename from framework/jinux-frame/src/arch/x86/timer/pit.rs
rename to framework/aster-frame/src/arch/x86/timer/pit.rs
diff --git a/framework/jinux-frame/src/boot/kcmdline.rs b/framework/aster-frame/src/boot/kcmdline.rs
similarity index 99%
rename from framework/jinux-frame/src/boot/kcmdline.rs
rename to framework/aster-frame/src/boot/kcmdline.rs
index c81d05b191..f68dff1b09 100644
--- 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/memory_region.rs b/framework/aster-frame/src/boot/memory_region.rs
similarity index 100%
rename from framework/jinux-frame/src/boot/memory_region.rs
rename to framework/aster-frame/src/boot/memory_region.rs
diff --git a/framework/jinux-frame/src/boot/mod.rs b/framework/aster-frame/src/boot/mod.rs
similarity index 95%
rename from framework/jinux-frame/src/boot/mod.rs
rename to framework/aster-frame/src/boot/mod.rs
index b0a0ab4e74..6afdc118ab 100644
--- 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.
@@ -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/bus/mmio/bus.rs b/framework/aster-frame/src/bus/mmio/bus.rs
similarity index 100%
rename from framework/jinux-frame/src/bus/mmio/bus.rs
rename to framework/aster-frame/src/bus/mmio/bus.rs
diff --git a/framework/jinux-frame/src/bus/mmio/device.rs b/framework/aster-frame/src/bus/mmio/device.rs
similarity index 100%
rename from framework/jinux-frame/src/bus/mmio/device.rs
rename to framework/aster-frame/src/bus/mmio/device.rs
diff --git a/framework/jinux-frame/src/bus/mmio/mod.rs b/framework/aster-frame/src/bus/mmio/mod.rs
similarity index 100%
rename from framework/jinux-frame/src/bus/mmio/mod.rs
rename to framework/aster-frame/src/bus/mmio/mod.rs
diff --git a/framework/jinux-frame/src/bus/mod.rs b/framework/aster-frame/src/bus/mod.rs
similarity index 100%
rename from framework/jinux-frame/src/bus/mod.rs
rename to framework/aster-frame/src/bus/mod.rs
diff --git a/framework/jinux-frame/src/bus/pci/bus.rs b/framework/aster-frame/src/bus/pci/bus.rs
similarity index 100%
rename from framework/jinux-frame/src/bus/pci/bus.rs
rename to framework/aster-frame/src/bus/pci/bus.rs
diff --git a/framework/jinux-frame/src/bus/pci/capability/mod.rs b/framework/aster-frame/src/bus/pci/capability/mod.rs
similarity index 100%
rename from framework/jinux-frame/src/bus/pci/capability/mod.rs
rename to framework/aster-frame/src/bus/pci/capability/mod.rs
diff --git a/framework/jinux-frame/src/bus/pci/capability/msix.rs b/framework/aster-frame/src/bus/pci/capability/msix.rs
similarity index 100%
rename from framework/jinux-frame/src/bus/pci/capability/msix.rs
rename to framework/aster-frame/src/bus/pci/capability/msix.rs
diff --git a/framework/jinux-frame/src/bus/pci/capability/vendor.rs b/framework/aster-frame/src/bus/pci/capability/vendor.rs
similarity index 100%
rename from framework/jinux-frame/src/bus/pci/capability/vendor.rs
rename to framework/aster-frame/src/bus/pci/capability/vendor.rs
diff --git a/framework/jinux-frame/src/bus/pci/cfg_space.rs b/framework/aster-frame/src/bus/pci/cfg_space.rs
similarity index 100%
rename from framework/jinux-frame/src/bus/pci/cfg_space.rs
rename to framework/aster-frame/src/bus/pci/cfg_space.rs
diff --git a/framework/jinux-frame/src/bus/pci/common_device.rs b/framework/aster-frame/src/bus/pci/common_device.rs
similarity index 100%
rename from framework/jinux-frame/src/bus/pci/common_device.rs
rename to framework/aster-frame/src/bus/pci/common_device.rs
diff --git a/framework/jinux-frame/src/bus/pci/device_info.rs b/framework/aster-frame/src/bus/pci/device_info.rs
similarity index 100%
rename from framework/jinux-frame/src/bus/pci/device_info.rs
rename to framework/aster-frame/src/bus/pci/device_info.rs
diff --git a/framework/jinux-frame/src/bus/pci/mod.rs b/framework/aster-frame/src/bus/pci/mod.rs
similarity index 100%
rename from framework/jinux-frame/src/bus/pci/mod.rs
rename to framework/aster-frame/src/bus/pci/mod.rs
diff --git a/framework/jinux-frame/src/config.rs b/framework/aster-frame/src/config.rs
similarity index 100%
rename from framework/jinux-frame/src/config.rs
rename to framework/aster-frame/src/config.rs
diff --git a/framework/jinux-frame/src/console.rs b/framework/aster-frame/src/console.rs
similarity index 100%
rename from framework/jinux-frame/src/console.rs
rename to framework/aster-frame/src/console.rs
diff --git a/framework/jinux-frame/src/cpu.rs b/framework/aster-frame/src/cpu.rs
similarity index 100%
rename from framework/jinux-frame/src/cpu.rs
rename to framework/aster-frame/src/cpu.rs
diff --git a/framework/jinux-frame/src/error.rs b/framework/aster-frame/src/error.rs
similarity index 100%
rename from framework/jinux-frame/src/error.rs
rename to framework/aster-frame/src/error.rs
diff --git a/framework/jinux-frame/src/io_mem.rs b/framework/aster-frame/src/io_mem.rs
similarity index 100%
rename from framework/jinux-frame/src/io_mem.rs
rename to framework/aster-frame/src/io_mem.rs
diff --git a/framework/jinux-frame/src/lib.rs b/framework/aster-frame/src/lib.rs
similarity index 98%
rename from framework/jinux-frame/src/lib.rs
rename to framework/aster-frame/src/lib.rs
index 0c6854125e..c20f38bdea 100644
--- 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/logger.rs b/framework/aster-frame/src/logger.rs
similarity index 100%
rename from framework/jinux-frame/src/logger.rs
rename to framework/aster-frame/src/logger.rs
diff --git a/framework/jinux-frame/src/panicking.rs b/framework/aster-frame/src/panicking.rs
similarity index 100%
rename from framework/jinux-frame/src/panicking.rs
rename to framework/aster-frame/src/panicking.rs
diff --git a/framework/jinux-frame/src/prelude.rs b/framework/aster-frame/src/prelude.rs
similarity index 100%
rename from framework/jinux-frame/src/prelude.rs
rename to framework/aster-frame/src/prelude.rs
diff --git a/framework/jinux-frame/src/sync/atomic_bits.rs b/framework/aster-frame/src/sync/atomic_bits.rs
similarity index 100%
rename from framework/jinux-frame/src/sync/atomic_bits.rs
rename to framework/aster-frame/src/sync/atomic_bits.rs
diff --git a/framework/jinux-frame/src/sync/mod.rs b/framework/aster-frame/src/sync/mod.rs
similarity index 100%
rename from framework/jinux-frame/src/sync/mod.rs
rename to framework/aster-frame/src/sync/mod.rs
diff --git a/framework/jinux-frame/src/sync/mutex.rs b/framework/aster-frame/src/sync/mutex.rs
similarity index 100%
rename from framework/jinux-frame/src/sync/mutex.rs
rename to framework/aster-frame/src/sync/mutex.rs
diff --git a/framework/jinux-frame/src/sync/rcu/mod.rs b/framework/aster-frame/src/sync/rcu/mod.rs
similarity index 100%
rename from framework/jinux-frame/src/sync/rcu/mod.rs
rename to framework/aster-frame/src/sync/rcu/mod.rs
diff --git a/framework/jinux-frame/src/sync/rcu/monitor.rs b/framework/aster-frame/src/sync/rcu/monitor.rs
similarity index 100%
rename from framework/jinux-frame/src/sync/rcu/monitor.rs
rename to framework/aster-frame/src/sync/rcu/monitor.rs
diff --git a/framework/jinux-frame/src/sync/rcu/owner_ptr.rs b/framework/aster-frame/src/sync/rcu/owner_ptr.rs
similarity index 100%
rename from framework/jinux-frame/src/sync/rcu/owner_ptr.rs
rename to framework/aster-frame/src/sync/rcu/owner_ptr.rs
diff --git a/framework/jinux-frame/src/sync/rwlock.rs b/framework/aster-frame/src/sync/rwlock.rs
similarity index 99%
rename from framework/jinux-frame/src/sync/rwlock.rs
rename to framework/aster-frame/src/sync/rwlock.rs
index ce4ce64dfb..7e8cbe46ba 100644
--- 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
similarity index 99%
rename from framework/jinux-frame/src/sync/rwmutex.rs
rename to framework/aster-frame/src/sync/rwmutex.rs
index 573e5e7911..46078ac42f 100644
--- 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/spin.rs b/framework/aster-frame/src/sync/spin.rs
similarity index 100%
rename from framework/jinux-frame/src/sync/spin.rs
rename to framework/aster-frame/src/sync/spin.rs
diff --git a/framework/jinux-frame/src/sync/wait.rs b/framework/aster-frame/src/sync/wait.rs
similarity index 100%
rename from framework/jinux-frame/src/sync/wait.rs
rename to framework/aster-frame/src/sync/wait.rs
diff --git a/framework/jinux-frame/src/task/mod.rs b/framework/aster-frame/src/task/mod.rs
similarity index 100%
rename from framework/jinux-frame/src/task/mod.rs
rename to framework/aster-frame/src/task/mod.rs
diff --git a/framework/jinux-frame/src/task/priority.rs b/framework/aster-frame/src/task/priority.rs
similarity index 100%
rename from framework/jinux-frame/src/task/priority.rs
rename to framework/aster-frame/src/task/priority.rs
diff --git a/framework/jinux-frame/src/task/processor.rs b/framework/aster-frame/src/task/processor.rs
similarity index 100%
rename from framework/jinux-frame/src/task/processor.rs
rename to framework/aster-frame/src/task/processor.rs
diff --git a/framework/jinux-frame/src/task/scheduler.rs b/framework/aster-frame/src/task/scheduler.rs
similarity index 100%
rename from framework/jinux-frame/src/task/scheduler.rs
rename to framework/aster-frame/src/task/scheduler.rs
diff --git a/framework/jinux-frame/src/task/switch.S b/framework/aster-frame/src/task/switch.S
similarity index 100%
rename from framework/jinux-frame/src/task/switch.S
rename to framework/aster-frame/src/task/switch.S
diff --git a/framework/jinux-frame/src/task/task.rs b/framework/aster-frame/src/task/task.rs
similarity index 100%
rename from framework/jinux-frame/src/task/task.rs
rename to framework/aster-frame/src/task/task.rs
diff --git a/framework/jinux-frame/src/timer.rs b/framework/aster-frame/src/timer.rs
similarity index 100%
rename from framework/jinux-frame/src/timer.rs
rename to framework/aster-frame/src/timer.rs
diff --git a/framework/jinux-frame/src/trap/handler.rs b/framework/aster-frame/src/trap/handler.rs
similarity index 100%
rename from framework/jinux-frame/src/trap/handler.rs
rename to framework/aster-frame/src/trap/handler.rs
diff --git a/framework/jinux-frame/src/trap/irq.rs b/framework/aster-frame/src/trap/irq.rs
similarity index 99%
rename from framework/jinux-frame/src/trap/irq.rs
rename to framework/aster-frame/src/trap/irq.rs
index 25c1020880..0f23b5b061 100644
--- 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/mod.rs b/framework/aster-frame/src/trap/mod.rs
similarity index 100%
rename from framework/jinux-frame/src/trap/mod.rs
rename to framework/aster-frame/src/trap/mod.rs
diff --git a/framework/jinux-frame/src/user.rs b/framework/aster-frame/src/user.rs
similarity index 98%
rename from framework/jinux-frame/src/user.rs
rename to framework/aster-frame/src/user.rs
index 97b9503900..9b89bc6c4f 100644
--- 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;
@@ -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/util/mod.rs b/framework/aster-frame/src/util/mod.rs
similarity index 100%
rename from framework/jinux-frame/src/util/mod.rs
rename to framework/aster-frame/src/util/mod.rs
diff --git a/framework/jinux-frame/src/util/recycle_allocator.rs b/framework/aster-frame/src/util/recycle_allocator.rs
similarity index 100%
rename from framework/jinux-frame/src/util/recycle_allocator.rs
rename to framework/aster-frame/src/util/recycle_allocator.rs
diff --git a/framework/jinux-frame/src/util/type_map.rs b/framework/aster-frame/src/util/type_map.rs
similarity index 100%
rename from framework/jinux-frame/src/util/type_map.rs
rename to framework/aster-frame/src/util/type_map.rs
diff --git a/framework/jinux-frame/src/vm/dma/dma_coherent.rs b/framework/aster-frame/src/vm/dma/dma_coherent.rs
similarity index 100%
rename from framework/jinux-frame/src/vm/dma/dma_coherent.rs
rename to framework/aster-frame/src/vm/dma/dma_coherent.rs
diff --git a/framework/jinux-frame/src/vm/dma/dma_stream.rs b/framework/aster-frame/src/vm/dma/dma_stream.rs
similarity index 100%
rename from framework/jinux-frame/src/vm/dma/dma_stream.rs
rename to framework/aster-frame/src/vm/dma/dma_stream.rs
diff --git a/framework/jinux-frame/src/vm/dma/mod.rs b/framework/aster-frame/src/vm/dma/mod.rs
similarity index 100%
rename from framework/jinux-frame/src/vm/dma/mod.rs
rename to framework/aster-frame/src/vm/dma/mod.rs
diff --git a/framework/jinux-frame/src/vm/frame.rs b/framework/aster-frame/src/vm/frame.rs
similarity index 100%
rename from framework/jinux-frame/src/vm/frame.rs
rename to framework/aster-frame/src/vm/frame.rs
diff --git a/framework/jinux-frame/src/vm/frame_allocator.rs b/framework/aster-frame/src/vm/frame_allocator.rs
similarity index 100%
rename from framework/jinux-frame/src/vm/frame_allocator.rs
rename to framework/aster-frame/src/vm/frame_allocator.rs
diff --git a/framework/jinux-frame/src/vm/heap_allocator.rs b/framework/aster-frame/src/vm/heap_allocator.rs
similarity index 100%
rename from framework/jinux-frame/src/vm/heap_allocator.rs
rename to framework/aster-frame/src/vm/heap_allocator.rs
diff --git a/framework/jinux-frame/src/vm/io.rs b/framework/aster-frame/src/vm/io.rs
similarity index 100%
rename from framework/jinux-frame/src/vm/io.rs
rename to framework/aster-frame/src/vm/io.rs
diff --git a/framework/jinux-frame/src/vm/memory_set.rs b/framework/aster-frame/src/vm/memory_set.rs
similarity index 100%
rename from framework/jinux-frame/src/vm/memory_set.rs
rename to framework/aster-frame/src/vm/memory_set.rs
diff --git a/framework/jinux-frame/src/vm/mod.rs b/framework/aster-frame/src/vm/mod.rs
similarity index 96%
rename from framework/jinux-frame/src/vm/mod.rs
rename to framework/aster-frame/src/vm/mod.rs
index 4a86befa22..bdd36c1797 100644
--- 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/offset.rs b/framework/aster-frame/src/vm/offset.rs
similarity index 100%
rename from framework/jinux-frame/src/vm/offset.rs
rename to framework/aster-frame/src/vm/offset.rs
diff --git a/framework/jinux-frame/src/vm/options.rs b/framework/aster-frame/src/vm/options.rs
similarity index 100%
rename from framework/jinux-frame/src/vm/options.rs
rename to framework/aster-frame/src/vm/options.rs
diff --git a/framework/jinux-frame/src/vm/page_table.rs b/framework/aster-frame/src/vm/page_table.rs
similarity index 100%
rename from framework/jinux-frame/src/vm/page_table.rs
rename to framework/aster-frame/src/vm/page_table.rs
diff --git a/framework/jinux-frame/src/vm/space.rs b/framework/aster-frame/src/vm/space.rs
similarity index 100%
rename from framework/jinux-frame/src/vm/space.rs
rename to framework/aster-frame/src/vm/space.rs
diff --git a/kernel/main.rs b/kernel/main.rs
index 340891903e..bbb7737d2a 100644
--- 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
index 87da25cd1f..dc21bb1af0 100644
--- 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
index 36afa6c5d0..7136d793ac 100755
--- 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/runner/Cargo.toml b/runner/Cargo.toml
index 69d11f0e91..778bddfb3d 100644
--- 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
index fec85025cc..c7db16aba0 100644
--- 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
index a976b1caf0..f5a13b69e6 100644
--- 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")
@@ -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();
}
@@ -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
index 1f7ab83e97..3a1ea0b2f4 100644
--- 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
index 8cb1454cc3..d88bd06948 100644
--- 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.
@@ -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
}
};
@@ -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
index 7602012378..5cf11734b0 100644
--- 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
@@ -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
@@ -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",
@@ -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);
@@ -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
index 99e0d23034..a3393222ee 100644
--- 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"
@@ -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
index c1410e17be..40bc59f3bb 100644
--- 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)]
@@ -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
index 6e022aaa56..82ec867677 100644
--- 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"
@@ -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
index 169f93ce6a..431856d1f7 100644
--- 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)]
@@ -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
index 623734d41d..d8c729ed90 100644
--- 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
index 383bf5e2bf..05c8820b75 100644
--- 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)]
@@ -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]
@@ -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
index 9726dad1ba..7db8afd7e7 100644
--- 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"
@@ -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
index 1644e88a0d..3edf755095 100644
--- 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)]
@@ -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
index d56d55ca1c..60562e8946 100644
--- 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"
@@ -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
index 1614acb438..04ea774669 100644
--- 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
index 032189fedf..aa595969ca 100644
--- 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
index ef59320f72..b688d42355 100644
--- 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
index b6c1e33f7c..9c165d56bb 100644
--- 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
index 978d160795..a6dc47b6c4 100644
--- 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
index 3e2ddf0f38..d44fc34a8c 100644
--- 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
index e71cd2b262..e5570c99ca 100644
--- 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"
@@ -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
index 925a71aba6..5bb1ea47e3 100644
--- 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;
@@ -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();
}
@@ -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(())
}
@@ -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
index fd6b5cefb8..62763d723d 100644
--- 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
index b4212f9614..f4e2373195 100644
--- 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
index d37fe2151d..6993abf414 100644
--- 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::{
@@ -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
index dc5b48c16f..fcb4b5fae1 100644
--- 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};
@@ -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();
}
@@ -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(())
}
@@ -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
index c1310718d5..eea3e13600 100644
--- 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
index 1971655bba..0fb980d5b3 100644
--- 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
index 3faecadc18..f3fc6bfc0d 100644
--- 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};
@@ -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
@@ -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
index aee89fc0f1..6b5e896716 100644
--- 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
index bca7865951..b761a2aa89 100644
--- 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;
@@ -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
index 85e8e3f0e8..60f2dce266 100644
--- 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},
@@ -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::{
@@ -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
index 1e6c428a77..e4d21dc8bb 100644
--- 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
index be15263ef7..13bb42c18b 100644
--- 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
index 8456356435..82ee9f27df 100644
--- 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
index c828bc7b66..46e083b86f 100644
--- 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
index 9e6c357013..f8a4c6a7a9 100644
--- 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
index adaae7b1f7..6d72489665 100644
--- 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
index 4862cf201f..f67f1f0976 100644
--- 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,
@@ -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
index 7f6cf9baa4..5e37120f00 100644
--- 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
index 886e72736a..4fd80e8c75 100644
--- 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
index 77ceda7b94..baeb093acb 100644
--- 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,
@@ -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
similarity index 91%
rename from services/libs/jinux-rights-proc/Cargo.toml
rename to services/libs/aster-rights-proc/Cargo.toml
index 81c8dd1340..bcdc003fc5 100644
--- 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
similarity index 99%
rename from services/libs/jinux-rights-proc/src/lib.rs
rename to services/libs/aster-rights-proc/src/lib.rs
index 21c7c80b19..3ca7d27e20 100644
--- 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/require_attr.rs b/services/libs/aster-rights-proc/src/require_attr.rs
similarity index 100%
rename from services/libs/jinux-rights-proc/src/require_attr.rs
rename to services/libs/aster-rights-proc/src/require_attr.rs
diff --git a/services/libs/jinux-rights-proc/src/require_item.rs b/services/libs/aster-rights-proc/src/require_item.rs
similarity index 100%
rename from services/libs/jinux-rights-proc/src/require_item.rs
rename to services/libs/aster-rights-proc/src/require_item.rs
diff --git a/services/libs/jinux-rights/Cargo.toml b/services/libs/aster-rights/Cargo.toml
similarity index 78%
rename from services/libs/jinux-rights/Cargo.toml
rename to services/libs/aster-rights/Cargo.toml
index 758231ac5a..c9f4f522e4 100644
--- 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"
@@ -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
similarity index 98%
rename from services/libs/jinux-rights/src/lib.rs
rename to services/libs/aster-rights/src/lib.rs
index 8b59cd2570..e7e929bff9 100644
--- 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
similarity index 72%
rename from services/libs/jinux-std/Cargo.toml
rename to services/libs/aster-std/Cargo.toml
index f826e428f9..e09364dc1d 100644
--- 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"
@@ -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
similarity index 94%
rename from services/libs/jinux-std/src/console.rs
rename to services/libs/aster-std/src/console.rs
index b64572d160..d42995e2fa 100644
--- 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/mod.rs b/services/libs/aster-std/src/device/mod.rs
similarity index 100%
rename from services/libs/jinux-std/src/device/mod.rs
rename to services/libs/aster-std/src/device/mod.rs
diff --git a/services/libs/jinux-std/src/device/null.rs b/services/libs/aster-std/src/device/null.rs
similarity index 100%
rename from services/libs/jinux-std/src/device/null.rs
rename to services/libs/aster-std/src/device/null.rs
diff --git a/services/libs/jinux-std/src/device/pty/mod.rs b/services/libs/aster-std/src/device/pty/mod.rs
similarity index 100%
rename from services/libs/jinux-std/src/device/pty/mod.rs
rename to services/libs/aster-std/src/device/pty/mod.rs
diff --git a/services/libs/jinux-std/src/device/pty/pty.rs b/services/libs/aster-std/src/device/pty/pty.rs
similarity index 100%
rename from services/libs/jinux-std/src/device/pty/pty.rs
rename to services/libs/aster-std/src/device/pty/pty.rs
diff --git a/services/libs/jinux-std/src/device/random.rs b/services/libs/aster-std/src/device/random.rs
similarity index 100%
rename from services/libs/jinux-std/src/device/random.rs
rename to services/libs/aster-std/src/device/random.rs
diff --git a/services/libs/jinux-std/src/device/tdxguest/mod.rs b/services/libs/aster-std/src/device/tdxguest/mod.rs
similarity index 100%
rename from services/libs/jinux-std/src/device/tdxguest/mod.rs
rename to services/libs/aster-std/src/device/tdxguest/mod.rs
diff --git a/services/libs/jinux-std/src/device/tty/device.rs b/services/libs/aster-std/src/device/tty/device.rs
similarity index 100%
rename from services/libs/jinux-std/src/device/tty/device.rs
rename to services/libs/aster-std/src/device/tty/device.rs
diff --git a/services/libs/jinux-std/src/device/tty/driver.rs b/services/libs/aster-std/src/device/tty/driver.rs
similarity index 95%
rename from services/libs/jinux-std/src/device/tty/driver.rs
rename to services/libs/aster-std/src/device/tty/driver.rs
index b78036faa9..8801680db3 100644
--- 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::{
@@ -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
similarity index 99%
rename from services/libs/jinux-std/src/device/tty/line_discipline.rs
rename to services/libs/aster-std/src/device/tty/line_discipline.rs
index 7764f4eb5b..29ace51903 100644
--- 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/mod.rs b/services/libs/aster-std/src/device/tty/mod.rs
similarity index 100%
rename from services/libs/jinux-std/src/device/tty/mod.rs
rename to services/libs/aster-std/src/device/tty/mod.rs
diff --git a/services/libs/jinux-std/src/device/tty/termio.rs b/services/libs/aster-std/src/device/tty/termio.rs
similarity index 100%
rename from services/libs/jinux-std/src/device/tty/termio.rs
rename to services/libs/aster-std/src/device/tty/termio.rs
diff --git a/services/libs/jinux-std/src/device/urandom.rs b/services/libs/aster-std/src/device/urandom.rs
similarity index 100%
rename from services/libs/jinux-std/src/device/urandom.rs
rename to services/libs/aster-std/src/device/urandom.rs
diff --git a/services/libs/jinux-std/src/device/zero.rs b/services/libs/aster-std/src/device/zero.rs
similarity index 100%
rename from services/libs/jinux-std/src/device/zero.rs
rename to services/libs/aster-std/src/device/zero.rs
diff --git a/services/libs/jinux-std/src/driver/mod.rs b/services/libs/aster-std/src/driver/mod.rs
similarity index 88%
rename from services/libs/jinux-std/src/driver/mod.rs
rename to services/libs/aster-std/src/driver/mod.rs
index 3c49bf8ec5..4a49e8285f 100644
--- 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
similarity index 91%
rename from services/libs/jinux-std/src/error.rs
rename to services/libs/aster-std/src/error.rs
index 2827c5afa4..679bd83a46 100644
--- 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),
}
}
}
@@ -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/events/events.rs b/services/libs/aster-std/src/events/events.rs
similarity index 100%
rename from services/libs/jinux-std/src/events/events.rs
rename to services/libs/aster-std/src/events/events.rs
diff --git a/services/libs/jinux-std/src/events/io_events.rs b/services/libs/aster-std/src/events/io_events.rs
similarity index 100%
rename from services/libs/jinux-std/src/events/io_events.rs
rename to services/libs/aster-std/src/events/io_events.rs
diff --git a/services/libs/jinux-std/src/events/mod.rs b/services/libs/aster-std/src/events/mod.rs
similarity index 100%
rename from services/libs/jinux-std/src/events/mod.rs
rename to services/libs/aster-std/src/events/mod.rs
diff --git a/services/libs/jinux-std/src/events/observer.rs b/services/libs/aster-std/src/events/observer.rs
similarity index 100%
rename from services/libs/jinux-std/src/events/observer.rs
rename to services/libs/aster-std/src/events/observer.rs
diff --git a/services/libs/jinux-std/src/events/subject.rs b/services/libs/aster-std/src/events/subject.rs
similarity index 100%
rename from services/libs/jinux-std/src/events/subject.rs
rename to services/libs/aster-std/src/events/subject.rs
diff --git a/services/libs/jinux-std/src/fs/device.rs b/services/libs/aster-std/src/fs/device.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/device.rs
rename to services/libs/aster-std/src/fs/device.rs
diff --git a/services/libs/jinux-std/src/fs/devpts/mod.rs b/services/libs/aster-std/src/fs/devpts/mod.rs
similarity index 98%
rename from services/libs/jinux-std/src/fs/devpts/mod.rs
rename to services/libs/aster-std/src/fs/devpts/mod.rs
index 25d115d44e..7b84d3efff 100644
--- 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/ptmx.rs b/services/libs/aster-std/src/fs/devpts/ptmx.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/devpts/ptmx.rs
rename to services/libs/aster-std/src/fs/devpts/ptmx.rs
diff --git a/services/libs/jinux-std/src/fs/devpts/slave.rs b/services/libs/aster-std/src/fs/devpts/slave.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/devpts/slave.rs
rename to services/libs/aster-std/src/fs/devpts/slave.rs
diff --git a/services/libs/jinux-std/src/fs/epoll/epoll_file.rs b/services/libs/aster-std/src/fs/epoll/epoll_file.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/epoll/epoll_file.rs
rename to services/libs/aster-std/src/fs/epoll/epoll_file.rs
diff --git a/services/libs/jinux-std/src/fs/epoll/mod.rs b/services/libs/aster-std/src/fs/epoll/mod.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/epoll/mod.rs
rename to services/libs/aster-std/src/fs/epoll/mod.rs
diff --git a/services/libs/jinux-std/src/fs/file_handle.rs b/services/libs/aster-std/src/fs/file_handle.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/file_handle.rs
rename to services/libs/aster-std/src/fs/file_handle.rs
diff --git a/services/libs/jinux-std/src/fs/file_table.rs b/services/libs/aster-std/src/fs/file_table.rs
similarity index 99%
rename from services/libs/jinux-std/src/fs/file_table.rs
rename to services/libs/aster-std/src/fs/file_table.rs
index 93e622df3d..b3b910ed4e 100644
--- 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/fs_resolver.rs b/services/libs/aster-std/src/fs/fs_resolver.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/fs_resolver.rs
rename to services/libs/aster-std/src/fs/fs_resolver.rs
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
similarity index 98%
rename from services/libs/jinux-std/src/fs/inode_handle/dyn_cap.rs
rename to services/libs/aster-std/src/fs/inode_handle/dyn_cap.rs
index fae4407c34..f554f46213 100644
--- 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
similarity index 99%
rename from services/libs/jinux-std/src/fs/inode_handle/mod.rs
rename to services/libs/aster-std/src/fs/inode_handle/mod.rs
index 665d6f4916..e84dba0a22 100644
--- 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
similarity index 87%
rename from services/libs/jinux-std/src/fs/inode_handle/static_cap.rs
rename to services/libs/aster-std/src/fs/inode_handle/static_cap.rs
index dcd525df70..1744f4815e 100644
--- 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/mod.rs b/services/libs/aster-std/src/fs/mod.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/mod.rs
rename to services/libs/aster-std/src/fs/mod.rs
diff --git a/services/libs/jinux-std/src/fs/pipe.rs b/services/libs/aster-std/src/fs/pipe.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/pipe.rs
rename to services/libs/aster-std/src/fs/pipe.rs
diff --git a/services/libs/jinux-std/src/fs/procfs/mod.rs b/services/libs/aster-std/src/fs/procfs/mod.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/procfs/mod.rs
rename to services/libs/aster-std/src/fs/procfs/mod.rs
diff --git a/services/libs/jinux-std/src/fs/procfs/pid/comm.rs b/services/libs/aster-std/src/fs/procfs/pid/comm.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/procfs/pid/comm.rs
rename to services/libs/aster-std/src/fs/procfs/pid/comm.rs
diff --git a/services/libs/jinux-std/src/fs/procfs/pid/exe.rs b/services/libs/aster-std/src/fs/procfs/pid/exe.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/procfs/pid/exe.rs
rename to services/libs/aster-std/src/fs/procfs/pid/exe.rs
diff --git a/services/libs/jinux-std/src/fs/procfs/pid/fd.rs b/services/libs/aster-std/src/fs/procfs/pid/fd.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/procfs/pid/fd.rs
rename to services/libs/aster-std/src/fs/procfs/pid/fd.rs
diff --git a/services/libs/jinux-std/src/fs/procfs/pid/mod.rs b/services/libs/aster-std/src/fs/procfs/pid/mod.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/procfs/pid/mod.rs
rename to services/libs/aster-std/src/fs/procfs/pid/mod.rs
diff --git a/services/libs/jinux-std/src/fs/procfs/self_.rs b/services/libs/aster-std/src/fs/procfs/self_.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/procfs/self_.rs
rename to services/libs/aster-std/src/fs/procfs/self_.rs
diff --git a/services/libs/jinux-std/src/fs/procfs/template/builder.rs b/services/libs/aster-std/src/fs/procfs/template/builder.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/procfs/template/builder.rs
rename to services/libs/aster-std/src/fs/procfs/template/builder.rs
diff --git a/services/libs/jinux-std/src/fs/procfs/template/dir.rs b/services/libs/aster-std/src/fs/procfs/template/dir.rs
similarity index 99%
rename from services/libs/jinux-std/src/fs/procfs/template/dir.rs
rename to services/libs/aster-std/src/fs/procfs/template/dir.rs
index 2f00ee35e3..f14d38a149 100644
--- 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
similarity index 99%
rename from services/libs/jinux-std/src/fs/procfs/template/file.rs
rename to services/libs/aster-std/src/fs/procfs/template/file.rs
index cb6fe1179a..f583d9d69f 100644
--- 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/mod.rs b/services/libs/aster-std/src/fs/procfs/template/mod.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/procfs/template/mod.rs
rename to services/libs/aster-std/src/fs/procfs/template/mod.rs
diff --git a/services/libs/jinux-std/src/fs/procfs/template/sym.rs b/services/libs/aster-std/src/fs/procfs/template/sym.rs
similarity index 98%
rename from services/libs/jinux-std/src/fs/procfs/template/sym.rs
rename to services/libs/aster-std/src/fs/procfs/template/sym.rs
index 355a029046..01a9867e00 100644
--- 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
similarity index 99%
rename from services/libs/jinux-std/src/fs/ramfs/fs.rs
rename to services/libs/aster-std/src/fs/ramfs/fs.rs
index 9d80d7d843..93467c71de 100644
--- 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/mod.rs b/services/libs/aster-std/src/fs/ramfs/mod.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/ramfs/mod.rs
rename to services/libs/aster-std/src/fs/ramfs/mod.rs
diff --git a/services/libs/jinux-std/src/fs/rootfs.rs b/services/libs/aster-std/src/fs/rootfs.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/rootfs.rs
rename to services/libs/aster-std/src/fs/rootfs.rs
diff --git a/services/libs/jinux-std/src/fs/utils/access_mode.rs b/services/libs/aster-std/src/fs/utils/access_mode.rs
similarity index 98%
rename from services/libs/jinux-std/src/fs/utils/access_mode.rs
rename to services/libs/aster-std/src/fs/utils/access_mode.rs
index 3929abd5f6..cbf76ba378 100644
--- 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
similarity index 99%
rename from services/libs/jinux-std/src/fs/utils/channel.rs
rename to services/libs/aster-std/src/fs/utils/channel.rs
index 605096c079..722953cafd 100644
--- 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/creation_flags.rs b/services/libs/aster-std/src/fs/utils/creation_flags.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/utils/creation_flags.rs
rename to services/libs/aster-std/src/fs/utils/creation_flags.rs
diff --git a/services/libs/jinux-std/src/fs/utils/dentry.rs b/services/libs/aster-std/src/fs/utils/dentry.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/utils/dentry.rs
rename to services/libs/aster-std/src/fs/utils/dentry.rs
diff --git a/services/libs/jinux-std/src/fs/utils/dirent_visitor.rs b/services/libs/aster-std/src/fs/utils/dirent_visitor.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/utils/dirent_visitor.rs
rename to services/libs/aster-std/src/fs/utils/dirent_visitor.rs
diff --git a/services/libs/jinux-std/src/fs/utils/direntry_vec.rs b/services/libs/aster-std/src/fs/utils/direntry_vec.rs
similarity index 96%
rename from services/libs/jinux-std/src/fs/utils/direntry_vec.rs
rename to services/libs/aster-std/src/fs/utils/direntry_vec.rs
index 5d139caacd..45c4b6b7ab 100644
--- 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/file_creation_mask.rs b/services/libs/aster-std/src/fs/utils/file_creation_mask.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/utils/file_creation_mask.rs
rename to services/libs/aster-std/src/fs/utils/file_creation_mask.rs
diff --git a/services/libs/jinux-std/src/fs/utils/fs.rs b/services/libs/aster-std/src/fs/utils/fs.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/utils/fs.rs
rename to services/libs/aster-std/src/fs/utils/fs.rs
diff --git a/services/libs/jinux-std/src/fs/utils/inode.rs b/services/libs/aster-std/src/fs/utils/inode.rs
similarity index 99%
rename from services/libs/jinux-std/src/fs/utils/inode.rs
rename to services/libs/aster-std/src/fs/utils/inode.rs
index 5726442fab..24b06a9de9 100644
--- 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/ioctl.rs b/services/libs/aster-std/src/fs/utils/ioctl.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/utils/ioctl.rs
rename to services/libs/aster-std/src/fs/utils/ioctl.rs
diff --git a/services/libs/jinux-std/src/fs/utils/mod.rs b/services/libs/aster-std/src/fs/utils/mod.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/utils/mod.rs
rename to services/libs/aster-std/src/fs/utils/mod.rs
diff --git a/services/libs/jinux-std/src/fs/utils/mount.rs b/services/libs/aster-std/src/fs/utils/mount.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/utils/mount.rs
rename to services/libs/aster-std/src/fs/utils/mount.rs
diff --git a/services/libs/jinux-std/src/fs/utils/page_cache.rs b/services/libs/aster-std/src/fs/utils/page_cache.rs
similarity index 98%
rename from services/libs/jinux-std/src/fs/utils/page_cache.rs
rename to services/libs/aster-std/src/fs/utils/page_cache.rs
index 0d62fc0f22..f22f9ab98d 100644
--- 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/status_flags.rs b/services/libs/aster-std/src/fs/utils/status_flags.rs
similarity index 100%
rename from services/libs/jinux-std/src/fs/utils/status_flags.rs
rename to services/libs/aster-std/src/fs/utils/status_flags.rs
diff --git a/services/libs/jinux-std/src/lib.rs b/services/libs/aster-std/src/lib.rs
similarity index 88%
rename from services/libs/jinux-std/src/lib.rs
rename to services/libs/aster-std/src/lib.rs
index b79b0e1b34..5a1b9c2cb3 100644
--- 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)]
@@ -28,7 +28,7 @@ use crate::{
Thread,
},
};
-use jinux_frame::{
+use aster_frame::{
arch::qemu::{exit_qemu, QemuExitCode},
boot,
};
@@ -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();
@@ -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/any_socket.rs b/services/libs/aster-std/src/net/iface/any_socket.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/iface/any_socket.rs
rename to services/libs/aster-std/src/net/iface/any_socket.rs
diff --git a/services/libs/jinux-std/src/net/iface/common.rs b/services/libs/aster-std/src/net/iface/common.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/iface/common.rs
rename to services/libs/aster-std/src/net/iface/common.rs
diff --git a/services/libs/jinux-std/src/net/iface/loopback.rs b/services/libs/aster-std/src/net/iface/loopback.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/iface/loopback.rs
rename to services/libs/aster-std/src/net/iface/loopback.rs
diff --git a/services/libs/jinux-std/src/net/iface/mod.rs b/services/libs/aster-std/src/net/iface/mod.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/iface/mod.rs
rename to services/libs/aster-std/src/net/iface/mod.rs
diff --git a/services/libs/jinux-std/src/net/iface/time.rs b/services/libs/aster-std/src/net/iface/time.rs
similarity index 76%
rename from services/libs/jinux-std/src/net/iface/time.rs
rename to services/libs/aster-std/src/net/iface/time.rs
index 4bcc1ff492..d7aced038e 100644
--- 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
similarity index 97%
rename from services/libs/jinux-std/src/net/iface/util.rs
rename to services/libs/aster-std/src/net/iface/util.rs
index a122696743..d4dd1acac0 100644
--- 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
similarity index 95%
rename from services/libs/jinux-std/src/net/iface/virtio.rs
rename to services/libs/aster-std/src/net/iface/virtio.rs
index 9b9c82e148..aa49034ff9 100644
--- 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,
@@ -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
similarity index 89%
rename from services/libs/jinux-std/src/net/mod.rs
rename to services/libs/aster-std/src/net/mod.rs
index dee7122c40..bf368dd371 100644
--- 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/socket/ip/always_some.rs b/services/libs/aster-std/src/net/socket/ip/always_some.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/socket/ip/always_some.rs
rename to services/libs/aster-std/src/net/socket/ip/always_some.rs
diff --git a/services/libs/jinux-std/src/net/socket/ip/common.rs b/services/libs/aster-std/src/net/socket/ip/common.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/socket/ip/common.rs
rename to services/libs/aster-std/src/net/socket/ip/common.rs
diff --git a/services/libs/jinux-std/src/net/socket/ip/datagram/bound.rs b/services/libs/aster-std/src/net/socket/ip/datagram/bound.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/socket/ip/datagram/bound.rs
rename to services/libs/aster-std/src/net/socket/ip/datagram/bound.rs
diff --git a/services/libs/jinux-std/src/net/socket/ip/datagram/mod.rs b/services/libs/aster-std/src/net/socket/ip/datagram/mod.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/socket/ip/datagram/mod.rs
rename to services/libs/aster-std/src/net/socket/ip/datagram/mod.rs
diff --git a/services/libs/jinux-std/src/net/socket/ip/datagram/unbound.rs b/services/libs/aster-std/src/net/socket/ip/datagram/unbound.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/socket/ip/datagram/unbound.rs
rename to services/libs/aster-std/src/net/socket/ip/datagram/unbound.rs
diff --git a/services/libs/jinux-std/src/net/socket/ip/mod.rs b/services/libs/aster-std/src/net/socket/ip/mod.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/socket/ip/mod.rs
rename to services/libs/aster-std/src/net/socket/ip/mod.rs
diff --git a/services/libs/jinux-std/src/net/socket/ip/stream/connected.rs b/services/libs/aster-std/src/net/socket/ip/stream/connected.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/socket/ip/stream/connected.rs
rename to services/libs/aster-std/src/net/socket/ip/stream/connected.rs
diff --git a/services/libs/jinux-std/src/net/socket/ip/stream/connecting.rs b/services/libs/aster-std/src/net/socket/ip/stream/connecting.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/socket/ip/stream/connecting.rs
rename to services/libs/aster-std/src/net/socket/ip/stream/connecting.rs
diff --git a/services/libs/jinux-std/src/net/socket/ip/stream/init.rs b/services/libs/aster-std/src/net/socket/ip/stream/init.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/socket/ip/stream/init.rs
rename to services/libs/aster-std/src/net/socket/ip/stream/init.rs
diff --git a/services/libs/jinux-std/src/net/socket/ip/stream/listen.rs b/services/libs/aster-std/src/net/socket/ip/stream/listen.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/socket/ip/stream/listen.rs
rename to services/libs/aster-std/src/net/socket/ip/stream/listen.rs
diff --git a/services/libs/jinux-std/src/net/socket/ip/stream/mod.rs b/services/libs/aster-std/src/net/socket/ip/stream/mod.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/socket/ip/stream/mod.rs
rename to services/libs/aster-std/src/net/socket/ip/stream/mod.rs
diff --git a/services/libs/jinux-std/src/net/socket/mod.rs b/services/libs/aster-std/src/net/socket/mod.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/socket/mod.rs
rename to services/libs/aster-std/src/net/socket/mod.rs
diff --git a/services/libs/jinux-std/src/net/socket/unix/addr.rs b/services/libs/aster-std/src/net/socket/unix/addr.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/socket/unix/addr.rs
rename to services/libs/aster-std/src/net/socket/unix/addr.rs
diff --git a/services/libs/jinux-std/src/net/socket/unix/mod.rs b/services/libs/aster-std/src/net/socket/unix/mod.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/socket/unix/mod.rs
rename to services/libs/aster-std/src/net/socket/unix/mod.rs
diff --git a/services/libs/jinux-std/src/net/socket/unix/stream/connected.rs b/services/libs/aster-std/src/net/socket/unix/stream/connected.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/socket/unix/stream/connected.rs
rename to services/libs/aster-std/src/net/socket/unix/stream/connected.rs
diff --git a/services/libs/jinux-std/src/net/socket/unix/stream/endpoint.rs b/services/libs/aster-std/src/net/socket/unix/stream/endpoint.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/socket/unix/stream/endpoint.rs
rename to services/libs/aster-std/src/net/socket/unix/stream/endpoint.rs
diff --git a/services/libs/jinux-std/src/net/socket/unix/stream/init.rs b/services/libs/aster-std/src/net/socket/unix/stream/init.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/socket/unix/stream/init.rs
rename to services/libs/aster-std/src/net/socket/unix/stream/init.rs
diff --git a/services/libs/jinux-std/src/net/socket/unix/stream/listener.rs b/services/libs/aster-std/src/net/socket/unix/stream/listener.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/socket/unix/stream/listener.rs
rename to services/libs/aster-std/src/net/socket/unix/stream/listener.rs
diff --git a/services/libs/jinux-std/src/net/socket/unix/stream/mod.rs b/services/libs/aster-std/src/net/socket/unix/stream/mod.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/socket/unix/stream/mod.rs
rename to services/libs/aster-std/src/net/socket/unix/stream/mod.rs
diff --git a/services/libs/jinux-std/src/net/socket/unix/stream/socket.rs b/services/libs/aster-std/src/net/socket/unix/stream/socket.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/socket/unix/stream/socket.rs
rename to services/libs/aster-std/src/net/socket/unix/stream/socket.rs
diff --git a/services/libs/jinux-std/src/net/socket/util/mod.rs b/services/libs/aster-std/src/net/socket/util/mod.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/socket/util/mod.rs
rename to services/libs/aster-std/src/net/socket/util/mod.rs
diff --git a/services/libs/jinux-std/src/net/socket/util/send_recv_flags.rs b/services/libs/aster-std/src/net/socket/util/send_recv_flags.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/socket/util/send_recv_flags.rs
rename to services/libs/aster-std/src/net/socket/util/send_recv_flags.rs
diff --git a/services/libs/jinux-std/src/net/socket/util/shutdown_cmd.rs b/services/libs/aster-std/src/net/socket/util/shutdown_cmd.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/socket/util/shutdown_cmd.rs
rename to services/libs/aster-std/src/net/socket/util/shutdown_cmd.rs
diff --git a/services/libs/jinux-std/src/net/socket/util/sock_options.rs b/services/libs/aster-std/src/net/socket/util/sock_options.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/socket/util/sock_options.rs
rename to services/libs/aster-std/src/net/socket/util/sock_options.rs
diff --git a/services/libs/jinux-std/src/net/socket/util/sockaddr.rs b/services/libs/aster-std/src/net/socket/util/sockaddr.rs
similarity index 100%
rename from services/libs/jinux-std/src/net/socket/util/sockaddr.rs
rename to services/libs/aster-std/src/net/socket/util/sockaddr.rs
diff --git a/services/libs/jinux-std/src/prelude.rs b/services/libs/aster-std/src/prelude.rs
similarity index 89%
rename from services/libs/jinux-std/src/prelude.rs
rename to services/libs/aster-std/src/prelude.rs
index d14de07243..13465285b0 100644
--- 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
similarity index 99%
rename from services/libs/jinux-std/src/process/clone.rs
rename to services/libs/aster-std/src/process/clone.rs
index 3f6327477f..4f901de00e 100644
--- 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
similarity index 99%
rename from services/libs/jinux-std/src/process/credentials/credentials_.rs
rename to services/libs/aster-std/src/process/credentials/credentials_.rs
index b26584da50..6b4f32e288 100644
--- 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/group.rs b/services/libs/aster-std/src/process/credentials/group.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/credentials/group.rs
rename to services/libs/aster-std/src/process/credentials/group.rs
diff --git a/services/libs/jinux-std/src/process/credentials/mod.rs b/services/libs/aster-std/src/process/credentials/mod.rs
similarity index 96%
rename from services/libs/jinux-std/src/process/credentials/mod.rs
rename to services/libs/aster-std/src/process/credentials/mod.rs
index e346aeb967..f5e162a356 100644
--- 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
similarity index 98%
rename from services/libs/jinux-std/src/process/credentials/static_cap.rs
rename to services/libs/aster-std/src/process/credentials/static_cap.rs
index ad2162844b..07e9848a33 100644
--- 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/user.rs b/services/libs/aster-std/src/process/credentials/user.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/credentials/user.rs
rename to services/libs/aster-std/src/process/credentials/user.rs
diff --git a/services/libs/jinux-std/src/process/exit.rs b/services/libs/aster-std/src/process/exit.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/exit.rs
rename to services/libs/aster-std/src/process/exit.rs
diff --git a/services/libs/jinux-std/src/process/kill.rs b/services/libs/aster-std/src/process/kill.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/kill.rs
rename to services/libs/aster-std/src/process/kill.rs
diff --git a/services/libs/jinux-std/src/process/mod.rs b/services/libs/aster-std/src/process/mod.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/mod.rs
rename to services/libs/aster-std/src/process/mod.rs
diff --git a/services/libs/jinux-std/src/process/posix_thread/builder.rs b/services/libs/aster-std/src/process/posix_thread/builder.rs
similarity index 98%
rename from services/libs/jinux-std/src/process/posix_thread/builder.rs
rename to services/libs/aster-std/src/process/posix_thread/builder.rs
index ead10779de..5507dace7b 100644
--- 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
similarity index 99%
rename from services/libs/jinux-std/src/process/posix_thread/futex.rs
rename to services/libs/aster-std/src/process/posix_thread/futex.rs
index 33a46b9306..1259f3f3f0 100644
--- 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
similarity index 99%
rename from services/libs/jinux-std/src/process/posix_thread/mod.rs
rename to services/libs/aster-std/src/process/posix_thread/mod.rs
index 414ab260ef..e936663f7b 100644
--- 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/name.rs b/services/libs/aster-std/src/process/posix_thread/name.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/posix_thread/name.rs
rename to services/libs/aster-std/src/process/posix_thread/name.rs
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
similarity index 97%
rename from services/libs/jinux-std/src/process/posix_thread/posix_thread_ext.rs
rename to services/libs/aster-std/src/process/posix_thread/posix_thread_ext.rs
index b093cb2c7a..8003bfbf42 100644
--- 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/robust_list.rs b/services/libs/aster-std/src/process/posix_thread/robust_list.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/posix_thread/robust_list.rs
rename to services/libs/aster-std/src/process/posix_thread/robust_list.rs
diff --git a/services/libs/jinux-std/src/process/process/builder.rs b/services/libs/aster-std/src/process/process/builder.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/process/builder.rs
rename to services/libs/aster-std/src/process/process/builder.rs
diff --git a/services/libs/jinux-std/src/process/process/job_control.rs b/services/libs/aster-std/src/process/process/job_control.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/process/job_control.rs
rename to services/libs/aster-std/src/process/process/job_control.rs
diff --git a/services/libs/jinux-std/src/process/process/mod.rs b/services/libs/aster-std/src/process/process/mod.rs
similarity index 99%
rename from services/libs/jinux-std/src/process/process/mod.rs
rename to services/libs/aster-std/src/process/process/mod.rs
index b0574666be..64cdeaf2ae 100644
--- 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/process_group.rs b/services/libs/aster-std/src/process/process/process_group.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/process/process_group.rs
rename to services/libs/aster-std/src/process/process/process_group.rs
diff --git a/services/libs/jinux-std/src/process/process/session.rs b/services/libs/aster-std/src/process/process/session.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/process/session.rs
rename to services/libs/aster-std/src/process/process/session.rs
diff --git a/services/libs/jinux-std/src/process/process/terminal.rs b/services/libs/aster-std/src/process/process/terminal.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/process/terminal.rs
rename to services/libs/aster-std/src/process/process/terminal.rs
diff --git a/services/libs/jinux-std/src/process/process_filter.rs b/services/libs/aster-std/src/process/process_filter.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/process_filter.rs
rename to services/libs/aster-std/src/process/process_filter.rs
diff --git a/services/libs/jinux-std/src/process/process_table.rs b/services/libs/aster-std/src/process/process_table.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/process_table.rs
rename to services/libs/aster-std/src/process/process_table.rs
diff --git a/services/libs/jinux-std/src/process/process_vm/mod.rs b/services/libs/aster-std/src/process/process_vm/mod.rs
similarity index 98%
rename from services/libs/jinux-std/src/process/process_vm/mod.rs
rename to services/libs/aster-std/src/process/process_vm/mod.rs
index 8a90841463..468b7aa7e0 100644
--- 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
similarity index 98%
rename from services/libs/jinux-std/src/process/process_vm/user_heap.rs
rename to services/libs/aster-std/src/process/process_vm/user_heap.rs
index df78f10ea8..7dff106e40 100644
--- 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/aux_vec.rs b/services/libs/aster-std/src/process/program_loader/elf/aux_vec.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/program_loader/elf/aux_vec.rs
rename to services/libs/aster-std/src/process/program_loader/elf/aux_vec.rs
diff --git a/services/libs/jinux-std/src/process/program_loader/elf/elf_file.rs b/services/libs/aster-std/src/process/program_loader/elf/elf_file.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/program_loader/elf/elf_file.rs
rename to services/libs/aster-std/src/process/program_loader/elf/elf_file.rs
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
similarity index 99%
rename from services/libs/jinux-std/src/process/program_loader/elf/init_stack.rs
rename to services/libs/aster-std/src/process/program_loader/elf/init_stack.rs
index 2f1ce78615..3d53b80534 100644
--- 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
similarity index 99%
rename from services/libs/jinux-std/src/process/program_loader/elf/load_elf.rs
rename to services/libs/aster-std/src/process/program_loader/elf/load_elf.rs
index d669ab3bdc..af4fdbb695 100644
--- 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/mod.rs b/services/libs/aster-std/src/process/program_loader/elf/mod.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/program_loader/elf/mod.rs
rename to services/libs/aster-std/src/process/program_loader/elf/mod.rs
diff --git a/services/libs/jinux-std/src/process/program_loader/mod.rs b/services/libs/aster-std/src/process/program_loader/mod.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/program_loader/mod.rs
rename to services/libs/aster-std/src/process/program_loader/mod.rs
diff --git a/services/libs/jinux-std/src/process/program_loader/shebang.rs b/services/libs/aster-std/src/process/program_loader/shebang.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/program_loader/shebang.rs
rename to services/libs/aster-std/src/process/program_loader/shebang.rs
diff --git a/services/libs/jinux-std/src/process/rlimit.rs b/services/libs/aster-std/src/process/rlimit.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/rlimit.rs
rename to services/libs/aster-std/src/process/rlimit.rs
diff --git a/services/libs/jinux-std/src/process/signal/c_types.rs b/services/libs/aster-std/src/process/signal/c_types.rs
similarity index 97%
rename from services/libs/jinux-std/src/process/signal/c_types.rs
rename to services/libs/aster-std/src/process/signal/c_types.rs
index 60ce41b7d8..15f4a94afc 100644
--- 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/constants.rs b/services/libs/aster-std/src/process/signal/constants.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/signal/constants.rs
rename to services/libs/aster-std/src/process/signal/constants.rs
diff --git a/services/libs/jinux-std/src/process/signal/events.rs b/services/libs/aster-std/src/process/signal/events.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/signal/events.rs
rename to services/libs/aster-std/src/process/signal/events.rs
diff --git a/services/libs/jinux-std/src/process/signal/mod.rs b/services/libs/aster-std/src/process/signal/mod.rs
similarity index 99%
rename from services/libs/jinux-std/src/process/signal/mod.rs
rename to services/libs/aster-std/src/process/signal/mod.rs
index 8ba2e74da8..6415374fe4 100644
--- 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
similarity index 99%
rename from services/libs/jinux-std/src/process/signal/pauser.rs
rename to services/libs/aster-std/src/process/signal/pauser.rs
index a242f89305..c277c895af 100644
--- 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/poll.rs b/services/libs/aster-std/src/process/signal/poll.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/signal/poll.rs
rename to services/libs/aster-std/src/process/signal/poll.rs
diff --git a/services/libs/jinux-std/src/process/signal/sig_action.rs b/services/libs/aster-std/src/process/signal/sig_action.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/signal/sig_action.rs
rename to services/libs/aster-std/src/process/signal/sig_action.rs
diff --git a/services/libs/jinux-std/src/process/signal/sig_disposition.rs b/services/libs/aster-std/src/process/signal/sig_disposition.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/signal/sig_disposition.rs
rename to services/libs/aster-std/src/process/signal/sig_disposition.rs
diff --git a/services/libs/jinux-std/src/process/signal/sig_mask.rs b/services/libs/aster-std/src/process/signal/sig_mask.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/signal/sig_mask.rs
rename to services/libs/aster-std/src/process/signal/sig_mask.rs
diff --git a/services/libs/jinux-std/src/process/signal/sig_num.rs b/services/libs/aster-std/src/process/signal/sig_num.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/signal/sig_num.rs
rename to services/libs/aster-std/src/process/signal/sig_num.rs
diff --git a/services/libs/jinux-std/src/process/signal/sig_queues.rs b/services/libs/aster-std/src/process/signal/sig_queues.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/signal/sig_queues.rs
rename to services/libs/aster-std/src/process/signal/sig_queues.rs
diff --git a/services/libs/jinux-std/src/process/signal/sig_stack.rs b/services/libs/aster-std/src/process/signal/sig_stack.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/signal/sig_stack.rs
rename to services/libs/aster-std/src/process/signal/sig_stack.rs
diff --git a/services/libs/jinux-std/src/process/signal/signals/fault.rs b/services/libs/aster-std/src/process/signal/signals/fault.rs
similarity index 96%
rename from services/libs/jinux-std/src/process/signal/signals/fault.rs
rename to services/libs/aster-std/src/process/signal/signals/fault.rs
index 3cf90533ac..799af8113c 100644
--- 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/kernel.rs b/services/libs/aster-std/src/process/signal/signals/kernel.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/signal/signals/kernel.rs
rename to services/libs/aster-std/src/process/signal/signals/kernel.rs
diff --git a/services/libs/jinux-std/src/process/signal/signals/mod.rs b/services/libs/aster-std/src/process/signal/signals/mod.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/signal/signals/mod.rs
rename to services/libs/aster-std/src/process/signal/signals/mod.rs
diff --git a/services/libs/jinux-std/src/process/signal/signals/user.rs b/services/libs/aster-std/src/process/signal/signals/user.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/signal/signals/user.rs
rename to services/libs/aster-std/src/process/signal/signals/user.rs
diff --git a/services/libs/jinux-std/src/process/status.rs b/services/libs/aster-std/src/process/status.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/status.rs
rename to services/libs/aster-std/src/process/status.rs
diff --git a/services/libs/jinux-std/src/process/term_status.rs b/services/libs/aster-std/src/process/term_status.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/term_status.rs
rename to services/libs/aster-std/src/process/term_status.rs
diff --git a/services/libs/jinux-std/src/process/wait.rs b/services/libs/aster-std/src/process/wait.rs
similarity index 100%
rename from services/libs/jinux-std/src/process/wait.rs
rename to services/libs/aster-std/src/process/wait.rs
diff --git a/services/libs/jinux-std/src/sched/mod.rs b/services/libs/aster-std/src/sched/mod.rs
similarity index 100%
rename from services/libs/jinux-std/src/sched/mod.rs
rename to services/libs/aster-std/src/sched/mod.rs
diff --git a/services/libs/jinux-std/src/sched/priority_scheduler.rs b/services/libs/aster-std/src/sched/priority_scheduler.rs
similarity index 96%
rename from services/libs/jinux-std/src/sched/priority_scheduler.rs
rename to services/libs/aster-std/src/sched/priority_scheduler.rs
index 061b406ae7..4523c1d98f 100644
--- 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/accept.rs b/services/libs/aster-std/src/syscall/accept.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/accept.rs
rename to services/libs/aster-std/src/syscall/accept.rs
diff --git a/services/libs/jinux-std/src/syscall/access.rs b/services/libs/aster-std/src/syscall/access.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/access.rs
rename to services/libs/aster-std/src/syscall/access.rs
diff --git a/services/libs/jinux-std/src/syscall/arch_prctl.rs b/services/libs/aster-std/src/syscall/arch_prctl.rs
similarity index 97%
rename from services/libs/jinux-std/src/syscall/arch_prctl.rs
rename to services/libs/aster-std/src/syscall/arch_prctl.rs
index 9e9f8c1195..c94a4a7e06 100644
--- 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/bind.rs b/services/libs/aster-std/src/syscall/bind.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/bind.rs
rename to services/libs/aster-std/src/syscall/bind.rs
diff --git a/services/libs/jinux-std/src/syscall/brk.rs b/services/libs/aster-std/src/syscall/brk.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/brk.rs
rename to services/libs/aster-std/src/syscall/brk.rs
diff --git a/services/libs/jinux-std/src/syscall/chdir.rs b/services/libs/aster-std/src/syscall/chdir.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/chdir.rs
rename to services/libs/aster-std/src/syscall/chdir.rs
diff --git a/services/libs/jinux-std/src/syscall/chmod.rs b/services/libs/aster-std/src/syscall/chmod.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/chmod.rs
rename to services/libs/aster-std/src/syscall/chmod.rs
diff --git a/services/libs/jinux-std/src/syscall/clock_gettime.rs b/services/libs/aster-std/src/syscall/clock_gettime.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/clock_gettime.rs
rename to services/libs/aster-std/src/syscall/clock_gettime.rs
diff --git a/services/libs/jinux-std/src/syscall/clock_nanosleep.rs b/services/libs/aster-std/src/syscall/clock_nanosleep.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/clock_nanosleep.rs
rename to services/libs/aster-std/src/syscall/clock_nanosleep.rs
diff --git a/services/libs/jinux-std/src/syscall/clone.rs b/services/libs/aster-std/src/syscall/clone.rs
similarity index 96%
rename from services/libs/jinux-std/src/syscall/clone.rs
rename to services/libs/aster-std/src/syscall/clone.rs
index 655715b64b..fc9d9f2402 100644
--- 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/close.rs b/services/libs/aster-std/src/syscall/close.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/close.rs
rename to services/libs/aster-std/src/syscall/close.rs
diff --git a/services/libs/jinux-std/src/syscall/connect.rs b/services/libs/aster-std/src/syscall/connect.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/connect.rs
rename to services/libs/aster-std/src/syscall/connect.rs
diff --git a/services/libs/jinux-std/src/syscall/constants.rs b/services/libs/aster-std/src/syscall/constants.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/constants.rs
rename to services/libs/aster-std/src/syscall/constants.rs
diff --git a/services/libs/jinux-std/src/syscall/dup.rs b/services/libs/aster-std/src/syscall/dup.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/dup.rs
rename to services/libs/aster-std/src/syscall/dup.rs
diff --git a/services/libs/jinux-std/src/syscall/epoll.rs b/services/libs/aster-std/src/syscall/epoll.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/epoll.rs
rename to services/libs/aster-std/src/syscall/epoll.rs
diff --git a/services/libs/jinux-std/src/syscall/execve.rs b/services/libs/aster-std/src/syscall/execve.rs
similarity index 99%
rename from services/libs/jinux-std/src/syscall/execve.rs
rename to services/libs/aster-std/src/syscall/execve.rs
index a4b624572d..b15e8579d8 100644
--- 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/exit.rs b/services/libs/aster-std/src/syscall/exit.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/exit.rs
rename to services/libs/aster-std/src/syscall/exit.rs
diff --git a/services/libs/jinux-std/src/syscall/exit_group.rs b/services/libs/aster-std/src/syscall/exit_group.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/exit_group.rs
rename to services/libs/aster-std/src/syscall/exit_group.rs
diff --git a/services/libs/jinux-std/src/syscall/fcntl.rs b/services/libs/aster-std/src/syscall/fcntl.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/fcntl.rs
rename to services/libs/aster-std/src/syscall/fcntl.rs
diff --git a/services/libs/jinux-std/src/syscall/fork.rs b/services/libs/aster-std/src/syscall/fork.rs
similarity index 93%
rename from services/libs/jinux-std/src/syscall/fork.rs
rename to services/libs/aster-std/src/syscall/fork.rs
index 11f2a365b1..3fcbaf0478 100644
--- 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/futex.rs b/services/libs/aster-std/src/syscall/futex.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/futex.rs
rename to services/libs/aster-std/src/syscall/futex.rs
diff --git a/services/libs/jinux-std/src/syscall/getcwd.rs b/services/libs/aster-std/src/syscall/getcwd.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/getcwd.rs
rename to services/libs/aster-std/src/syscall/getcwd.rs
diff --git a/services/libs/jinux-std/src/syscall/getdents64.rs b/services/libs/aster-std/src/syscall/getdents64.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/getdents64.rs
rename to services/libs/aster-std/src/syscall/getdents64.rs
diff --git a/services/libs/jinux-std/src/syscall/getegid.rs b/services/libs/aster-std/src/syscall/getegid.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/getegid.rs
rename to services/libs/aster-std/src/syscall/getegid.rs
diff --git a/services/libs/jinux-std/src/syscall/geteuid.rs b/services/libs/aster-std/src/syscall/geteuid.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/geteuid.rs
rename to services/libs/aster-std/src/syscall/geteuid.rs
diff --git a/services/libs/jinux-std/src/syscall/getgid.rs b/services/libs/aster-std/src/syscall/getgid.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/getgid.rs
rename to services/libs/aster-std/src/syscall/getgid.rs
diff --git a/services/libs/jinux-std/src/syscall/getgroups.rs b/services/libs/aster-std/src/syscall/getgroups.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/getgroups.rs
rename to services/libs/aster-std/src/syscall/getgroups.rs
diff --git a/services/libs/jinux-std/src/syscall/getpeername.rs b/services/libs/aster-std/src/syscall/getpeername.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/getpeername.rs
rename to services/libs/aster-std/src/syscall/getpeername.rs
diff --git a/services/libs/jinux-std/src/syscall/getpgrp.rs b/services/libs/aster-std/src/syscall/getpgrp.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/getpgrp.rs
rename to services/libs/aster-std/src/syscall/getpgrp.rs
diff --git a/services/libs/jinux-std/src/syscall/getpid.rs b/services/libs/aster-std/src/syscall/getpid.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/getpid.rs
rename to services/libs/aster-std/src/syscall/getpid.rs
diff --git a/services/libs/jinux-std/src/syscall/getppid.rs b/services/libs/aster-std/src/syscall/getppid.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/getppid.rs
rename to services/libs/aster-std/src/syscall/getppid.rs
diff --git a/services/libs/jinux-std/src/syscall/getrandom.rs b/services/libs/aster-std/src/syscall/getrandom.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/getrandom.rs
rename to services/libs/aster-std/src/syscall/getrandom.rs
diff --git a/services/libs/jinux-std/src/syscall/getresgid.rs b/services/libs/aster-std/src/syscall/getresgid.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/getresgid.rs
rename to services/libs/aster-std/src/syscall/getresgid.rs
diff --git a/services/libs/jinux-std/src/syscall/getresuid.rs b/services/libs/aster-std/src/syscall/getresuid.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/getresuid.rs
rename to services/libs/aster-std/src/syscall/getresuid.rs
diff --git a/services/libs/jinux-std/src/syscall/getsid.rs b/services/libs/aster-std/src/syscall/getsid.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/getsid.rs
rename to services/libs/aster-std/src/syscall/getsid.rs
diff --git a/services/libs/jinux-std/src/syscall/getsockname.rs b/services/libs/aster-std/src/syscall/getsockname.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/getsockname.rs
rename to services/libs/aster-std/src/syscall/getsockname.rs
diff --git a/services/libs/jinux-std/src/syscall/getsockopt.rs b/services/libs/aster-std/src/syscall/getsockopt.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/getsockopt.rs
rename to services/libs/aster-std/src/syscall/getsockopt.rs
diff --git a/services/libs/jinux-std/src/syscall/gettid.rs b/services/libs/aster-std/src/syscall/gettid.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/gettid.rs
rename to services/libs/aster-std/src/syscall/gettid.rs
diff --git a/services/libs/jinux-std/src/syscall/gettimeofday.rs b/services/libs/aster-std/src/syscall/gettimeofday.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/gettimeofday.rs
rename to services/libs/aster-std/src/syscall/gettimeofday.rs
diff --git a/services/libs/jinux-std/src/syscall/getuid.rs b/services/libs/aster-std/src/syscall/getuid.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/getuid.rs
rename to services/libs/aster-std/src/syscall/getuid.rs
diff --git a/services/libs/jinux-std/src/syscall/ioctl.rs b/services/libs/aster-std/src/syscall/ioctl.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/ioctl.rs
rename to services/libs/aster-std/src/syscall/ioctl.rs
diff --git a/services/libs/jinux-std/src/syscall/kill.rs b/services/libs/aster-std/src/syscall/kill.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/kill.rs
rename to services/libs/aster-std/src/syscall/kill.rs
diff --git a/services/libs/jinux-std/src/syscall/link.rs b/services/libs/aster-std/src/syscall/link.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/link.rs
rename to services/libs/aster-std/src/syscall/link.rs
diff --git a/services/libs/jinux-std/src/syscall/listen.rs b/services/libs/aster-std/src/syscall/listen.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/listen.rs
rename to services/libs/aster-std/src/syscall/listen.rs
diff --git a/services/libs/jinux-std/src/syscall/lseek.rs b/services/libs/aster-std/src/syscall/lseek.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/lseek.rs
rename to services/libs/aster-std/src/syscall/lseek.rs
diff --git a/services/libs/jinux-std/src/syscall/madvise.rs b/services/libs/aster-std/src/syscall/madvise.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/madvise.rs
rename to services/libs/aster-std/src/syscall/madvise.rs
diff --git a/services/libs/jinux-std/src/syscall/mkdir.rs b/services/libs/aster-std/src/syscall/mkdir.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/mkdir.rs
rename to services/libs/aster-std/src/syscall/mkdir.rs
diff --git a/services/libs/jinux-std/src/syscall/mmap.rs b/services/libs/aster-std/src/syscall/mmap.rs
similarity index 99%
rename from services/libs/jinux-std/src/syscall/mmap.rs
rename to services/libs/aster-std/src/syscall/mmap.rs
index 5b58fe917a..e739bae54d 100644
--- 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
similarity index 99%
rename from services/libs/jinux-std/src/syscall/mod.rs
rename to services/libs/aster-std/src/syscall/mod.rs
index dcd62aabbd..731b413214 100644
--- 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/mprotect.rs b/services/libs/aster-std/src/syscall/mprotect.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/mprotect.rs
rename to services/libs/aster-std/src/syscall/mprotect.rs
diff --git a/services/libs/jinux-std/src/syscall/munmap.rs b/services/libs/aster-std/src/syscall/munmap.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/munmap.rs
rename to services/libs/aster-std/src/syscall/munmap.rs
diff --git a/services/libs/jinux-std/src/syscall/open.rs b/services/libs/aster-std/src/syscall/open.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/open.rs
rename to services/libs/aster-std/src/syscall/open.rs
diff --git a/services/libs/jinux-std/src/syscall/pause.rs b/services/libs/aster-std/src/syscall/pause.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/pause.rs
rename to services/libs/aster-std/src/syscall/pause.rs
diff --git a/services/libs/jinux-std/src/syscall/pipe.rs b/services/libs/aster-std/src/syscall/pipe.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/pipe.rs
rename to services/libs/aster-std/src/syscall/pipe.rs
diff --git a/services/libs/jinux-std/src/syscall/poll.rs b/services/libs/aster-std/src/syscall/poll.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/poll.rs
rename to services/libs/aster-std/src/syscall/poll.rs
diff --git a/services/libs/jinux-std/src/syscall/prctl.rs b/services/libs/aster-std/src/syscall/prctl.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/prctl.rs
rename to services/libs/aster-std/src/syscall/prctl.rs
diff --git a/services/libs/jinux-std/src/syscall/pread64.rs b/services/libs/aster-std/src/syscall/pread64.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/pread64.rs
rename to services/libs/aster-std/src/syscall/pread64.rs
diff --git a/services/libs/jinux-std/src/syscall/prlimit64.rs b/services/libs/aster-std/src/syscall/prlimit64.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/prlimit64.rs
rename to services/libs/aster-std/src/syscall/prlimit64.rs
diff --git a/services/libs/jinux-std/src/syscall/read.rs b/services/libs/aster-std/src/syscall/read.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/read.rs
rename to services/libs/aster-std/src/syscall/read.rs
diff --git a/services/libs/jinux-std/src/syscall/readlink.rs b/services/libs/aster-std/src/syscall/readlink.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/readlink.rs
rename to services/libs/aster-std/src/syscall/readlink.rs
diff --git a/services/libs/jinux-std/src/syscall/recvfrom.rs b/services/libs/aster-std/src/syscall/recvfrom.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/recvfrom.rs
rename to services/libs/aster-std/src/syscall/recvfrom.rs
diff --git a/services/libs/jinux-std/src/syscall/rename.rs b/services/libs/aster-std/src/syscall/rename.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/rename.rs
rename to services/libs/aster-std/src/syscall/rename.rs
diff --git a/services/libs/jinux-std/src/syscall/rmdir.rs b/services/libs/aster-std/src/syscall/rmdir.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/rmdir.rs
rename to services/libs/aster-std/src/syscall/rmdir.rs
diff --git a/services/libs/jinux-std/src/syscall/rt_sigaction.rs b/services/libs/aster-std/src/syscall/rt_sigaction.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/rt_sigaction.rs
rename to services/libs/aster-std/src/syscall/rt_sigaction.rs
diff --git a/services/libs/jinux-std/src/syscall/rt_sigprocmask.rs b/services/libs/aster-std/src/syscall/rt_sigprocmask.rs
similarity index 98%
rename from services/libs/jinux-std/src/syscall/rt_sigprocmask.rs
rename to services/libs/aster-std/src/syscall/rt_sigprocmask.rs
index 0219d104c2..c39356707c 100644
--- 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
similarity index 98%
rename from services/libs/jinux-std/src/syscall/rt_sigreturn.rs
rename to services/libs/aster-std/src/syscall/rt_sigreturn.rs
index 4132b5ab7c..c74e6f6e31 100644
--- 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/sched_yield.rs b/services/libs/aster-std/src/syscall/sched_yield.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/sched_yield.rs
rename to services/libs/aster-std/src/syscall/sched_yield.rs
diff --git a/services/libs/jinux-std/src/syscall/select.rs b/services/libs/aster-std/src/syscall/select.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/select.rs
rename to services/libs/aster-std/src/syscall/select.rs
diff --git a/services/libs/jinux-std/src/syscall/sendto.rs b/services/libs/aster-std/src/syscall/sendto.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/sendto.rs
rename to services/libs/aster-std/src/syscall/sendto.rs
diff --git a/services/libs/jinux-std/src/syscall/set_robust_list.rs b/services/libs/aster-std/src/syscall/set_robust_list.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/set_robust_list.rs
rename to services/libs/aster-std/src/syscall/set_robust_list.rs
diff --git a/services/libs/jinux-std/src/syscall/set_tid_address.rs b/services/libs/aster-std/src/syscall/set_tid_address.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/set_tid_address.rs
rename to services/libs/aster-std/src/syscall/set_tid_address.rs
diff --git a/services/libs/jinux-std/src/syscall/setfsgid.rs b/services/libs/aster-std/src/syscall/setfsgid.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/setfsgid.rs
rename to services/libs/aster-std/src/syscall/setfsgid.rs
diff --git a/services/libs/jinux-std/src/syscall/setfsuid.rs b/services/libs/aster-std/src/syscall/setfsuid.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/setfsuid.rs
rename to services/libs/aster-std/src/syscall/setfsuid.rs
diff --git a/services/libs/jinux-std/src/syscall/setgid.rs b/services/libs/aster-std/src/syscall/setgid.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/setgid.rs
rename to services/libs/aster-std/src/syscall/setgid.rs
diff --git a/services/libs/jinux-std/src/syscall/setgroups.rs b/services/libs/aster-std/src/syscall/setgroups.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/setgroups.rs
rename to services/libs/aster-std/src/syscall/setgroups.rs
diff --git a/services/libs/jinux-std/src/syscall/setpgid.rs b/services/libs/aster-std/src/syscall/setpgid.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/setpgid.rs
rename to services/libs/aster-std/src/syscall/setpgid.rs
diff --git a/services/libs/jinux-std/src/syscall/setregid.rs b/services/libs/aster-std/src/syscall/setregid.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/setregid.rs
rename to services/libs/aster-std/src/syscall/setregid.rs
diff --git a/services/libs/jinux-std/src/syscall/setresgid.rs b/services/libs/aster-std/src/syscall/setresgid.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/setresgid.rs
rename to services/libs/aster-std/src/syscall/setresgid.rs
diff --git a/services/libs/jinux-std/src/syscall/setresuid.rs b/services/libs/aster-std/src/syscall/setresuid.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/setresuid.rs
rename to services/libs/aster-std/src/syscall/setresuid.rs
diff --git a/services/libs/jinux-std/src/syscall/setreuid.rs b/services/libs/aster-std/src/syscall/setreuid.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/setreuid.rs
rename to services/libs/aster-std/src/syscall/setreuid.rs
diff --git a/services/libs/jinux-std/src/syscall/setsid.rs b/services/libs/aster-std/src/syscall/setsid.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/setsid.rs
rename to services/libs/aster-std/src/syscall/setsid.rs
diff --git a/services/libs/jinux-std/src/syscall/setsockopt.rs b/services/libs/aster-std/src/syscall/setsockopt.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/setsockopt.rs
rename to services/libs/aster-std/src/syscall/setsockopt.rs
diff --git a/services/libs/jinux-std/src/syscall/setuid.rs b/services/libs/aster-std/src/syscall/setuid.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/setuid.rs
rename to services/libs/aster-std/src/syscall/setuid.rs
diff --git a/services/libs/jinux-std/src/syscall/shutdown.rs b/services/libs/aster-std/src/syscall/shutdown.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/shutdown.rs
rename to services/libs/aster-std/src/syscall/shutdown.rs
diff --git a/services/libs/jinux-std/src/syscall/sigaltstack.rs b/services/libs/aster-std/src/syscall/sigaltstack.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/sigaltstack.rs
rename to services/libs/aster-std/src/syscall/sigaltstack.rs
diff --git a/services/libs/jinux-std/src/syscall/socket.rs b/services/libs/aster-std/src/syscall/socket.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/socket.rs
rename to services/libs/aster-std/src/syscall/socket.rs
diff --git a/services/libs/jinux-std/src/syscall/socketpair.rs b/services/libs/aster-std/src/syscall/socketpair.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/socketpair.rs
rename to services/libs/aster-std/src/syscall/socketpair.rs
diff --git a/services/libs/jinux-std/src/syscall/stat.rs b/services/libs/aster-std/src/syscall/stat.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/stat.rs
rename to services/libs/aster-std/src/syscall/stat.rs
diff --git a/services/libs/jinux-std/src/syscall/statfs.rs b/services/libs/aster-std/src/syscall/statfs.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/statfs.rs
rename to services/libs/aster-std/src/syscall/statfs.rs
diff --git a/services/libs/jinux-std/src/syscall/symlink.rs b/services/libs/aster-std/src/syscall/symlink.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/symlink.rs
rename to services/libs/aster-std/src/syscall/symlink.rs
diff --git a/services/libs/jinux-std/src/syscall/tgkill.rs b/services/libs/aster-std/src/syscall/tgkill.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/tgkill.rs
rename to services/libs/aster-std/src/syscall/tgkill.rs
diff --git a/services/libs/jinux-std/src/syscall/time.rs b/services/libs/aster-std/src/syscall/time.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/time.rs
rename to services/libs/aster-std/src/syscall/time.rs
diff --git a/services/libs/jinux-std/src/syscall/umask.rs b/services/libs/aster-std/src/syscall/umask.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/umask.rs
rename to services/libs/aster-std/src/syscall/umask.rs
diff --git a/services/libs/jinux-std/src/syscall/uname.rs b/services/libs/aster-std/src/syscall/uname.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/uname.rs
rename to services/libs/aster-std/src/syscall/uname.rs
diff --git a/services/libs/jinux-std/src/syscall/unlink.rs b/services/libs/aster-std/src/syscall/unlink.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/unlink.rs
rename to services/libs/aster-std/src/syscall/unlink.rs
diff --git a/services/libs/jinux-std/src/syscall/utimens.rs b/services/libs/aster-std/src/syscall/utimens.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/utimens.rs
rename to services/libs/aster-std/src/syscall/utimens.rs
diff --git a/services/libs/jinux-std/src/syscall/wait4.rs b/services/libs/aster-std/src/syscall/wait4.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/wait4.rs
rename to services/libs/aster-std/src/syscall/wait4.rs
diff --git a/services/libs/jinux-std/src/syscall/waitid.rs b/services/libs/aster-std/src/syscall/waitid.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/waitid.rs
rename to services/libs/aster-std/src/syscall/waitid.rs
diff --git a/services/libs/jinux-std/src/syscall/write.rs b/services/libs/aster-std/src/syscall/write.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/write.rs
rename to services/libs/aster-std/src/syscall/write.rs
diff --git a/services/libs/jinux-std/src/syscall/writev.rs b/services/libs/aster-std/src/syscall/writev.rs
similarity index 100%
rename from services/libs/jinux-std/src/syscall/writev.rs
rename to services/libs/aster-std/src/syscall/writev.rs
diff --git a/services/libs/jinux-std/src/thread/exception.rs b/services/libs/aster-std/src/thread/exception.rs
similarity index 98%
rename from services/libs/jinux-std/src/thread/exception.rs
rename to services/libs/aster-std/src/thread/exception.rs
index 4bdd22fada..6a690c54af 100644
--- 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
similarity index 97%
rename from services/libs/jinux-std/src/thread/kernel_thread.rs
rename to services/libs/aster-std/src/thread/kernel_thread.rs
index 1b0a5d7885..be39fb5b3d 100644
--- 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
similarity index 98%
rename from services/libs/jinux-std/src/thread/mod.rs
rename to services/libs/aster-std/src/thread/mod.rs
index 86dab103ab..c321170c74 100644
--- 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/status.rs b/services/libs/aster-std/src/thread/status.rs
similarity index 100%
rename from services/libs/jinux-std/src/thread/status.rs
rename to services/libs/aster-std/src/thread/status.rs
diff --git a/services/libs/jinux-std/src/thread/task.rs b/services/libs/aster-std/src/thread/task.rs
similarity index 99%
rename from services/libs/jinux-std/src/thread/task.rs
rename to services/libs/aster-std/src/thread/task.rs
index e5e7a567f0..856161045a 100644
--- 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/thread_table.rs b/services/libs/aster-std/src/thread/thread_table.rs
similarity index 100%
rename from services/libs/jinux-std/src/thread/thread_table.rs
rename to services/libs/aster-std/src/thread/thread_table.rs
diff --git a/services/libs/jinux-std/src/thread/work_queue/mod.rs b/services/libs/aster-std/src/thread/work_queue/mod.rs
similarity index 98%
rename from services/libs/jinux-std/src/thread/work_queue/mod.rs
rename to services/libs/aster-std/src/thread/work_queue/mod.rs
index 5aae0107ca..4e55e7b69a 100644
--- 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;
@@ -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/simple_scheduler.rs b/services/libs/aster-std/src/thread/work_queue/simple_scheduler.rs
similarity index 100%
rename from services/libs/jinux-std/src/thread/work_queue/simple_scheduler.rs
rename to services/libs/aster-std/src/thread/work_queue/simple_scheduler.rs
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
similarity index 97%
rename from services/libs/jinux-std/src/thread/work_queue/work_item.rs
rename to services/libs/aster-std/src/thread/work_queue/work_item.rs
index 3434732139..919a5318d1 100644
--- 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
similarity index 98%
rename from services/libs/jinux-std/src/thread/work_queue/worker.rs
rename to services/libs/aster-std/src/thread/work_queue/worker.rs
index d988868ce7..3ba850ed88 100644
--- 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
similarity index 98%
rename from services/libs/jinux-std/src/thread/work_queue/worker_pool.rs
rename to services/libs/aster-std/src/thread/work_queue/worker_pool.rs
index 57fc0dfd1c..462864cd12 100644
--- 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
similarity index 98%
rename from services/libs/jinux-std/src/time/mod.rs
rename to services/libs/aster-std/src/time/mod.rs
index 5ffed2d136..7c9e737daa 100644
--- 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
similarity index 95%
rename from services/libs/jinux-std/src/time/system_time.rs
rename to services/libs/aster-std/src/time/system_time.rs
index e1584953d5..bca7a387b0 100644
--- 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::*;
@@ -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
similarity index 98%
rename from services/libs/jinux-std/src/util/mod.rs
rename to services/libs/aster-std/src/util/mod.rs
index 9441e989ba..210358bc8e 100644
--- 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/net/addr.rs b/services/libs/aster-std/src/util/net/addr.rs
similarity index 100%
rename from services/libs/jinux-std/src/util/net/addr.rs
rename to services/libs/aster-std/src/util/net/addr.rs
diff --git a/services/libs/jinux-std/src/util/net/mod.rs b/services/libs/aster-std/src/util/net/mod.rs
similarity index 100%
rename from services/libs/jinux-std/src/util/net/mod.rs
rename to services/libs/aster-std/src/util/net/mod.rs
diff --git a/services/libs/jinux-std/src/util/net/socket.rs b/services/libs/aster-std/src/util/net/socket.rs
similarity index 100%
rename from services/libs/jinux-std/src/util/net/socket.rs
rename to services/libs/aster-std/src/util/net/socket.rs
diff --git a/services/libs/jinux-std/src/vdso.rs b/services/libs/aster-std/src/vdso.rs
similarity index 96%
rename from services/libs/jinux-std/src/vdso.rs
rename to services/libs/aster-std/src/vdso.rs
index 0a14325583..242b9a17fa 100644
--- 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;
@@ -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);
@@ -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
similarity index 82%
rename from services/libs/jinux-std/src/vm/mod.rs
rename to services/libs/aster-std/src/vm/mod.rs
index 1ed93e8cd9..28b205c30e 100644
--- 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/page_fault_handler.rs b/services/libs/aster-std/src/vm/page_fault_handler.rs
similarity index 100%
rename from services/libs/jinux-std/src/vm/page_fault_handler.rs
rename to services/libs/aster-std/src/vm/page_fault_handler.rs
diff --git a/services/libs/jinux-std/src/vm/perms.rs b/services/libs/aster-std/src/vm/perms.rs
similarity index 97%
rename from services/libs/jinux-std/src/vm/perms.rs
rename to services/libs/aster-std/src/vm/perms.rs
index 2e3794f6ae..5422358834 100644
--- 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
similarity index 95%
rename from services/libs/jinux-std/src/vm/vmar/dyn_cap.rs
rename to services/libs/aster-std/src/vm/vmar/dyn_cap.rs
index 9c39044594..138dcbe386 100644
--- 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::*;
@@ -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();
@@ -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
similarity index 99%
rename from services/libs/jinux-std/src/vm/vmar/mod.rs
rename to services/libs/aster-std/src/vm/vmar/mod.rs
index 4c19882a04..ced1b01df5 100644
--- 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
similarity index 96%
rename from services/libs/jinux-std/src/vm/vmar/options.rs
rename to services/libs/aster-std/src/vm/vmar/options.rs
index cb43a81ca8..df0ae43cf0 100644
--- 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;
@@ -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;
@@ -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;
@@ -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
similarity index 95%
rename from services/libs/jinux-std/src/vm/vmar/static_cap.rs
rename to services/libs/aster-std/src/vm/vmar/static_cap.rs
index 76b900e1dc..248ac40a7d 100644
--- 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};
@@ -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();
@@ -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
similarity index 99%
rename from services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
rename to services/libs/aster-std/src/vm/vmar/vm_mapping.rs
index 53b603a64b..b1c4bd9528 100644
--- 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
similarity index 96%
rename from services/libs/jinux-std/src/vm/vmo/dyn_cap.rs
rename to services/libs/aster-std/src/vm/vmo/dyn_cap.rs
index 9eb0c6b346..0ee957d5ea 100644
--- 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::{
@@ -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
similarity index 98%
rename from services/libs/jinux-std/src/vm/vmo/mod.rs
rename to services/libs/aster-std/src/vm/vmo/mod.rs
index 74d41c7014..3d37eecf7d 100644
--- 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::*;
@@ -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
similarity index 96%
rename from services/libs/jinux-std/src/vm/vmo/options.rs
rename to services/libs/aster-std/src/vm/vmo/options.rs
index a1291eb98e..88e559cc4b 100644
--- 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};
@@ -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()
@@ -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()
@@ -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)
@@ -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()
@@ -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()
@@ -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()
@@ -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()
@@ -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()
@@ -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
similarity index 98%
rename from services/libs/jinux-std/src/vm/vmo/pager.rs
rename to services/libs/aster-std/src/vm/vmo/pager.rs
index 0f0e475131..f738586892 100644
--- 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
similarity index 95%
rename from services/libs/jinux-std/src/vm/vmo/static_cap.rs
rename to services/libs/aster-std/src/vm/vmo/static_cap.rs
index 0b4a6dcc8b..b728b4e185 100644
--- 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::{
@@ -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
similarity index 58%
rename from services/libs/jinux-util/Cargo.toml
rename to services/libs/aster-util/Cargo.toml
index 77daec7cbe..d21d6723f5 100644
--- 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/coeff.rs b/services/libs/aster-util/src/coeff.rs
similarity index 100%
rename from services/libs/jinux-util/src/coeff.rs
rename to services/libs/aster-util/src/coeff.rs
diff --git a/services/libs/jinux-util/src/dup.rs b/services/libs/aster-util/src/dup.rs
similarity index 91%
rename from services/libs/jinux-util/src/dup.rs
rename to services/libs/aster-util/src/dup.rs
index e4ece7d3c3..0b9b9e99e7 100644
--- 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/id_allocator.rs b/services/libs/aster-util/src/id_allocator.rs
similarity index 100%
rename from services/libs/jinux-util/src/id_allocator.rs
rename to services/libs/aster-util/src/id_allocator.rs
diff --git a/services/libs/jinux-util/src/lib.rs b/services/libs/aster-util/src/lib.rs
similarity index 86%
rename from services/libs/jinux-util/src/lib.rs
rename to services/libs/aster-util/src/lib.rs
index 48ffec6cc4..27f75cc710 100644
--- 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
similarity index 95%
rename from services/libs/jinux-util/src/safe_ptr.rs
rename to services/libs/aster-util/src/safe_ptr.rs
index 220f57360e..8d86bb25cb 100644
--- 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;
@@ -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/slot_vec.rs b/services/libs/aster-util/src/slot_vec.rs
similarity index 100%
rename from services/libs/jinux-util/src/slot_vec.rs
rename to services/libs/aster-util/src/slot_vec.rs
diff --git a/services/libs/jinux-util/src/union_read_ptr.rs b/services/libs/aster-util/src/union_read_ptr.rs
similarity index 95%
rename from services/libs/jinux-util/src/union_read_ptr.rs
rename to services/libs/aster-util/src/union_read_ptr.rs
index 2cf404a1bd..9e902c990e 100644
--- 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
index 82af27a7e3..e5871e67e4 100644
--- 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
index df8f37a1b9..07b8a7404a 100644
--- 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
index 669daac229..f11eb3dcb8 100644
--- 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
index 402e80a4ca..854e16da2a 100755
--- 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
@@ -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
@@ -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
@@ -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
index 39d7d4bb5b..99ee9114f9 100644
--- 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
@@ -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 \
@@ -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
@@ -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
index 19b1d50edb..69149de907 100644
--- 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
index 11f9c5d5ea..92af52d14c 100755
--- 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/.github/workflows/integration_test.yml b/.github/workflows/integration_test.yml
index df94fbab1e..962999bfa2 100644
--- 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
index a9b4dc572f..bfcfa9542e 100644
--- 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/framework/libs/ktest/src/lib.rs b/framework/libs/ktest/src/lib.rs
index 5e2f1c24e4..7ba5795027 100644
--- 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:
@@ -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
@@ -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
index a885e13986..8d800feef3 100644
--- 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
index 9b864904fa..d78412f11d 100644
--- 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
@@ -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."; \
@@ -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)
|
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.
|
2023-12-25T03:34:33Z
|
0.2
|
6dbf5d560deafea0dcec228e4cb2d5e53c756174
|
|
asterinas/asterinas
| 395
|
asterinas__asterinas-395
|
[
"254"
] |
576578baf4025686ae4c2893c2aafbc8d1e14722
|
diff --git a/services/libs/jinux-std/src/device/mod.rs b/services/libs/jinux-std/src/device/mod.rs
index fa9e6a0d97..2fc391eeff 100644
--- 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);
@@ -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
index dd64aa1aa6..7137a64edf 100644
--- 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;
@@ -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)
}
@@ -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
index a6a8173728..8ee323a677 100644
--- 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
index 34ca3044af..748edb3ecc 100644
--- 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.
@@ -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 {
@@ -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();
@@ -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() {
@@ -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() {
@@ -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 => {
@@ -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()
}
}
@@ -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
index 91a0567c4f..4ed22a5e20 100644
--- 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;
@@ -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)
}
@@ -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/tty/device.rs b/services/libs/jinux-std/src/device/tty/device.rs
new file mode 100644
index 0000000000..e5f8afb799
--- /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
index c8defa6b2c..7764f4eb5b 100644
--- 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};
@@ -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.
@@ -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() {
@@ -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())),
}
@@ -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' {
@@ -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;
}
@@ -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.
@@ -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);
@@ -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);
@@ -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 {
@@ -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);
@@ -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;
}
@@ -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
@@ -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)
}
@@ -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
index 395ca0f756..1aea18dadb 100644
--- 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();
}
@@ -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)
}
@@ -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 => {
@@ -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
index 529b3c8d71..687ecb762b 100644
--- 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;
@@ -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)
}
@@ -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
index 7d5f1f22d4..e3b695cd97 100644
--- 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;
@@ -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;
@@ -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
index c85c74eb81..b85c577d68 100644
--- 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 b/services/libs/jinux-std/src/fs/devpts/master.rs
deleted file mode 100644
index bfddebfc65..0000000000
--- 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
index f960872e72..25d115d44e 100644
--- 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,
@@ -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;
@@ -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()
@@ -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);
@@ -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
index fcba7bab2f..c8031d997a 100644
--- 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::*;
@@ -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,
@@ -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 {
@@ -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 {
@@ -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
index 83e7ffc991..408bdb15ea 100644
--- 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;
@@ -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
index 2036d7557b..05dbe218b7 100644
--- 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::*;
@@ -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
index 39d3ef4600..93e622df3d 100644
--- 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
index b286aa5811..fae4407c34 100644
--- 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()),
@@ -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)
}
@@ -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 {
@@ -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
index aa9101f160..665d6f4916 100644
--- 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)]
@@ -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,
@@ -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 {
@@ -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();
}
@@ -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 {
@@ -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_ {
@@ -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
index 2614b307b2..f1fec834a4 100644
--- 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
index 317d2834c2..d7bdc01e22 100644
--- 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
index 13f18d10e4..3feb36f0f6 100644
--- 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
index 5a0132a4b8..2573ff1596 100644
--- 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
index e0d9b4dbdf..fa38ab0c21 100644
--- 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. */
@@ -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)?;
@@ -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)
}
@@ -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
index 8857923f94..2bd217f71c 100644
--- 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);
}
}
}
@@ -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
index b467a525a8..5aa8884a81 100644
--- 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;
@@ -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
index def036130c..dd49dcc399 100644
--- 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};
@@ -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>>>,
@@ -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,
@@ -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
@@ -126,7 +117,6 @@ impl<'a> ProcessBuilder<'a> {
argv,
envp,
process_vm,
- process_group,
file_table,
fs,
umask,
@@ -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();
@@ -168,7 +154,6 @@ impl<'a> ProcessBuilder<'a> {
threads,
executable_path.to_string(),
process_vm,
- process_group_ref,
file_table,
fs,
umask,
@@ -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/job_control.rs b/services/libs/jinux-std/src/process/process/job_control.rs
new file mode 100644
index 0000000000..d5af056c65
--- /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
index 4767861249..ee12e34839 100644
--- 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;
@@ -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;
@@ -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.
@@ -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
@@ -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>>,
@@ -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,
@@ -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)
}
@@ -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)
}
@@ -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()
@@ -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 *************
@@ -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/process/process_group.rs b/services/libs/jinux-std/src/process/process/process_group.rs
new file mode 100644
index 0000000000..3cc8190502
--- /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 a/services/libs/jinux-std/src/process/process/session.rs b/services/libs/jinux-std/src/process/process/session.rs
new file mode 100644
index 0000000000..18ff44c4f5
--- /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 a/services/libs/jinux-std/src/process/process/terminal.rs b/services/libs/jinux-std/src/process/process/terminal.rs
new file mode 100644
index 0000000000..94d66b319a
--- /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 b/services/libs/jinux-std/src/process/process_group.rs
deleted file mode 100644
index 1a18ea0cd3..0000000000
--- 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
index 428659843f..d5d216c34e 100644
--- 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()
@@ -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
index 4272c9bf86..9b687ea8a1 100644
--- 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
index 4732be6211..99e4d45724 100644
--- 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/syscall/getsid.rs b/services/libs/jinux-std/src/syscall/getsid.rs
new file mode 100644
index 0000000000..721644c3de
--- /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
index d9a4070e8f..e0c82be0b5 100644
--- 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
index d245667aaa..d3b95f5030 100644
--- 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;
@@ -119,6 +121,7 @@ mod getpgrp;
mod getpid;
mod getppid;
mod getrandom;
+mod getsid;
mod getsockname;
mod getsockopt;
mod gettid;
@@ -155,6 +158,7 @@ mod sendto;
mod set_robust_list;
mod set_tid_address;
mod setpgid;
+mod setsid;
mod setsockopt;
mod shutdown;
mod socket;
@@ -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,
@@ -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
index 86244b93d7..36e8636c34 100644
--- 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};
@@ -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"
@@ -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/setsid.rs b/services/libs/jinux-std/src/syscall/setsid.rs
new file mode 100644
index 0000000000..40a315f2c1
--- /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
index c02236dd8f..014fa0d64e 100644
--- 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
index b1ae4463fc..59e5facf81 100644
--- 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/regression/syscall_test/blocklists/pty_test b/regression/syscall_test/blocklists/pty_test
index 3d712cd4fd..88a3265eee 100644
--- 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
|
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
|
2023-08-30T11:25:32Z
|
0.2
|
6dbf5d560deafea0dcec228e4cb2d5e53c756174
|
|
asterinas/asterinas
| 334
|
asterinas__asterinas-334
|
[
"214"
] |
25c4f0f2bcaa0bc8c650b0f4ee7b0d78e2a836b2
|
diff --git a/regression/apps/Makefile b/regression/apps/Makefile
index 09db3e9c42..5f70f66350 100644
--- 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/pty/Makefile b/regression/apps/pty/Makefile
new file mode 100644
index 0000000000..05ff449d2d
--- /dev/null
+++ b/regression/apps/pty/Makefile
@@ -0,0 +1,3 @@
+include ../test_common.mk
+
+EXTRA_C_FLAGS :=
diff --git a/regression/apps/pty/open_pty.c b/regression/apps/pty/open_pty.c
new file mode 100644
index 0000000000..220d2f3eb3
--- /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/services/libs/jinux-std/src/device/mod.rs b/services/libs/jinux-std/src/device/mod.rs
index 899206d626..fa9e6a0d97 100644
--- 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 b/services/libs/jinux-std/src/device/pty.rs
deleted file mode 100644
index 5aba6e7b72..0000000000
--- 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/mod.rs b/services/libs/jinux-std/src/device/pty/mod.rs
new file mode 100644
index 0000000000..998b594762
--- /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 a/services/libs/jinux-std/src/device/pty/pty.rs b/services/libs/jinux-std/src/device/pty/pty.rs
new file mode 100644
index 0000000000..e8d1cc1f85
--- /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
index 2a55f8a965..2d52c318e4 100644
--- 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
@@ -25,6 +25,8 @@ pub struct LineDiscipline {
foreground: SpinLock<Weak<ProcessGroup>>,
/// termios
termios: SpinLock<KernelTermios>,
+ /// Windows size,
+ winsize: SpinLock<WinSize>,
/// Pollee
pollee: Pollee,
}
@@ -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'
@@ -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"),
@@ -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
index 5d5aff5ee3..1564266bf9 100644
--- 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;
@@ -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
index 60d3e54494..00615ec16a 100644
--- 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
}
}
@@ -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,
@@ -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,
@@ -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)]
@@ -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
@@ -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
index 911f074c0b..88a97cd0ec 100644
--- 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>);
@@ -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);
}
}
@@ -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
index a661274b83..ac2a0ddd7b 100644
--- 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;
@@ -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
index 2297c33649..027e243eba 100644
--- 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;
@@ -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
index 58c0c4d81a..9a57cb0206 100644
--- 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
index e8b944f985..617f6c36b0 100644
--- 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])
}
@@ -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
index 3e2d47c0ab..994c948804 100644
--- 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(())
}
@@ -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)?;
@@ -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)
}
}
@@ -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/regression/apps/scripts/run_tests.sh b/regression/apps/scripts/run_tests.sh
index 7556dde7f5..d39bc54428 100755
--- 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
index a8198e8dee..8789dc56f7 100644
--- 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 a/regression/syscall_test/blocklists/pty_test b/regression/syscall_test/blocklists/pty_test
new file mode 100644
index 0000000000..3d712cd4fd
--- /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
|
Implement pseudo terminals
Maybe we need #209 for pty, since each pty will be a device under devfs.
|
2023-08-01T06:37:18Z
|
0.1
|
25c4f0f2bcaa0bc8c650b0f4ee7b0d78e2a836b2
|
|
asterinas/asterinas
| 327
|
asterinas__asterinas-327
|
[
"340"
] |
dbfb2e1a62a9981a67cc01ff7310981744ec2ac5
|
diff --git a/tools/docker/.gitignore b/tools/docker/.gitignore
new file mode 100644
index 0000000000..c4d86dc34f
--- /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
index ab0f054034..c2f7486893 100644
--- 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 \
@@ -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
index 1cc10a5b21..8a871aa568 100755
--- 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} \
|
diff --git a/regression/syscall_test/Makefile b/regression/syscall_test/Makefile
index d91d80822b..a8198e8dee 100644
--- 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
@@ -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
@@ -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
|
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.
|
2023-07-27T07:11:21Z
|
0.1
|
25c4f0f2bcaa0bc8c650b0f4ee7b0d78e2a836b2
|
|
asterinas/asterinas
| 183
|
asterinas__asterinas-183
|
[
"115"
] |
888853a6de752e97c6f94fff83c00594be42929f
|
diff --git a/src/.cargo/config.toml b/.cargo/config.toml
similarity index 100%
rename from src/.cargo/config.toml
rename to .cargo/config.toml
diff --git a/.gitattributes b/.gitattributes
index 5da8683478..112cce3c07 100644
--- 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
index 9981fa9924..19881b377b 100644
--- 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.lock b/Cargo.lock
similarity index 100%
rename from src/Cargo.lock
rename to Cargo.lock
diff --git a/src/Cargo.toml b/Cargo.toml
similarity index 79%
rename from src/Cargo.toml
rename to Cargo.toml
index ef60250eb6..143ce953ac 100644
--- 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"
@@ -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/Components.toml b/Components.toml
similarity index 100%
rename from src/Components.toml
rename to Components.toml
diff --git a/Makefile b/Makefile
index ee191869de..b8cf032494 100644
--- 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
@@ -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
index 0fdd7f844e..d2ef2e41a0 100644
--- 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.
@@ -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/Cargo.toml b/boot/Cargo.toml
similarity index 100%
rename from src/boot/Cargo.toml
rename to boot/Cargo.toml
diff --git a/src/boot/limine/conf/limine.cfg b/boot/limine/conf/limine.cfg
similarity index 100%
rename from src/boot/limine/conf/limine.cfg
rename to boot/limine/conf/limine.cfg
diff --git a/src/boot/limine/conf/linker.ld b/boot/limine/conf/linker.ld
similarity index 100%
rename from src/boot/limine/conf/linker.ld
rename to boot/limine/conf/linker.ld
diff --git a/src/boot/limine/scripts/limine-build.sh b/boot/limine/scripts/limine-build.sh
similarity index 95%
rename from src/boot/limine/scripts/limine-build.sh
rename to boot/limine/scripts/limine-build.sh
index 7267124098..69188a64f0 100755
--- 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/src/main.rs b/boot/src/main.rs
similarity index 100%
rename from src/boot/src/main.rs
rename to boot/src/main.rs
diff --git a/src/build.rs b/build.rs
similarity index 100%
rename from src/build.rs
rename to build.rs
diff --git a/src/framework/README.md b/framework/README.md
similarity index 100%
rename from src/framework/README.md
rename to framework/README.md
diff --git a/src/framework/jinux-frame/Cargo.toml b/framework/jinux-frame/Cargo.toml
similarity index 94%
rename from src/framework/jinux-frame/Cargo.toml
rename to framework/jinux-frame/Cargo.toml
index 6645f749bb..025c188339 100644
--- 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/src/arch/mod.rs b/framework/jinux-frame/src/arch/mod.rs
similarity index 100%
rename from src/framework/jinux-frame/src/arch/mod.rs
rename to framework/jinux-frame/src/arch/mod.rs
diff --git a/src/framework/jinux-frame/src/arch/x86/boot/limine.rs b/framework/jinux-frame/src/arch/x86/boot/limine.rs
similarity index 100%
rename from src/framework/jinux-frame/src/arch/x86/boot/limine.rs
rename to framework/jinux-frame/src/arch/x86/boot/limine.rs
diff --git a/src/framework/jinux-frame/src/arch/x86/boot/mod.rs b/framework/jinux-frame/src/arch/x86/boot/mod.rs
similarity index 100%
rename from src/framework/jinux-frame/src/arch/x86/boot/mod.rs
rename to framework/jinux-frame/src/arch/x86/boot/mod.rs
diff --git a/src/framework/jinux-frame/src/arch/x86/cpu.rs b/framework/jinux-frame/src/arch/x86/cpu.rs
similarity index 100%
rename from src/framework/jinux-frame/src/arch/x86/cpu.rs
rename to framework/jinux-frame/src/arch/x86/cpu.rs
diff --git a/src/framework/jinux-frame/src/arch/x86/device/cmos.rs b/framework/jinux-frame/src/arch/x86/device/cmos.rs
similarity index 100%
rename from src/framework/jinux-frame/src/arch/x86/device/cmos.rs
rename to framework/jinux-frame/src/arch/x86/device/cmos.rs
diff --git a/src/framework/jinux-frame/src/arch/x86/device/io_port.rs b/framework/jinux-frame/src/arch/x86/device/io_port.rs
similarity index 100%
rename from src/framework/jinux-frame/src/arch/x86/device/io_port.rs
rename to framework/jinux-frame/src/arch/x86/device/io_port.rs
diff --git a/src/framework/jinux-frame/src/arch/x86/device/mod.rs b/framework/jinux-frame/src/arch/x86/device/mod.rs
similarity index 100%
rename from src/framework/jinux-frame/src/arch/x86/device/mod.rs
rename to framework/jinux-frame/src/arch/x86/device/mod.rs
diff --git a/src/framework/jinux-frame/src/arch/x86/device/pci.rs b/framework/jinux-frame/src/arch/x86/device/pci.rs
similarity index 100%
rename from src/framework/jinux-frame/src/arch/x86/device/pci.rs
rename to framework/jinux-frame/src/arch/x86/device/pci.rs
diff --git a/src/framework/jinux-frame/src/arch/x86/device/serial.rs b/framework/jinux-frame/src/arch/x86/device/serial.rs
similarity index 100%
rename from src/framework/jinux-frame/src/arch/x86/device/serial.rs
rename to framework/jinux-frame/src/arch/x86/device/serial.rs
diff --git a/src/framework/jinux-frame/src/arch/x86/irq.rs b/framework/jinux-frame/src/arch/x86/irq.rs
similarity index 100%
rename from src/framework/jinux-frame/src/arch/x86/irq.rs
rename to framework/jinux-frame/src/arch/x86/irq.rs
diff --git a/src/framework/jinux-frame/src/arch/x86/kernel/acpi.rs b/framework/jinux-frame/src/arch/x86/kernel/acpi.rs
similarity index 100%
rename from src/framework/jinux-frame/src/arch/x86/kernel/acpi.rs
rename to framework/jinux-frame/src/arch/x86/kernel/acpi.rs
diff --git a/src/framework/jinux-frame/src/arch/x86/kernel/ioapic.rs b/framework/jinux-frame/src/arch/x86/kernel/ioapic.rs
similarity index 100%
rename from src/framework/jinux-frame/src/arch/x86/kernel/ioapic.rs
rename to framework/jinux-frame/src/arch/x86/kernel/ioapic.rs
diff --git a/src/framework/jinux-frame/src/arch/x86/kernel/mod.rs b/framework/jinux-frame/src/arch/x86/kernel/mod.rs
similarity index 100%
rename from src/framework/jinux-frame/src/arch/x86/kernel/mod.rs
rename to framework/jinux-frame/src/arch/x86/kernel/mod.rs
diff --git a/src/framework/jinux-frame/src/arch/x86/kernel/pic.rs b/framework/jinux-frame/src/arch/x86/kernel/pic.rs
similarity index 100%
rename from src/framework/jinux-frame/src/arch/x86/kernel/pic.rs
rename to framework/jinux-frame/src/arch/x86/kernel/pic.rs
diff --git a/src/framework/jinux-frame/src/arch/x86/kernel/xapic.rs b/framework/jinux-frame/src/arch/x86/kernel/xapic.rs
similarity index 100%
rename from src/framework/jinux-frame/src/arch/x86/kernel/xapic.rs
rename to framework/jinux-frame/src/arch/x86/kernel/xapic.rs
diff --git a/src/framework/jinux-frame/src/arch/x86/mm/mod.rs b/framework/jinux-frame/src/arch/x86/mm/mod.rs
similarity index 100%
rename from src/framework/jinux-frame/src/arch/x86/mm/mod.rs
rename to framework/jinux-frame/src/arch/x86/mm/mod.rs
diff --git a/src/framework/jinux-frame/src/arch/x86/mod.rs b/framework/jinux-frame/src/arch/x86/mod.rs
similarity index 100%
rename from src/framework/jinux-frame/src/arch/x86/mod.rs
rename to framework/jinux-frame/src/arch/x86/mod.rs
diff --git a/src/framework/jinux-frame/src/arch/x86/timer/apic.rs b/framework/jinux-frame/src/arch/x86/timer/apic.rs
similarity index 100%
rename from src/framework/jinux-frame/src/arch/x86/timer/apic.rs
rename to framework/jinux-frame/src/arch/x86/timer/apic.rs
diff --git a/src/framework/jinux-frame/src/arch/x86/timer/hpet.rs b/framework/jinux-frame/src/arch/x86/timer/hpet.rs
similarity index 100%
rename from src/framework/jinux-frame/src/arch/x86/timer/hpet.rs
rename to framework/jinux-frame/src/arch/x86/timer/hpet.rs
diff --git a/src/framework/jinux-frame/src/arch/x86/timer/mod.rs b/framework/jinux-frame/src/arch/x86/timer/mod.rs
similarity index 100%
rename from src/framework/jinux-frame/src/arch/x86/timer/mod.rs
rename to framework/jinux-frame/src/arch/x86/timer/mod.rs
diff --git a/src/framework/jinux-frame/src/arch/x86/timer/pit.rs b/framework/jinux-frame/src/arch/x86/timer/pit.rs
similarity index 100%
rename from src/framework/jinux-frame/src/arch/x86/timer/pit.rs
rename to framework/jinux-frame/src/arch/x86/timer/pit.rs
diff --git a/src/framework/jinux-frame/src/config.rs b/framework/jinux-frame/src/config.rs
similarity index 100%
rename from src/framework/jinux-frame/src/config.rs
rename to framework/jinux-frame/src/config.rs
diff --git a/src/framework/jinux-frame/src/cpu.rs b/framework/jinux-frame/src/cpu.rs
similarity index 100%
rename from src/framework/jinux-frame/src/cpu.rs
rename to framework/jinux-frame/src/cpu.rs
diff --git a/src/framework/jinux-frame/src/error.rs b/framework/jinux-frame/src/error.rs
similarity index 100%
rename from src/framework/jinux-frame/src/error.rs
rename to framework/jinux-frame/src/error.rs
diff --git a/src/framework/jinux-frame/src/lib.rs b/framework/jinux-frame/src/lib.rs
similarity index 100%
rename from src/framework/jinux-frame/src/lib.rs
rename to framework/jinux-frame/src/lib.rs
diff --git a/src/framework/jinux-frame/src/logger.rs b/framework/jinux-frame/src/logger.rs
similarity index 100%
rename from src/framework/jinux-frame/src/logger.rs
rename to framework/jinux-frame/src/logger.rs
diff --git a/src/framework/jinux-frame/src/prelude.rs b/framework/jinux-frame/src/prelude.rs
similarity index 100%
rename from src/framework/jinux-frame/src/prelude.rs
rename to framework/jinux-frame/src/prelude.rs
diff --git a/src/framework/jinux-frame/src/sync/atomic_bits.rs b/framework/jinux-frame/src/sync/atomic_bits.rs
similarity index 100%
rename from src/framework/jinux-frame/src/sync/atomic_bits.rs
rename to framework/jinux-frame/src/sync/atomic_bits.rs
diff --git a/src/framework/jinux-frame/src/sync/mod.rs b/framework/jinux-frame/src/sync/mod.rs
similarity index 100%
rename from src/framework/jinux-frame/src/sync/mod.rs
rename to framework/jinux-frame/src/sync/mod.rs
diff --git a/src/framework/jinux-frame/src/sync/mutex.rs b/framework/jinux-frame/src/sync/mutex.rs
similarity index 100%
rename from src/framework/jinux-frame/src/sync/mutex.rs
rename to framework/jinux-frame/src/sync/mutex.rs
diff --git a/src/framework/jinux-frame/src/sync/rcu/mod.rs b/framework/jinux-frame/src/sync/rcu/mod.rs
similarity index 100%
rename from src/framework/jinux-frame/src/sync/rcu/mod.rs
rename to framework/jinux-frame/src/sync/rcu/mod.rs
diff --git a/src/framework/jinux-frame/src/sync/rcu/monitor.rs b/framework/jinux-frame/src/sync/rcu/monitor.rs
similarity index 100%
rename from src/framework/jinux-frame/src/sync/rcu/monitor.rs
rename to framework/jinux-frame/src/sync/rcu/monitor.rs
diff --git a/src/framework/jinux-frame/src/sync/rcu/owner_ptr.rs b/framework/jinux-frame/src/sync/rcu/owner_ptr.rs
similarity index 100%
rename from src/framework/jinux-frame/src/sync/rcu/owner_ptr.rs
rename to framework/jinux-frame/src/sync/rcu/owner_ptr.rs
diff --git a/src/framework/jinux-frame/src/sync/spin.rs b/framework/jinux-frame/src/sync/spin.rs
similarity index 100%
rename from src/framework/jinux-frame/src/sync/spin.rs
rename to framework/jinux-frame/src/sync/spin.rs
diff --git a/src/framework/jinux-frame/src/sync/wait.rs b/framework/jinux-frame/src/sync/wait.rs
similarity index 100%
rename from src/framework/jinux-frame/src/sync/wait.rs
rename to framework/jinux-frame/src/sync/wait.rs
diff --git a/src/framework/jinux-frame/src/task/mod.rs b/framework/jinux-frame/src/task/mod.rs
similarity index 100%
rename from src/framework/jinux-frame/src/task/mod.rs
rename to framework/jinux-frame/src/task/mod.rs
diff --git a/src/framework/jinux-frame/src/task/processor.rs b/framework/jinux-frame/src/task/processor.rs
similarity index 100%
rename from src/framework/jinux-frame/src/task/processor.rs
rename to framework/jinux-frame/src/task/processor.rs
diff --git a/src/framework/jinux-frame/src/task/scheduler.rs b/framework/jinux-frame/src/task/scheduler.rs
similarity index 100%
rename from src/framework/jinux-frame/src/task/scheduler.rs
rename to framework/jinux-frame/src/task/scheduler.rs
diff --git a/src/framework/jinux-frame/src/task/switch.S b/framework/jinux-frame/src/task/switch.S
similarity index 100%
rename from src/framework/jinux-frame/src/task/switch.S
rename to framework/jinux-frame/src/task/switch.S
diff --git a/src/framework/jinux-frame/src/task/task.rs b/framework/jinux-frame/src/task/task.rs
similarity index 100%
rename from src/framework/jinux-frame/src/task/task.rs
rename to framework/jinux-frame/src/task/task.rs
diff --git a/src/framework/jinux-frame/src/timer.rs b/framework/jinux-frame/src/timer.rs
similarity index 100%
rename from src/framework/jinux-frame/src/timer.rs
rename to framework/jinux-frame/src/timer.rs
diff --git a/src/framework/jinux-frame/src/trap/handler.rs b/framework/jinux-frame/src/trap/handler.rs
similarity index 100%
rename from src/framework/jinux-frame/src/trap/handler.rs
rename to framework/jinux-frame/src/trap/handler.rs
diff --git a/src/framework/jinux-frame/src/trap/irq.rs b/framework/jinux-frame/src/trap/irq.rs
similarity index 100%
rename from src/framework/jinux-frame/src/trap/irq.rs
rename to framework/jinux-frame/src/trap/irq.rs
diff --git a/src/framework/jinux-frame/src/trap/mod.rs b/framework/jinux-frame/src/trap/mod.rs
similarity index 100%
rename from src/framework/jinux-frame/src/trap/mod.rs
rename to framework/jinux-frame/src/trap/mod.rs
diff --git a/src/framework/jinux-frame/src/user.rs b/framework/jinux-frame/src/user.rs
similarity index 100%
rename from src/framework/jinux-frame/src/user.rs
rename to framework/jinux-frame/src/user.rs
diff --git a/src/framework/jinux-frame/src/util/mod.rs b/framework/jinux-frame/src/util/mod.rs
similarity index 100%
rename from src/framework/jinux-frame/src/util/mod.rs
rename to framework/jinux-frame/src/util/mod.rs
diff --git a/src/framework/jinux-frame/src/util/recycle_allocator.rs b/framework/jinux-frame/src/util/recycle_allocator.rs
similarity index 100%
rename from src/framework/jinux-frame/src/util/recycle_allocator.rs
rename to framework/jinux-frame/src/util/recycle_allocator.rs
diff --git a/src/framework/jinux-frame/src/util/type_map.rs b/framework/jinux-frame/src/util/type_map.rs
similarity index 100%
rename from src/framework/jinux-frame/src/util/type_map.rs
rename to framework/jinux-frame/src/util/type_map.rs
diff --git a/src/framework/jinux-frame/src/vm/frame.rs b/framework/jinux-frame/src/vm/frame.rs
similarity index 100%
rename from src/framework/jinux-frame/src/vm/frame.rs
rename to framework/jinux-frame/src/vm/frame.rs
diff --git a/src/framework/jinux-frame/src/vm/frame_allocator.rs b/framework/jinux-frame/src/vm/frame_allocator.rs
similarity index 100%
rename from src/framework/jinux-frame/src/vm/frame_allocator.rs
rename to framework/jinux-frame/src/vm/frame_allocator.rs
diff --git a/src/framework/jinux-frame/src/vm/heap_allocator.rs b/framework/jinux-frame/src/vm/heap_allocator.rs
similarity index 100%
rename from src/framework/jinux-frame/src/vm/heap_allocator.rs
rename to framework/jinux-frame/src/vm/heap_allocator.rs
diff --git a/src/framework/jinux-frame/src/vm/io.rs b/framework/jinux-frame/src/vm/io.rs
similarity index 100%
rename from src/framework/jinux-frame/src/vm/io.rs
rename to framework/jinux-frame/src/vm/io.rs
diff --git a/src/framework/jinux-frame/src/vm/memory_set.rs b/framework/jinux-frame/src/vm/memory_set.rs
similarity index 100%
rename from src/framework/jinux-frame/src/vm/memory_set.rs
rename to framework/jinux-frame/src/vm/memory_set.rs
diff --git a/src/framework/jinux-frame/src/vm/mod.rs b/framework/jinux-frame/src/vm/mod.rs
similarity index 100%
rename from src/framework/jinux-frame/src/vm/mod.rs
rename to framework/jinux-frame/src/vm/mod.rs
diff --git a/src/framework/jinux-frame/src/vm/offset.rs b/framework/jinux-frame/src/vm/offset.rs
similarity index 100%
rename from src/framework/jinux-frame/src/vm/offset.rs
rename to framework/jinux-frame/src/vm/offset.rs
diff --git a/src/framework/jinux-frame/src/vm/page_table.rs b/framework/jinux-frame/src/vm/page_table.rs
similarity index 100%
rename from src/framework/jinux-frame/src/vm/page_table.rs
rename to framework/jinux-frame/src/vm/page_table.rs
diff --git a/src/framework/jinux-frame/src/vm/space.rs b/framework/jinux-frame/src/vm/space.rs
similarity index 100%
rename from src/framework/jinux-frame/src/vm/space.rs
rename to framework/jinux-frame/src/vm/space.rs
diff --git a/src/framework/align_ext/Cargo.toml b/framework/libs/align_ext/Cargo.toml
similarity index 100%
rename from src/framework/align_ext/Cargo.toml
rename to framework/libs/align_ext/Cargo.toml
diff --git a/src/framework/align_ext/src/lib.rs b/framework/libs/align_ext/src/lib.rs
similarity index 100%
rename from src/framework/align_ext/src/lib.rs
rename to framework/libs/align_ext/src/lib.rs
diff --git a/src/README.md b/kernel/README.md
similarity index 100%
rename from src/README.md
rename to kernel/README.md
diff --git a/src/src/main.rs b/kernel/main.rs
similarity index 100%
rename from src/src/main.rs
rename to kernel/main.rs
diff --git a/src/apps/bin/Makefile b/regression/apps/bin/Makefile
similarity index 100%
rename from src/apps/bin/Makefile
rename to regression/apps/bin/Makefile
diff --git a/src/apps/bin/sh b/regression/apps/bin/sh
similarity index 100%
rename from src/apps/bin/sh
rename to regression/apps/bin/sh
diff --git a/src/apps/busybox/README.md b/regression/apps/busybox/README.md
similarity index 100%
rename from src/apps/busybox/README.md
rename to regression/apps/busybox/README.md
diff --git a/src/apps/busybox/busybox b/regression/apps/busybox/busybox
similarity index 100%
rename from src/apps/busybox/busybox
rename to regression/apps/busybox/busybox
diff --git a/src/apps/execve/Makefile b/regression/apps/execve/Makefile
similarity index 100%
rename from src/apps/execve/Makefile
rename to regression/apps/execve/Makefile
diff --git a/src/apps/execve/execve b/regression/apps/execve/execve
similarity index 100%
rename from src/apps/execve/execve
rename to regression/apps/execve/execve
diff --git a/src/apps/execve/execve.c b/regression/apps/execve/execve.c
similarity index 100%
rename from src/apps/execve/execve.c
rename to regression/apps/execve/execve.c
diff --git a/src/apps/execve/hello b/regression/apps/execve/hello
similarity index 100%
rename from src/apps/execve/hello
rename to regression/apps/execve/hello
diff --git a/src/apps/execve/hello.c b/regression/apps/execve/hello.c
similarity index 100%
rename from src/apps/execve/hello.c
rename to regression/apps/execve/hello.c
diff --git a/src/apps/fork/Makefile b/regression/apps/fork/Makefile
similarity index 100%
rename from src/apps/fork/Makefile
rename to regression/apps/fork/Makefile
diff --git a/src/apps/fork/fork b/regression/apps/fork/fork
similarity index 100%
rename from src/apps/fork/fork
rename to regression/apps/fork/fork
diff --git a/src/apps/fork/fork.s b/regression/apps/fork/fork.s
similarity index 100%
rename from src/apps/fork/fork.s
rename to regression/apps/fork/fork.s
diff --git a/src/apps/fork_c/Makefile b/regression/apps/fork_c/Makefile
similarity index 100%
rename from src/apps/fork_c/Makefile
rename to regression/apps/fork_c/Makefile
diff --git a/src/apps/fork_c/fork b/regression/apps/fork_c/fork
similarity index 100%
rename from src/apps/fork_c/fork
rename to regression/apps/fork_c/fork
diff --git a/src/apps/fork_c/fork.c b/regression/apps/fork_c/fork.c
similarity index 100%
rename from src/apps/fork_c/fork.c
rename to regression/apps/fork_c/fork.c
diff --git a/src/apps/hello_c/Makefile b/regression/apps/hello_c/Makefile
similarity index 100%
rename from src/apps/hello_c/Makefile
rename to regression/apps/hello_c/Makefile
diff --git a/regression/apps/hello_c/hello b/regression/apps/hello_c/hello
new file mode 100755
index 0000000000..4db2c3de77
--- /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/apps/hello_c/hello.c b/regression/apps/hello_c/hello.c
similarity index 100%
rename from src/apps/hello_c/hello.c
rename to regression/apps/hello_c/hello.c
diff --git a/src/apps/hello_pie/Makefile b/regression/apps/hello_pie/Makefile
similarity index 100%
rename from src/apps/hello_pie/Makefile
rename to regression/apps/hello_pie/Makefile
diff --git a/src/apps/hello_pie/hello b/regression/apps/hello_pie/hello
similarity index 100%
rename from src/apps/hello_pie/hello
rename to regression/apps/hello_pie/hello
diff --git a/src/apps/hello_pie/hello.c b/regression/apps/hello_pie/hello.c
similarity index 100%
rename from src/apps/hello_pie/hello.c
rename to regression/apps/hello_pie/hello.c
diff --git a/src/apps/hello_world/Makefile b/regression/apps/hello_world/Makefile
similarity index 100%
rename from src/apps/hello_world/Makefile
rename to regression/apps/hello_world/Makefile
diff --git a/src/apps/hello_world/hello_world b/regression/apps/hello_world/hello_world
similarity index 100%
rename from src/apps/hello_world/hello_world
rename to regression/apps/hello_world/hello_world
diff --git a/src/apps/hello_world/hello_world.s b/regression/apps/hello_world/hello_world.s
similarity index 100%
rename from src/apps/hello_world/hello_world.s
rename to regression/apps/hello_world/hello_world.s
diff --git a/src/apps/pthread/Makefile b/regression/apps/pthread/Makefile
similarity index 100%
rename from src/apps/pthread/Makefile
rename to regression/apps/pthread/Makefile
diff --git a/src/apps/signal_c/Makefile b/regression/apps/signal_c/Makefile
similarity index 100%
rename from src/apps/signal_c/Makefile
rename to regression/apps/signal_c/Makefile
diff --git a/src/ramdisk/Makefile b/regression/ramdisk/Makefile
similarity index 100%
rename from src/ramdisk/Makefile
rename to regression/ramdisk/Makefile
diff --git a/src/ramdisk/mkinitramfs b/regression/ramdisk/mkinitramfs
similarity index 100%
rename from src/ramdisk/mkinitramfs
rename to regression/ramdisk/mkinitramfs
diff --git a/src/services/comps/block/Cargo.toml b/services/comps/block/Cargo.toml
similarity index 89%
rename from src/services/comps/block/Cargo.toml
rename to services/comps/block/Cargo.toml
index 41b617a920..d500b8c51e 100644
--- 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/src/lib.rs b/services/comps/block/src/lib.rs
similarity index 100%
rename from src/services/comps/block/src/lib.rs
rename to services/comps/block/src/lib.rs
diff --git a/src/services/comps/block/src/virtio.rs b/services/comps/block/src/virtio.rs
similarity index 100%
rename from src/services/comps/block/src/virtio.rs
rename to services/comps/block/src/virtio.rs
diff --git a/src/services/comps/framebuffer/Cargo.toml b/services/comps/framebuffer/Cargo.toml
similarity index 87%
rename from src/services/comps/framebuffer/Cargo.toml
rename to services/comps/framebuffer/Cargo.toml
index c352813d79..623734d41d 100644
--- 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/src/lib.rs b/services/comps/framebuffer/src/lib.rs
similarity index 100%
rename from src/services/comps/framebuffer/src/lib.rs
rename to services/comps/framebuffer/src/lib.rs
diff --git a/src/services/comps/input/Cargo.toml b/services/comps/input/Cargo.toml
similarity index 90%
rename from src/services/comps/input/Cargo.toml
rename to services/comps/input/Cargo.toml
index 1753c6de02..0f0c378163 100644
--- 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/src/lib.rs b/services/comps/input/src/lib.rs
similarity index 100%
rename from src/services/comps/input/src/lib.rs
rename to services/comps/input/src/lib.rs
diff --git a/src/services/comps/input/src/virtio.rs b/services/comps/input/src/virtio.rs
similarity index 100%
rename from src/services/comps/input/src/virtio.rs
rename to services/comps/input/src/virtio.rs
diff --git a/src/services/comps/pci/Cargo.toml b/services/comps/pci/Cargo.toml
similarity index 89%
rename from src/services/comps/pci/Cargo.toml
rename to services/comps/pci/Cargo.toml
index 15ff93b695..70bb4672b9 100644
--- 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/src/capability/exp.rs b/services/comps/pci/src/capability/exp.rs
similarity index 100%
rename from src/services/comps/pci/src/capability/exp.rs
rename to services/comps/pci/src/capability/exp.rs
diff --git a/src/services/comps/pci/src/capability/mod.rs b/services/comps/pci/src/capability/mod.rs
similarity index 100%
rename from src/services/comps/pci/src/capability/mod.rs
rename to services/comps/pci/src/capability/mod.rs
diff --git a/src/services/comps/pci/src/capability/msi.rs b/services/comps/pci/src/capability/msi.rs
similarity index 100%
rename from src/services/comps/pci/src/capability/msi.rs
rename to services/comps/pci/src/capability/msi.rs
diff --git a/src/services/comps/pci/src/capability/msix.rs b/services/comps/pci/src/capability/msix.rs
similarity index 100%
rename from src/services/comps/pci/src/capability/msix.rs
rename to services/comps/pci/src/capability/msix.rs
diff --git a/src/services/comps/pci/src/capability/pm.rs b/services/comps/pci/src/capability/pm.rs
similarity index 100%
rename from src/services/comps/pci/src/capability/pm.rs
rename to services/comps/pci/src/capability/pm.rs
diff --git a/src/services/comps/pci/src/capability/sata.rs b/services/comps/pci/src/capability/sata.rs
similarity index 100%
rename from src/services/comps/pci/src/capability/sata.rs
rename to services/comps/pci/src/capability/sata.rs
diff --git a/src/services/comps/pci/src/capability/vendor/mod.rs b/services/comps/pci/src/capability/vendor/mod.rs
similarity index 100%
rename from src/services/comps/pci/src/capability/vendor/mod.rs
rename to services/comps/pci/src/capability/vendor/mod.rs
diff --git a/src/services/comps/pci/src/capability/vendor/virtio.rs b/services/comps/pci/src/capability/vendor/virtio.rs
similarity index 100%
rename from src/services/comps/pci/src/capability/vendor/virtio.rs
rename to services/comps/pci/src/capability/vendor/virtio.rs
diff --git a/src/services/comps/pci/src/lib.rs b/services/comps/pci/src/lib.rs
similarity index 100%
rename from src/services/comps/pci/src/lib.rs
rename to services/comps/pci/src/lib.rs
diff --git a/src/services/comps/pci/src/msix.rs b/services/comps/pci/src/msix.rs
similarity index 100%
rename from src/services/comps/pci/src/msix.rs
rename to services/comps/pci/src/msix.rs
diff --git a/src/services/comps/pci/src/util.rs b/services/comps/pci/src/util.rs
similarity index 100%
rename from src/services/comps/pci/src/util.rs
rename to services/comps/pci/src/util.rs
diff --git a/src/services/comps/time/Cargo.toml b/services/comps/time/Cargo.toml
similarity index 83%
rename from src/services/comps/time/Cargo.toml
rename to services/comps/time/Cargo.toml
index 24cc2b9d03..9bd5822a62 100644
--- 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/src/lib.rs b/services/comps/time/src/lib.rs
similarity index 100%
rename from src/services/comps/time/src/lib.rs
rename to services/comps/time/src/lib.rs
diff --git a/src/services/comps/time/src/rtc.rs b/services/comps/time/src/rtc.rs
similarity index 100%
rename from src/services/comps/time/src/rtc.rs
rename to services/comps/time/src/rtc.rs
diff --git a/src/services/comps/virtio/Cargo.toml b/services/comps/virtio/Cargo.toml
similarity index 89%
rename from src/services/comps/virtio/Cargo.toml
rename to services/comps/virtio/Cargo.toml
index e694302688..11546d5014 100644
--- 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/src/device/block/device.rs b/services/comps/virtio/src/device/block/device.rs
similarity index 100%
rename from src/services/comps/virtio/src/device/block/device.rs
rename to services/comps/virtio/src/device/block/device.rs
diff --git a/src/services/comps/virtio/src/device/block/mod.rs b/services/comps/virtio/src/device/block/mod.rs
similarity index 100%
rename from src/services/comps/virtio/src/device/block/mod.rs
rename to services/comps/virtio/src/device/block/mod.rs
diff --git a/src/services/comps/virtio/src/device/input/device.rs b/services/comps/virtio/src/device/input/device.rs
similarity index 100%
rename from src/services/comps/virtio/src/device/input/device.rs
rename to services/comps/virtio/src/device/input/device.rs
diff --git a/src/services/comps/virtio/src/device/input/mod.rs b/services/comps/virtio/src/device/input/mod.rs
similarity index 100%
rename from src/services/comps/virtio/src/device/input/mod.rs
rename to services/comps/virtio/src/device/input/mod.rs
diff --git a/src/services/comps/virtio/src/device/mod.rs b/services/comps/virtio/src/device/mod.rs
similarity index 100%
rename from src/services/comps/virtio/src/device/mod.rs
rename to services/comps/virtio/src/device/mod.rs
diff --git a/src/services/comps/virtio/src/lib.rs b/services/comps/virtio/src/lib.rs
similarity index 100%
rename from src/services/comps/virtio/src/lib.rs
rename to services/comps/virtio/src/lib.rs
diff --git a/src/services/comps/virtio/src/queue.rs b/services/comps/virtio/src/queue.rs
similarity index 100%
rename from src/services/comps/virtio/src/queue.rs
rename to services/comps/virtio/src/queue.rs
diff --git a/src/services/comp-sys/cargo-component/.gitignore b/services/libs/comp-sys/cargo-component/.gitignore
similarity index 100%
rename from src/services/comp-sys/cargo-component/.gitignore
rename to services/libs/comp-sys/cargo-component/.gitignore
diff --git a/src/services/comp-sys/cargo-component/Cargo.lock b/services/libs/comp-sys/cargo-component/Cargo.lock
similarity index 100%
rename from src/services/comp-sys/cargo-component/Cargo.lock
rename to services/libs/comp-sys/cargo-component/Cargo.lock
diff --git a/src/services/comp-sys/cargo-component/Cargo.toml b/services/libs/comp-sys/cargo-component/Cargo.toml
similarity index 100%
rename from src/services/comp-sys/cargo-component/Cargo.toml
rename to services/libs/comp-sys/cargo-component/Cargo.toml
diff --git a/src/services/comp-sys/cargo-component/README.md b/services/libs/comp-sys/cargo-component/README.md
similarity index 100%
rename from src/services/comp-sys/cargo-component/README.md
rename to services/libs/comp-sys/cargo-component/README.md
diff --git a/src/services/comp-sys/cargo-component/analysis/Cargo.toml b/services/libs/comp-sys/cargo-component/analysis/Cargo.toml
similarity index 100%
rename from src/services/comp-sys/cargo-component/analysis/Cargo.toml
rename to services/libs/comp-sys/cargo-component/analysis/Cargo.toml
diff --git a/src/services/comp-sys/cargo-component/analysis/src/conf.rs b/services/libs/comp-sys/cargo-component/analysis/src/conf.rs
similarity index 100%
rename from src/services/comp-sys/cargo-component/analysis/src/conf.rs
rename to services/libs/comp-sys/cargo-component/analysis/src/conf.rs
diff --git a/src/services/comp-sys/cargo-component/analysis/src/lib.rs b/services/libs/comp-sys/cargo-component/analysis/src/lib.rs
similarity index 100%
rename from src/services/comp-sys/cargo-component/analysis/src/lib.rs
rename to services/libs/comp-sys/cargo-component/analysis/src/lib.rs
diff --git a/src/services/comp-sys/cargo-component/build.rs b/services/libs/comp-sys/cargo-component/build.rs
similarity index 100%
rename from src/services/comp-sys/cargo-component/build.rs
rename to services/libs/comp-sys/cargo-component/build.rs
diff --git a/src/services/comp-sys/cargo-component/rust-toolchain.toml b/services/libs/comp-sys/cargo-component/rust-toolchain.toml
similarity index 100%
rename from src/services/comp-sys/cargo-component/rust-toolchain.toml
rename to services/libs/comp-sys/cargo-component/rust-toolchain.toml
diff --git a/src/services/comp-sys/cargo-component/src/driver.rs b/services/libs/comp-sys/cargo-component/src/driver.rs
similarity index 100%
rename from src/services/comp-sys/cargo-component/src/driver.rs
rename to services/libs/comp-sys/cargo-component/src/driver.rs
diff --git a/src/services/comp-sys/cargo-component/src/main.rs b/services/libs/comp-sys/cargo-component/src/main.rs
similarity index 100%
rename from src/services/comp-sys/cargo-component/src/main.rs
rename to services/libs/comp-sys/cargo-component/src/main.rs
diff --git a/src/services/comp-sys/component-macro/Cargo.toml b/services/libs/comp-sys/component-macro/Cargo.toml
similarity index 100%
rename from src/services/comp-sys/component-macro/Cargo.toml
rename to services/libs/comp-sys/component-macro/Cargo.toml
diff --git a/src/services/comp-sys/component-macro/src/init_comp.rs b/services/libs/comp-sys/component-macro/src/init_comp.rs
similarity index 100%
rename from src/services/comp-sys/component-macro/src/init_comp.rs
rename to services/libs/comp-sys/component-macro/src/init_comp.rs
diff --git a/src/services/comp-sys/component-macro/src/lib.rs b/services/libs/comp-sys/component-macro/src/lib.rs
similarity index 100%
rename from src/services/comp-sys/component-macro/src/lib.rs
rename to services/libs/comp-sys/component-macro/src/lib.rs
diff --git a/src/services/comp-sys/component-macro/src/priority.rs b/services/libs/comp-sys/component-macro/src/priority.rs
similarity index 100%
rename from src/services/comp-sys/component-macro/src/priority.rs
rename to services/libs/comp-sys/component-macro/src/priority.rs
diff --git a/src/services/comp-sys/component/Cargo.toml b/services/libs/comp-sys/component/Cargo.toml
similarity index 100%
rename from src/services/comp-sys/component/Cargo.toml
rename to services/libs/comp-sys/component/Cargo.toml
diff --git a/src/services/comp-sys/component/README.md b/services/libs/comp-sys/component/README.md
similarity index 100%
rename from src/services/comp-sys/component/README.md
rename to services/libs/comp-sys/component/README.md
diff --git a/src/services/comp-sys/component/src/lib.rs b/services/libs/comp-sys/component/src/lib.rs
similarity index 100%
rename from src/services/comp-sys/component/src/lib.rs
rename to services/libs/comp-sys/component/src/lib.rs
diff --git a/src/services/comp-sys/controlled/Cargo.toml b/services/libs/comp-sys/controlled/Cargo.toml
similarity index 100%
rename from src/services/comp-sys/controlled/Cargo.toml
rename to services/libs/comp-sys/controlled/Cargo.toml
diff --git a/src/services/comp-sys/controlled/src/lib.rs b/services/libs/comp-sys/controlled/src/lib.rs
similarity index 100%
rename from src/services/comp-sys/controlled/src/lib.rs
rename to services/libs/comp-sys/controlled/src/lib.rs
diff --git a/src/services/libs/cpio-decoder/Cargo.toml b/services/libs/cpio-decoder/Cargo.toml
similarity index 100%
rename from src/services/libs/cpio-decoder/Cargo.toml
rename to services/libs/cpio-decoder/Cargo.toml
diff --git a/src/services/libs/cpio-decoder/src/error.rs b/services/libs/cpio-decoder/src/error.rs
similarity index 100%
rename from src/services/libs/cpio-decoder/src/error.rs
rename to services/libs/cpio-decoder/src/error.rs
diff --git a/src/services/libs/cpio-decoder/src/lib.rs b/services/libs/cpio-decoder/src/lib.rs
similarity index 100%
rename from src/services/libs/cpio-decoder/src/lib.rs
rename to services/libs/cpio-decoder/src/lib.rs
diff --git a/src/services/libs/jinux-rights-proc/Cargo.toml b/services/libs/jinux-rights-proc/Cargo.toml
similarity index 100%
rename from src/services/libs/jinux-rights-proc/Cargo.toml
rename to services/libs/jinux-rights-proc/Cargo.toml
diff --git a/src/services/libs/jinux-rights-proc/src/lib.rs b/services/libs/jinux-rights-proc/src/lib.rs
similarity index 100%
rename from src/services/libs/jinux-rights-proc/src/lib.rs
rename to services/libs/jinux-rights-proc/src/lib.rs
diff --git a/src/services/libs/jinux-rights-proc/src/require_attr.rs b/services/libs/jinux-rights-proc/src/require_attr.rs
similarity index 100%
rename from src/services/libs/jinux-rights-proc/src/require_attr.rs
rename to services/libs/jinux-rights-proc/src/require_attr.rs
diff --git a/src/services/libs/jinux-std/Cargo.toml b/services/libs/jinux-std/Cargo.toml
similarity index 91%
rename from src/services/libs/jinux-std/Cargo.toml
rename to services/libs/jinux-std/Cargo.toml
index 52b2861569..06d3a2fa54 100644
--- 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/driver/mod.rs b/services/libs/jinux-std/src/driver/mod.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/driver/mod.rs
rename to services/libs/jinux-std/src/driver/mod.rs
diff --git a/src/services/libs/jinux-std/src/driver/tty.rs b/services/libs/jinux-std/src/driver/tty.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/driver/tty.rs
rename to services/libs/jinux-std/src/driver/tty.rs
diff --git a/src/services/libs/jinux-std/src/error.rs b/services/libs/jinux-std/src/error.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/error.rs
rename to services/libs/jinux-std/src/error.rs
diff --git a/src/services/libs/jinux-std/src/events/events.rs b/services/libs/jinux-std/src/events/events.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/events/events.rs
rename to services/libs/jinux-std/src/events/events.rs
diff --git a/src/services/libs/jinux-std/src/events/mod.rs b/services/libs/jinux-std/src/events/mod.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/events/mod.rs
rename to services/libs/jinux-std/src/events/mod.rs
diff --git a/src/services/libs/jinux-std/src/events/observer.rs b/services/libs/jinux-std/src/events/observer.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/events/observer.rs
rename to services/libs/jinux-std/src/events/observer.rs
diff --git a/src/services/libs/jinux-std/src/events/subject.rs b/services/libs/jinux-std/src/events/subject.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/events/subject.rs
rename to services/libs/jinux-std/src/events/subject.rs
diff --git a/src/services/libs/jinux-std/src/fs/file_handle/file.rs b/services/libs/jinux-std/src/fs/file_handle/file.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/file_handle/file.rs
rename to services/libs/jinux-std/src/fs/file_handle/file.rs
diff --git a/src/services/libs/jinux-std/src/fs/file_handle/inode_handle/dyn_cap.rs b/services/libs/jinux-std/src/fs/file_handle/inode_handle/dyn_cap.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/file_handle/inode_handle/dyn_cap.rs
rename to services/libs/jinux-std/src/fs/file_handle/inode_handle/dyn_cap.rs
diff --git a/src/services/libs/jinux-std/src/fs/file_handle/inode_handle/mod.rs b/services/libs/jinux-std/src/fs/file_handle/inode_handle/mod.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/file_handle/inode_handle/mod.rs
rename to services/libs/jinux-std/src/fs/file_handle/inode_handle/mod.rs
diff --git a/src/services/libs/jinux-std/src/fs/file_handle/inode_handle/static_cap.rs b/services/libs/jinux-std/src/fs/file_handle/inode_handle/static_cap.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/file_handle/inode_handle/static_cap.rs
rename to services/libs/jinux-std/src/fs/file_handle/inode_handle/static_cap.rs
diff --git a/src/services/libs/jinux-std/src/fs/file_handle/mod.rs b/services/libs/jinux-std/src/fs/file_handle/mod.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/file_handle/mod.rs
rename to services/libs/jinux-std/src/fs/file_handle/mod.rs
diff --git a/src/services/libs/jinux-std/src/fs/file_table.rs b/services/libs/jinux-std/src/fs/file_table.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/file_table.rs
rename to services/libs/jinux-std/src/fs/file_table.rs
diff --git a/src/services/libs/jinux-std/src/fs/fs_resolver.rs b/services/libs/jinux-std/src/fs/fs_resolver.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/fs_resolver.rs
rename to services/libs/jinux-std/src/fs/fs_resolver.rs
diff --git a/src/services/libs/jinux-std/src/fs/initramfs.rs b/services/libs/jinux-std/src/fs/initramfs.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/initramfs.rs
rename to services/libs/jinux-std/src/fs/initramfs.rs
diff --git a/src/services/libs/jinux-std/src/fs/mod.rs b/services/libs/jinux-std/src/fs/mod.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/mod.rs
rename to services/libs/jinux-std/src/fs/mod.rs
diff --git a/src/services/libs/jinux-std/src/fs/procfs/mod.rs b/services/libs/jinux-std/src/fs/procfs/mod.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/procfs/mod.rs
rename to services/libs/jinux-std/src/fs/procfs/mod.rs
diff --git a/src/services/libs/jinux-std/src/fs/procfs/pid/comm.rs b/services/libs/jinux-std/src/fs/procfs/pid/comm.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/procfs/pid/comm.rs
rename to services/libs/jinux-std/src/fs/procfs/pid/comm.rs
diff --git a/src/services/libs/jinux-std/src/fs/procfs/pid/exe.rs b/services/libs/jinux-std/src/fs/procfs/pid/exe.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/procfs/pid/exe.rs
rename to services/libs/jinux-std/src/fs/procfs/pid/exe.rs
diff --git a/src/services/libs/jinux-std/src/fs/procfs/pid/fd.rs b/services/libs/jinux-std/src/fs/procfs/pid/fd.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/procfs/pid/fd.rs
rename to services/libs/jinux-std/src/fs/procfs/pid/fd.rs
diff --git a/src/services/libs/jinux-std/src/fs/procfs/pid/mod.rs b/services/libs/jinux-std/src/fs/procfs/pid/mod.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/procfs/pid/mod.rs
rename to services/libs/jinux-std/src/fs/procfs/pid/mod.rs
diff --git a/src/services/libs/jinux-std/src/fs/procfs/self_.rs b/services/libs/jinux-std/src/fs/procfs/self_.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/procfs/self_.rs
rename to services/libs/jinux-std/src/fs/procfs/self_.rs
diff --git a/src/services/libs/jinux-std/src/fs/procfs/template/builder.rs b/services/libs/jinux-std/src/fs/procfs/template/builder.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/procfs/template/builder.rs
rename to services/libs/jinux-std/src/fs/procfs/template/builder.rs
diff --git a/src/services/libs/jinux-std/src/fs/procfs/template/dir.rs b/services/libs/jinux-std/src/fs/procfs/template/dir.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/procfs/template/dir.rs
rename to services/libs/jinux-std/src/fs/procfs/template/dir.rs
diff --git a/src/services/libs/jinux-std/src/fs/procfs/template/file.rs b/services/libs/jinux-std/src/fs/procfs/template/file.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/procfs/template/file.rs
rename to services/libs/jinux-std/src/fs/procfs/template/file.rs
diff --git a/src/services/libs/jinux-std/src/fs/procfs/template/mod.rs b/services/libs/jinux-std/src/fs/procfs/template/mod.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/procfs/template/mod.rs
rename to services/libs/jinux-std/src/fs/procfs/template/mod.rs
diff --git a/src/services/libs/jinux-std/src/fs/procfs/template/sym.rs b/services/libs/jinux-std/src/fs/procfs/template/sym.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/procfs/template/sym.rs
rename to services/libs/jinux-std/src/fs/procfs/template/sym.rs
diff --git a/src/services/libs/jinux-std/src/fs/ramfs/fs.rs b/services/libs/jinux-std/src/fs/ramfs/fs.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/ramfs/fs.rs
rename to services/libs/jinux-std/src/fs/ramfs/fs.rs
diff --git a/src/services/libs/jinux-std/src/fs/ramfs/mod.rs b/services/libs/jinux-std/src/fs/ramfs/mod.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/ramfs/mod.rs
rename to services/libs/jinux-std/src/fs/ramfs/mod.rs
diff --git a/src/services/libs/jinux-std/src/fs/stdio.rs b/services/libs/jinux-std/src/fs/stdio.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/stdio.rs
rename to services/libs/jinux-std/src/fs/stdio.rs
diff --git a/src/services/libs/jinux-std/src/fs/utils/access_mode.rs b/services/libs/jinux-std/src/fs/utils/access_mode.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/utils/access_mode.rs
rename to services/libs/jinux-std/src/fs/utils/access_mode.rs
diff --git a/src/services/libs/jinux-std/src/fs/utils/creation_flags.rs b/services/libs/jinux-std/src/fs/utils/creation_flags.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/utils/creation_flags.rs
rename to services/libs/jinux-std/src/fs/utils/creation_flags.rs
diff --git a/src/services/libs/jinux-std/src/fs/utils/dentry_cache.rs b/services/libs/jinux-std/src/fs/utils/dentry_cache.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/utils/dentry_cache.rs
rename to services/libs/jinux-std/src/fs/utils/dentry_cache.rs
diff --git a/src/services/libs/jinux-std/src/fs/utils/dirent_visitor.rs b/services/libs/jinux-std/src/fs/utils/dirent_visitor.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/utils/dirent_visitor.rs
rename to services/libs/jinux-std/src/fs/utils/dirent_visitor.rs
diff --git a/src/services/libs/jinux-std/src/fs/utils/direntry_vec.rs b/services/libs/jinux-std/src/fs/utils/direntry_vec.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/utils/direntry_vec.rs
rename to services/libs/jinux-std/src/fs/utils/direntry_vec.rs
diff --git a/src/services/libs/jinux-std/src/fs/utils/fcntl.rs b/services/libs/jinux-std/src/fs/utils/fcntl.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/utils/fcntl.rs
rename to services/libs/jinux-std/src/fs/utils/fcntl.rs
diff --git a/src/services/libs/jinux-std/src/fs/utils/file_creation_mask.rs b/services/libs/jinux-std/src/fs/utils/file_creation_mask.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/utils/file_creation_mask.rs
rename to services/libs/jinux-std/src/fs/utils/file_creation_mask.rs
diff --git a/src/services/libs/jinux-std/src/fs/utils/fs.rs b/services/libs/jinux-std/src/fs/utils/fs.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/utils/fs.rs
rename to services/libs/jinux-std/src/fs/utils/fs.rs
diff --git a/src/services/libs/jinux-std/src/fs/utils/inode.rs b/services/libs/jinux-std/src/fs/utils/inode.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/utils/inode.rs
rename to services/libs/jinux-std/src/fs/utils/inode.rs
diff --git a/src/services/libs/jinux-std/src/fs/utils/io_events.rs b/services/libs/jinux-std/src/fs/utils/io_events.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/utils/io_events.rs
rename to services/libs/jinux-std/src/fs/utils/io_events.rs
diff --git a/src/services/libs/jinux-std/src/fs/utils/ioctl.rs b/services/libs/jinux-std/src/fs/utils/ioctl.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/utils/ioctl.rs
rename to services/libs/jinux-std/src/fs/utils/ioctl.rs
diff --git a/src/services/libs/jinux-std/src/fs/utils/mod.rs b/services/libs/jinux-std/src/fs/utils/mod.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/utils/mod.rs
rename to services/libs/jinux-std/src/fs/utils/mod.rs
diff --git a/src/services/libs/jinux-std/src/fs/utils/page_cache.rs b/services/libs/jinux-std/src/fs/utils/page_cache.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/utils/page_cache.rs
rename to services/libs/jinux-std/src/fs/utils/page_cache.rs
diff --git a/src/services/libs/jinux-std/src/fs/utils/poll.rs b/services/libs/jinux-std/src/fs/utils/poll.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/utils/poll.rs
rename to services/libs/jinux-std/src/fs/utils/poll.rs
diff --git a/src/services/libs/jinux-std/src/fs/utils/status_flags.rs b/services/libs/jinux-std/src/fs/utils/status_flags.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/utils/status_flags.rs
rename to services/libs/jinux-std/src/fs/utils/status_flags.rs
diff --git a/src/services/libs/jinux-std/src/fs/utils/vnode.rs b/services/libs/jinux-std/src/fs/utils/vnode.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/fs/utils/vnode.rs
rename to services/libs/jinux-std/src/fs/utils/vnode.rs
diff --git a/src/services/libs/jinux-std/src/lib.rs b/services/libs/jinux-std/src/lib.rs
similarity index 97%
rename from src/services/libs/jinux-std/src/lib.rs
rename to services/libs/jinux-std/src/lib.rs
index 8338214ef7..905cdd18e8 100644
--- 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/prelude.rs b/services/libs/jinux-std/src/prelude.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/prelude.rs
rename to services/libs/jinux-std/src/prelude.rs
diff --git a/src/services/libs/jinux-std/src/process/clone.rs b/services/libs/jinux-std/src/process/clone.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/clone.rs
rename to services/libs/jinux-std/src/process/clone.rs
diff --git a/src/services/libs/jinux-std/src/process/fifo_scheduler.rs b/services/libs/jinux-std/src/process/fifo_scheduler.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/fifo_scheduler.rs
rename to services/libs/jinux-std/src/process/fifo_scheduler.rs
diff --git a/src/services/libs/jinux-std/src/process/mod.rs b/services/libs/jinux-std/src/process/mod.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/mod.rs
rename to services/libs/jinux-std/src/process/mod.rs
diff --git a/src/services/libs/jinux-std/src/process/posix_thread/builder.rs b/services/libs/jinux-std/src/process/posix_thread/builder.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/posix_thread/builder.rs
rename to services/libs/jinux-std/src/process/posix_thread/builder.rs
diff --git a/src/services/libs/jinux-std/src/process/posix_thread/futex.rs b/services/libs/jinux-std/src/process/posix_thread/futex.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/posix_thread/futex.rs
rename to services/libs/jinux-std/src/process/posix_thread/futex.rs
diff --git a/src/services/libs/jinux-std/src/process/posix_thread/mod.rs b/services/libs/jinux-std/src/process/posix_thread/mod.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/posix_thread/mod.rs
rename to services/libs/jinux-std/src/process/posix_thread/mod.rs
diff --git a/src/services/libs/jinux-std/src/process/posix_thread/name.rs b/services/libs/jinux-std/src/process/posix_thread/name.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/posix_thread/name.rs
rename to services/libs/jinux-std/src/process/posix_thread/name.rs
diff --git a/src/services/libs/jinux-std/src/process/posix_thread/posix_thread_ext.rs b/services/libs/jinux-std/src/process/posix_thread/posix_thread_ext.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/posix_thread/posix_thread_ext.rs
rename to services/libs/jinux-std/src/process/posix_thread/posix_thread_ext.rs
diff --git a/src/services/libs/jinux-std/src/process/posix_thread/robust_list.rs b/services/libs/jinux-std/src/process/posix_thread/robust_list.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/posix_thread/robust_list.rs
rename to services/libs/jinux-std/src/process/posix_thread/robust_list.rs
diff --git a/src/services/libs/jinux-std/src/process/process_filter.rs b/services/libs/jinux-std/src/process/process_filter.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/process_filter.rs
rename to services/libs/jinux-std/src/process/process_filter.rs
diff --git a/src/services/libs/jinux-std/src/process/process_group.rs b/services/libs/jinux-std/src/process/process_group.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/process_group.rs
rename to services/libs/jinux-std/src/process/process_group.rs
diff --git a/src/services/libs/jinux-std/src/process/process_table.rs b/services/libs/jinux-std/src/process/process_table.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/process_table.rs
rename to services/libs/jinux-std/src/process/process_table.rs
diff --git a/src/services/libs/jinux-std/src/process/process_vm/mmap_flags.rs b/services/libs/jinux-std/src/process/process_vm/mmap_flags.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/process_vm/mmap_flags.rs
rename to services/libs/jinux-std/src/process/process_vm/mmap_flags.rs
diff --git a/src/services/libs/jinux-std/src/process/process_vm/mod.rs b/services/libs/jinux-std/src/process/process_vm/mod.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/process_vm/mod.rs
rename to services/libs/jinux-std/src/process/process_vm/mod.rs
diff --git a/src/services/libs/jinux-std/src/process/process_vm/user_heap.rs b/services/libs/jinux-std/src/process/process_vm/user_heap.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/process_vm/user_heap.rs
rename to services/libs/jinux-std/src/process/process_vm/user_heap.rs
diff --git a/src/services/libs/jinux-std/src/process/program_loader/elf/aux_vec.rs b/services/libs/jinux-std/src/process/program_loader/elf/aux_vec.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/program_loader/elf/aux_vec.rs
rename to services/libs/jinux-std/src/process/program_loader/elf/aux_vec.rs
diff --git a/src/services/libs/jinux-std/src/process/program_loader/elf/elf_file.rs b/services/libs/jinux-std/src/process/program_loader/elf/elf_file.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/program_loader/elf/elf_file.rs
rename to services/libs/jinux-std/src/process/program_loader/elf/elf_file.rs
diff --git a/src/services/libs/jinux-std/src/process/program_loader/elf/init_stack.rs b/services/libs/jinux-std/src/process/program_loader/elf/init_stack.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/program_loader/elf/init_stack.rs
rename to services/libs/jinux-std/src/process/program_loader/elf/init_stack.rs
diff --git a/src/services/libs/jinux-std/src/process/program_loader/elf/load_elf.rs b/services/libs/jinux-std/src/process/program_loader/elf/load_elf.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/program_loader/elf/load_elf.rs
rename to services/libs/jinux-std/src/process/program_loader/elf/load_elf.rs
diff --git a/src/services/libs/jinux-std/src/process/program_loader/elf/mod.rs b/services/libs/jinux-std/src/process/program_loader/elf/mod.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/program_loader/elf/mod.rs
rename to services/libs/jinux-std/src/process/program_loader/elf/mod.rs
diff --git a/src/services/libs/jinux-std/src/process/program_loader/mod.rs b/services/libs/jinux-std/src/process/program_loader/mod.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/program_loader/mod.rs
rename to services/libs/jinux-std/src/process/program_loader/mod.rs
diff --git a/src/services/libs/jinux-std/src/process/program_loader/shebang.rs b/services/libs/jinux-std/src/process/program_loader/shebang.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/program_loader/shebang.rs
rename to services/libs/jinux-std/src/process/program_loader/shebang.rs
diff --git a/src/services/libs/jinux-std/src/process/rlimit.rs b/services/libs/jinux-std/src/process/rlimit.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/rlimit.rs
rename to services/libs/jinux-std/src/process/rlimit.rs
diff --git a/src/services/libs/jinux-std/src/process/signal/c_types.rs b/services/libs/jinux-std/src/process/signal/c_types.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/signal/c_types.rs
rename to services/libs/jinux-std/src/process/signal/c_types.rs
diff --git a/src/services/libs/jinux-std/src/process/signal/constants.rs b/services/libs/jinux-std/src/process/signal/constants.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/signal/constants.rs
rename to services/libs/jinux-std/src/process/signal/constants.rs
diff --git a/src/services/libs/jinux-std/src/process/signal/mod.rs b/services/libs/jinux-std/src/process/signal/mod.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/signal/mod.rs
rename to services/libs/jinux-std/src/process/signal/mod.rs
diff --git a/src/services/libs/jinux-std/src/process/signal/sig_action.rs b/services/libs/jinux-std/src/process/signal/sig_action.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/signal/sig_action.rs
rename to services/libs/jinux-std/src/process/signal/sig_action.rs
diff --git a/src/services/libs/jinux-std/src/process/signal/sig_disposition.rs b/services/libs/jinux-std/src/process/signal/sig_disposition.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/signal/sig_disposition.rs
rename to services/libs/jinux-std/src/process/signal/sig_disposition.rs
diff --git a/src/services/libs/jinux-std/src/process/signal/sig_mask.rs b/services/libs/jinux-std/src/process/signal/sig_mask.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/signal/sig_mask.rs
rename to services/libs/jinux-std/src/process/signal/sig_mask.rs
diff --git a/src/services/libs/jinux-std/src/process/signal/sig_num.rs b/services/libs/jinux-std/src/process/signal/sig_num.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/signal/sig_num.rs
rename to services/libs/jinux-std/src/process/signal/sig_num.rs
diff --git a/src/services/libs/jinux-std/src/process/signal/sig_queues.rs b/services/libs/jinux-std/src/process/signal/sig_queues.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/signal/sig_queues.rs
rename to services/libs/jinux-std/src/process/signal/sig_queues.rs
diff --git a/src/services/libs/jinux-std/src/process/signal/signals/fault.rs b/services/libs/jinux-std/src/process/signal/signals/fault.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/signal/signals/fault.rs
rename to services/libs/jinux-std/src/process/signal/signals/fault.rs
diff --git a/src/services/libs/jinux-std/src/process/signal/signals/kernel.rs b/services/libs/jinux-std/src/process/signal/signals/kernel.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/signal/signals/kernel.rs
rename to services/libs/jinux-std/src/process/signal/signals/kernel.rs
diff --git a/src/services/libs/jinux-std/src/process/signal/signals/mod.rs b/services/libs/jinux-std/src/process/signal/signals/mod.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/signal/signals/mod.rs
rename to services/libs/jinux-std/src/process/signal/signals/mod.rs
diff --git a/src/services/libs/jinux-std/src/process/signal/signals/user.rs b/services/libs/jinux-std/src/process/signal/signals/user.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/signal/signals/user.rs
rename to services/libs/jinux-std/src/process/signal/signals/user.rs
diff --git a/src/services/libs/jinux-std/src/process/status.rs b/services/libs/jinux-std/src/process/status.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/status.rs
rename to services/libs/jinux-std/src/process/status.rs
diff --git a/src/services/libs/jinux-std/src/process/wait.rs b/services/libs/jinux-std/src/process/wait.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/process/wait.rs
rename to services/libs/jinux-std/src/process/wait.rs
diff --git a/src/services/libs/jinux-std/src/rights.rs b/services/libs/jinux-std/src/rights.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/rights.rs
rename to services/libs/jinux-std/src/rights.rs
diff --git a/src/services/libs/jinux-std/src/syscall/access.rs b/services/libs/jinux-std/src/syscall/access.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/access.rs
rename to services/libs/jinux-std/src/syscall/access.rs
diff --git a/src/services/libs/jinux-std/src/syscall/arch_prctl.rs b/services/libs/jinux-std/src/syscall/arch_prctl.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/arch_prctl.rs
rename to services/libs/jinux-std/src/syscall/arch_prctl.rs
diff --git a/src/services/libs/jinux-std/src/syscall/brk.rs b/services/libs/jinux-std/src/syscall/brk.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/brk.rs
rename to services/libs/jinux-std/src/syscall/brk.rs
diff --git a/src/services/libs/jinux-std/src/syscall/chdir.rs b/services/libs/jinux-std/src/syscall/chdir.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/chdir.rs
rename to services/libs/jinux-std/src/syscall/chdir.rs
diff --git a/src/services/libs/jinux-std/src/syscall/clock_nanosleep.rs b/services/libs/jinux-std/src/syscall/clock_nanosleep.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/clock_nanosleep.rs
rename to services/libs/jinux-std/src/syscall/clock_nanosleep.rs
diff --git a/src/services/libs/jinux-std/src/syscall/clone.rs b/services/libs/jinux-std/src/syscall/clone.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/clone.rs
rename to services/libs/jinux-std/src/syscall/clone.rs
diff --git a/src/services/libs/jinux-std/src/syscall/close.rs b/services/libs/jinux-std/src/syscall/close.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/close.rs
rename to services/libs/jinux-std/src/syscall/close.rs
diff --git a/src/services/libs/jinux-std/src/syscall/constants.rs b/services/libs/jinux-std/src/syscall/constants.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/constants.rs
rename to services/libs/jinux-std/src/syscall/constants.rs
diff --git a/src/services/libs/jinux-std/src/syscall/dup.rs b/services/libs/jinux-std/src/syscall/dup.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/dup.rs
rename to services/libs/jinux-std/src/syscall/dup.rs
diff --git a/src/services/libs/jinux-std/src/syscall/execve.rs b/services/libs/jinux-std/src/syscall/execve.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/execve.rs
rename to services/libs/jinux-std/src/syscall/execve.rs
diff --git a/src/services/libs/jinux-std/src/syscall/exit.rs b/services/libs/jinux-std/src/syscall/exit.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/exit.rs
rename to services/libs/jinux-std/src/syscall/exit.rs
diff --git a/src/services/libs/jinux-std/src/syscall/exit_group.rs b/services/libs/jinux-std/src/syscall/exit_group.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/exit_group.rs
rename to services/libs/jinux-std/src/syscall/exit_group.rs
diff --git a/src/services/libs/jinux-std/src/syscall/fcntl.rs b/services/libs/jinux-std/src/syscall/fcntl.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/fcntl.rs
rename to services/libs/jinux-std/src/syscall/fcntl.rs
diff --git a/src/services/libs/jinux-std/src/syscall/fork.rs b/services/libs/jinux-std/src/syscall/fork.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/fork.rs
rename to services/libs/jinux-std/src/syscall/fork.rs
diff --git a/src/services/libs/jinux-std/src/syscall/futex.rs b/services/libs/jinux-std/src/syscall/futex.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/futex.rs
rename to services/libs/jinux-std/src/syscall/futex.rs
diff --git a/src/services/libs/jinux-std/src/syscall/getcwd.rs b/services/libs/jinux-std/src/syscall/getcwd.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/getcwd.rs
rename to services/libs/jinux-std/src/syscall/getcwd.rs
diff --git a/src/services/libs/jinux-std/src/syscall/getdents64.rs b/services/libs/jinux-std/src/syscall/getdents64.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/getdents64.rs
rename to services/libs/jinux-std/src/syscall/getdents64.rs
diff --git a/src/services/libs/jinux-std/src/syscall/getegid.rs b/services/libs/jinux-std/src/syscall/getegid.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/getegid.rs
rename to services/libs/jinux-std/src/syscall/getegid.rs
diff --git a/src/services/libs/jinux-std/src/syscall/geteuid.rs b/services/libs/jinux-std/src/syscall/geteuid.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/geteuid.rs
rename to services/libs/jinux-std/src/syscall/geteuid.rs
diff --git a/src/services/libs/jinux-std/src/syscall/getgid.rs b/services/libs/jinux-std/src/syscall/getgid.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/getgid.rs
rename to services/libs/jinux-std/src/syscall/getgid.rs
diff --git a/src/services/libs/jinux-std/src/syscall/getpgrp.rs b/services/libs/jinux-std/src/syscall/getpgrp.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/getpgrp.rs
rename to services/libs/jinux-std/src/syscall/getpgrp.rs
diff --git a/src/services/libs/jinux-std/src/syscall/getpid.rs b/services/libs/jinux-std/src/syscall/getpid.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/getpid.rs
rename to services/libs/jinux-std/src/syscall/getpid.rs
diff --git a/src/services/libs/jinux-std/src/syscall/getppid.rs b/services/libs/jinux-std/src/syscall/getppid.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/getppid.rs
rename to services/libs/jinux-std/src/syscall/getppid.rs
diff --git a/src/services/libs/jinux-std/src/syscall/gettid.rs b/services/libs/jinux-std/src/syscall/gettid.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/gettid.rs
rename to services/libs/jinux-std/src/syscall/gettid.rs
diff --git a/src/services/libs/jinux-std/src/syscall/getuid.rs b/services/libs/jinux-std/src/syscall/getuid.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/getuid.rs
rename to services/libs/jinux-std/src/syscall/getuid.rs
diff --git a/src/services/libs/jinux-std/src/syscall/ioctl.rs b/services/libs/jinux-std/src/syscall/ioctl.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/ioctl.rs
rename to services/libs/jinux-std/src/syscall/ioctl.rs
diff --git a/src/services/libs/jinux-std/src/syscall/kill.rs b/services/libs/jinux-std/src/syscall/kill.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/kill.rs
rename to services/libs/jinux-std/src/syscall/kill.rs
diff --git a/src/services/libs/jinux-std/src/syscall/link.rs b/services/libs/jinux-std/src/syscall/link.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/link.rs
rename to services/libs/jinux-std/src/syscall/link.rs
diff --git a/src/services/libs/jinux-std/src/syscall/lseek.rs b/services/libs/jinux-std/src/syscall/lseek.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/lseek.rs
rename to services/libs/jinux-std/src/syscall/lseek.rs
diff --git a/src/services/libs/jinux-std/src/syscall/madvise.rs b/services/libs/jinux-std/src/syscall/madvise.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/madvise.rs
rename to services/libs/jinux-std/src/syscall/madvise.rs
diff --git a/src/services/libs/jinux-std/src/syscall/mkdir.rs b/services/libs/jinux-std/src/syscall/mkdir.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/mkdir.rs
rename to services/libs/jinux-std/src/syscall/mkdir.rs
diff --git a/src/services/libs/jinux-std/src/syscall/mmap.rs b/services/libs/jinux-std/src/syscall/mmap.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/mmap.rs
rename to services/libs/jinux-std/src/syscall/mmap.rs
diff --git a/src/services/libs/jinux-std/src/syscall/mod.rs b/services/libs/jinux-std/src/syscall/mod.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/mod.rs
rename to services/libs/jinux-std/src/syscall/mod.rs
diff --git a/src/services/libs/jinux-std/src/syscall/mprotect.rs b/services/libs/jinux-std/src/syscall/mprotect.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/mprotect.rs
rename to services/libs/jinux-std/src/syscall/mprotect.rs
diff --git a/src/services/libs/jinux-std/src/syscall/munmap.rs b/services/libs/jinux-std/src/syscall/munmap.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/munmap.rs
rename to services/libs/jinux-std/src/syscall/munmap.rs
diff --git a/src/services/libs/jinux-std/src/syscall/open.rs b/services/libs/jinux-std/src/syscall/open.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/open.rs
rename to services/libs/jinux-std/src/syscall/open.rs
diff --git a/src/services/libs/jinux-std/src/syscall/pause.rs b/services/libs/jinux-std/src/syscall/pause.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/pause.rs
rename to services/libs/jinux-std/src/syscall/pause.rs
diff --git a/src/services/libs/jinux-std/src/syscall/poll.rs b/services/libs/jinux-std/src/syscall/poll.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/poll.rs
rename to services/libs/jinux-std/src/syscall/poll.rs
diff --git a/src/services/libs/jinux-std/src/syscall/prctl.rs b/services/libs/jinux-std/src/syscall/prctl.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/prctl.rs
rename to services/libs/jinux-std/src/syscall/prctl.rs
diff --git a/src/services/libs/jinux-std/src/syscall/pread64.rs b/services/libs/jinux-std/src/syscall/pread64.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/pread64.rs
rename to services/libs/jinux-std/src/syscall/pread64.rs
diff --git a/src/services/libs/jinux-std/src/syscall/prlimit64.rs b/services/libs/jinux-std/src/syscall/prlimit64.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/prlimit64.rs
rename to services/libs/jinux-std/src/syscall/prlimit64.rs
diff --git a/src/services/libs/jinux-std/src/syscall/read.rs b/services/libs/jinux-std/src/syscall/read.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/read.rs
rename to services/libs/jinux-std/src/syscall/read.rs
diff --git a/src/services/libs/jinux-std/src/syscall/readlink.rs b/services/libs/jinux-std/src/syscall/readlink.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/readlink.rs
rename to services/libs/jinux-std/src/syscall/readlink.rs
diff --git a/src/services/libs/jinux-std/src/syscall/rename.rs b/services/libs/jinux-std/src/syscall/rename.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/rename.rs
rename to services/libs/jinux-std/src/syscall/rename.rs
diff --git a/src/services/libs/jinux-std/src/syscall/rmdir.rs b/services/libs/jinux-std/src/syscall/rmdir.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/rmdir.rs
rename to services/libs/jinux-std/src/syscall/rmdir.rs
diff --git a/src/services/libs/jinux-std/src/syscall/rt_sigaction.rs b/services/libs/jinux-std/src/syscall/rt_sigaction.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/rt_sigaction.rs
rename to services/libs/jinux-std/src/syscall/rt_sigaction.rs
diff --git a/src/services/libs/jinux-std/src/syscall/rt_sigprocmask.rs b/services/libs/jinux-std/src/syscall/rt_sigprocmask.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/rt_sigprocmask.rs
rename to services/libs/jinux-std/src/syscall/rt_sigprocmask.rs
diff --git a/src/services/libs/jinux-std/src/syscall/rt_sigreturn.rs b/services/libs/jinux-std/src/syscall/rt_sigreturn.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/rt_sigreturn.rs
rename to services/libs/jinux-std/src/syscall/rt_sigreturn.rs
diff --git a/src/services/libs/jinux-std/src/syscall/sched_yield.rs b/services/libs/jinux-std/src/syscall/sched_yield.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/sched_yield.rs
rename to services/libs/jinux-std/src/syscall/sched_yield.rs
diff --git a/src/services/libs/jinux-std/src/syscall/set_robust_list.rs b/services/libs/jinux-std/src/syscall/set_robust_list.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/set_robust_list.rs
rename to services/libs/jinux-std/src/syscall/set_robust_list.rs
diff --git a/src/services/libs/jinux-std/src/syscall/set_tid_address.rs b/services/libs/jinux-std/src/syscall/set_tid_address.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/set_tid_address.rs
rename to services/libs/jinux-std/src/syscall/set_tid_address.rs
diff --git a/src/services/libs/jinux-std/src/syscall/setpgid.rs b/services/libs/jinux-std/src/syscall/setpgid.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/setpgid.rs
rename to services/libs/jinux-std/src/syscall/setpgid.rs
diff --git a/src/services/libs/jinux-std/src/syscall/stat.rs b/services/libs/jinux-std/src/syscall/stat.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/stat.rs
rename to services/libs/jinux-std/src/syscall/stat.rs
diff --git a/src/services/libs/jinux-std/src/syscall/symlink.rs b/services/libs/jinux-std/src/syscall/symlink.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/symlink.rs
rename to services/libs/jinux-std/src/syscall/symlink.rs
diff --git a/src/services/libs/jinux-std/src/syscall/tgkill.rs b/services/libs/jinux-std/src/syscall/tgkill.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/tgkill.rs
rename to services/libs/jinux-std/src/syscall/tgkill.rs
diff --git a/src/services/libs/jinux-std/src/syscall/time.rs b/services/libs/jinux-std/src/syscall/time.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/time.rs
rename to services/libs/jinux-std/src/syscall/time.rs
diff --git a/src/services/libs/jinux-std/src/syscall/umask.rs b/services/libs/jinux-std/src/syscall/umask.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/umask.rs
rename to services/libs/jinux-std/src/syscall/umask.rs
diff --git a/src/services/libs/jinux-std/src/syscall/uname.rs b/services/libs/jinux-std/src/syscall/uname.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/uname.rs
rename to services/libs/jinux-std/src/syscall/uname.rs
diff --git a/src/services/libs/jinux-std/src/syscall/unlink.rs b/services/libs/jinux-std/src/syscall/unlink.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/unlink.rs
rename to services/libs/jinux-std/src/syscall/unlink.rs
diff --git a/src/services/libs/jinux-std/src/syscall/utimens.rs b/services/libs/jinux-std/src/syscall/utimens.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/utimens.rs
rename to services/libs/jinux-std/src/syscall/utimens.rs
diff --git a/src/services/libs/jinux-std/src/syscall/wait4.rs b/services/libs/jinux-std/src/syscall/wait4.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/wait4.rs
rename to services/libs/jinux-std/src/syscall/wait4.rs
diff --git a/src/services/libs/jinux-std/src/syscall/waitid.rs b/services/libs/jinux-std/src/syscall/waitid.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/waitid.rs
rename to services/libs/jinux-std/src/syscall/waitid.rs
diff --git a/src/services/libs/jinux-std/src/syscall/write.rs b/services/libs/jinux-std/src/syscall/write.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/write.rs
rename to services/libs/jinux-std/src/syscall/write.rs
diff --git a/src/services/libs/jinux-std/src/syscall/writev.rs b/services/libs/jinux-std/src/syscall/writev.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/syscall/writev.rs
rename to services/libs/jinux-std/src/syscall/writev.rs
diff --git a/src/services/libs/jinux-std/src/thread/exception.rs b/services/libs/jinux-std/src/thread/exception.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/thread/exception.rs
rename to services/libs/jinux-std/src/thread/exception.rs
diff --git a/src/services/libs/jinux-std/src/thread/kernel_thread.rs b/services/libs/jinux-std/src/thread/kernel_thread.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/thread/kernel_thread.rs
rename to services/libs/jinux-std/src/thread/kernel_thread.rs
diff --git a/src/services/libs/jinux-std/src/thread/mod.rs b/services/libs/jinux-std/src/thread/mod.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/thread/mod.rs
rename to services/libs/jinux-std/src/thread/mod.rs
diff --git a/src/services/libs/jinux-std/src/thread/status.rs b/services/libs/jinux-std/src/thread/status.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/thread/status.rs
rename to services/libs/jinux-std/src/thread/status.rs
diff --git a/src/services/libs/jinux-std/src/thread/task.rs b/services/libs/jinux-std/src/thread/task.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/thread/task.rs
rename to services/libs/jinux-std/src/thread/task.rs
diff --git a/src/services/libs/jinux-std/src/thread/thread_table.rs b/services/libs/jinux-std/src/thread/thread_table.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/thread/thread_table.rs
rename to services/libs/jinux-std/src/thread/thread_table.rs
diff --git a/src/services/libs/jinux-std/src/time/mod.rs b/services/libs/jinux-std/src/time/mod.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/time/mod.rs
rename to services/libs/jinux-std/src/time/mod.rs
diff --git a/src/services/libs/jinux-std/src/time/system_time.rs b/services/libs/jinux-std/src/time/system_time.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/time/system_time.rs
rename to services/libs/jinux-std/src/time/system_time.rs
diff --git a/src/services/libs/jinux-std/src/tty/line_discipline.rs b/services/libs/jinux-std/src/tty/line_discipline.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/tty/line_discipline.rs
rename to services/libs/jinux-std/src/tty/line_discipline.rs
diff --git a/src/services/libs/jinux-std/src/tty/mod.rs b/services/libs/jinux-std/src/tty/mod.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/tty/mod.rs
rename to services/libs/jinux-std/src/tty/mod.rs
diff --git a/src/services/libs/jinux-std/src/tty/termio.rs b/services/libs/jinux-std/src/tty/termio.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/tty/termio.rs
rename to services/libs/jinux-std/src/tty/termio.rs
diff --git a/src/services/libs/jinux-std/src/util/mod.rs b/services/libs/jinux-std/src/util/mod.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/util/mod.rs
rename to services/libs/jinux-std/src/util/mod.rs
diff --git a/src/services/libs/jinux-std/src/vm/mod.rs b/services/libs/jinux-std/src/vm/mod.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/vm/mod.rs
rename to services/libs/jinux-std/src/vm/mod.rs
diff --git a/src/services/libs/jinux-std/src/vm/page_fault_handler.rs b/services/libs/jinux-std/src/vm/page_fault_handler.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/vm/page_fault_handler.rs
rename to services/libs/jinux-std/src/vm/page_fault_handler.rs
diff --git a/src/services/libs/jinux-std/src/vm/perms.rs b/services/libs/jinux-std/src/vm/perms.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/vm/perms.rs
rename to services/libs/jinux-std/src/vm/perms.rs
diff --git a/src/services/libs/jinux-std/src/vm/vmar/dyn_cap.rs b/services/libs/jinux-std/src/vm/vmar/dyn_cap.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/vm/vmar/dyn_cap.rs
rename to services/libs/jinux-std/src/vm/vmar/dyn_cap.rs
diff --git a/src/services/libs/jinux-std/src/vm/vmar/mod.rs b/services/libs/jinux-std/src/vm/vmar/mod.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/vm/vmar/mod.rs
rename to services/libs/jinux-std/src/vm/vmar/mod.rs
diff --git a/src/services/libs/jinux-std/src/vm/vmar/options.rs b/services/libs/jinux-std/src/vm/vmar/options.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/vm/vmar/options.rs
rename to services/libs/jinux-std/src/vm/vmar/options.rs
diff --git a/src/services/libs/jinux-std/src/vm/vmar/static_cap.rs b/services/libs/jinux-std/src/vm/vmar/static_cap.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/vm/vmar/static_cap.rs
rename to services/libs/jinux-std/src/vm/vmar/static_cap.rs
diff --git a/src/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs b/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
rename to services/libs/jinux-std/src/vm/vmar/vm_mapping.rs
diff --git a/src/services/libs/jinux-std/src/vm/vmo/dyn_cap.rs b/services/libs/jinux-std/src/vm/vmo/dyn_cap.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/vm/vmo/dyn_cap.rs
rename to services/libs/jinux-std/src/vm/vmo/dyn_cap.rs
diff --git a/src/services/libs/jinux-std/src/vm/vmo/mod.rs b/services/libs/jinux-std/src/vm/vmo/mod.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/vm/vmo/mod.rs
rename to services/libs/jinux-std/src/vm/vmo/mod.rs
diff --git a/src/services/libs/jinux-std/src/vm/vmo/options.rs b/services/libs/jinux-std/src/vm/vmo/options.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/vm/vmo/options.rs
rename to services/libs/jinux-std/src/vm/vmo/options.rs
diff --git a/src/services/libs/jinux-std/src/vm/vmo/pager.rs b/services/libs/jinux-std/src/vm/vmo/pager.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/vm/vmo/pager.rs
rename to services/libs/jinux-std/src/vm/vmo/pager.rs
diff --git a/src/services/libs/jinux-std/src/vm/vmo/static_cap.rs b/services/libs/jinux-std/src/vm/vmo/static_cap.rs
similarity index 100%
rename from src/services/libs/jinux-std/src/vm/vmo/static_cap.rs
rename to services/libs/jinux-std/src/vm/vmo/static_cap.rs
diff --git a/src/services/libs/jinux-util/Cargo.toml b/services/libs/jinux-util/Cargo.toml
similarity index 100%
rename from src/services/libs/jinux-util/Cargo.toml
rename to services/libs/jinux-util/Cargo.toml
diff --git a/src/services/libs/jinux-util/src/frame_ptr.rs b/services/libs/jinux-util/src/frame_ptr.rs
similarity index 100%
rename from src/services/libs/jinux-util/src/frame_ptr.rs
rename to services/libs/jinux-util/src/frame_ptr.rs
diff --git a/src/services/libs/jinux-util/src/lib.rs b/services/libs/jinux-util/src/lib.rs
similarity index 100%
rename from src/services/libs/jinux-util/src/lib.rs
rename to services/libs/jinux-util/src/lib.rs
diff --git a/src/services/libs/jinux-util/src/union_read_ptr.rs b/services/libs/jinux-util/src/union_read_ptr.rs
similarity index 100%
rename from src/services/libs/jinux-util/src/union_read_ptr.rs
rename to services/libs/jinux-util/src/union_read_ptr.rs
diff --git a/src/services/libs/typeflags-util/Cargo.toml b/services/libs/typeflags-util/Cargo.toml
similarity index 100%
rename from src/services/libs/typeflags-util/Cargo.toml
rename to services/libs/typeflags-util/Cargo.toml
diff --git a/src/services/libs/typeflags-util/src/assert.rs b/services/libs/typeflags-util/src/assert.rs
similarity index 100%
rename from src/services/libs/typeflags-util/src/assert.rs
rename to services/libs/typeflags-util/src/assert.rs
diff --git a/src/services/libs/typeflags-util/src/bool.rs b/services/libs/typeflags-util/src/bool.rs
similarity index 100%
rename from src/services/libs/typeflags-util/src/bool.rs
rename to services/libs/typeflags-util/src/bool.rs
diff --git a/src/services/libs/typeflags-util/src/extend.rs b/services/libs/typeflags-util/src/extend.rs
similarity index 100%
rename from src/services/libs/typeflags-util/src/extend.rs
rename to services/libs/typeflags-util/src/extend.rs
diff --git a/src/services/libs/typeflags-util/src/if_.rs b/services/libs/typeflags-util/src/if_.rs
similarity index 100%
rename from src/services/libs/typeflags-util/src/if_.rs
rename to services/libs/typeflags-util/src/if_.rs
diff --git a/src/services/libs/typeflags-util/src/lib.rs b/services/libs/typeflags-util/src/lib.rs
similarity index 100%
rename from src/services/libs/typeflags-util/src/lib.rs
rename to services/libs/typeflags-util/src/lib.rs
diff --git a/src/services/libs/typeflags-util/src/same.rs b/services/libs/typeflags-util/src/same.rs
similarity index 100%
rename from src/services/libs/typeflags-util/src/same.rs
rename to services/libs/typeflags-util/src/same.rs
diff --git a/src/services/libs/typeflags-util/src/set.rs b/services/libs/typeflags-util/src/set.rs
similarity index 100%
rename from src/services/libs/typeflags-util/src/set.rs
rename to services/libs/typeflags-util/src/set.rs
diff --git a/src/services/libs/typeflags/Cargo.toml b/services/libs/typeflags/Cargo.toml
similarity index 100%
rename from src/services/libs/typeflags/Cargo.toml
rename to services/libs/typeflags/Cargo.toml
diff --git a/src/services/libs/typeflags/src/flag_set.rs b/services/libs/typeflags/src/flag_set.rs
similarity index 100%
rename from src/services/libs/typeflags/src/flag_set.rs
rename to services/libs/typeflags/src/flag_set.rs
diff --git a/src/services/libs/typeflags/src/lib.rs b/services/libs/typeflags/src/lib.rs
similarity index 100%
rename from src/services/libs/typeflags/src/lib.rs
rename to services/libs/typeflags/src/lib.rs
diff --git a/src/services/libs/typeflags/src/type_flag.rs b/services/libs/typeflags/src/type_flag.rs
similarity index 100%
rename from src/services/libs/typeflags/src/type_flag.rs
rename to services/libs/typeflags/src/type_flag.rs
diff --git a/src/services/libs/typeflags/src/util.rs b/services/libs/typeflags/src/util.rs
similarity index 100%
rename from src/services/libs/typeflags/src/util.rs
rename to services/libs/typeflags/src/util.rs
diff --git a/src/apps/hello_c/hello b/src/apps/hello_c/hello
deleted file mode 100755
index aff26147fd..0000000000
Binary files a/src/apps/hello_c/hello and /dev/null differ
diff --git a/src/x86_64-custom.json b/x86_64-custom.json
similarity index 100%
rename from src/x86_64-custom.json
rename to x86_64-custom.json
|
diff --git a/src/apps/pthread/pthread_test b/regression/apps/pthread/pthread_test
similarity index 100%
rename from src/apps/pthread/pthread_test
rename to regression/apps/pthread/pthread_test
diff --git a/src/apps/pthread/pthread_test.c b/regression/apps/pthread/pthread_test.c
similarity index 100%
rename from src/apps/pthread/pthread_test.c
rename to regression/apps/pthread/pthread_test.c
diff --git a/src/apps/scripts/run_tests.sh b/regression/apps/scripts/run_tests.sh
similarity index 100%
rename from src/apps/scripts/run_tests.sh
rename to regression/apps/scripts/run_tests.sh
diff --git a/src/apps/scripts/test_cmd.sh b/regression/apps/scripts/test_cmd.sh
similarity index 100%
rename from src/apps/scripts/test_cmd.sh
rename to regression/apps/scripts/test_cmd.sh
diff --git a/src/apps/signal_c/signal_test b/regression/apps/signal_c/signal_test
similarity index 100%
rename from src/apps/signal_c/signal_test
rename to regression/apps/signal_c/signal_test
diff --git a/src/apps/signal_c/signal_test.c b/regression/apps/signal_c/signal_test.c
similarity index 100%
rename from src/apps/signal_c/signal_test.c
rename to regression/apps/signal_c/signal_test.c
diff --git a/src/services/comp-sys/cargo-component/tests/duplicate_lib_name.rs b/services/libs/comp-sys/cargo-component/tests/duplicate_lib_name.rs
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/duplicate_lib_name.rs
rename to services/libs/comp-sys/cargo-component/tests/duplicate_lib_name.rs
diff --git a/src/services/comp-sys/cargo-component/tests/duplicate_lib_name_test/Cargo.toml b/services/libs/comp-sys/cargo-component/tests/duplicate_lib_name_test/Cargo.toml
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/duplicate_lib_name_test/Cargo.toml
rename to services/libs/comp-sys/cargo-component/tests/duplicate_lib_name_test/Cargo.toml
diff --git a/src/services/comp-sys/cargo-component/tests/duplicate_lib_name_test/Components.toml b/services/libs/comp-sys/cargo-component/tests/duplicate_lib_name_test/Components.toml
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/duplicate_lib_name_test/Components.toml
rename to services/libs/comp-sys/cargo-component/tests/duplicate_lib_name_test/Components.toml
diff --git a/src/services/comp-sys/cargo-component/tests/duplicate_lib_name_test/src/lib.rs b/services/libs/comp-sys/cargo-component/tests/duplicate_lib_name_test/src/lib.rs
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/duplicate_lib_name_test/src/lib.rs
rename to services/libs/comp-sys/cargo-component/tests/duplicate_lib_name_test/src/lib.rs
diff --git a/src/services/comp-sys/cargo-component/tests/missing_toml.rs b/services/libs/comp-sys/cargo-component/tests/missing_toml.rs
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/missing_toml.rs
rename to services/libs/comp-sys/cargo-component/tests/missing_toml.rs
diff --git a/src/services/comp-sys/cargo-component/tests/missing_toml_test/Cargo.toml b/services/libs/comp-sys/cargo-component/tests/missing_toml_test/Cargo.toml
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/missing_toml_test/Cargo.toml
rename to services/libs/comp-sys/cargo-component/tests/missing_toml_test/Cargo.toml
diff --git a/src/services/comp-sys/cargo-component/tests/missing_toml_test/src/lib.rs b/services/libs/comp-sys/cargo-component/tests/missing_toml_test/src/lib.rs
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/missing_toml_test/src/lib.rs
rename to services/libs/comp-sys/cargo-component/tests/missing_toml_test/src/lib.rs
diff --git a/src/services/comp-sys/cargo-component/tests/reexport.rs b/services/libs/comp-sys/cargo-component/tests/reexport.rs
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/reexport.rs
rename to services/libs/comp-sys/cargo-component/tests/reexport.rs
diff --git a/src/services/comp-sys/cargo-component/tests/reexport_test/Cargo.toml b/services/libs/comp-sys/cargo-component/tests/reexport_test/Cargo.toml
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/reexport_test/Cargo.toml
rename to services/libs/comp-sys/cargo-component/tests/reexport_test/Cargo.toml
diff --git a/src/services/comp-sys/cargo-component/tests/reexport_test/Components.toml b/services/libs/comp-sys/cargo-component/tests/reexport_test/Components.toml
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/reexport_test/Components.toml
rename to services/libs/comp-sys/cargo-component/tests/reexport_test/Components.toml
diff --git a/src/services/comp-sys/cargo-component/tests/reexport_test/bar/Cargo.toml b/services/libs/comp-sys/cargo-component/tests/reexport_test/bar/Cargo.toml
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/reexport_test/bar/Cargo.toml
rename to services/libs/comp-sys/cargo-component/tests/reexport_test/bar/Cargo.toml
diff --git a/src/services/comp-sys/cargo-component/tests/reexport_test/bar/src/lib.rs b/services/libs/comp-sys/cargo-component/tests/reexport_test/bar/src/lib.rs
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/reexport_test/bar/src/lib.rs
rename to services/libs/comp-sys/cargo-component/tests/reexport_test/bar/src/lib.rs
diff --git a/src/services/comp-sys/cargo-component/tests/reexport_test/baz/Cargo.toml b/services/libs/comp-sys/cargo-component/tests/reexport_test/baz/Cargo.toml
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/reexport_test/baz/Cargo.toml
rename to services/libs/comp-sys/cargo-component/tests/reexport_test/baz/Cargo.toml
diff --git a/src/services/comp-sys/cargo-component/tests/reexport_test/baz/src/lib.rs b/services/libs/comp-sys/cargo-component/tests/reexport_test/baz/src/lib.rs
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/reexport_test/baz/src/lib.rs
rename to services/libs/comp-sys/cargo-component/tests/reexport_test/baz/src/lib.rs
diff --git a/src/services/comp-sys/cargo-component/tests/reexport_test/foo/Cargo.toml b/services/libs/comp-sys/cargo-component/tests/reexport_test/foo/Cargo.toml
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/reexport_test/foo/Cargo.toml
rename to services/libs/comp-sys/cargo-component/tests/reexport_test/foo/Cargo.toml
diff --git a/src/services/comp-sys/cargo-component/tests/reexport_test/foo/src/lib.rs b/services/libs/comp-sys/cargo-component/tests/reexport_test/foo/src/lib.rs
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/reexport_test/foo/src/lib.rs
rename to services/libs/comp-sys/cargo-component/tests/reexport_test/foo/src/lib.rs
diff --git a/src/services/comp-sys/cargo-component/tests/regression.rs b/services/libs/comp-sys/cargo-component/tests/regression.rs
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/regression.rs
rename to services/libs/comp-sys/cargo-component/tests/regression.rs
diff --git a/src/services/comp-sys/cargo-component/tests/regression_test/Cargo.toml b/services/libs/comp-sys/cargo-component/tests/regression_test/Cargo.toml
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/regression_test/Cargo.toml
rename to services/libs/comp-sys/cargo-component/tests/regression_test/Cargo.toml
diff --git a/src/services/comp-sys/cargo-component/tests/regression_test/Components.toml b/services/libs/comp-sys/cargo-component/tests/regression_test/Components.toml
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/regression_test/Components.toml
rename to services/libs/comp-sys/cargo-component/tests/regression_test/Components.toml
diff --git a/src/services/comp-sys/cargo-component/tests/regression_test/bar/Cargo.toml b/services/libs/comp-sys/cargo-component/tests/regression_test/bar/Cargo.toml
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/regression_test/bar/Cargo.toml
rename to services/libs/comp-sys/cargo-component/tests/regression_test/bar/Cargo.toml
diff --git a/src/services/comp-sys/cargo-component/tests/regression_test/bar/src/lib.rs b/services/libs/comp-sys/cargo-component/tests/regression_test/bar/src/lib.rs
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/regression_test/bar/src/lib.rs
rename to services/libs/comp-sys/cargo-component/tests/regression_test/bar/src/lib.rs
diff --git a/src/services/comp-sys/cargo-component/tests/regression_test/foo/Cargo.toml b/services/libs/comp-sys/cargo-component/tests/regression_test/foo/Cargo.toml
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/regression_test/foo/Cargo.toml
rename to services/libs/comp-sys/cargo-component/tests/regression_test/foo/Cargo.toml
diff --git a/src/services/comp-sys/cargo-component/tests/regression_test/foo/src/lib.rs b/services/libs/comp-sys/cargo-component/tests/regression_test/foo/src/lib.rs
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/regression_test/foo/src/lib.rs
rename to services/libs/comp-sys/cargo-component/tests/regression_test/foo/src/lib.rs
diff --git a/src/services/comp-sys/cargo-component/tests/test_utils/mod.rs b/services/libs/comp-sys/cargo-component/tests/test_utils/mod.rs
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/test_utils/mod.rs
rename to services/libs/comp-sys/cargo-component/tests/test_utils/mod.rs
diff --git a/src/services/comp-sys/cargo-component/tests/trait_method.rs b/services/libs/comp-sys/cargo-component/tests/trait_method.rs
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/trait_method.rs
rename to services/libs/comp-sys/cargo-component/tests/trait_method.rs
diff --git a/src/services/comp-sys/cargo-component/tests/trait_method_test/Cargo.toml b/services/libs/comp-sys/cargo-component/tests/trait_method_test/Cargo.toml
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/trait_method_test/Cargo.toml
rename to services/libs/comp-sys/cargo-component/tests/trait_method_test/Cargo.toml
diff --git a/src/services/comp-sys/cargo-component/tests/trait_method_test/Components.toml b/services/libs/comp-sys/cargo-component/tests/trait_method_test/Components.toml
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/trait_method_test/Components.toml
rename to services/libs/comp-sys/cargo-component/tests/trait_method_test/Components.toml
diff --git a/src/services/comp-sys/cargo-component/tests/trait_method_test/bar/Cargo.toml b/services/libs/comp-sys/cargo-component/tests/trait_method_test/bar/Cargo.toml
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/trait_method_test/bar/Cargo.toml
rename to services/libs/comp-sys/cargo-component/tests/trait_method_test/bar/Cargo.toml
diff --git a/src/services/comp-sys/cargo-component/tests/trait_method_test/bar/src/lib.rs b/services/libs/comp-sys/cargo-component/tests/trait_method_test/bar/src/lib.rs
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/trait_method_test/bar/src/lib.rs
rename to services/libs/comp-sys/cargo-component/tests/trait_method_test/bar/src/lib.rs
diff --git a/src/services/comp-sys/cargo-component/tests/trait_method_test/foo/Cargo.toml b/services/libs/comp-sys/cargo-component/tests/trait_method_test/foo/Cargo.toml
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/trait_method_test/foo/Cargo.toml
rename to services/libs/comp-sys/cargo-component/tests/trait_method_test/foo/Cargo.toml
diff --git a/src/services/comp-sys/cargo-component/tests/trait_method_test/foo/src/lib.rs b/services/libs/comp-sys/cargo-component/tests/trait_method_test/foo/src/lib.rs
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/trait_method_test/foo/src/lib.rs
rename to services/libs/comp-sys/cargo-component/tests/trait_method_test/foo/src/lib.rs
diff --git a/src/services/comp-sys/cargo-component/tests/violate_policy.rs b/services/libs/comp-sys/cargo-component/tests/violate_policy.rs
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/violate_policy.rs
rename to services/libs/comp-sys/cargo-component/tests/violate_policy.rs
diff --git a/src/services/comp-sys/cargo-component/tests/violate_policy_test/Cargo.toml b/services/libs/comp-sys/cargo-component/tests/violate_policy_test/Cargo.toml
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/violate_policy_test/Cargo.toml
rename to services/libs/comp-sys/cargo-component/tests/violate_policy_test/Cargo.toml
diff --git a/src/services/comp-sys/cargo-component/tests/violate_policy_test/Components.toml b/services/libs/comp-sys/cargo-component/tests/violate_policy_test/Components.toml
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/violate_policy_test/Components.toml
rename to services/libs/comp-sys/cargo-component/tests/violate_policy_test/Components.toml
diff --git a/src/services/comp-sys/cargo-component/tests/violate_policy_test/bar/Cargo.toml b/services/libs/comp-sys/cargo-component/tests/violate_policy_test/bar/Cargo.toml
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/violate_policy_test/bar/Cargo.toml
rename to services/libs/comp-sys/cargo-component/tests/violate_policy_test/bar/Cargo.toml
diff --git a/src/services/comp-sys/cargo-component/tests/violate_policy_test/bar/src/lib.rs b/services/libs/comp-sys/cargo-component/tests/violate_policy_test/bar/src/lib.rs
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/violate_policy_test/bar/src/lib.rs
rename to services/libs/comp-sys/cargo-component/tests/violate_policy_test/bar/src/lib.rs
diff --git a/src/services/comp-sys/cargo-component/tests/violate_policy_test/foo/Cargo.toml b/services/libs/comp-sys/cargo-component/tests/violate_policy_test/foo/Cargo.toml
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/violate_policy_test/foo/Cargo.toml
rename to services/libs/comp-sys/cargo-component/tests/violate_policy_test/foo/Cargo.toml
diff --git a/src/services/comp-sys/cargo-component/tests/violate_policy_test/foo/src/lib.rs b/services/libs/comp-sys/cargo-component/tests/violate_policy_test/foo/src/lib.rs
similarity index 100%
rename from src/services/comp-sys/cargo-component/tests/violate_policy_test/foo/src/lib.rs
rename to services/libs/comp-sys/cargo-component/tests/violate_policy_test/foo/src/lib.rs
diff --git a/src/services/comp-sys/component/tests/init-order/Cargo.toml b/services/libs/comp-sys/component/tests/init-order/Cargo.toml
similarity index 100%
rename from src/services/comp-sys/component/tests/init-order/Cargo.toml
rename to services/libs/comp-sys/component/tests/init-order/Cargo.toml
diff --git a/src/services/comp-sys/component/tests/init-order/Components.toml b/services/libs/comp-sys/component/tests/init-order/Components.toml
similarity index 100%
rename from src/services/comp-sys/component/tests/init-order/Components.toml
rename to services/libs/comp-sys/component/tests/init-order/Components.toml
diff --git a/src/services/comp-sys/component/tests/init-order/first-init/Cargo.toml b/services/libs/comp-sys/component/tests/init-order/first-init/Cargo.toml
similarity index 100%
rename from src/services/comp-sys/component/tests/init-order/first-init/Cargo.toml
rename to services/libs/comp-sys/component/tests/init-order/first-init/Cargo.toml
diff --git a/src/services/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
similarity index 100%
rename from src/services/comp-sys/component/tests/init-order/first-init/src/lib.rs
rename to services/libs/comp-sys/component/tests/init-order/first-init/src/lib.rs
diff --git a/src/services/comp-sys/component/tests/init-order/second-init/Cargo.toml b/services/libs/comp-sys/component/tests/init-order/second-init/Cargo.toml
similarity index 100%
rename from src/services/comp-sys/component/tests/init-order/second-init/Cargo.toml
rename to services/libs/comp-sys/component/tests/init-order/second-init/Cargo.toml
diff --git a/src/services/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
similarity index 100%
rename from src/services/comp-sys/component/tests/init-order/second-init/src/lib.rs
rename to services/libs/comp-sys/component/tests/init-order/second-init/src/lib.rs
diff --git a/src/services/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
similarity index 100%
rename from src/services/comp-sys/component/tests/init-order/second-init/tests/test.rs
rename to services/libs/comp-sys/component/tests/init-order/second-init/tests/test.rs
diff --git a/src/services/comp-sys/component/tests/init-order/src/main.rs b/services/libs/comp-sys/component/tests/init-order/src/main.rs
similarity index 100%
rename from src/services/comp-sys/component/tests/init-order/src/main.rs
rename to services/libs/comp-sys/component/tests/init-order/src/main.rs
diff --git a/src/services/comp-sys/component/tests/init-order/tests/test.rs b/services/libs/comp-sys/component/tests/init-order/tests/test.rs
similarity index 100%
rename from src/services/comp-sys/component/tests/init-order/tests/test.rs
rename to services/libs/comp-sys/component/tests/init-order/tests/test.rs
diff --git a/src/services/libs/cpio-decoder/src/test.rs b/services/libs/cpio-decoder/src/test.rs
similarity index 100%
rename from src/services/libs/cpio-decoder/src/test.rs
rename to services/libs/cpio-decoder/src/test.rs
diff --git a/src/tests/console_input.rs b/tests/console_input.rs
similarity index 100%
rename from src/tests/console_input.rs
rename to tests/console_input.rs
diff --git a/src/tests/framebuffer.rs b/tests/framebuffer.rs
similarity index 100%
rename from src/tests/framebuffer.rs
rename to tests/framebuffer.rs
diff --git a/src/tests/rtc.rs b/tests/rtc.rs
similarity index 100%
rename from src/tests/rtc.rs
rename to tests/rtc.rs
diff --git a/src/tests/test_example.rs b/tests/test_example.rs
similarity index 100%
rename from src/tests/test_example.rs
rename to tests/test_example.rs
diff --git a/src/tests/timer_test.rs b/tests/timer_test.rs
similarity index 100%
rename from src/tests/timer_test.rs
rename to tests/timer_test.rs
|
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`
|
2023-04-10T03:22:03Z
|
0.1
|
25c4f0f2bcaa0bc8c650b0f4ee7b0d78e2a836b2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.