Dataset Viewer
Auto-converted to Parquet Duplicate
repo
stringclasses
1 value
pull_number
int64
183
1.37k
instance_id
stringlengths
24
25
issue_numbers
sequencelengths
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)): ![kernel](https://github.com/asterinas/asterinas/assets/30975570/0ea5b99b-c769-4342-b17f-0d17e100ef8d) ([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: ![kernel_vmspacerw](https://github.com/asterinas/asterinas/assets/30975570/6e960bd7-ed26-49d0-91a5-1289673b6215) ([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, &current_thread.tid()) + .write_val(child_tid_ptr, &current_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, &current_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\(...TRUNCATED)
"diff --git a/.github/workflows/test_asterinas.yml b/.github/workflows/test_asterinas.yml\nindex 5e2(...TRUNCATED)
"ktest as a kernel\n<!-- Thank you for taking the time to propose a new idea or significant change. (...TRUNCATED)
"This proposal aims to address to problems.\r\n\r\n> * a lot of runtime needed when running ktest, w(...TRUNCATED)
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\nindex(...TRUNCATED)
"diff --git a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs b/osdk/tests/(...TRUNCATED)
"Sporadic SMP syscall test aborts\n<!-- Thank you for taking the time to report a bug. Your input is(...TRUNCATED)
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\nindex 1c5c386004..7d4b9b0(...TRUNCATED)
"diff --git a/osdk/tests/cli/mod.rs b/osdk/tests/cli/mod.rs\nindex ed909baaf0..4a7fbc1fda 100644\n--(...TRUNCATED)
"OSDK should support creating crate with `-` in its name\nAs discovered by #1133, `cargo osdk new --(...TRUNCATED)
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\nindex dfff76268f..4(...TRUNCATED)
"diff --git a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs b/osdk/tests/(...TRUNCATED)
"Lockless mutability for current task data.\n**This is currently a work-in-progress RFC**\r\n\r\n<!-(...TRUNCATED)
"Let's say we have a function `foo` with `#[code_context::task]` attribute. How would this `foo` fun(...TRUNCATED)
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_sock(...TRUNCATED)
"diff --git a/test/apps/network/listen_backlog.c b/test/apps/network/listen_backlog.c\nindex 9491891(...TRUNCATED)
"Polling ifaces may not ensure packets be transmitted\nThe problem occurs when I trying to send two (...TRUNCATED)
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\nindex(...TRUNCATED)
"diff --git a/.github/workflows/test_asterinas.yml b/.github/workflows/test_asterinas.yml\nindex 414(...TRUNCATED)
"CPU local memory is used before initialized\nThe use (in `ostd`):\r\n`init` → `mm::heap_allocator(...TRUNCATED)
"Modifying `ostd::arch::x86::cpu::get_cpu_local_base` to\r\n``` rust\r\n/// Gets the base address fo(...TRUNCATED)
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.r(...TRUNCATED)
"diff --git a/osdk/tests/examples_in_book/write_a_kernel_in_100_lines_templates/lib.rs b/osdk/tests/(...TRUNCATED)
"The APIs of `VmSpace` are vulnerable to race conditions\n```rust\r\n#[derive(Debug, Clone)]\r\npub (...TRUNCATED)
2024-07-04T11:40:07Z
0.6
6414111cc57b42db2bae1a0c8b01b85c3830a3b3
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
1