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}, 171496ba7bSLoGin exception::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)] 881496ba7bSLoGin pub enum KernelThreadClosure { 891496ba7bSLoGin UsizeClosure((Box<dyn Fn(usize) -> i32 + Send + Sync>, usize)), 901496ba7bSLoGin EmptyClosure((Box<dyn Fn() -> i32 + Send + Sync>, ())), 911496ba7bSLoGin // 添加其他类型入参的闭包,返回值必须是i32 921496ba7bSLoGin } 931496ba7bSLoGin 941496ba7bSLoGin impl KernelThreadClosure { 951496ba7bSLoGin pub fn run(self) -> i32 { 961496ba7bSLoGin match self { 971496ba7bSLoGin Self::UsizeClosure((func, arg)) => func(arg), 981496ba7bSLoGin Self::EmptyClosure((func, _arg)) => func(), 991496ba7bSLoGin } 1001496ba7bSLoGin } 1011496ba7bSLoGin } 1021496ba7bSLoGin 1031496ba7bSLoGin pub struct KernelThreadCreateInfo { 1041496ba7bSLoGin /// 内核线程的入口函数、传入参数 1051496ba7bSLoGin closure: SpinLock<Option<Box<KernelThreadClosure>>>, 1061496ba7bSLoGin /// 内核线程的名字 1071496ba7bSLoGin name: String, 1081496ba7bSLoGin /// 是否已经完成创建 todo:使用comletion机制优化这里 1091496ba7bSLoGin created: AtomicKernelThreadCreateStatus, 1101496ba7bSLoGin result_pcb: SpinLock<Option<Arc<ProcessControlBlock>>>, 1111496ba7bSLoGin /// 不安全的Arc引用计数,当内核线程创建失败时,需要减少这个计数 1121496ba7bSLoGin has_unsafe_arc_instance: AtomicBool, 1131496ba7bSLoGin self_ref: Weak<Self>, 114de71ec25SLoGin /// 如果该值为true在进入bootstrap stage2之后,就会进入睡眠状态 115de71ec25SLoGin to_mark_sleep: AtomicBool, 1161496ba7bSLoGin } 1171496ba7bSLoGin 1181496ba7bSLoGin #[atomic_enum] 1191496ba7bSLoGin #[derive(PartialEq)] 1201496ba7bSLoGin pub enum KernelThreadCreateStatus { 1211496ba7bSLoGin Created, 1221496ba7bSLoGin NotCreated, 1231496ba7bSLoGin ErrorOccured, 1241496ba7bSLoGin } 1251496ba7bSLoGin 1261496ba7bSLoGin #[allow(dead_code)] 1271496ba7bSLoGin impl KernelThreadCreateInfo { 1281496ba7bSLoGin pub fn new(func: KernelThreadClosure, name: String) -> Arc<Self> { 1291496ba7bSLoGin let result = Arc::new(Self { 1301496ba7bSLoGin closure: SpinLock::new(Some(Box::new(func))), 1311496ba7bSLoGin name, 1321496ba7bSLoGin created: AtomicKernelThreadCreateStatus::new(KernelThreadCreateStatus::NotCreated), 1331496ba7bSLoGin result_pcb: SpinLock::new(None), 1341496ba7bSLoGin has_unsafe_arc_instance: AtomicBool::new(false), 1351496ba7bSLoGin self_ref: Weak::new(), 136de71ec25SLoGin to_mark_sleep: AtomicBool::new(true), 1371496ba7bSLoGin }); 1381496ba7bSLoGin let tmp = result.clone(); 1391496ba7bSLoGin unsafe { 1401496ba7bSLoGin let tmp = Arc::into_raw(tmp) as *mut Self; 1411496ba7bSLoGin (*tmp).self_ref = Arc::downgrade(&result); 1421496ba7bSLoGin Arc::from_raw(tmp); 1431496ba7bSLoGin } 1441496ba7bSLoGin 1451496ba7bSLoGin return result; 1461496ba7bSLoGin } 1471496ba7bSLoGin 1481496ba7bSLoGin /// 创建者调用这函数,等待创建完成后,获取创建结果 1491496ba7bSLoGin /// 1501496ba7bSLoGin /// ## 返回值 1511496ba7bSLoGin /// 1521496ba7bSLoGin /// - Some(Arc<ProcessControlBlock>) 创建成功,返回新创建的内核线程的PCB 1531496ba7bSLoGin /// - None 创建失败 1541496ba7bSLoGin pub fn poll_result(&self) -> Option<Arc<ProcessControlBlock>> { 1551496ba7bSLoGin loop { 1561496ba7bSLoGin match self.created.load(Ordering::SeqCst) { 1571496ba7bSLoGin KernelThreadCreateStatus::Created => { 1581496ba7bSLoGin return self.result_pcb.lock().take(); 1591496ba7bSLoGin } 1601496ba7bSLoGin KernelThreadCreateStatus::NotCreated => { 1611496ba7bSLoGin spin_loop(); 1621496ba7bSLoGin } 1631496ba7bSLoGin KernelThreadCreateStatus::ErrorOccured => { 1641496ba7bSLoGin // 创建失败,减少不安全的Arc引用计数 1651496ba7bSLoGin let to_delete = self.has_unsafe_arc_instance.swap(false, Ordering::SeqCst); 1661496ba7bSLoGin if to_delete { 1671496ba7bSLoGin let self_ref = self.self_ref.upgrade().unwrap(); 1681496ba7bSLoGin unsafe { Arc::decrement_strong_count(&self_ref) }; 1691496ba7bSLoGin } 1701496ba7bSLoGin return None; 1711496ba7bSLoGin } 1721496ba7bSLoGin } 1731496ba7bSLoGin } 1741496ba7bSLoGin } 1751496ba7bSLoGin 1761496ba7bSLoGin pub fn take_closure(&self) -> Option<Box<KernelThreadClosure>> { 1771496ba7bSLoGin return self.closure.lock().take(); 1781496ba7bSLoGin } 1791496ba7bSLoGin 1801496ba7bSLoGin pub fn name(&self) -> &String { 1811496ba7bSLoGin &self.name 1821496ba7bSLoGin } 1831496ba7bSLoGin 1841496ba7bSLoGin pub unsafe fn set_create_ok(&self, pcb: Arc<ProcessControlBlock>) { 1851496ba7bSLoGin // todo: 使用completion机制优化这里 1861496ba7bSLoGin self.result_pcb.lock().replace(pcb); 1871496ba7bSLoGin self.created 1881496ba7bSLoGin .store(KernelThreadCreateStatus::Created, Ordering::SeqCst); 1891496ba7bSLoGin } 1901496ba7bSLoGin 1911496ba7bSLoGin /// 生成一个不安全的Arc指针(用于创建内核线程时传递参数) 1921496ba7bSLoGin pub fn generate_unsafe_arc_ptr(self: Arc<Self>) -> *const Self { 1931496ba7bSLoGin assert!( 1941496ba7bSLoGin self.has_unsafe_arc_instance 1951496ba7bSLoGin .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) 1961496ba7bSLoGin .is_ok(), 1971496ba7bSLoGin "Cannot generate unsafe arc ptr when there is already one." 1981496ba7bSLoGin ); 1991496ba7bSLoGin let ptr = Arc::into_raw(self); 2001496ba7bSLoGin return ptr; 2011496ba7bSLoGin } 2021496ba7bSLoGin 2031496ba7bSLoGin pub unsafe fn parse_unsafe_arc_ptr(ptr: *const Self) -> Arc<Self> { 2041496ba7bSLoGin let arc = Arc::from_raw(ptr); 2051496ba7bSLoGin assert!( 2061496ba7bSLoGin arc.has_unsafe_arc_instance 2071496ba7bSLoGin .compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst) 2081496ba7bSLoGin .is_ok(), 2091496ba7bSLoGin "Cannot parse unsafe arc ptr when there is no one." 2101496ba7bSLoGin ); 2111496ba7bSLoGin assert!(Arc::strong_count(&arc) > 0); 2121496ba7bSLoGin return arc; 2131496ba7bSLoGin } 214de71ec25SLoGin 215de71ec25SLoGin /// 设置是否在进入bootstrap stage2之后,就进入睡眠状态 216de71ec25SLoGin /// 217de71ec25SLoGin /// ## 参数 218de71ec25SLoGin /// 219de71ec25SLoGin /// - to_mark_sleep: 是否在进入bootstrap stage2之后,就进入睡眠状态 220de71ec25SLoGin /// 221de71ec25SLoGin /// ## 返回值 222de71ec25SLoGin /// 如果已经创建完成,返回EINVAL 223de71ec25SLoGin pub fn set_to_mark_sleep(&self, to_mark_sleep: bool) -> Result<(), SystemError> { 224de71ec25SLoGin let result_guard = self.result_pcb.lock(); 225de71ec25SLoGin if result_guard.is_some() { 226de71ec25SLoGin // 已经创建完成,不需要设置 227de71ec25SLoGin return Err(SystemError::EINVAL); 228de71ec25SLoGin } 229de71ec25SLoGin self.to_mark_sleep.store(to_mark_sleep, Ordering::SeqCst); 230de71ec25SLoGin return Ok(()); 231de71ec25SLoGin } 232de71ec25SLoGin 233de71ec25SLoGin pub fn to_mark_sleep(&self) -> bool { 234de71ec25SLoGin self.to_mark_sleep.load(Ordering::SeqCst) 235de71ec25SLoGin } 2361496ba7bSLoGin } 2371496ba7bSLoGin 2381496ba7bSLoGin pub struct KernelThreadMechanism; 2391496ba7bSLoGin 2401496ba7bSLoGin impl KernelThreadMechanism { 2411496ba7bSLoGin pub fn init_stage1() { 242de71ec25SLoGin assert!(ProcessManager::current_pcb().pid() == Pid::new(0)); 2431496ba7bSLoGin kinfo!("Initializing kernel thread mechanism stage1..."); 2441496ba7bSLoGin 2451496ba7bSLoGin // 初始化第一个内核线程 2461496ba7bSLoGin 2471496ba7bSLoGin let create_info = KernelThreadCreateInfo::new( 2481496ba7bSLoGin KernelThreadClosure::EmptyClosure((Box::new(initial_kernel_thread), ())), 2491496ba7bSLoGin "init".to_string(), 2501496ba7bSLoGin ); 2514fda81ceSLoGin 2524fda81ceSLoGin let irq_guard: crate::exception::IrqFlagsGuard = 2534fda81ceSLoGin unsafe { CurrentIrqArch::save_and_disable_irq() }; 2541496ba7bSLoGin // 由于当前是pid=0的idle进程,而__inner_create要求当前是kthread,所以先临时设置为kthread 2551496ba7bSLoGin ProcessManager::current_pcb() 2561496ba7bSLoGin .flags 25770a4e555SLoGin .get_mut() 2581496ba7bSLoGin .insert(ProcessFlags::KTHREAD); 259de71ec25SLoGin create_info 260de71ec25SLoGin .set_to_mark_sleep(false) 261de71ec25SLoGin .expect("Failed to set to_mark_sleep"); 2624fda81ceSLoGin 2631496ba7bSLoGin KernelThreadMechanism::__inner_create( 2641496ba7bSLoGin &create_info, 2651496ba7bSLoGin CloneFlags::CLONE_VM | CloneFlags::CLONE_SIGNAL, 2661496ba7bSLoGin ) 2671496ba7bSLoGin .unwrap_or_else(|e| panic!("Failed to create initial kernel thread, error: {:?}", e)); 2681496ba7bSLoGin 2691496ba7bSLoGin ProcessManager::current_pcb() 2701496ba7bSLoGin .flags 27170a4e555SLoGin .get_mut() 2721496ba7bSLoGin .remove(ProcessFlags::KTHREAD); 2734fda81ceSLoGin 2741496ba7bSLoGin drop(irq_guard); 2751496ba7bSLoGin kinfo!("Initializing kernel thread mechanism stage1 complete"); 2761496ba7bSLoGin } 2771496ba7bSLoGin 2781496ba7bSLoGin pub fn init_stage2() { 2791496ba7bSLoGin assert!(ProcessManager::current_pcb() 2801496ba7bSLoGin .flags() 2811496ba7bSLoGin .contains(ProcessFlags::KTHREAD)); 2821496ba7bSLoGin static INIT: Once = Once::new(); 2831496ba7bSLoGin INIT.call_once(|| { 2841496ba7bSLoGin kinfo!("Initializing kernel thread mechanism stage2..."); 2851496ba7bSLoGin // 初始化kthreadd 2861496ba7bSLoGin let closure = KernelThreadClosure::EmptyClosure((Box::new(Self::kthread_daemon), ())); 2871496ba7bSLoGin let info = KernelThreadCreateInfo::new(closure, "kthreadd".to_string()); 288971462beSGnoCiYeH let kthreadd_pid: Pid = Self::__inner_create( 289971462beSGnoCiYeH &info, 290971462beSGnoCiYeH CloneFlags::CLONE_VM | CloneFlags::CLONE_FS | CloneFlags::CLONE_SIGNAL, 291971462beSGnoCiYeH ) 2921496ba7bSLoGin .expect("Failed to create kthread daemon"); 2931496ba7bSLoGin let pcb = ProcessManager::find(kthreadd_pid).unwrap(); 294de71ec25SLoGin ProcessManager::wakeup(&pcb).expect("Failed to wakeup kthread daemon"); 2951496ba7bSLoGin unsafe { 2961496ba7bSLoGin KTHREAD_DAEMON_PCB.replace(pcb); 2971496ba7bSLoGin } 2981496ba7bSLoGin kinfo!("Initializing kernel thread mechanism stage2 complete"); 2991496ba7bSLoGin }); 3001496ba7bSLoGin } 3011496ba7bSLoGin 3021496ba7bSLoGin /// 创建一个新的内核线程 3031496ba7bSLoGin /// 3041496ba7bSLoGin /// ## 参数 3051496ba7bSLoGin /// 3061496ba7bSLoGin /// - func: 内核线程的入口函数、传入参数 3071496ba7bSLoGin /// - name: 内核线程的名字 3081496ba7bSLoGin /// 3091496ba7bSLoGin /// ## 返回值 3101496ba7bSLoGin /// 3111496ba7bSLoGin /// - Some(Arc<ProcessControlBlock>) 创建成功,返回新创建的内核线程的PCB 3121496ba7bSLoGin #[allow(dead_code)] 3131496ba7bSLoGin pub fn create(func: KernelThreadClosure, name: String) -> Option<Arc<ProcessControlBlock>> { 3141496ba7bSLoGin let info = KernelThreadCreateInfo::new(func, name); 3151496ba7bSLoGin while unsafe { KTHREAD_DAEMON_PCB.is_none() } { 3161496ba7bSLoGin // 等待kthreadd启动 3171496ba7bSLoGin spin_loop() 3181496ba7bSLoGin } 3191496ba7bSLoGin KTHREAD_CREATE_LIST.lock().push_back(info.clone()); 3201496ba7bSLoGin ProcessManager::wakeup(unsafe { KTHREAD_DAEMON_PCB.as_ref().unwrap() }) 3211496ba7bSLoGin .expect("Failed to wakeup kthread daemon"); 3221496ba7bSLoGin return info.poll_result(); 3231496ba7bSLoGin } 3241496ba7bSLoGin 3251496ba7bSLoGin /// 创建并运行一个新的内核线程 3261496ba7bSLoGin /// 3271496ba7bSLoGin /// ## 参数 3281496ba7bSLoGin /// 3291496ba7bSLoGin /// - func: 内核线程的入口函数、传入参数 3301496ba7bSLoGin /// - name: 内核线程的名字 3311496ba7bSLoGin /// 3321496ba7bSLoGin /// ## 返回值 3331496ba7bSLoGin /// 3341496ba7bSLoGin /// - Some(Arc<ProcessControlBlock>) 创建成功,返回新创建的内核线程的PCB 3351496ba7bSLoGin #[allow(dead_code)] 3361496ba7bSLoGin pub fn create_and_run( 3371496ba7bSLoGin func: KernelThreadClosure, 3381496ba7bSLoGin name: String, 3391496ba7bSLoGin ) -> Option<Arc<ProcessControlBlock>> { 3401496ba7bSLoGin let pcb = Self::create(func, name)?; 3411496ba7bSLoGin ProcessManager::wakeup(&pcb) 3421496ba7bSLoGin .expect(format!("Failed to wakeup kthread: {:?}", pcb.pid()).as_str()); 3431496ba7bSLoGin return Some(pcb); 3441496ba7bSLoGin } 3451496ba7bSLoGin 3461496ba7bSLoGin /// 停止一个内核线程 3471496ba7bSLoGin /// 3481496ba7bSLoGin /// 如果目标内核线程的数据检查失败,会panic 3491496ba7bSLoGin /// 3501496ba7bSLoGin /// ## 返回值 3511496ba7bSLoGin /// 3521496ba7bSLoGin /// - Ok(i32) 目标内核线程的退出码 3531496ba7bSLoGin #[allow(dead_code)] 3541496ba7bSLoGin pub fn stop(pcb: &Arc<ProcessControlBlock>) -> Result<usize, SystemError> { 3551496ba7bSLoGin if !pcb.flags().contains(ProcessFlags::KTHREAD) { 3561496ba7bSLoGin panic!("Cannt stop a non-kthread process"); 3571496ba7bSLoGin } 3581496ba7bSLoGin 3591496ba7bSLoGin let mut worker_private = pcb.worker_private(); 3601496ba7bSLoGin assert!( 3611496ba7bSLoGin worker_private.is_some(), 3621496ba7bSLoGin "kthread stop: worker_private is none, pid: {:?}", 3631496ba7bSLoGin pcb.pid() 3641496ba7bSLoGin ); 3651496ba7bSLoGin worker_private 3661496ba7bSLoGin .as_mut() 3671496ba7bSLoGin .unwrap() 3681496ba7bSLoGin .kernel_thread_mut() 3691496ba7bSLoGin .expect("Error type of worker private") 3701496ba7bSLoGin .flags 3711496ba7bSLoGin .insert(KernelThreadFlags::SHOULD_STOP); 3721496ba7bSLoGin 3731496ba7bSLoGin drop(worker_private); 3741496ba7bSLoGin 3751496ba7bSLoGin ProcessManager::wakeup(pcb).ok(); 3761496ba7bSLoGin 3771496ba7bSLoGin // 忙等目标内核线程退出 3781496ba7bSLoGin // todo: 使用completion机制优化这里 3791496ba7bSLoGin loop { 3800d6cf65aSLoGin if let ProcessState::Exited(code) = pcb.sched_info().inner_lock_read_irqsave().state() { 3811496ba7bSLoGin return Ok(code); 3821496ba7bSLoGin } 3831496ba7bSLoGin spin_loop(); 3841496ba7bSLoGin } 3851496ba7bSLoGin } 3861496ba7bSLoGin 3871496ba7bSLoGin /// 判断一个内核线程是否应当停止 3881496ba7bSLoGin /// 3891496ba7bSLoGin /// ## 参数 3901496ba7bSLoGin /// 3911496ba7bSLoGin /// - pcb: 目标内核线程的PCB 3921496ba7bSLoGin /// 3931496ba7bSLoGin /// ## 返回值 3941496ba7bSLoGin /// 3951496ba7bSLoGin /// - bool 是否应当停止. true表示应当停止,false表示不应当停止. 如果目标进程不是内核线程,返回false 3961496ba7bSLoGin /// 3971496ba7bSLoGin /// ## Panic 3981496ba7bSLoGin /// 3991496ba7bSLoGin /// 如果目标内核线程的数据检查失败,会panic 4001496ba7bSLoGin #[allow(dead_code)] 4011496ba7bSLoGin pub fn should_stop(pcb: &Arc<ProcessControlBlock>) -> bool { 4021496ba7bSLoGin if !pcb.flags().contains(ProcessFlags::KTHREAD) { 4031496ba7bSLoGin return false; 4041496ba7bSLoGin } 4051496ba7bSLoGin 4061496ba7bSLoGin let worker_private = pcb.worker_private(); 4071496ba7bSLoGin assert!( 4081496ba7bSLoGin worker_private.is_some(), 4091496ba7bSLoGin "kthread should_stop: worker_private is none, pid: {:?}", 4101496ba7bSLoGin pcb.pid() 4111496ba7bSLoGin ); 4121496ba7bSLoGin return worker_private 4131496ba7bSLoGin .as_ref() 4141496ba7bSLoGin .unwrap() 4151496ba7bSLoGin .kernel_thread() 4161496ba7bSLoGin .expect("Error type of worker private") 4171496ba7bSLoGin .flags 4181496ba7bSLoGin .contains(KernelThreadFlags::SHOULD_STOP); 4191496ba7bSLoGin } 4201496ba7bSLoGin 4211496ba7bSLoGin /// A daemon thread which creates other kernel threads 4221496ba7bSLoGin fn kthread_daemon() -> i32 { 4231496ba7bSLoGin let current_pcb = ProcessManager::current_pcb(); 4241496ba7bSLoGin kdebug!("kthread_daemon: pid: {:?}", current_pcb.pid()); 4251496ba7bSLoGin { 4261496ba7bSLoGin // 初始化worker_private 4271496ba7bSLoGin let mut worker_private_guard = current_pcb.worker_private(); 4281496ba7bSLoGin let worker_private = WorkerPrivate::KernelThread(KernelThreadPcbPrivate::new()); 4291496ba7bSLoGin *worker_private_guard = Some(worker_private); 4301496ba7bSLoGin } 4311496ba7bSLoGin // 设置为kthread 4321496ba7bSLoGin current_pcb.flags().insert(ProcessFlags::KTHREAD); 4331496ba7bSLoGin drop(current_pcb); 4341496ba7bSLoGin 4351496ba7bSLoGin loop { 4361496ba7bSLoGin let mut list = KTHREAD_CREATE_LIST.lock(); 4371496ba7bSLoGin while let Some(info) = list.pop_front() { 4381496ba7bSLoGin drop(list); 4391496ba7bSLoGin 4401496ba7bSLoGin // create a new kernel thread 4411496ba7bSLoGin let result: Result<Pid, SystemError> = 4421496ba7bSLoGin Self::__inner_create(&info, CloneFlags::CLONE_FS | CloneFlags::CLONE_SIGNAL); 4431496ba7bSLoGin 4441496ba7bSLoGin if result.is_err() { 4451496ba7bSLoGin // 创建失败 4461496ba7bSLoGin info.created 4471496ba7bSLoGin .store(KernelThreadCreateStatus::ErrorOccured, Ordering::SeqCst); 4481496ba7bSLoGin }; 4491496ba7bSLoGin list = KTHREAD_CREATE_LIST.lock(); 4501496ba7bSLoGin } 4511496ba7bSLoGin drop(list); 4521496ba7bSLoGin 4531496ba7bSLoGin let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() }; 4541496ba7bSLoGin ProcessManager::mark_sleep(true).ok(); 4551496ba7bSLoGin drop(irq_guard); 4561496ba7bSLoGin sched(); 4571496ba7bSLoGin } 4581496ba7bSLoGin } 4591496ba7bSLoGin } 4601496ba7bSLoGin 4611496ba7bSLoGin /// 内核线程启动的第二阶段 4621496ba7bSLoGin /// 4631496ba7bSLoGin /// 该函数只能被`kernel_thread_bootstrap_stage1`调用(jmp到该函数) 4641496ba7bSLoGin /// 4651496ba7bSLoGin /// ## 参数 4661496ba7bSLoGin /// 4671496ba7bSLoGin /// - ptr: 传入的参数,是一个指向`Arc<KernelThreadCreateInfo>`的指针 4681496ba7bSLoGin pub unsafe extern "C" fn kernel_thread_bootstrap_stage2(ptr: *const KernelThreadCreateInfo) -> ! { 4691496ba7bSLoGin let info = KernelThreadCreateInfo::parse_unsafe_arc_ptr(ptr); 4701496ba7bSLoGin 4711496ba7bSLoGin let closure: Box<KernelThreadClosure> = info.take_closure().unwrap(); 4721496ba7bSLoGin info.set_create_ok(ProcessManager::current_pcb()); 473de71ec25SLoGin let to_mark_sleep = info.to_mark_sleep(); 4741496ba7bSLoGin drop(info); 4751496ba7bSLoGin 476de71ec25SLoGin if to_mark_sleep { 477de71ec25SLoGin // 进入睡眠状态 4781496ba7bSLoGin let irq_guard = CurrentIrqArch::save_and_disable_irq(); 4791496ba7bSLoGin ProcessManager::mark_sleep(true).expect("Failed to mark sleep"); 4801496ba7bSLoGin drop(irq_guard); 481de71ec25SLoGin sched(); 482de71ec25SLoGin } 4831496ba7bSLoGin 4841496ba7bSLoGin let mut retval = SystemError::EINTR.to_posix_errno(); 4851496ba7bSLoGin 4861496ba7bSLoGin if !KernelThreadMechanism::should_stop(&ProcessManager::current_pcb()) { 4871496ba7bSLoGin retval = closure.run(); 4881496ba7bSLoGin } 4891496ba7bSLoGin 4901496ba7bSLoGin ProcessManager::exit(retval as usize); 4911496ba7bSLoGin } 4921496ba7bSLoGin 493*5b59005fSLoGin /// 初始化内核线程机制 494*5b59005fSLoGin #[inline(never)] 4951496ba7bSLoGin pub fn kthread_init() { 4961496ba7bSLoGin static INIT: Once = Once::new(); 4971496ba7bSLoGin INIT.call_once(|| { 4981496ba7bSLoGin KernelThreadMechanism::init_stage1(); 4991496ba7bSLoGin }); 5001496ba7bSLoGin } 501