xref: /DragonOS/kernel/src/process/kthread.rs (revision dc9b4fea1bcff86cfb49293552654e2dd038ae9e)
11496ba7bSLoGin use core::{
21496ba7bSLoGin     hint::spin_loop,
3f0c87a89SGnoCiYeH     sync::atomic::{compiler_fence, 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;
132eab6dd7S曾俊 use log::info;
1491e9d4abSLoGin use system_error::SystemError;
151496ba7bSLoGin 
161496ba7bSLoGin use crate::{
17f0c87a89SGnoCiYeH     arch::CurrentIrqArch,
18e2841179SLoGin     exception::{irqdesc::IrqAction, InterruptArch},
19c566df45SLoGin     init::initial_kthread::initial_kernel_thread,
201496ba7bSLoGin     libs::{once::Once, spinlock::SpinLock},
211496ba7bSLoGin     process::{ProcessManager, ProcessState},
22f0c87a89SGnoCiYeH     sched::{schedule, SchedMode},
231496ba7bSLoGin };
241496ba7bSLoGin 
25c566df45SLoGin use super::{fork::CloneFlags, Pid, ProcessControlBlock, ProcessFlags};
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 {
kernel_thread(&self) -> Option<&KernelThreadPcbPrivate>401496ba7bSLoGin     pub fn kernel_thread(&self) -> Option<&KernelThreadPcbPrivate> {
411496ba7bSLoGin         match self {
421496ba7bSLoGin             Self::KernelThread(x) => Some(x),
431496ba7bSLoGin         }
441496ba7bSLoGin     }
451496ba7bSLoGin 
kernel_thread_mut(&mut self) -> Option<&mut KernelThreadPcbPrivate>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 {
new() -> Self681496ba7bSLoGin     pub fn new() -> Self {
691496ba7bSLoGin         Self {
701496ba7bSLoGin             flags: KernelThreadFlags::empty(),
711496ba7bSLoGin         }
721496ba7bSLoGin     }
731496ba7bSLoGin 
flags(&self) -> &KernelThreadFlags741496ba7bSLoGin     pub fn flags(&self) -> &KernelThreadFlags {
751496ba7bSLoGin         &self.flags
761496ba7bSLoGin     }
771496ba7bSLoGin 
flags_mut(&mut self) -> &mut KernelThreadFlags781496ba7bSLoGin     pub fn flags_mut(&mut self) -> &mut KernelThreadFlags {
791496ba7bSLoGin         &mut self.flags
801496ba7bSLoGin     }
811496ba7bSLoGin }
821496ba7bSLoGin 
83*dc9b4feaSLoGin impl Default for KernelThreadPcbPrivate {
default() -> Self84*dc9b4feaSLoGin     fn default() -> Self {
85*dc9b4feaSLoGin         Self::new()
86*dc9b4feaSLoGin     }
87*dc9b4feaSLoGin }
88*dc9b4feaSLoGin 
891496ba7bSLoGin /// 内核线程的闭包,参数必须与闭包的参数一致,返回值必须是i32
901496ba7bSLoGin ///
911496ba7bSLoGin /// 元组的第一个元素是闭包,第二个元素是闭包的参数对象
921496ba7bSLoGin ///
931496ba7bSLoGin /// 对于非原始类型的参数,需要使用Box包装
941496ba7bSLoGin #[allow(dead_code)]
95b5b571e0SLoGin #[allow(clippy::type_complexity)]
961496ba7bSLoGin pub enum KernelThreadClosure {
971496ba7bSLoGin     UsizeClosure((Box<dyn Fn(usize) -> i32 + Send + Sync>, usize)),
9859fdb447SLoGin     StaticUsizeClosure((&'static fn(usize) -> i32, usize)),
991496ba7bSLoGin     EmptyClosure((Box<dyn Fn() -> i32 + Send + Sync>, ())),
10059fdb447SLoGin     StaticEmptyClosure((&'static fn() -> i32, ())),
101e2841179SLoGin     IrqThread(
102e2841179SLoGin         (
103e2841179SLoGin             &'static dyn Fn(Arc<IrqAction>) -> Result<(), SystemError>,
104e2841179SLoGin             Arc<IrqAction>,
105e2841179SLoGin         ),
106e2841179SLoGin     ),
1071496ba7bSLoGin     // 添加其他类型入参的闭包,返回值必须是i32
1081496ba7bSLoGin }
1091496ba7bSLoGin 
110e2841179SLoGin unsafe impl Send for KernelThreadClosure {}
111e2841179SLoGin unsafe impl Sync for KernelThreadClosure {}
112e2841179SLoGin 
1131496ba7bSLoGin impl KernelThreadClosure {
run(self) -> i321141496ba7bSLoGin     pub fn run(self) -> i32 {
1151496ba7bSLoGin         match self {
1161496ba7bSLoGin             Self::UsizeClosure((func, arg)) => func(arg),
1171496ba7bSLoGin             Self::EmptyClosure((func, _arg)) => func(),
118e2841179SLoGin             Self::StaticUsizeClosure((func, arg)) => func(arg),
119e2841179SLoGin             Self::StaticEmptyClosure((func, _arg)) => func(),
120e2841179SLoGin             Self::IrqThread((func, arg)) => {
121e2841179SLoGin                 func(arg).map(|_| 0).unwrap_or_else(|e| e.to_posix_errno())
122e2841179SLoGin             }
1231496ba7bSLoGin         }
1241496ba7bSLoGin     }
1251496ba7bSLoGin }
1261496ba7bSLoGin 
1271496ba7bSLoGin pub struct KernelThreadCreateInfo {
1281496ba7bSLoGin     /// 内核线程的入口函数、传入参数
1291496ba7bSLoGin     closure: SpinLock<Option<Box<KernelThreadClosure>>>,
1301496ba7bSLoGin     /// 内核线程的名字
1311496ba7bSLoGin     name: String,
1321496ba7bSLoGin     /// 是否已经完成创建 todo:使用comletion机制优化这里
1331496ba7bSLoGin     created: AtomicKernelThreadCreateStatus,
1341496ba7bSLoGin     result_pcb: SpinLock<Option<Arc<ProcessControlBlock>>>,
1351496ba7bSLoGin     /// 不安全的Arc引用计数,当内核线程创建失败时,需要减少这个计数
1361496ba7bSLoGin     has_unsafe_arc_instance: AtomicBool,
1371496ba7bSLoGin     self_ref: Weak<Self>,
138de71ec25SLoGin     /// 如果该值为true在进入bootstrap stage2之后,就会进入睡眠状态
139de71ec25SLoGin     to_mark_sleep: AtomicBool,
1401496ba7bSLoGin }
1411496ba7bSLoGin 
1421496ba7bSLoGin #[atomic_enum]
1431496ba7bSLoGin #[derive(PartialEq)]
1441496ba7bSLoGin pub enum KernelThreadCreateStatus {
1451496ba7bSLoGin     Created,
1461496ba7bSLoGin     NotCreated,
1471496ba7bSLoGin     ErrorOccured,
1481496ba7bSLoGin }
1491496ba7bSLoGin 
1501496ba7bSLoGin #[allow(dead_code)]
1511496ba7bSLoGin impl KernelThreadCreateInfo {
new(func: KernelThreadClosure, name: String) -> Arc<Self>1521496ba7bSLoGin     pub fn new(func: KernelThreadClosure, name: String) -> Arc<Self> {
1531496ba7bSLoGin         let result = Arc::new(Self {
1541496ba7bSLoGin             closure: SpinLock::new(Some(Box::new(func))),
1551496ba7bSLoGin             name,
1561496ba7bSLoGin             created: AtomicKernelThreadCreateStatus::new(KernelThreadCreateStatus::NotCreated),
1571496ba7bSLoGin             result_pcb: SpinLock::new(None),
1581496ba7bSLoGin             has_unsafe_arc_instance: AtomicBool::new(false),
1591496ba7bSLoGin             self_ref: Weak::new(),
160de71ec25SLoGin             to_mark_sleep: AtomicBool::new(true),
1611496ba7bSLoGin         });
1621496ba7bSLoGin         let tmp = result.clone();
1631496ba7bSLoGin         unsafe {
1641496ba7bSLoGin             let tmp = Arc::into_raw(tmp) as *mut Self;
1651496ba7bSLoGin             (*tmp).self_ref = Arc::downgrade(&result);
1661496ba7bSLoGin             Arc::from_raw(tmp);
1671496ba7bSLoGin         }
1681496ba7bSLoGin 
1691496ba7bSLoGin         return result;
1701496ba7bSLoGin     }
1711496ba7bSLoGin 
1721496ba7bSLoGin     /// 创建者调用这函数,等待创建完成后,获取创建结果
1731496ba7bSLoGin     ///
1741496ba7bSLoGin     /// ## 返回值
1751496ba7bSLoGin     ///
1761496ba7bSLoGin     /// - Some(Arc<ProcessControlBlock>) 创建成功,返回新创建的内核线程的PCB
1771496ba7bSLoGin     /// - None 创建失败
poll_result(&self) -> Option<Arc<ProcessControlBlock>>1781496ba7bSLoGin     pub fn poll_result(&self) -> Option<Arc<ProcessControlBlock>> {
1791496ba7bSLoGin         loop {
1801496ba7bSLoGin             match self.created.load(Ordering::SeqCst) {
1811496ba7bSLoGin                 KernelThreadCreateStatus::Created => {
1821496ba7bSLoGin                     return self.result_pcb.lock().take();
1831496ba7bSLoGin                 }
1841496ba7bSLoGin                 KernelThreadCreateStatus::NotCreated => {
1851496ba7bSLoGin                     spin_loop();
1861496ba7bSLoGin                 }
1871496ba7bSLoGin                 KernelThreadCreateStatus::ErrorOccured => {
1881496ba7bSLoGin                     // 创建失败,减少不安全的Arc引用计数
1891496ba7bSLoGin                     let to_delete = self.has_unsafe_arc_instance.swap(false, Ordering::SeqCst);
1901496ba7bSLoGin                     if to_delete {
1911496ba7bSLoGin                         let self_ref = self.self_ref.upgrade().unwrap();
1921496ba7bSLoGin                         unsafe { Arc::decrement_strong_count(&self_ref) };
1931496ba7bSLoGin                     }
1941496ba7bSLoGin                     return None;
1951496ba7bSLoGin                 }
1961496ba7bSLoGin             }
1971496ba7bSLoGin         }
1981496ba7bSLoGin     }
1991496ba7bSLoGin 
take_closure(&self) -> Option<Box<KernelThreadClosure>>2001496ba7bSLoGin     pub fn take_closure(&self) -> Option<Box<KernelThreadClosure>> {
2011496ba7bSLoGin         return self.closure.lock().take();
2021496ba7bSLoGin     }
2031496ba7bSLoGin 
name(&self) -> &String2041496ba7bSLoGin     pub fn name(&self) -> &String {
2051496ba7bSLoGin         &self.name
2061496ba7bSLoGin     }
2071496ba7bSLoGin 
set_create_ok(&self, pcb: Arc<ProcessControlBlock>)2081496ba7bSLoGin     pub unsafe fn set_create_ok(&self, pcb: Arc<ProcessControlBlock>) {
2091496ba7bSLoGin         // todo: 使用completion机制优化这里
2101496ba7bSLoGin         self.result_pcb.lock().replace(pcb);
2111496ba7bSLoGin         self.created
2121496ba7bSLoGin             .store(KernelThreadCreateStatus::Created, Ordering::SeqCst);
2131496ba7bSLoGin     }
2141496ba7bSLoGin 
2151496ba7bSLoGin     /// 生成一个不安全的Arc指针(用于创建内核线程时传递参数)
generate_unsafe_arc_ptr(self: Arc<Self>) -> *const Self2161496ba7bSLoGin     pub fn generate_unsafe_arc_ptr(self: Arc<Self>) -> *const Self {
2171496ba7bSLoGin         assert!(
2181496ba7bSLoGin             self.has_unsafe_arc_instance
2191496ba7bSLoGin                 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
2201496ba7bSLoGin                 .is_ok(),
2211496ba7bSLoGin             "Cannot generate unsafe arc ptr when there is already one."
2221496ba7bSLoGin         );
2231496ba7bSLoGin         let ptr = Arc::into_raw(self);
2241496ba7bSLoGin         return ptr;
2251496ba7bSLoGin     }
2261496ba7bSLoGin 
parse_unsafe_arc_ptr(ptr: *const Self) -> Arc<Self>2271496ba7bSLoGin     pub unsafe fn parse_unsafe_arc_ptr(ptr: *const Self) -> Arc<Self> {
2281496ba7bSLoGin         let arc = Arc::from_raw(ptr);
2291496ba7bSLoGin         assert!(
2301496ba7bSLoGin             arc.has_unsafe_arc_instance
2311496ba7bSLoGin                 .compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst)
2321496ba7bSLoGin                 .is_ok(),
2331496ba7bSLoGin             "Cannot parse unsafe arc ptr when there is no one."
2341496ba7bSLoGin         );
2351496ba7bSLoGin         assert!(Arc::strong_count(&arc) > 0);
2361496ba7bSLoGin         return arc;
2371496ba7bSLoGin     }
238de71ec25SLoGin 
239de71ec25SLoGin     /// 设置是否在进入bootstrap stage2之后,就进入睡眠状态
240de71ec25SLoGin     ///
241de71ec25SLoGin     /// ## 参数
242de71ec25SLoGin     ///
243de71ec25SLoGin     /// - to_mark_sleep: 是否在进入bootstrap stage2之后,就进入睡眠状态
244de71ec25SLoGin     ///
245de71ec25SLoGin     /// ## 返回值
246de71ec25SLoGin     /// 如果已经创建完成,返回EINVAL
set_to_mark_sleep(&self, to_mark_sleep: bool) -> Result<(), SystemError>247de71ec25SLoGin     pub fn set_to_mark_sleep(&self, to_mark_sleep: bool) -> Result<(), SystemError> {
248de71ec25SLoGin         let result_guard = self.result_pcb.lock();
249de71ec25SLoGin         if result_guard.is_some() {
250de71ec25SLoGin             // 已经创建完成,不需要设置
251de71ec25SLoGin             return Err(SystemError::EINVAL);
252de71ec25SLoGin         }
253de71ec25SLoGin         self.to_mark_sleep.store(to_mark_sleep, Ordering::SeqCst);
254de71ec25SLoGin         return Ok(());
255de71ec25SLoGin     }
256de71ec25SLoGin 
to_mark_sleep(&self) -> bool257de71ec25SLoGin     pub fn to_mark_sleep(&self) -> bool {
258de71ec25SLoGin         self.to_mark_sleep.load(Ordering::SeqCst)
259de71ec25SLoGin     }
2601496ba7bSLoGin }
2611496ba7bSLoGin 
2621496ba7bSLoGin pub struct KernelThreadMechanism;
2631496ba7bSLoGin 
2641496ba7bSLoGin impl KernelThreadMechanism {
init_stage1()2651496ba7bSLoGin     pub fn init_stage1() {
266de71ec25SLoGin         assert!(ProcessManager::current_pcb().pid() == Pid::new(0));
2672eab6dd7S曾俊         info!("Initializing kernel thread mechanism stage1...");
2681496ba7bSLoGin 
2691496ba7bSLoGin         // 初始化第一个内核线程
2701496ba7bSLoGin 
2711496ba7bSLoGin         let create_info = KernelThreadCreateInfo::new(
2721496ba7bSLoGin             KernelThreadClosure::EmptyClosure((Box::new(initial_kernel_thread), ())),
2731496ba7bSLoGin             "init".to_string(),
2741496ba7bSLoGin         );
2754fda81ceSLoGin 
2764fda81ceSLoGin         let irq_guard: crate::exception::IrqFlagsGuard =
2774fda81ceSLoGin             unsafe { CurrentIrqArch::save_and_disable_irq() };
2781496ba7bSLoGin         // 由于当前是pid=0的idle进程,而__inner_create要求当前是kthread,所以先临时设置为kthread
2791496ba7bSLoGin         ProcessManager::current_pcb()
2801496ba7bSLoGin             .flags
28170a4e555SLoGin             .get_mut()
2821496ba7bSLoGin             .insert(ProcessFlags::KTHREAD);
283de71ec25SLoGin         create_info
284de71ec25SLoGin             .set_to_mark_sleep(false)
285de71ec25SLoGin             .expect("Failed to set to_mark_sleep");
2864fda81ceSLoGin 
2871496ba7bSLoGin         KernelThreadMechanism::__inner_create(
2881496ba7bSLoGin             &create_info,
2891496ba7bSLoGin             CloneFlags::CLONE_VM | CloneFlags::CLONE_SIGNAL,
2901496ba7bSLoGin         )
2911496ba7bSLoGin         .unwrap_or_else(|e| panic!("Failed to create initial kernel thread, error: {:?}", e));
2921496ba7bSLoGin 
2931496ba7bSLoGin         ProcessManager::current_pcb()
2941496ba7bSLoGin             .flags
29570a4e555SLoGin             .get_mut()
2961496ba7bSLoGin             .remove(ProcessFlags::KTHREAD);
2974fda81ceSLoGin 
2981496ba7bSLoGin         drop(irq_guard);
2992eab6dd7S曾俊         info!("Initializing kernel thread mechanism stage1 complete");
3001496ba7bSLoGin     }
3011496ba7bSLoGin 
init_stage2()3021496ba7bSLoGin     pub fn init_stage2() {
3031496ba7bSLoGin         assert!(ProcessManager::current_pcb()
3041496ba7bSLoGin             .flags()
3051496ba7bSLoGin             .contains(ProcessFlags::KTHREAD));
3061496ba7bSLoGin         static INIT: Once = Once::new();
3071496ba7bSLoGin         INIT.call_once(|| {
3082eab6dd7S曾俊             info!("Initializing kernel thread mechanism stage2...");
3091496ba7bSLoGin             // 初始化kthreadd
3101496ba7bSLoGin             let closure = KernelThreadClosure::EmptyClosure((Box::new(Self::kthread_daemon), ()));
3111496ba7bSLoGin             let info = KernelThreadCreateInfo::new(closure, "kthreadd".to_string());
312f0c87a89SGnoCiYeH             info.set_to_mark_sleep(false)
313f0c87a89SGnoCiYeH                 .expect("kthreadadd should be run first");
314971462beSGnoCiYeH             let kthreadd_pid: Pid = Self::__inner_create(
315971462beSGnoCiYeH                 &info,
316971462beSGnoCiYeH                 CloneFlags::CLONE_VM | CloneFlags::CLONE_FS | CloneFlags::CLONE_SIGNAL,
317971462beSGnoCiYeH             )
3181496ba7bSLoGin             .expect("Failed to create kthread daemon");
3191496ba7bSLoGin             let pcb = ProcessManager::find(kthreadd_pid).unwrap();
320de71ec25SLoGin             ProcessManager::wakeup(&pcb).expect("Failed to wakeup kthread daemon");
3211496ba7bSLoGin             unsafe {
3221496ba7bSLoGin                 KTHREAD_DAEMON_PCB.replace(pcb);
3231496ba7bSLoGin             }
3242eab6dd7S曾俊             info!("Initialize kernel thread mechanism stage2 complete");
3251496ba7bSLoGin         });
3261496ba7bSLoGin     }
3271496ba7bSLoGin 
3281496ba7bSLoGin     /// 创建一个新的内核线程
3291496ba7bSLoGin     ///
3301496ba7bSLoGin     /// ## 参数
3311496ba7bSLoGin     ///
3321496ba7bSLoGin     /// - func: 内核线程的入口函数、传入参数
3331496ba7bSLoGin     /// - name: 内核线程的名字
3341496ba7bSLoGin     ///
3351496ba7bSLoGin     /// ## 返回值
3361496ba7bSLoGin     ///
3371496ba7bSLoGin     /// - Some(Arc<ProcessControlBlock>) 创建成功,返回新创建的内核线程的PCB
3381496ba7bSLoGin     #[allow(dead_code)]
create(func: KernelThreadClosure, name: String) -> Option<Arc<ProcessControlBlock>>3391496ba7bSLoGin     pub fn create(func: KernelThreadClosure, name: String) -> Option<Arc<ProcessControlBlock>> {
3401496ba7bSLoGin         let info = KernelThreadCreateInfo::new(func, name);
3411496ba7bSLoGin         while unsafe { KTHREAD_DAEMON_PCB.is_none() } {
3421496ba7bSLoGin             // 等待kthreadd启动
3431496ba7bSLoGin             spin_loop()
3441496ba7bSLoGin         }
3451496ba7bSLoGin         KTHREAD_CREATE_LIST.lock().push_back(info.clone());
346f0c87a89SGnoCiYeH         compiler_fence(Ordering::SeqCst);
3471496ba7bSLoGin         ProcessManager::wakeup(unsafe { KTHREAD_DAEMON_PCB.as_ref().unwrap() })
3481496ba7bSLoGin             .expect("Failed to wakeup kthread daemon");
3491496ba7bSLoGin         return info.poll_result();
3501496ba7bSLoGin     }
3511496ba7bSLoGin 
3521496ba7bSLoGin     /// 创建并运行一个新的内核线程
3531496ba7bSLoGin     ///
3541496ba7bSLoGin     /// ## 参数
3551496ba7bSLoGin     ///
3561496ba7bSLoGin     /// - func: 内核线程的入口函数、传入参数
3571496ba7bSLoGin     /// - name: 内核线程的名字
3581496ba7bSLoGin     ///
3591496ba7bSLoGin     /// ## 返回值
3601496ba7bSLoGin     ///
3611496ba7bSLoGin     /// - Some(Arc<ProcessControlBlock>) 创建成功,返回新创建的内核线程的PCB
3621496ba7bSLoGin     #[allow(dead_code)]
create_and_run( func: KernelThreadClosure, name: String, ) -> Option<Arc<ProcessControlBlock>>3631496ba7bSLoGin     pub fn create_and_run(
3641496ba7bSLoGin         func: KernelThreadClosure,
3651496ba7bSLoGin         name: String,
3661496ba7bSLoGin     ) -> Option<Arc<ProcessControlBlock>> {
3671496ba7bSLoGin         let pcb = Self::create(func, name)?;
3681496ba7bSLoGin         ProcessManager::wakeup(&pcb)
369b5b571e0SLoGin             .unwrap_or_else(|_| panic!("Failed to wakeup kthread: {:?}", pcb.pid()));
3701496ba7bSLoGin         return Some(pcb);
3711496ba7bSLoGin     }
3721496ba7bSLoGin 
3731496ba7bSLoGin     /// 停止一个内核线程
3741496ba7bSLoGin     ///
3751496ba7bSLoGin     /// 如果目标内核线程的数据检查失败,会panic
3761496ba7bSLoGin     ///
3771496ba7bSLoGin     /// ## 返回值
3781496ba7bSLoGin     ///
3791496ba7bSLoGin     /// - Ok(i32) 目标内核线程的退出码
3801496ba7bSLoGin     #[allow(dead_code)]
stop(pcb: &Arc<ProcessControlBlock>) -> Result<usize, SystemError>3811496ba7bSLoGin     pub fn stop(pcb: &Arc<ProcessControlBlock>) -> Result<usize, SystemError> {
3821496ba7bSLoGin         if !pcb.flags().contains(ProcessFlags::KTHREAD) {
3831496ba7bSLoGin             panic!("Cannt stop a non-kthread process");
3841496ba7bSLoGin         }
3851496ba7bSLoGin 
3861496ba7bSLoGin         let mut worker_private = pcb.worker_private();
3871496ba7bSLoGin         assert!(
3881496ba7bSLoGin             worker_private.is_some(),
3891496ba7bSLoGin             "kthread stop: worker_private is none, pid: {:?}",
3901496ba7bSLoGin             pcb.pid()
3911496ba7bSLoGin         );
3921496ba7bSLoGin         worker_private
3931496ba7bSLoGin             .as_mut()
3941496ba7bSLoGin             .unwrap()
3951496ba7bSLoGin             .kernel_thread_mut()
3961496ba7bSLoGin             .expect("Error type of worker private")
3971496ba7bSLoGin             .flags
3981496ba7bSLoGin             .insert(KernelThreadFlags::SHOULD_STOP);
3991496ba7bSLoGin 
4001496ba7bSLoGin         drop(worker_private);
4011496ba7bSLoGin 
4021496ba7bSLoGin         ProcessManager::wakeup(pcb).ok();
4031496ba7bSLoGin 
4041496ba7bSLoGin         // 忙等目标内核线程退出
4051496ba7bSLoGin         // todo: 使用completion机制优化这里
4061496ba7bSLoGin         loop {
4070d6cf65aSLoGin             if let ProcessState::Exited(code) = pcb.sched_info().inner_lock_read_irqsave().state() {
4081496ba7bSLoGin                 return Ok(code);
4091496ba7bSLoGin             }
4101496ba7bSLoGin             spin_loop();
4111496ba7bSLoGin         }
4121496ba7bSLoGin     }
4131496ba7bSLoGin 
4141496ba7bSLoGin     /// 判断一个内核线程是否应当停止
4151496ba7bSLoGin     ///
4161496ba7bSLoGin     /// ## 参数
4171496ba7bSLoGin     ///
4181496ba7bSLoGin     /// - pcb: 目标内核线程的PCB
4191496ba7bSLoGin     ///
4201496ba7bSLoGin     /// ## 返回值
4211496ba7bSLoGin     ///
4221496ba7bSLoGin     /// - bool 是否应当停止. true表示应当停止,false表示不应当停止. 如果目标进程不是内核线程,返回false
4231496ba7bSLoGin     ///
4241496ba7bSLoGin     /// ## Panic
4251496ba7bSLoGin     ///
4261496ba7bSLoGin     /// 如果目标内核线程的数据检查失败,会panic
4271496ba7bSLoGin     #[allow(dead_code)]
should_stop(pcb: &Arc<ProcessControlBlock>) -> bool4281496ba7bSLoGin     pub fn should_stop(pcb: &Arc<ProcessControlBlock>) -> bool {
4291496ba7bSLoGin         if !pcb.flags().contains(ProcessFlags::KTHREAD) {
4301496ba7bSLoGin             return false;
4311496ba7bSLoGin         }
4321496ba7bSLoGin 
4331496ba7bSLoGin         let worker_private = pcb.worker_private();
4341496ba7bSLoGin         assert!(
4351496ba7bSLoGin             worker_private.is_some(),
4361496ba7bSLoGin             "kthread should_stop: worker_private is none, pid: {:?}",
4371496ba7bSLoGin             pcb.pid()
4381496ba7bSLoGin         );
4391496ba7bSLoGin         return worker_private
4401496ba7bSLoGin             .as_ref()
4411496ba7bSLoGin             .unwrap()
4421496ba7bSLoGin             .kernel_thread()
4431496ba7bSLoGin             .expect("Error type of worker private")
4441496ba7bSLoGin             .flags
4451496ba7bSLoGin             .contains(KernelThreadFlags::SHOULD_STOP);
4461496ba7bSLoGin     }
4471496ba7bSLoGin 
4481496ba7bSLoGin     /// A daemon thread which creates other kernel threads
44959fdb447SLoGin     #[inline(never)]
kthread_daemon() -> i324501496ba7bSLoGin     fn kthread_daemon() -> i32 {
4511496ba7bSLoGin         let current_pcb = ProcessManager::current_pcb();
4521496ba7bSLoGin         {
4531496ba7bSLoGin             // 初始化worker_private
4541496ba7bSLoGin             let mut worker_private_guard = current_pcb.worker_private();
4551496ba7bSLoGin             let worker_private = WorkerPrivate::KernelThread(KernelThreadPcbPrivate::new());
4561496ba7bSLoGin             *worker_private_guard = Some(worker_private);
4571496ba7bSLoGin         }
4581496ba7bSLoGin         // 设置为kthread
4591496ba7bSLoGin         current_pcb.flags().insert(ProcessFlags::KTHREAD);
4601496ba7bSLoGin         drop(current_pcb);
4611496ba7bSLoGin 
4621496ba7bSLoGin         loop {
4631496ba7bSLoGin             let mut list = KTHREAD_CREATE_LIST.lock();
4641496ba7bSLoGin             while let Some(info) = list.pop_front() {
4651496ba7bSLoGin                 drop(list);
4661496ba7bSLoGin                 // create a new kernel thread
46759fdb447SLoGin                 let result: Result<Pid, SystemError> = Self::__inner_create(
46859fdb447SLoGin                     &info,
46959fdb447SLoGin                     CloneFlags::CLONE_VM | CloneFlags::CLONE_FS | CloneFlags::CLONE_SIGNAL,
47059fdb447SLoGin                 );
4711496ba7bSLoGin                 if result.is_err() {
4721496ba7bSLoGin                     // 创建失败
4731496ba7bSLoGin                     info.created
4741496ba7bSLoGin                         .store(KernelThreadCreateStatus::ErrorOccured, Ordering::SeqCst);
4751496ba7bSLoGin                 };
4761496ba7bSLoGin                 list = KTHREAD_CREATE_LIST.lock();
4771496ba7bSLoGin             }
4781496ba7bSLoGin             drop(list);
4791496ba7bSLoGin 
4801496ba7bSLoGin             let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
4811496ba7bSLoGin             ProcessManager::mark_sleep(true).ok();
4821496ba7bSLoGin             drop(irq_guard);
483f0c87a89SGnoCiYeH             schedule(SchedMode::SM_NONE);
4841496ba7bSLoGin         }
4851496ba7bSLoGin     }
4861496ba7bSLoGin }
4871496ba7bSLoGin 
4881496ba7bSLoGin /// 内核线程启动的第二阶段
4891496ba7bSLoGin ///
4901496ba7bSLoGin /// 该函数只能被`kernel_thread_bootstrap_stage1`调用(jmp到该函数)
4911496ba7bSLoGin ///
4921496ba7bSLoGin /// ## 参数
4931496ba7bSLoGin ///
4941496ba7bSLoGin /// - ptr: 传入的参数,是一个指向`Arc<KernelThreadCreateInfo>`的指针
kernel_thread_bootstrap_stage2(ptr: *const KernelThreadCreateInfo) -> !4951496ba7bSLoGin pub unsafe extern "C" fn kernel_thread_bootstrap_stage2(ptr: *const KernelThreadCreateInfo) -> ! {
4961496ba7bSLoGin     let info = KernelThreadCreateInfo::parse_unsafe_arc_ptr(ptr);
4971496ba7bSLoGin 
4981496ba7bSLoGin     let closure: Box<KernelThreadClosure> = info.take_closure().unwrap();
4991496ba7bSLoGin     info.set_create_ok(ProcessManager::current_pcb());
500de71ec25SLoGin     let to_mark_sleep = info.to_mark_sleep();
5011496ba7bSLoGin     drop(info);
5021496ba7bSLoGin 
503de71ec25SLoGin     if to_mark_sleep {
504de71ec25SLoGin         // 进入睡眠状态
5051496ba7bSLoGin         let irq_guard = CurrentIrqArch::save_and_disable_irq();
5061496ba7bSLoGin         ProcessManager::mark_sleep(true).expect("Failed to mark sleep");
5071496ba7bSLoGin         drop(irq_guard);
508f0c87a89SGnoCiYeH         schedule(SchedMode::SM_NONE);
509de71ec25SLoGin     }
5101496ba7bSLoGin 
5111496ba7bSLoGin     let mut retval = SystemError::EINTR.to_posix_errno();
5121496ba7bSLoGin 
5131496ba7bSLoGin     if !KernelThreadMechanism::should_stop(&ProcessManager::current_pcb()) {
5141496ba7bSLoGin         retval = closure.run();
5151496ba7bSLoGin     }
5161496ba7bSLoGin 
5171496ba7bSLoGin     ProcessManager::exit(retval as usize);
5181496ba7bSLoGin }
5191496ba7bSLoGin 
5205b59005fSLoGin /// 初始化内核线程机制
5215b59005fSLoGin #[inline(never)]
kthread_init()5221496ba7bSLoGin pub fn kthread_init() {
5231496ba7bSLoGin     static INIT: Once = Once::new();
5241496ba7bSLoGin     INIT.call_once(|| {
5251496ba7bSLoGin         KernelThreadMechanism::init_stage1();
5261496ba7bSLoGin     });
5271496ba7bSLoGin }
528