xref: /DragonOS/kernel/src/process/kthread.rs (revision 4fda81ce81939d83b74c8042d6fb4223deff3685)
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;
131496ba7bSLoGin 
141496ba7bSLoGin use crate::{
151496ba7bSLoGin     arch::{sched::sched, CurrentIrqArch},
161496ba7bSLoGin     exception::InterruptArch,
171496ba7bSLoGin     kdebug, kinfo,
181496ba7bSLoGin     libs::{once::Once, spinlock::SpinLock},
191496ba7bSLoGin     process::{ProcessManager, ProcessState},
201496ba7bSLoGin     syscall::SystemError,
211496ba7bSLoGin };
221496ba7bSLoGin 
231496ba7bSLoGin use super::{
241496ba7bSLoGin     fork::CloneFlags, init::initial_kernel_thread, Pid, ProcessControlBlock, ProcessFlags,
251496ba7bSLoGin };
261496ba7bSLoGin 
271496ba7bSLoGin /// 内核线程的创建任务列表
281496ba7bSLoGin static KTHREAD_CREATE_LIST: SpinLock<LinkedList<Arc<KernelThreadCreateInfo>>> =
291496ba7bSLoGin     SpinLock::new(LinkedList::new());
301496ba7bSLoGin 
311496ba7bSLoGin static mut KTHREAD_DAEMON_PCB: Option<Arc<ProcessControlBlock>> = None;
321496ba7bSLoGin 
331496ba7bSLoGin #[derive(Debug)]
341496ba7bSLoGin pub enum WorkerPrivate {
351496ba7bSLoGin     KernelThread(KernelThreadPcbPrivate),
361496ba7bSLoGin }
371496ba7bSLoGin 
381496ba7bSLoGin #[allow(dead_code)]
391496ba7bSLoGin impl WorkerPrivate {
401496ba7bSLoGin     pub fn kernel_thread(&self) -> Option<&KernelThreadPcbPrivate> {
411496ba7bSLoGin         match self {
421496ba7bSLoGin             Self::KernelThread(x) => Some(x),
431496ba7bSLoGin         }
441496ba7bSLoGin     }
451496ba7bSLoGin 
461496ba7bSLoGin     pub fn kernel_thread_mut(&mut self) -> Option<&mut KernelThreadPcbPrivate> {
471496ba7bSLoGin         match self {
481496ba7bSLoGin             Self::KernelThread(x) => Some(x),
491496ba7bSLoGin         }
501496ba7bSLoGin     }
511496ba7bSLoGin }
521496ba7bSLoGin 
531496ba7bSLoGin bitflags! {
541496ba7bSLoGin     pub struct KernelThreadFlags: u32 {
551496ba7bSLoGin         const IS_PER_CPU = 1 << 0;
561496ba7bSLoGin         const SHOULD_STOP = 1 << 1;
571496ba7bSLoGin         const SHOULD_PARK = 1 << 2;
581496ba7bSLoGin     }
591496ba7bSLoGin }
601496ba7bSLoGin 
611496ba7bSLoGin #[derive(Debug)]
621496ba7bSLoGin pub struct KernelThreadPcbPrivate {
631496ba7bSLoGin     flags: KernelThreadFlags,
641496ba7bSLoGin }
651496ba7bSLoGin 
661496ba7bSLoGin #[allow(dead_code)]
671496ba7bSLoGin impl KernelThreadPcbPrivate {
681496ba7bSLoGin     pub fn new() -> Self {
691496ba7bSLoGin         Self {
701496ba7bSLoGin             flags: KernelThreadFlags::empty(),
711496ba7bSLoGin         }
721496ba7bSLoGin     }
731496ba7bSLoGin 
741496ba7bSLoGin     pub fn flags(&self) -> &KernelThreadFlags {
751496ba7bSLoGin         &self.flags
761496ba7bSLoGin     }
771496ba7bSLoGin 
781496ba7bSLoGin     pub fn flags_mut(&mut self) -> &mut KernelThreadFlags {
791496ba7bSLoGin         &mut self.flags
801496ba7bSLoGin     }
811496ba7bSLoGin }
821496ba7bSLoGin 
831496ba7bSLoGin /// 内核线程的闭包,参数必须与闭包的参数一致,返回值必须是i32
841496ba7bSLoGin ///
851496ba7bSLoGin /// 元组的第一个元素是闭包,第二个元素是闭包的参数对象
861496ba7bSLoGin ///
871496ba7bSLoGin /// 对于非原始类型的参数,需要使用Box包装
881496ba7bSLoGin #[allow(dead_code)]
891496ba7bSLoGin pub enum KernelThreadClosure {
901496ba7bSLoGin     UsizeClosure((Box<dyn Fn(usize) -> i32 + Send + Sync>, usize)),
911496ba7bSLoGin     EmptyClosure((Box<dyn Fn() -> i32 + Send + Sync>, ())),
921496ba7bSLoGin     // 添加其他类型入参的闭包,返回值必须是i32
931496ba7bSLoGin }
941496ba7bSLoGin 
951496ba7bSLoGin impl KernelThreadClosure {
961496ba7bSLoGin     pub fn run(self) -> i32 {
971496ba7bSLoGin         match self {
981496ba7bSLoGin             Self::UsizeClosure((func, arg)) => func(arg),
991496ba7bSLoGin             Self::EmptyClosure((func, _arg)) => func(),
1001496ba7bSLoGin         }
1011496ba7bSLoGin     }
1021496ba7bSLoGin }
1031496ba7bSLoGin 
1041496ba7bSLoGin pub struct KernelThreadCreateInfo {
1051496ba7bSLoGin     /// 内核线程的入口函数、传入参数
1061496ba7bSLoGin     closure: SpinLock<Option<Box<KernelThreadClosure>>>,
1071496ba7bSLoGin     /// 内核线程的名字
1081496ba7bSLoGin     name: String,
1091496ba7bSLoGin     /// 是否已经完成创建 todo:使用comletion机制优化这里
1101496ba7bSLoGin     created: AtomicKernelThreadCreateStatus,
1111496ba7bSLoGin     result_pcb: SpinLock<Option<Arc<ProcessControlBlock>>>,
1121496ba7bSLoGin     /// 不安全的Arc引用计数,当内核线程创建失败时,需要减少这个计数
1131496ba7bSLoGin     has_unsafe_arc_instance: AtomicBool,
1141496ba7bSLoGin     self_ref: Weak<Self>,
115de71ec25SLoGin     /// 如果该值为true在进入bootstrap stage2之后,就会进入睡眠状态
116de71ec25SLoGin     to_mark_sleep: AtomicBool,
1171496ba7bSLoGin }
1181496ba7bSLoGin 
1191496ba7bSLoGin #[atomic_enum]
1201496ba7bSLoGin #[derive(PartialEq)]
1211496ba7bSLoGin pub enum KernelThreadCreateStatus {
1221496ba7bSLoGin     Created,
1231496ba7bSLoGin     NotCreated,
1241496ba7bSLoGin     ErrorOccured,
1251496ba7bSLoGin }
1261496ba7bSLoGin 
1271496ba7bSLoGin #[allow(dead_code)]
1281496ba7bSLoGin impl KernelThreadCreateInfo {
1291496ba7bSLoGin     pub fn new(func: KernelThreadClosure, name: String) -> Arc<Self> {
1301496ba7bSLoGin         let result = Arc::new(Self {
1311496ba7bSLoGin             closure: SpinLock::new(Some(Box::new(func))),
1321496ba7bSLoGin             name,
1331496ba7bSLoGin             created: AtomicKernelThreadCreateStatus::new(KernelThreadCreateStatus::NotCreated),
1341496ba7bSLoGin             result_pcb: SpinLock::new(None),
1351496ba7bSLoGin             has_unsafe_arc_instance: AtomicBool::new(false),
1361496ba7bSLoGin             self_ref: Weak::new(),
137de71ec25SLoGin             to_mark_sleep: AtomicBool::new(true),
1381496ba7bSLoGin         });
1391496ba7bSLoGin         let tmp = result.clone();
1401496ba7bSLoGin         unsafe {
1411496ba7bSLoGin             let tmp = Arc::into_raw(tmp) as *mut Self;
1421496ba7bSLoGin             (*tmp).self_ref = Arc::downgrade(&result);
1431496ba7bSLoGin             Arc::from_raw(tmp);
1441496ba7bSLoGin         }
1451496ba7bSLoGin 
1461496ba7bSLoGin         return result;
1471496ba7bSLoGin     }
1481496ba7bSLoGin 
1491496ba7bSLoGin     /// 创建者调用这函数,等待创建完成后,获取创建结果
1501496ba7bSLoGin     ///
1511496ba7bSLoGin     /// ## 返回值
1521496ba7bSLoGin     ///
1531496ba7bSLoGin     /// - Some(Arc<ProcessControlBlock>) 创建成功,返回新创建的内核线程的PCB
1541496ba7bSLoGin     /// - None 创建失败
1551496ba7bSLoGin     pub fn poll_result(&self) -> Option<Arc<ProcessControlBlock>> {
1561496ba7bSLoGin         loop {
1571496ba7bSLoGin             match self.created.load(Ordering::SeqCst) {
1581496ba7bSLoGin                 KernelThreadCreateStatus::Created => {
1591496ba7bSLoGin                     return self.result_pcb.lock().take();
1601496ba7bSLoGin                 }
1611496ba7bSLoGin                 KernelThreadCreateStatus::NotCreated => {
1621496ba7bSLoGin                     spin_loop();
1631496ba7bSLoGin                 }
1641496ba7bSLoGin                 KernelThreadCreateStatus::ErrorOccured => {
1651496ba7bSLoGin                     // 创建失败,减少不安全的Arc引用计数
1661496ba7bSLoGin                     let to_delete = self.has_unsafe_arc_instance.swap(false, Ordering::SeqCst);
1671496ba7bSLoGin                     if to_delete {
1681496ba7bSLoGin                         let self_ref = self.self_ref.upgrade().unwrap();
1691496ba7bSLoGin                         unsafe { Arc::decrement_strong_count(&self_ref) };
1701496ba7bSLoGin                     }
1711496ba7bSLoGin                     return None;
1721496ba7bSLoGin                 }
1731496ba7bSLoGin             }
1741496ba7bSLoGin         }
1751496ba7bSLoGin     }
1761496ba7bSLoGin 
1771496ba7bSLoGin     pub fn take_closure(&self) -> Option<Box<KernelThreadClosure>> {
1781496ba7bSLoGin         return self.closure.lock().take();
1791496ba7bSLoGin     }
1801496ba7bSLoGin 
1811496ba7bSLoGin     pub fn name(&self) -> &String {
1821496ba7bSLoGin         &self.name
1831496ba7bSLoGin     }
1841496ba7bSLoGin 
1851496ba7bSLoGin     pub unsafe fn set_create_ok(&self, pcb: Arc<ProcessControlBlock>) {
1861496ba7bSLoGin         // todo: 使用completion机制优化这里
1871496ba7bSLoGin         self.result_pcb.lock().replace(pcb);
1881496ba7bSLoGin         self.created
1891496ba7bSLoGin             .store(KernelThreadCreateStatus::Created, Ordering::SeqCst);
1901496ba7bSLoGin     }
1911496ba7bSLoGin 
1921496ba7bSLoGin     /// 生成一个不安全的Arc指针(用于创建内核线程时传递参数)
1931496ba7bSLoGin     pub fn generate_unsafe_arc_ptr(self: Arc<Self>) -> *const Self {
1941496ba7bSLoGin         assert!(
1951496ba7bSLoGin             self.has_unsafe_arc_instance
1961496ba7bSLoGin                 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
1971496ba7bSLoGin                 .is_ok(),
1981496ba7bSLoGin             "Cannot generate unsafe arc ptr when there is already one."
1991496ba7bSLoGin         );
2001496ba7bSLoGin         let ptr = Arc::into_raw(self);
2011496ba7bSLoGin         return ptr;
2021496ba7bSLoGin     }
2031496ba7bSLoGin 
2041496ba7bSLoGin     pub unsafe fn parse_unsafe_arc_ptr(ptr: *const Self) -> Arc<Self> {
2051496ba7bSLoGin         let arc = Arc::from_raw(ptr);
2061496ba7bSLoGin         assert!(
2071496ba7bSLoGin             arc.has_unsafe_arc_instance
2081496ba7bSLoGin                 .compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst)
2091496ba7bSLoGin                 .is_ok(),
2101496ba7bSLoGin             "Cannot parse unsafe arc ptr when there is no one."
2111496ba7bSLoGin         );
2121496ba7bSLoGin         assert!(Arc::strong_count(&arc) > 0);
2131496ba7bSLoGin         return arc;
2141496ba7bSLoGin     }
215de71ec25SLoGin 
216de71ec25SLoGin     /// 设置是否在进入bootstrap stage2之后,就进入睡眠状态
217de71ec25SLoGin     ///
218de71ec25SLoGin     /// ## 参数
219de71ec25SLoGin     ///
220de71ec25SLoGin     /// - to_mark_sleep: 是否在进入bootstrap stage2之后,就进入睡眠状态
221de71ec25SLoGin     ///
222de71ec25SLoGin     /// ## 返回值
223de71ec25SLoGin     /// 如果已经创建完成,返回EINVAL
224de71ec25SLoGin     pub fn set_to_mark_sleep(&self, to_mark_sleep: bool) -> Result<(), SystemError> {
225de71ec25SLoGin         let result_guard = self.result_pcb.lock();
226de71ec25SLoGin         if result_guard.is_some() {
227de71ec25SLoGin             // 已经创建完成,不需要设置
228de71ec25SLoGin             return Err(SystemError::EINVAL);
229de71ec25SLoGin         }
230de71ec25SLoGin         self.to_mark_sleep.store(to_mark_sleep, Ordering::SeqCst);
231de71ec25SLoGin         return Ok(());
232de71ec25SLoGin     }
233de71ec25SLoGin 
234de71ec25SLoGin     pub fn to_mark_sleep(&self) -> bool {
235de71ec25SLoGin         self.to_mark_sleep.load(Ordering::SeqCst)
236de71ec25SLoGin     }
2371496ba7bSLoGin }
2381496ba7bSLoGin 
2391496ba7bSLoGin pub struct KernelThreadMechanism;
2401496ba7bSLoGin 
2411496ba7bSLoGin impl KernelThreadMechanism {
2421496ba7bSLoGin     pub fn init_stage1() {
243de71ec25SLoGin         assert!(ProcessManager::current_pcb().pid() == Pid::new(0));
2441496ba7bSLoGin         kinfo!("Initializing kernel thread mechanism stage1...");
2451496ba7bSLoGin 
2461496ba7bSLoGin         // 初始化第一个内核线程
2471496ba7bSLoGin 
2481496ba7bSLoGin         let create_info = KernelThreadCreateInfo::new(
2491496ba7bSLoGin             KernelThreadClosure::EmptyClosure((Box::new(initial_kernel_thread), ())),
2501496ba7bSLoGin             "init".to_string(),
2511496ba7bSLoGin         );
252*4fda81ceSLoGin 
253*4fda81ceSLoGin         let irq_guard: crate::exception::IrqFlagsGuard =
254*4fda81ceSLoGin             unsafe { CurrentIrqArch::save_and_disable_irq() };
2551496ba7bSLoGin         // 由于当前是pid=0的idle进程,而__inner_create要求当前是kthread,所以先临时设置为kthread
2561496ba7bSLoGin         ProcessManager::current_pcb()
2571496ba7bSLoGin             .flags
25870a4e555SLoGin             .get_mut()
2591496ba7bSLoGin             .insert(ProcessFlags::KTHREAD);
260de71ec25SLoGin         create_info
261de71ec25SLoGin             .set_to_mark_sleep(false)
262de71ec25SLoGin             .expect("Failed to set to_mark_sleep");
263*4fda81ceSLoGin 
2641496ba7bSLoGin         KernelThreadMechanism::__inner_create(
2651496ba7bSLoGin             &create_info,
2661496ba7bSLoGin             CloneFlags::CLONE_VM | CloneFlags::CLONE_SIGNAL,
2671496ba7bSLoGin         )
2681496ba7bSLoGin         .unwrap_or_else(|e| panic!("Failed to create initial kernel thread, error: {:?}", e));
2691496ba7bSLoGin 
2701496ba7bSLoGin         ProcessManager::current_pcb()
2711496ba7bSLoGin             .flags
27270a4e555SLoGin             .get_mut()
2731496ba7bSLoGin             .remove(ProcessFlags::KTHREAD);
274*4fda81ceSLoGin 
2751496ba7bSLoGin         drop(irq_guard);
2761496ba7bSLoGin         kinfo!("Initializing kernel thread mechanism stage1 complete");
2771496ba7bSLoGin     }
2781496ba7bSLoGin 
2791496ba7bSLoGin     pub fn init_stage2() {
2801496ba7bSLoGin         assert!(ProcessManager::current_pcb()
2811496ba7bSLoGin             .flags()
2821496ba7bSLoGin             .contains(ProcessFlags::KTHREAD));
2831496ba7bSLoGin         static INIT: Once = Once::new();
2841496ba7bSLoGin         INIT.call_once(|| {
2851496ba7bSLoGin             kinfo!("Initializing kernel thread mechanism stage2...");
2861496ba7bSLoGin             // 初始化kthreadd
2871496ba7bSLoGin             let closure = KernelThreadClosure::EmptyClosure((Box::new(Self::kthread_daemon), ()));
2881496ba7bSLoGin             let info = KernelThreadCreateInfo::new(closure, "kthreadd".to_string());
289971462beSGnoCiYeH             let kthreadd_pid: Pid = Self::__inner_create(
290971462beSGnoCiYeH                 &info,
291971462beSGnoCiYeH                 CloneFlags::CLONE_VM | CloneFlags::CLONE_FS | CloneFlags::CLONE_SIGNAL,
292971462beSGnoCiYeH             )
2931496ba7bSLoGin             .expect("Failed to create kthread daemon");
2941496ba7bSLoGin 
2951496ba7bSLoGin             let pcb = ProcessManager::find(kthreadd_pid).unwrap();
296de71ec25SLoGin             ProcessManager::wakeup(&pcb).expect("Failed to wakeup kthread daemon");
2971496ba7bSLoGin             unsafe {
2981496ba7bSLoGin                 KTHREAD_DAEMON_PCB.replace(pcb);
2991496ba7bSLoGin             }
3001496ba7bSLoGin             kinfo!("Initializing kernel thread mechanism stage2 complete");
3011496ba7bSLoGin         });
3021496ba7bSLoGin     }
3031496ba7bSLoGin 
3041496ba7bSLoGin     /// 创建一个新的内核线程
3051496ba7bSLoGin     ///
3061496ba7bSLoGin     /// ## 参数
3071496ba7bSLoGin     ///
3081496ba7bSLoGin     /// - func: 内核线程的入口函数、传入参数
3091496ba7bSLoGin     /// - name: 内核线程的名字
3101496ba7bSLoGin     ///
3111496ba7bSLoGin     /// ## 返回值
3121496ba7bSLoGin     ///
3131496ba7bSLoGin     /// - Some(Arc<ProcessControlBlock>) 创建成功,返回新创建的内核线程的PCB
3141496ba7bSLoGin     #[allow(dead_code)]
3151496ba7bSLoGin     pub fn create(func: KernelThreadClosure, name: String) -> Option<Arc<ProcessControlBlock>> {
3161496ba7bSLoGin         let info = KernelThreadCreateInfo::new(func, name);
3171496ba7bSLoGin         while unsafe { KTHREAD_DAEMON_PCB.is_none() } {
3181496ba7bSLoGin             // 等待kthreadd启动
3191496ba7bSLoGin             spin_loop()
3201496ba7bSLoGin         }
3211496ba7bSLoGin         KTHREAD_CREATE_LIST.lock().push_back(info.clone());
3221496ba7bSLoGin         ProcessManager::wakeup(unsafe { KTHREAD_DAEMON_PCB.as_ref().unwrap() })
3231496ba7bSLoGin             .expect("Failed to wakeup kthread daemon");
3241496ba7bSLoGin         return info.poll_result();
3251496ba7bSLoGin     }
3261496ba7bSLoGin 
3271496ba7bSLoGin     /// 创建并运行一个新的内核线程
3281496ba7bSLoGin     ///
3291496ba7bSLoGin     /// ## 参数
3301496ba7bSLoGin     ///
3311496ba7bSLoGin     /// - func: 内核线程的入口函数、传入参数
3321496ba7bSLoGin     /// - name: 内核线程的名字
3331496ba7bSLoGin     ///
3341496ba7bSLoGin     /// ## 返回值
3351496ba7bSLoGin     ///
3361496ba7bSLoGin     /// - Some(Arc<ProcessControlBlock>) 创建成功,返回新创建的内核线程的PCB
3371496ba7bSLoGin     #[allow(dead_code)]
3381496ba7bSLoGin     pub fn create_and_run(
3391496ba7bSLoGin         func: KernelThreadClosure,
3401496ba7bSLoGin         name: String,
3411496ba7bSLoGin     ) -> Option<Arc<ProcessControlBlock>> {
3421496ba7bSLoGin         let pcb = Self::create(func, name)?;
3431496ba7bSLoGin         ProcessManager::wakeup(&pcb)
3441496ba7bSLoGin             .expect(format!("Failed to wakeup kthread: {:?}", pcb.pid()).as_str());
3451496ba7bSLoGin         return Some(pcb);
3461496ba7bSLoGin     }
3471496ba7bSLoGin 
3481496ba7bSLoGin     /// 停止一个内核线程
3491496ba7bSLoGin     ///
3501496ba7bSLoGin     /// 如果目标内核线程的数据检查失败,会panic
3511496ba7bSLoGin     ///
3521496ba7bSLoGin     /// ## 返回值
3531496ba7bSLoGin     ///
3541496ba7bSLoGin     /// - Ok(i32) 目标内核线程的退出码
3551496ba7bSLoGin     #[allow(dead_code)]
3561496ba7bSLoGin     pub fn stop(pcb: &Arc<ProcessControlBlock>) -> Result<usize, SystemError> {
3571496ba7bSLoGin         if !pcb.flags().contains(ProcessFlags::KTHREAD) {
3581496ba7bSLoGin             panic!("Cannt stop a non-kthread process");
3591496ba7bSLoGin         }
3601496ba7bSLoGin 
3611496ba7bSLoGin         let mut worker_private = pcb.worker_private();
3621496ba7bSLoGin         assert!(
3631496ba7bSLoGin             worker_private.is_some(),
3641496ba7bSLoGin             "kthread stop: worker_private is none, pid: {:?}",
3651496ba7bSLoGin             pcb.pid()
3661496ba7bSLoGin         );
3671496ba7bSLoGin         worker_private
3681496ba7bSLoGin             .as_mut()
3691496ba7bSLoGin             .unwrap()
3701496ba7bSLoGin             .kernel_thread_mut()
3711496ba7bSLoGin             .expect("Error type of worker private")
3721496ba7bSLoGin             .flags
3731496ba7bSLoGin             .insert(KernelThreadFlags::SHOULD_STOP);
3741496ba7bSLoGin 
3751496ba7bSLoGin         drop(worker_private);
3761496ba7bSLoGin 
3771496ba7bSLoGin         ProcessManager::wakeup(pcb).ok();
3781496ba7bSLoGin 
3791496ba7bSLoGin         // 忙等目标内核线程退出
3801496ba7bSLoGin         // todo: 使用completion机制优化这里
3811496ba7bSLoGin         loop {
3821496ba7bSLoGin             if let ProcessState::Exited(code) = pcb.sched_info().state() {
3831496ba7bSLoGin                 return Ok(code);
3841496ba7bSLoGin             }
3851496ba7bSLoGin             spin_loop();
3861496ba7bSLoGin         }
3871496ba7bSLoGin     }
3881496ba7bSLoGin 
3891496ba7bSLoGin     /// 判断一个内核线程是否应当停止
3901496ba7bSLoGin     ///
3911496ba7bSLoGin     /// ## 参数
3921496ba7bSLoGin     ///
3931496ba7bSLoGin     /// - pcb: 目标内核线程的PCB
3941496ba7bSLoGin     ///
3951496ba7bSLoGin     /// ## 返回值
3961496ba7bSLoGin     ///
3971496ba7bSLoGin     /// - bool 是否应当停止. true表示应当停止,false表示不应当停止. 如果目标进程不是内核线程,返回false
3981496ba7bSLoGin     ///
3991496ba7bSLoGin     /// ## Panic
4001496ba7bSLoGin     ///
4011496ba7bSLoGin     /// 如果目标内核线程的数据检查失败,会panic
4021496ba7bSLoGin     #[allow(dead_code)]
4031496ba7bSLoGin     pub fn should_stop(pcb: &Arc<ProcessControlBlock>) -> bool {
4041496ba7bSLoGin         if !pcb.flags().contains(ProcessFlags::KTHREAD) {
4051496ba7bSLoGin             return false;
4061496ba7bSLoGin         }
4071496ba7bSLoGin 
4081496ba7bSLoGin         let worker_private = pcb.worker_private();
4091496ba7bSLoGin         assert!(
4101496ba7bSLoGin             worker_private.is_some(),
4111496ba7bSLoGin             "kthread should_stop: worker_private is none, pid: {:?}",
4121496ba7bSLoGin             pcb.pid()
4131496ba7bSLoGin         );
4141496ba7bSLoGin         return worker_private
4151496ba7bSLoGin             .as_ref()
4161496ba7bSLoGin             .unwrap()
4171496ba7bSLoGin             .kernel_thread()
4181496ba7bSLoGin             .expect("Error type of worker private")
4191496ba7bSLoGin             .flags
4201496ba7bSLoGin             .contains(KernelThreadFlags::SHOULD_STOP);
4211496ba7bSLoGin     }
4221496ba7bSLoGin 
4231496ba7bSLoGin     /// A daemon thread which creates other kernel threads
4241496ba7bSLoGin     fn kthread_daemon() -> i32 {
4251496ba7bSLoGin         let current_pcb = ProcessManager::current_pcb();
4261496ba7bSLoGin         kdebug!("kthread_daemon: pid: {:?}", current_pcb.pid());
4271496ba7bSLoGin         {
4281496ba7bSLoGin             // 初始化worker_private
4291496ba7bSLoGin             let mut worker_private_guard = current_pcb.worker_private();
4301496ba7bSLoGin             let worker_private = WorkerPrivate::KernelThread(KernelThreadPcbPrivate::new());
4311496ba7bSLoGin             *worker_private_guard = Some(worker_private);
4321496ba7bSLoGin         }
4331496ba7bSLoGin         // 设置为kthread
4341496ba7bSLoGin         current_pcb.flags().insert(ProcessFlags::KTHREAD);
4351496ba7bSLoGin         drop(current_pcb);
4361496ba7bSLoGin 
4371496ba7bSLoGin         loop {
4381496ba7bSLoGin             let mut list = KTHREAD_CREATE_LIST.lock();
4391496ba7bSLoGin             while let Some(info) = list.pop_front() {
4401496ba7bSLoGin                 drop(list);
4411496ba7bSLoGin 
4421496ba7bSLoGin                 // create a new kernel thread
4431496ba7bSLoGin                 let result: Result<Pid, SystemError> =
4441496ba7bSLoGin                     Self::__inner_create(&info, CloneFlags::CLONE_FS | CloneFlags::CLONE_SIGNAL);
4451496ba7bSLoGin 
4461496ba7bSLoGin                 if result.is_err() {
4471496ba7bSLoGin                     // 创建失败
4481496ba7bSLoGin                     info.created
4491496ba7bSLoGin                         .store(KernelThreadCreateStatus::ErrorOccured, Ordering::SeqCst);
4501496ba7bSLoGin                 };
4511496ba7bSLoGin                 list = KTHREAD_CREATE_LIST.lock();
4521496ba7bSLoGin             }
4531496ba7bSLoGin             drop(list);
4541496ba7bSLoGin 
4551496ba7bSLoGin             let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
4561496ba7bSLoGin             ProcessManager::mark_sleep(true).ok();
4571496ba7bSLoGin             drop(irq_guard);
4581496ba7bSLoGin             sched();
4591496ba7bSLoGin         }
4601496ba7bSLoGin     }
4611496ba7bSLoGin }
4621496ba7bSLoGin 
4631496ba7bSLoGin /// 内核线程启动的第二阶段
4641496ba7bSLoGin ///
4651496ba7bSLoGin /// 该函数只能被`kernel_thread_bootstrap_stage1`调用(jmp到该函数)
4661496ba7bSLoGin ///
4671496ba7bSLoGin /// ## 参数
4681496ba7bSLoGin ///
4691496ba7bSLoGin /// - ptr: 传入的参数,是一个指向`Arc<KernelThreadCreateInfo>`的指针
4701496ba7bSLoGin pub unsafe extern "C" fn kernel_thread_bootstrap_stage2(ptr: *const KernelThreadCreateInfo) -> ! {
4711496ba7bSLoGin     let info = KernelThreadCreateInfo::parse_unsafe_arc_ptr(ptr);
4721496ba7bSLoGin 
4731496ba7bSLoGin     let closure: Box<KernelThreadClosure> = info.take_closure().unwrap();
4741496ba7bSLoGin     info.set_create_ok(ProcessManager::current_pcb());
475de71ec25SLoGin     let to_mark_sleep = info.to_mark_sleep();
4761496ba7bSLoGin     drop(info);
4771496ba7bSLoGin 
478de71ec25SLoGin     if to_mark_sleep {
479de71ec25SLoGin         // 进入睡眠状态
4801496ba7bSLoGin         let irq_guard = CurrentIrqArch::save_and_disable_irq();
4811496ba7bSLoGin         ProcessManager::mark_sleep(true).expect("Failed to mark sleep");
4821496ba7bSLoGin         drop(irq_guard);
483de71ec25SLoGin         sched();
484de71ec25SLoGin     }
4851496ba7bSLoGin 
4861496ba7bSLoGin     let mut retval = SystemError::EINTR.to_posix_errno();
4871496ba7bSLoGin 
4881496ba7bSLoGin     if !KernelThreadMechanism::should_stop(&ProcessManager::current_pcb()) {
4891496ba7bSLoGin         retval = closure.run();
4901496ba7bSLoGin     }
4911496ba7bSLoGin 
4921496ba7bSLoGin     ProcessManager::exit(retval as usize);
4931496ba7bSLoGin }
4941496ba7bSLoGin 
4951496ba7bSLoGin pub fn kthread_init() {
4961496ba7bSLoGin     static INIT: Once = Once::new();
4971496ba7bSLoGin     INIT.call_once(|| {
4981496ba7bSLoGin         KernelThreadMechanism::init_stage1();
4991496ba7bSLoGin     });
5001496ba7bSLoGin }
501