11496ba7bSLoGin use core::{ 21496ba7bSLoGin hint::spin_loop, 31496ba7bSLoGin sync::atomic::{AtomicBool, Ordering}, 41496ba7bSLoGin }; 51496ba7bSLoGin 61496ba7bSLoGin use alloc::{ 71496ba7bSLoGin boxed::Box, 81496ba7bSLoGin collections::LinkedList, 91496ba7bSLoGin string::{String, ToString}, 101496ba7bSLoGin sync::{Arc, Weak}, 111496ba7bSLoGin }; 121496ba7bSLoGin use atomic_enum::atomic_enum; 1391e9d4abSLoGin use system_error::SystemError; 141496ba7bSLoGin 151496ba7bSLoGin use crate::{ 161496ba7bSLoGin arch::{sched::sched, CurrentIrqArch}, 17e2841179SLoGin exception::{irqdesc::IrqAction, InterruptArch}, 18c566df45SLoGin init::initial_kthread::initial_kernel_thread, 191496ba7bSLoGin kdebug, kinfo, 201496ba7bSLoGin libs::{once::Once, spinlock::SpinLock}, 211496ba7bSLoGin process::{ProcessManager, ProcessState}, 221496ba7bSLoGin }; 231496ba7bSLoGin 24c566df45SLoGin use super::{fork::CloneFlags, Pid, ProcessControlBlock, ProcessFlags}; 251496ba7bSLoGin 261496ba7bSLoGin /// 内核线程的创建任务列表 271496ba7bSLoGin static KTHREAD_CREATE_LIST: SpinLock<LinkedList<Arc<KernelThreadCreateInfo>>> = 281496ba7bSLoGin SpinLock::new(LinkedList::new()); 291496ba7bSLoGin 301496ba7bSLoGin static mut KTHREAD_DAEMON_PCB: Option<Arc<ProcessControlBlock>> = None; 311496ba7bSLoGin 321496ba7bSLoGin #[derive(Debug)] 331496ba7bSLoGin pub enum WorkerPrivate { 341496ba7bSLoGin KernelThread(KernelThreadPcbPrivate), 351496ba7bSLoGin } 361496ba7bSLoGin 371496ba7bSLoGin #[allow(dead_code)] 381496ba7bSLoGin impl WorkerPrivate { 391496ba7bSLoGin pub fn kernel_thread(&self) -> Option<&KernelThreadPcbPrivate> { 401496ba7bSLoGin match self { 411496ba7bSLoGin Self::KernelThread(x) => Some(x), 421496ba7bSLoGin } 431496ba7bSLoGin } 441496ba7bSLoGin 451496ba7bSLoGin pub fn kernel_thread_mut(&mut self) -> Option<&mut KernelThreadPcbPrivate> { 461496ba7bSLoGin match self { 471496ba7bSLoGin Self::KernelThread(x) => Some(x), 481496ba7bSLoGin } 491496ba7bSLoGin } 501496ba7bSLoGin } 511496ba7bSLoGin 521496ba7bSLoGin bitflags! { 531496ba7bSLoGin pub struct KernelThreadFlags: u32 { 541496ba7bSLoGin const IS_PER_CPU = 1 << 0; 551496ba7bSLoGin const SHOULD_STOP = 1 << 1; 561496ba7bSLoGin const SHOULD_PARK = 1 << 2; 571496ba7bSLoGin } 581496ba7bSLoGin } 591496ba7bSLoGin 601496ba7bSLoGin #[derive(Debug)] 611496ba7bSLoGin pub struct KernelThreadPcbPrivate { 621496ba7bSLoGin flags: KernelThreadFlags, 631496ba7bSLoGin } 641496ba7bSLoGin 651496ba7bSLoGin #[allow(dead_code)] 661496ba7bSLoGin impl KernelThreadPcbPrivate { 671496ba7bSLoGin pub fn new() -> Self { 681496ba7bSLoGin Self { 691496ba7bSLoGin flags: KernelThreadFlags::empty(), 701496ba7bSLoGin } 711496ba7bSLoGin } 721496ba7bSLoGin 731496ba7bSLoGin pub fn flags(&self) -> &KernelThreadFlags { 741496ba7bSLoGin &self.flags 751496ba7bSLoGin } 761496ba7bSLoGin 771496ba7bSLoGin pub fn flags_mut(&mut self) -> &mut KernelThreadFlags { 781496ba7bSLoGin &mut self.flags 791496ba7bSLoGin } 801496ba7bSLoGin } 811496ba7bSLoGin 821496ba7bSLoGin /// 内核线程的闭包,参数必须与闭包的参数一致,返回值必须是i32 831496ba7bSLoGin /// 841496ba7bSLoGin /// 元组的第一个元素是闭包,第二个元素是闭包的参数对象 851496ba7bSLoGin /// 861496ba7bSLoGin /// 对于非原始类型的参数,需要使用Box包装 871496ba7bSLoGin #[allow(dead_code)] 88*b5b571e0SLoGin #[allow(clippy::type_complexity)] 891496ba7bSLoGin pub enum KernelThreadClosure { 901496ba7bSLoGin UsizeClosure((Box<dyn Fn(usize) -> i32 + Send + Sync>, usize)), 9159fdb447SLoGin StaticUsizeClosure((&'static fn(usize) -> i32, usize)), 921496ba7bSLoGin EmptyClosure((Box<dyn Fn() -> i32 + Send + Sync>, ())), 9359fdb447SLoGin StaticEmptyClosure((&'static fn() -> i32, ())), 94e2841179SLoGin IrqThread( 95e2841179SLoGin ( 96e2841179SLoGin &'static dyn Fn(Arc<IrqAction>) -> Result<(), SystemError>, 97e2841179SLoGin Arc<IrqAction>, 98e2841179SLoGin ), 99e2841179SLoGin ), 1001496ba7bSLoGin // 添加其他类型入参的闭包,返回值必须是i32 1011496ba7bSLoGin } 1021496ba7bSLoGin 103e2841179SLoGin unsafe impl Send for KernelThreadClosure {} 104e2841179SLoGin unsafe impl Sync for KernelThreadClosure {} 105e2841179SLoGin 1061496ba7bSLoGin impl KernelThreadClosure { 1071496ba7bSLoGin pub fn run(self) -> i32 { 1081496ba7bSLoGin match self { 1091496ba7bSLoGin Self::UsizeClosure((func, arg)) => func(arg), 1101496ba7bSLoGin Self::EmptyClosure((func, _arg)) => func(), 111e2841179SLoGin Self::StaticUsizeClosure((func, arg)) => func(arg), 112e2841179SLoGin Self::StaticEmptyClosure((func, _arg)) => func(), 113e2841179SLoGin Self::IrqThread((func, arg)) => { 114e2841179SLoGin func(arg).map(|_| 0).unwrap_or_else(|e| e.to_posix_errno()) 115e2841179SLoGin } 1161496ba7bSLoGin } 1171496ba7bSLoGin } 1181496ba7bSLoGin } 1191496ba7bSLoGin 1201496ba7bSLoGin pub struct KernelThreadCreateInfo { 1211496ba7bSLoGin /// 内核线程的入口函数、传入参数 1221496ba7bSLoGin closure: SpinLock<Option<Box<KernelThreadClosure>>>, 1231496ba7bSLoGin /// 内核线程的名字 1241496ba7bSLoGin name: String, 1251496ba7bSLoGin /// 是否已经完成创建 todo:使用comletion机制优化这里 1261496ba7bSLoGin created: AtomicKernelThreadCreateStatus, 1271496ba7bSLoGin result_pcb: SpinLock<Option<Arc<ProcessControlBlock>>>, 1281496ba7bSLoGin /// 不安全的Arc引用计数,当内核线程创建失败时,需要减少这个计数 1291496ba7bSLoGin has_unsafe_arc_instance: AtomicBool, 1301496ba7bSLoGin self_ref: Weak<Self>, 131de71ec25SLoGin /// 如果该值为true在进入bootstrap stage2之后,就会进入睡眠状态 132de71ec25SLoGin to_mark_sleep: AtomicBool, 1331496ba7bSLoGin } 1341496ba7bSLoGin 1351496ba7bSLoGin #[atomic_enum] 1361496ba7bSLoGin #[derive(PartialEq)] 1371496ba7bSLoGin pub enum KernelThreadCreateStatus { 1381496ba7bSLoGin Created, 1391496ba7bSLoGin NotCreated, 1401496ba7bSLoGin ErrorOccured, 1411496ba7bSLoGin } 1421496ba7bSLoGin 1431496ba7bSLoGin #[allow(dead_code)] 1441496ba7bSLoGin impl KernelThreadCreateInfo { 1451496ba7bSLoGin pub fn new(func: KernelThreadClosure, name: String) -> Arc<Self> { 1461496ba7bSLoGin let result = Arc::new(Self { 1471496ba7bSLoGin closure: SpinLock::new(Some(Box::new(func))), 1481496ba7bSLoGin name, 1491496ba7bSLoGin created: AtomicKernelThreadCreateStatus::new(KernelThreadCreateStatus::NotCreated), 1501496ba7bSLoGin result_pcb: SpinLock::new(None), 1511496ba7bSLoGin has_unsafe_arc_instance: AtomicBool::new(false), 1521496ba7bSLoGin self_ref: Weak::new(), 153de71ec25SLoGin to_mark_sleep: AtomicBool::new(true), 1541496ba7bSLoGin }); 1551496ba7bSLoGin let tmp = result.clone(); 1561496ba7bSLoGin unsafe { 1571496ba7bSLoGin let tmp = Arc::into_raw(tmp) as *mut Self; 1581496ba7bSLoGin (*tmp).self_ref = Arc::downgrade(&result); 1591496ba7bSLoGin Arc::from_raw(tmp); 1601496ba7bSLoGin } 1611496ba7bSLoGin 1621496ba7bSLoGin return result; 1631496ba7bSLoGin } 1641496ba7bSLoGin 1651496ba7bSLoGin /// 创建者调用这函数,等待创建完成后,获取创建结果 1661496ba7bSLoGin /// 1671496ba7bSLoGin /// ## 返回值 1681496ba7bSLoGin /// 1691496ba7bSLoGin /// - Some(Arc<ProcessControlBlock>) 创建成功,返回新创建的内核线程的PCB 1701496ba7bSLoGin /// - None 创建失败 1711496ba7bSLoGin pub fn poll_result(&self) -> Option<Arc<ProcessControlBlock>> { 1721496ba7bSLoGin loop { 1731496ba7bSLoGin match self.created.load(Ordering::SeqCst) { 1741496ba7bSLoGin KernelThreadCreateStatus::Created => { 1751496ba7bSLoGin return self.result_pcb.lock().take(); 1761496ba7bSLoGin } 1771496ba7bSLoGin KernelThreadCreateStatus::NotCreated => { 1781496ba7bSLoGin spin_loop(); 1791496ba7bSLoGin } 1801496ba7bSLoGin KernelThreadCreateStatus::ErrorOccured => { 1811496ba7bSLoGin // 创建失败,减少不安全的Arc引用计数 1821496ba7bSLoGin let to_delete = self.has_unsafe_arc_instance.swap(false, Ordering::SeqCst); 1831496ba7bSLoGin if to_delete { 1841496ba7bSLoGin let self_ref = self.self_ref.upgrade().unwrap(); 1851496ba7bSLoGin unsafe { Arc::decrement_strong_count(&self_ref) }; 1861496ba7bSLoGin } 1871496ba7bSLoGin return None; 1881496ba7bSLoGin } 1891496ba7bSLoGin } 1901496ba7bSLoGin } 1911496ba7bSLoGin } 1921496ba7bSLoGin 1931496ba7bSLoGin pub fn take_closure(&self) -> Option<Box<KernelThreadClosure>> { 1941496ba7bSLoGin return self.closure.lock().take(); 1951496ba7bSLoGin } 1961496ba7bSLoGin 1971496ba7bSLoGin pub fn name(&self) -> &String { 1981496ba7bSLoGin &self.name 1991496ba7bSLoGin } 2001496ba7bSLoGin 2011496ba7bSLoGin pub unsafe fn set_create_ok(&self, pcb: Arc<ProcessControlBlock>) { 2021496ba7bSLoGin // todo: 使用completion机制优化这里 2031496ba7bSLoGin self.result_pcb.lock().replace(pcb); 2041496ba7bSLoGin self.created 2051496ba7bSLoGin .store(KernelThreadCreateStatus::Created, Ordering::SeqCst); 2061496ba7bSLoGin } 2071496ba7bSLoGin 2081496ba7bSLoGin /// 生成一个不安全的Arc指针(用于创建内核线程时传递参数) 2091496ba7bSLoGin pub fn generate_unsafe_arc_ptr(self: Arc<Self>) -> *const Self { 2101496ba7bSLoGin assert!( 2111496ba7bSLoGin self.has_unsafe_arc_instance 2121496ba7bSLoGin .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) 2131496ba7bSLoGin .is_ok(), 2141496ba7bSLoGin "Cannot generate unsafe arc ptr when there is already one." 2151496ba7bSLoGin ); 2161496ba7bSLoGin let ptr = Arc::into_raw(self); 2171496ba7bSLoGin return ptr; 2181496ba7bSLoGin } 2191496ba7bSLoGin 2201496ba7bSLoGin pub unsafe fn parse_unsafe_arc_ptr(ptr: *const Self) -> Arc<Self> { 2211496ba7bSLoGin let arc = Arc::from_raw(ptr); 2221496ba7bSLoGin assert!( 2231496ba7bSLoGin arc.has_unsafe_arc_instance 2241496ba7bSLoGin .compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst) 2251496ba7bSLoGin .is_ok(), 2261496ba7bSLoGin "Cannot parse unsafe arc ptr when there is no one." 2271496ba7bSLoGin ); 2281496ba7bSLoGin assert!(Arc::strong_count(&arc) > 0); 2291496ba7bSLoGin return arc; 2301496ba7bSLoGin } 231de71ec25SLoGin 232de71ec25SLoGin /// 设置是否在进入bootstrap stage2之后,就进入睡眠状态 233de71ec25SLoGin /// 234de71ec25SLoGin /// ## 参数 235de71ec25SLoGin /// 236de71ec25SLoGin /// - to_mark_sleep: 是否在进入bootstrap stage2之后,就进入睡眠状态 237de71ec25SLoGin /// 238de71ec25SLoGin /// ## 返回值 239de71ec25SLoGin /// 如果已经创建完成,返回EINVAL 240de71ec25SLoGin pub fn set_to_mark_sleep(&self, to_mark_sleep: bool) -> Result<(), SystemError> { 241de71ec25SLoGin let result_guard = self.result_pcb.lock(); 242de71ec25SLoGin if result_guard.is_some() { 243de71ec25SLoGin // 已经创建完成,不需要设置 244de71ec25SLoGin return Err(SystemError::EINVAL); 245de71ec25SLoGin } 246de71ec25SLoGin self.to_mark_sleep.store(to_mark_sleep, Ordering::SeqCst); 247de71ec25SLoGin return Ok(()); 248de71ec25SLoGin } 249de71ec25SLoGin 250de71ec25SLoGin pub fn to_mark_sleep(&self) -> bool { 251de71ec25SLoGin self.to_mark_sleep.load(Ordering::SeqCst) 252de71ec25SLoGin } 2531496ba7bSLoGin } 2541496ba7bSLoGin 2551496ba7bSLoGin pub struct KernelThreadMechanism; 2561496ba7bSLoGin 2571496ba7bSLoGin impl KernelThreadMechanism { 2581496ba7bSLoGin pub fn init_stage1() { 259de71ec25SLoGin assert!(ProcessManager::current_pcb().pid() == Pid::new(0)); 2601496ba7bSLoGin kinfo!("Initializing kernel thread mechanism stage1..."); 2611496ba7bSLoGin 2621496ba7bSLoGin // 初始化第一个内核线程 2631496ba7bSLoGin 2641496ba7bSLoGin let create_info = KernelThreadCreateInfo::new( 2651496ba7bSLoGin KernelThreadClosure::EmptyClosure((Box::new(initial_kernel_thread), ())), 2661496ba7bSLoGin "init".to_string(), 2671496ba7bSLoGin ); 2684fda81ceSLoGin 2694fda81ceSLoGin let irq_guard: crate::exception::IrqFlagsGuard = 2704fda81ceSLoGin unsafe { CurrentIrqArch::save_and_disable_irq() }; 2711496ba7bSLoGin // 由于当前是pid=0的idle进程,而__inner_create要求当前是kthread,所以先临时设置为kthread 2721496ba7bSLoGin ProcessManager::current_pcb() 2731496ba7bSLoGin .flags 27470a4e555SLoGin .get_mut() 2751496ba7bSLoGin .insert(ProcessFlags::KTHREAD); 276de71ec25SLoGin create_info 277de71ec25SLoGin .set_to_mark_sleep(false) 278de71ec25SLoGin .expect("Failed to set to_mark_sleep"); 2794fda81ceSLoGin 2801496ba7bSLoGin KernelThreadMechanism::__inner_create( 2811496ba7bSLoGin &create_info, 2821496ba7bSLoGin CloneFlags::CLONE_VM | CloneFlags::CLONE_SIGNAL, 2831496ba7bSLoGin ) 2841496ba7bSLoGin .unwrap_or_else(|e| panic!("Failed to create initial kernel thread, error: {:?}", e)); 2851496ba7bSLoGin 2861496ba7bSLoGin ProcessManager::current_pcb() 2871496ba7bSLoGin .flags 28870a4e555SLoGin .get_mut() 2891496ba7bSLoGin .remove(ProcessFlags::KTHREAD); 2904fda81ceSLoGin 2911496ba7bSLoGin drop(irq_guard); 2921496ba7bSLoGin kinfo!("Initializing kernel thread mechanism stage1 complete"); 2931496ba7bSLoGin } 2941496ba7bSLoGin 2951496ba7bSLoGin pub fn init_stage2() { 2961496ba7bSLoGin assert!(ProcessManager::current_pcb() 2971496ba7bSLoGin .flags() 2981496ba7bSLoGin .contains(ProcessFlags::KTHREAD)); 2991496ba7bSLoGin static INIT: Once = Once::new(); 3001496ba7bSLoGin INIT.call_once(|| { 3011496ba7bSLoGin kinfo!("Initializing kernel thread mechanism stage2..."); 3021496ba7bSLoGin // 初始化kthreadd 3031496ba7bSLoGin let closure = KernelThreadClosure::EmptyClosure((Box::new(Self::kthread_daemon), ())); 3041496ba7bSLoGin let info = KernelThreadCreateInfo::new(closure, "kthreadd".to_string()); 305971462beSGnoCiYeH let kthreadd_pid: Pid = Self::__inner_create( 306971462beSGnoCiYeH &info, 307971462beSGnoCiYeH CloneFlags::CLONE_VM | CloneFlags::CLONE_FS | CloneFlags::CLONE_SIGNAL, 308971462beSGnoCiYeH ) 3091496ba7bSLoGin .expect("Failed to create kthread daemon"); 3101496ba7bSLoGin let pcb = ProcessManager::find(kthreadd_pid).unwrap(); 311de71ec25SLoGin ProcessManager::wakeup(&pcb).expect("Failed to wakeup kthread daemon"); 3121496ba7bSLoGin unsafe { 3131496ba7bSLoGin KTHREAD_DAEMON_PCB.replace(pcb); 3141496ba7bSLoGin } 31559fdb447SLoGin kinfo!("Initialize kernel thread mechanism stage2 complete"); 3161496ba7bSLoGin }); 3171496ba7bSLoGin } 3181496ba7bSLoGin 3191496ba7bSLoGin /// 创建一个新的内核线程 3201496ba7bSLoGin /// 3211496ba7bSLoGin /// ## 参数 3221496ba7bSLoGin /// 3231496ba7bSLoGin /// - func: 内核线程的入口函数、传入参数 3241496ba7bSLoGin /// - name: 内核线程的名字 3251496ba7bSLoGin /// 3261496ba7bSLoGin /// ## 返回值 3271496ba7bSLoGin /// 3281496ba7bSLoGin /// - Some(Arc<ProcessControlBlock>) 创建成功,返回新创建的内核线程的PCB 3291496ba7bSLoGin #[allow(dead_code)] 3301496ba7bSLoGin pub fn create(func: KernelThreadClosure, name: String) -> Option<Arc<ProcessControlBlock>> { 3311496ba7bSLoGin let info = KernelThreadCreateInfo::new(func, name); 3321496ba7bSLoGin while unsafe { KTHREAD_DAEMON_PCB.is_none() } { 3331496ba7bSLoGin // 等待kthreadd启动 3341496ba7bSLoGin spin_loop() 3351496ba7bSLoGin } 3361496ba7bSLoGin KTHREAD_CREATE_LIST.lock().push_back(info.clone()); 3371496ba7bSLoGin ProcessManager::wakeup(unsafe { KTHREAD_DAEMON_PCB.as_ref().unwrap() }) 3381496ba7bSLoGin .expect("Failed to wakeup kthread daemon"); 3391496ba7bSLoGin return info.poll_result(); 3401496ba7bSLoGin } 3411496ba7bSLoGin 3421496ba7bSLoGin /// 创建并运行一个新的内核线程 3431496ba7bSLoGin /// 3441496ba7bSLoGin /// ## 参数 3451496ba7bSLoGin /// 3461496ba7bSLoGin /// - func: 内核线程的入口函数、传入参数 3471496ba7bSLoGin /// - name: 内核线程的名字 3481496ba7bSLoGin /// 3491496ba7bSLoGin /// ## 返回值 3501496ba7bSLoGin /// 3511496ba7bSLoGin /// - Some(Arc<ProcessControlBlock>) 创建成功,返回新创建的内核线程的PCB 3521496ba7bSLoGin #[allow(dead_code)] 3531496ba7bSLoGin pub fn create_and_run( 3541496ba7bSLoGin func: KernelThreadClosure, 3551496ba7bSLoGin name: String, 3561496ba7bSLoGin ) -> Option<Arc<ProcessControlBlock>> { 3571496ba7bSLoGin let pcb = Self::create(func, name)?; 3581496ba7bSLoGin ProcessManager::wakeup(&pcb) 359*b5b571e0SLoGin .unwrap_or_else(|_| panic!("Failed to wakeup kthread: {:?}", pcb.pid())); 3601496ba7bSLoGin return Some(pcb); 3611496ba7bSLoGin } 3621496ba7bSLoGin 3631496ba7bSLoGin /// 停止一个内核线程 3641496ba7bSLoGin /// 3651496ba7bSLoGin /// 如果目标内核线程的数据检查失败,会panic 3661496ba7bSLoGin /// 3671496ba7bSLoGin /// ## 返回值 3681496ba7bSLoGin /// 3691496ba7bSLoGin /// - Ok(i32) 目标内核线程的退出码 3701496ba7bSLoGin #[allow(dead_code)] 3711496ba7bSLoGin pub fn stop(pcb: &Arc<ProcessControlBlock>) -> Result<usize, SystemError> { 3721496ba7bSLoGin if !pcb.flags().contains(ProcessFlags::KTHREAD) { 3731496ba7bSLoGin panic!("Cannt stop a non-kthread process"); 3741496ba7bSLoGin } 3751496ba7bSLoGin 3761496ba7bSLoGin let mut worker_private = pcb.worker_private(); 3771496ba7bSLoGin assert!( 3781496ba7bSLoGin worker_private.is_some(), 3791496ba7bSLoGin "kthread stop: worker_private is none, pid: {:?}", 3801496ba7bSLoGin pcb.pid() 3811496ba7bSLoGin ); 3821496ba7bSLoGin worker_private 3831496ba7bSLoGin .as_mut() 3841496ba7bSLoGin .unwrap() 3851496ba7bSLoGin .kernel_thread_mut() 3861496ba7bSLoGin .expect("Error type of worker private") 3871496ba7bSLoGin .flags 3881496ba7bSLoGin .insert(KernelThreadFlags::SHOULD_STOP); 3891496ba7bSLoGin 3901496ba7bSLoGin drop(worker_private); 3911496ba7bSLoGin 3921496ba7bSLoGin ProcessManager::wakeup(pcb).ok(); 3931496ba7bSLoGin 3941496ba7bSLoGin // 忙等目标内核线程退出 3951496ba7bSLoGin // todo: 使用completion机制优化这里 3961496ba7bSLoGin loop { 3970d6cf65aSLoGin if let ProcessState::Exited(code) = pcb.sched_info().inner_lock_read_irqsave().state() { 3981496ba7bSLoGin return Ok(code); 3991496ba7bSLoGin } 4001496ba7bSLoGin spin_loop(); 4011496ba7bSLoGin } 4021496ba7bSLoGin } 4031496ba7bSLoGin 4041496ba7bSLoGin /// 判断一个内核线程是否应当停止 4051496ba7bSLoGin /// 4061496ba7bSLoGin /// ## 参数 4071496ba7bSLoGin /// 4081496ba7bSLoGin /// - pcb: 目标内核线程的PCB 4091496ba7bSLoGin /// 4101496ba7bSLoGin /// ## 返回值 4111496ba7bSLoGin /// 4121496ba7bSLoGin /// - bool 是否应当停止. true表示应当停止,false表示不应当停止. 如果目标进程不是内核线程,返回false 4131496ba7bSLoGin /// 4141496ba7bSLoGin /// ## Panic 4151496ba7bSLoGin /// 4161496ba7bSLoGin /// 如果目标内核线程的数据检查失败,会panic 4171496ba7bSLoGin #[allow(dead_code)] 4181496ba7bSLoGin pub fn should_stop(pcb: &Arc<ProcessControlBlock>) -> bool { 4191496ba7bSLoGin if !pcb.flags().contains(ProcessFlags::KTHREAD) { 4201496ba7bSLoGin return false; 4211496ba7bSLoGin } 4221496ba7bSLoGin 4231496ba7bSLoGin let worker_private = pcb.worker_private(); 4241496ba7bSLoGin assert!( 4251496ba7bSLoGin worker_private.is_some(), 4261496ba7bSLoGin "kthread should_stop: worker_private is none, pid: {:?}", 4271496ba7bSLoGin pcb.pid() 4281496ba7bSLoGin ); 4291496ba7bSLoGin return worker_private 4301496ba7bSLoGin .as_ref() 4311496ba7bSLoGin .unwrap() 4321496ba7bSLoGin .kernel_thread() 4331496ba7bSLoGin .expect("Error type of worker private") 4341496ba7bSLoGin .flags 4351496ba7bSLoGin .contains(KernelThreadFlags::SHOULD_STOP); 4361496ba7bSLoGin } 4371496ba7bSLoGin 4381496ba7bSLoGin /// A daemon thread which creates other kernel threads 43959fdb447SLoGin #[inline(never)] 4401496ba7bSLoGin fn kthread_daemon() -> i32 { 4411496ba7bSLoGin let current_pcb = ProcessManager::current_pcb(); 4421496ba7bSLoGin kdebug!("kthread_daemon: pid: {:?}", current_pcb.pid()); 4431496ba7bSLoGin { 4441496ba7bSLoGin // 初始化worker_private 4451496ba7bSLoGin let mut worker_private_guard = current_pcb.worker_private(); 4461496ba7bSLoGin let worker_private = WorkerPrivate::KernelThread(KernelThreadPcbPrivate::new()); 4471496ba7bSLoGin *worker_private_guard = Some(worker_private); 4481496ba7bSLoGin } 4491496ba7bSLoGin // 设置为kthread 4501496ba7bSLoGin current_pcb.flags().insert(ProcessFlags::KTHREAD); 4511496ba7bSLoGin drop(current_pcb); 4521496ba7bSLoGin 4531496ba7bSLoGin loop { 4541496ba7bSLoGin let mut list = KTHREAD_CREATE_LIST.lock(); 4551496ba7bSLoGin while let Some(info) = list.pop_front() { 4561496ba7bSLoGin drop(list); 4571496ba7bSLoGin 4581496ba7bSLoGin // create a new kernel thread 45959fdb447SLoGin let result: Result<Pid, SystemError> = Self::__inner_create( 46059fdb447SLoGin &info, 46159fdb447SLoGin CloneFlags::CLONE_VM | CloneFlags::CLONE_FS | CloneFlags::CLONE_SIGNAL, 46259fdb447SLoGin ); 4631496ba7bSLoGin if result.is_err() { 4641496ba7bSLoGin // 创建失败 4651496ba7bSLoGin info.created 4661496ba7bSLoGin .store(KernelThreadCreateStatus::ErrorOccured, Ordering::SeqCst); 4671496ba7bSLoGin }; 4681496ba7bSLoGin list = KTHREAD_CREATE_LIST.lock(); 4691496ba7bSLoGin } 4701496ba7bSLoGin drop(list); 4711496ba7bSLoGin 4721496ba7bSLoGin let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() }; 4731496ba7bSLoGin ProcessManager::mark_sleep(true).ok(); 4741496ba7bSLoGin drop(irq_guard); 4751496ba7bSLoGin sched(); 4761496ba7bSLoGin } 4771496ba7bSLoGin } 4781496ba7bSLoGin } 4791496ba7bSLoGin 4801496ba7bSLoGin /// 内核线程启动的第二阶段 4811496ba7bSLoGin /// 4821496ba7bSLoGin /// 该函数只能被`kernel_thread_bootstrap_stage1`调用(jmp到该函数) 4831496ba7bSLoGin /// 4841496ba7bSLoGin /// ## 参数 4851496ba7bSLoGin /// 4861496ba7bSLoGin /// - ptr: 传入的参数,是一个指向`Arc<KernelThreadCreateInfo>`的指针 4871496ba7bSLoGin pub unsafe extern "C" fn kernel_thread_bootstrap_stage2(ptr: *const KernelThreadCreateInfo) -> ! { 4881496ba7bSLoGin let info = KernelThreadCreateInfo::parse_unsafe_arc_ptr(ptr); 4891496ba7bSLoGin 4901496ba7bSLoGin let closure: Box<KernelThreadClosure> = info.take_closure().unwrap(); 4911496ba7bSLoGin info.set_create_ok(ProcessManager::current_pcb()); 492de71ec25SLoGin let to_mark_sleep = info.to_mark_sleep(); 4931496ba7bSLoGin drop(info); 4941496ba7bSLoGin 495de71ec25SLoGin if to_mark_sleep { 496de71ec25SLoGin // 进入睡眠状态 4971496ba7bSLoGin let irq_guard = CurrentIrqArch::save_and_disable_irq(); 4981496ba7bSLoGin ProcessManager::mark_sleep(true).expect("Failed to mark sleep"); 4991496ba7bSLoGin drop(irq_guard); 500de71ec25SLoGin sched(); 501de71ec25SLoGin } 5021496ba7bSLoGin 5031496ba7bSLoGin let mut retval = SystemError::EINTR.to_posix_errno(); 5041496ba7bSLoGin 5051496ba7bSLoGin if !KernelThreadMechanism::should_stop(&ProcessManager::current_pcb()) { 5061496ba7bSLoGin retval = closure.run(); 5071496ba7bSLoGin } 5081496ba7bSLoGin 5091496ba7bSLoGin ProcessManager::exit(retval as usize); 5101496ba7bSLoGin } 5111496ba7bSLoGin 5125b59005fSLoGin /// 初始化内核线程机制 5135b59005fSLoGin #[inline(never)] 5141496ba7bSLoGin pub fn kthread_init() { 5151496ba7bSLoGin static INIT: Once = Once::new(); 5161496ba7bSLoGin INIT.call_once(|| { 5171496ba7bSLoGin KernelThreadMechanism::init_stage1(); 5181496ba7bSLoGin }); 5191496ba7bSLoGin } 520