xref: /DragonOS/kernel/src/process/kthread.rs (revision 83ed0ebc293d5a10245089f627f52770fd5b9dd4)
1 use core::{
2     hint::spin_loop,
3     sync::atomic::{AtomicBool, Ordering},
4 };
5 
6 use alloc::{
7     boxed::Box,
8     collections::LinkedList,
9     string::{String, ToString},
10     sync::{Arc, Weak},
11 };
12 use atomic_enum::atomic_enum;
13 
14 use crate::{
15     arch::{sched::sched, CurrentIrqArch},
16     exception::InterruptArch,
17     kdebug, kinfo,
18     libs::{once::Once, spinlock::SpinLock},
19     process::{ProcessManager, ProcessState},
20     syscall::SystemError,
21 };
22 
23 use super::{
24     fork::CloneFlags, init::initial_kernel_thread, Pid, ProcessControlBlock, ProcessFlags,
25 };
26 
27 /// 内核线程的创建任务列表
28 static KTHREAD_CREATE_LIST: SpinLock<LinkedList<Arc<KernelThreadCreateInfo>>> =
29     SpinLock::new(LinkedList::new());
30 
31 static mut KTHREAD_DAEMON_PCB: Option<Arc<ProcessControlBlock>> = None;
32 
33 #[derive(Debug)]
34 pub enum WorkerPrivate {
35     KernelThread(KernelThreadPcbPrivate),
36 }
37 
38 #[allow(dead_code)]
39 impl WorkerPrivate {
40     pub fn kernel_thread(&self) -> Option<&KernelThreadPcbPrivate> {
41         match self {
42             Self::KernelThread(x) => Some(x),
43         }
44     }
45 
46     pub fn kernel_thread_mut(&mut self) -> Option<&mut KernelThreadPcbPrivate> {
47         match self {
48             Self::KernelThread(x) => Some(x),
49         }
50     }
51 }
52 
53 bitflags! {
54     pub struct KernelThreadFlags: u32 {
55         const IS_PER_CPU = 1 << 0;
56         const SHOULD_STOP = 1 << 1;
57         const SHOULD_PARK = 1 << 2;
58     }
59 }
60 
61 #[derive(Debug)]
62 pub struct KernelThreadPcbPrivate {
63     flags: KernelThreadFlags,
64 }
65 
66 #[allow(dead_code)]
67 impl KernelThreadPcbPrivate {
68     pub fn new() -> Self {
69         Self {
70             flags: KernelThreadFlags::empty(),
71         }
72     }
73 
74     pub fn flags(&self) -> &KernelThreadFlags {
75         &self.flags
76     }
77 
78     pub fn flags_mut(&mut self) -> &mut KernelThreadFlags {
79         &mut self.flags
80     }
81 }
82 
83 /// 内核线程的闭包,参数必须与闭包的参数一致,返回值必须是i32
84 ///
85 /// 元组的第一个元素是闭包,第二个元素是闭包的参数对象
86 ///
87 /// 对于非原始类型的参数,需要使用Box包装
88 #[allow(dead_code)]
89 pub enum KernelThreadClosure {
90     UsizeClosure((Box<dyn Fn(usize) -> i32 + Send + Sync>, usize)),
91     EmptyClosure((Box<dyn Fn() -> i32 + Send + Sync>, ())),
92     // 添加其他类型入参的闭包,返回值必须是i32
93 }
94 
95 impl KernelThreadClosure {
96     pub fn run(self) -> i32 {
97         match self {
98             Self::UsizeClosure((func, arg)) => func(arg),
99             Self::EmptyClosure((func, _arg)) => func(),
100         }
101     }
102 }
103 
104 pub struct KernelThreadCreateInfo {
105     /// 内核线程的入口函数、传入参数
106     closure: SpinLock<Option<Box<KernelThreadClosure>>>,
107     /// 内核线程的名字
108     name: String,
109     /// 是否已经完成创建 todo:使用comletion机制优化这里
110     created: AtomicKernelThreadCreateStatus,
111     result_pcb: SpinLock<Option<Arc<ProcessControlBlock>>>,
112     /// 不安全的Arc引用计数,当内核线程创建失败时,需要减少这个计数
113     has_unsafe_arc_instance: AtomicBool,
114     self_ref: Weak<Self>,
115     /// 如果该值为true在进入bootstrap stage2之后,就会进入睡眠状态
116     to_mark_sleep: AtomicBool,
117 }
118 
119 #[atomic_enum]
120 #[derive(PartialEq)]
121 pub enum KernelThreadCreateStatus {
122     Created,
123     NotCreated,
124     ErrorOccured,
125 }
126 
127 #[allow(dead_code)]
128 impl KernelThreadCreateInfo {
129     pub fn new(func: KernelThreadClosure, name: String) -> Arc<Self> {
130         let result = Arc::new(Self {
131             closure: SpinLock::new(Some(Box::new(func))),
132             name,
133             created: AtomicKernelThreadCreateStatus::new(KernelThreadCreateStatus::NotCreated),
134             result_pcb: SpinLock::new(None),
135             has_unsafe_arc_instance: AtomicBool::new(false),
136             self_ref: Weak::new(),
137             to_mark_sleep: AtomicBool::new(true),
138         });
139         let tmp = result.clone();
140         unsafe {
141             let tmp = Arc::into_raw(tmp) as *mut Self;
142             (*tmp).self_ref = Arc::downgrade(&result);
143             Arc::from_raw(tmp);
144         }
145 
146         return result;
147     }
148 
149     /// 创建者调用这函数,等待创建完成后,获取创建结果
150     ///
151     /// ## 返回值
152     ///
153     /// - Some(Arc<ProcessControlBlock>) 创建成功,返回新创建的内核线程的PCB
154     /// - None 创建失败
155     pub fn poll_result(&self) -> Option<Arc<ProcessControlBlock>> {
156         loop {
157             match self.created.load(Ordering::SeqCst) {
158                 KernelThreadCreateStatus::Created => {
159                     return self.result_pcb.lock().take();
160                 }
161                 KernelThreadCreateStatus::NotCreated => {
162                     spin_loop();
163                 }
164                 KernelThreadCreateStatus::ErrorOccured => {
165                     // 创建失败,减少不安全的Arc引用计数
166                     let to_delete = self.has_unsafe_arc_instance.swap(false, Ordering::SeqCst);
167                     if to_delete {
168                         let self_ref = self.self_ref.upgrade().unwrap();
169                         unsafe { Arc::decrement_strong_count(&self_ref) };
170                     }
171                     return None;
172                 }
173             }
174         }
175     }
176 
177     pub fn take_closure(&self) -> Option<Box<KernelThreadClosure>> {
178         return self.closure.lock().take();
179     }
180 
181     pub fn name(&self) -> &String {
182         &self.name
183     }
184 
185     pub unsafe fn set_create_ok(&self, pcb: Arc<ProcessControlBlock>) {
186         // todo: 使用completion机制优化这里
187         self.result_pcb.lock().replace(pcb);
188         self.created
189             .store(KernelThreadCreateStatus::Created, Ordering::SeqCst);
190     }
191 
192     /// 生成一个不安全的Arc指针(用于创建内核线程时传递参数)
193     pub fn generate_unsafe_arc_ptr(self: Arc<Self>) -> *const Self {
194         assert!(
195             self.has_unsafe_arc_instance
196                 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
197                 .is_ok(),
198             "Cannot generate unsafe arc ptr when there is already one."
199         );
200         let ptr = Arc::into_raw(self);
201         return ptr;
202     }
203 
204     pub unsafe fn parse_unsafe_arc_ptr(ptr: *const Self) -> Arc<Self> {
205         let arc = Arc::from_raw(ptr);
206         assert!(
207             arc.has_unsafe_arc_instance
208                 .compare_exchange(true, false, Ordering::SeqCst, Ordering::SeqCst)
209                 .is_ok(),
210             "Cannot parse unsafe arc ptr when there is no one."
211         );
212         assert!(Arc::strong_count(&arc) > 0);
213         return arc;
214     }
215 
216     /// 设置是否在进入bootstrap stage2之后,就进入睡眠状态
217     ///
218     /// ## 参数
219     ///
220     /// - to_mark_sleep: 是否在进入bootstrap stage2之后,就进入睡眠状态
221     ///
222     /// ## 返回值
223     /// 如果已经创建完成,返回EINVAL
224     pub fn set_to_mark_sleep(&self, to_mark_sleep: bool) -> Result<(), SystemError> {
225         let result_guard = self.result_pcb.lock();
226         if result_guard.is_some() {
227             // 已经创建完成,不需要设置
228             return Err(SystemError::EINVAL);
229         }
230         self.to_mark_sleep.store(to_mark_sleep, Ordering::SeqCst);
231         return Ok(());
232     }
233 
234     pub fn to_mark_sleep(&self) -> bool {
235         self.to_mark_sleep.load(Ordering::SeqCst)
236     }
237 }
238 
239 pub struct KernelThreadMechanism;
240 
241 impl KernelThreadMechanism {
242     pub fn init_stage1() {
243         assert!(ProcessManager::current_pcb().pid() == Pid::new(0));
244         kinfo!("Initializing kernel thread mechanism stage1...");
245 
246         // 初始化第一个内核线程
247 
248         let create_info = KernelThreadCreateInfo::new(
249             KernelThreadClosure::EmptyClosure((Box::new(initial_kernel_thread), ())),
250             "init".to_string(),
251         );
252 
253         let irq_guard: crate::exception::IrqFlagsGuard =
254             unsafe { CurrentIrqArch::save_and_disable_irq() };
255         // 由于当前是pid=0的idle进程,而__inner_create要求当前是kthread,所以先临时设置为kthread
256         ProcessManager::current_pcb()
257             .flags
258             .get_mut()
259             .insert(ProcessFlags::KTHREAD);
260         create_info
261             .set_to_mark_sleep(false)
262             .expect("Failed to set to_mark_sleep");
263 
264         KernelThreadMechanism::__inner_create(
265             &create_info,
266             CloneFlags::CLONE_VM | CloneFlags::CLONE_SIGNAL,
267         )
268         .unwrap_or_else(|e| panic!("Failed to create initial kernel thread, error: {:?}", e));
269 
270         ProcessManager::current_pcb()
271             .flags
272             .get_mut()
273             .remove(ProcessFlags::KTHREAD);
274 
275         drop(irq_guard);
276         kinfo!("Initializing kernel thread mechanism stage1 complete");
277     }
278 
279     pub fn init_stage2() {
280         assert!(ProcessManager::current_pcb()
281             .flags()
282             .contains(ProcessFlags::KTHREAD));
283         static INIT: Once = Once::new();
284         INIT.call_once(|| {
285             kinfo!("Initializing kernel thread mechanism stage2...");
286             // 初始化kthreadd
287             let closure = KernelThreadClosure::EmptyClosure((Box::new(Self::kthread_daemon), ()));
288             let info = KernelThreadCreateInfo::new(closure, "kthreadd".to_string());
289             let kthreadd_pid: Pid = Self::__inner_create(
290                 &info,
291                 CloneFlags::CLONE_VM | CloneFlags::CLONE_FS | CloneFlags::CLONE_SIGNAL,
292             )
293             .expect("Failed to create kthread daemon");
294 
295             let pcb = ProcessManager::find(kthreadd_pid).unwrap();
296             ProcessManager::wakeup(&pcb).expect("Failed to wakeup kthread daemon");
297             unsafe {
298                 KTHREAD_DAEMON_PCB.replace(pcb);
299             }
300             kinfo!("Initializing kernel thread mechanism stage2 complete");
301         });
302     }
303 
304     /// 创建一个新的内核线程
305     ///
306     /// ## 参数
307     ///
308     /// - func: 内核线程的入口函数、传入参数
309     /// - name: 内核线程的名字
310     ///
311     /// ## 返回值
312     ///
313     /// - Some(Arc<ProcessControlBlock>) 创建成功,返回新创建的内核线程的PCB
314     #[allow(dead_code)]
315     pub fn create(func: KernelThreadClosure, name: String) -> Option<Arc<ProcessControlBlock>> {
316         let info = KernelThreadCreateInfo::new(func, name);
317         while unsafe { KTHREAD_DAEMON_PCB.is_none() } {
318             // 等待kthreadd启动
319             spin_loop()
320         }
321         KTHREAD_CREATE_LIST.lock().push_back(info.clone());
322         ProcessManager::wakeup(unsafe { KTHREAD_DAEMON_PCB.as_ref().unwrap() })
323             .expect("Failed to wakeup kthread daemon");
324         return info.poll_result();
325     }
326 
327     /// 创建并运行一个新的内核线程
328     ///
329     /// ## 参数
330     ///
331     /// - func: 内核线程的入口函数、传入参数
332     /// - name: 内核线程的名字
333     ///
334     /// ## 返回值
335     ///
336     /// - Some(Arc<ProcessControlBlock>) 创建成功,返回新创建的内核线程的PCB
337     #[allow(dead_code)]
338     pub fn create_and_run(
339         func: KernelThreadClosure,
340         name: String,
341     ) -> Option<Arc<ProcessControlBlock>> {
342         let pcb = Self::create(func, name)?;
343         ProcessManager::wakeup(&pcb)
344             .expect(format!("Failed to wakeup kthread: {:?}", pcb.pid()).as_str());
345         return Some(pcb);
346     }
347 
348     /// 停止一个内核线程
349     ///
350     /// 如果目标内核线程的数据检查失败,会panic
351     ///
352     /// ## 返回值
353     ///
354     /// - Ok(i32) 目标内核线程的退出码
355     #[allow(dead_code)]
356     pub fn stop(pcb: &Arc<ProcessControlBlock>) -> Result<usize, SystemError> {
357         if !pcb.flags().contains(ProcessFlags::KTHREAD) {
358             panic!("Cannt stop a non-kthread process");
359         }
360 
361         let mut worker_private = pcb.worker_private();
362         assert!(
363             worker_private.is_some(),
364             "kthread stop: worker_private is none, pid: {:?}",
365             pcb.pid()
366         );
367         worker_private
368             .as_mut()
369             .unwrap()
370             .kernel_thread_mut()
371             .expect("Error type of worker private")
372             .flags
373             .insert(KernelThreadFlags::SHOULD_STOP);
374 
375         drop(worker_private);
376 
377         ProcessManager::wakeup(pcb).ok();
378 
379         // 忙等目标内核线程退出
380         // todo: 使用completion机制优化这里
381         loop {
382             if let ProcessState::Exited(code) = pcb.sched_info().state() {
383                 return Ok(code);
384             }
385             spin_loop();
386         }
387     }
388 
389     /// 判断一个内核线程是否应当停止
390     ///
391     /// ## 参数
392     ///
393     /// - pcb: 目标内核线程的PCB
394     ///
395     /// ## 返回值
396     ///
397     /// - bool 是否应当停止. true表示应当停止,false表示不应当停止. 如果目标进程不是内核线程,返回false
398     ///
399     /// ## Panic
400     ///
401     /// 如果目标内核线程的数据检查失败,会panic
402     #[allow(dead_code)]
403     pub fn should_stop(pcb: &Arc<ProcessControlBlock>) -> bool {
404         if !pcb.flags().contains(ProcessFlags::KTHREAD) {
405             return false;
406         }
407 
408         let worker_private = pcb.worker_private();
409         assert!(
410             worker_private.is_some(),
411             "kthread should_stop: worker_private is none, pid: {:?}",
412             pcb.pid()
413         );
414         return worker_private
415             .as_ref()
416             .unwrap()
417             .kernel_thread()
418             .expect("Error type of worker private")
419             .flags
420             .contains(KernelThreadFlags::SHOULD_STOP);
421     }
422 
423     /// A daemon thread which creates other kernel threads
424     fn kthread_daemon() -> i32 {
425         let current_pcb = ProcessManager::current_pcb();
426         kdebug!("kthread_daemon: pid: {:?}", current_pcb.pid());
427         {
428             // 初始化worker_private
429             let mut worker_private_guard = current_pcb.worker_private();
430             let worker_private = WorkerPrivate::KernelThread(KernelThreadPcbPrivate::new());
431             *worker_private_guard = Some(worker_private);
432         }
433         // 设置为kthread
434         current_pcb.flags().insert(ProcessFlags::KTHREAD);
435         drop(current_pcb);
436 
437         loop {
438             let mut list = KTHREAD_CREATE_LIST.lock();
439             while let Some(info) = list.pop_front() {
440                 drop(list);
441 
442                 // create a new kernel thread
443                 let result: Result<Pid, SystemError> =
444                     Self::__inner_create(&info, CloneFlags::CLONE_FS | CloneFlags::CLONE_SIGNAL);
445 
446                 if result.is_err() {
447                     // 创建失败
448                     info.created
449                         .store(KernelThreadCreateStatus::ErrorOccured, Ordering::SeqCst);
450                 };
451                 list = KTHREAD_CREATE_LIST.lock();
452             }
453             drop(list);
454 
455             let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
456             ProcessManager::mark_sleep(true).ok();
457             drop(irq_guard);
458             sched();
459         }
460     }
461 }
462 
463 /// 内核线程启动的第二阶段
464 ///
465 /// 该函数只能被`kernel_thread_bootstrap_stage1`调用(jmp到该函数)
466 ///
467 /// ## 参数
468 ///
469 /// - ptr: 传入的参数,是一个指向`Arc<KernelThreadCreateInfo>`的指针
470 pub unsafe extern "C" fn kernel_thread_bootstrap_stage2(ptr: *const KernelThreadCreateInfo) -> ! {
471     let info = KernelThreadCreateInfo::parse_unsafe_arc_ptr(ptr);
472 
473     let closure: Box<KernelThreadClosure> = info.take_closure().unwrap();
474     info.set_create_ok(ProcessManager::current_pcb());
475     let to_mark_sleep = info.to_mark_sleep();
476     drop(info);
477 
478     if to_mark_sleep {
479         // 进入睡眠状态
480         let irq_guard = CurrentIrqArch::save_and_disable_irq();
481         ProcessManager::mark_sleep(true).expect("Failed to mark sleep");
482         drop(irq_guard);
483         sched();
484     }
485 
486     let mut retval = SystemError::EINTR.to_posix_errno();
487 
488     if !KernelThreadMechanism::should_stop(&ProcessManager::current_pcb()) {
489         retval = closure.run();
490     }
491 
492     ProcessManager::exit(retval as usize);
493 }
494 
495 pub fn kthread_init() {
496     static INIT: Once = Once::new();
497     INIT.call_once(|| {
498         KernelThreadMechanism::init_stage1();
499     });
500 }
501