xref: /DragonOS/kernel/src/process/mod.rs (revision 70a4e5550a9fb49b537092287c3ddc36448c5b78)
1 use core::{
2     hash::{Hash, Hasher},
3     hint::spin_loop,
4     intrinsics::{likely, unlikely},
5     mem::ManuallyDrop,
6     sync::atomic::{compiler_fence, AtomicBool, AtomicI32, AtomicIsize, AtomicUsize, Ordering},
7 };
8 
9 use alloc::{
10     string::{String, ToString},
11     sync::{Arc, Weak},
12     vec::Vec,
13 };
14 use hashbrown::HashMap;
15 
16 use crate::{
17     arch::{
18         ipc::signal::{SigSet, Signal},
19         process::ArchPCBInfo,
20         sched::sched,
21         CurrentIrqArch,
22     },
23     exception::InterruptArch,
24     filesystem::{
25         procfs::procfs_unregister_pid,
26         vfs::{file::FileDescriptorVec, FileType},
27     },
28     ipc::signal_types::{SigInfo, SigPending, SignalStruct},
29     kdebug, kinfo,
30     libs::{
31         align::AlignedBox,
32         casting::DowncastArc,
33         futex::{
34             constant::{FutexFlag, FUTEX_BITSET_MATCH_ANY},
35             futex::Futex,
36         },
37         lock_free_flags::LockFreeFlags,
38         rwlock::{RwLock, RwLockReadGuard, RwLockUpgradableGuard, RwLockWriteGuard},
39         spinlock::{SpinLock, SpinLockGuard},
40         wait_queue::WaitQueue,
41     },
42     mm::{percpu::PerCpuVar, set_INITIAL_PROCESS_ADDRESS_SPACE, ucontext::AddressSpace, VirtAddr},
43     net::socket::SocketInode,
44     sched::{
45         completion::Completion,
46         core::{sched_enqueue, CPU_EXECUTING},
47         SchedPolicy, SchedPriority,
48     },
49     smp::kick_cpu,
50     syscall::{user_access::clear_user, Syscall, SystemError},
51 };
52 
53 use self::kthread::WorkerPrivate;
54 
55 pub mod abi;
56 pub mod c_adapter;
57 pub mod exec;
58 pub mod fork;
59 pub mod idle;
60 pub mod init;
61 pub mod kthread;
62 pub mod pid;
63 pub mod process;
64 pub mod syscall;
65 
66 /// 系统中所有进程的pcb
67 static ALL_PROCESS: SpinLock<Option<HashMap<Pid, Arc<ProcessControlBlock>>>> = SpinLock::new(None);
68 
69 pub static mut SWITCH_RESULT: Option<PerCpuVar<SwitchResult>> = None;
70 
71 /// 一个只改变1次的全局变量,标志进程管理器是否已经初始化完成
72 static mut __PROCESS_MANAGEMENT_INIT_DONE: bool = false;
73 
74 #[derive(Debug)]
75 pub struct SwitchResult {
76     pub prev_pcb: Option<Arc<ProcessControlBlock>>,
77     pub next_pcb: Option<Arc<ProcessControlBlock>>,
78 }
79 
80 impl SwitchResult {
81     pub fn new() -> Self {
82         Self {
83             prev_pcb: None,
84             next_pcb: None,
85         }
86     }
87 }
88 
89 #[derive(Debug)]
90 pub struct ProcessManager;
91 impl ProcessManager {
92     fn init() {
93         static INIT_FLAG: AtomicBool = AtomicBool::new(false);
94         if INIT_FLAG
95             .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
96             .is_err()
97         {
98             panic!("ProcessManager has been initialized!");
99         }
100 
101         unsafe {
102             compiler_fence(Ordering::SeqCst);
103             kdebug!("To create address space for INIT process.");
104             // test_buddy();
105             set_INITIAL_PROCESS_ADDRESS_SPACE(
106                 AddressSpace::new(true).expect("Failed to create address space for INIT process."),
107             );
108             kdebug!("INIT process address space created.");
109             compiler_fence(Ordering::SeqCst);
110         };
111 
112         ALL_PROCESS.lock().replace(HashMap::new());
113         Self::arch_init();
114         kdebug!("process arch init done.");
115         Self::init_idle();
116         kdebug!("process idle init done.");
117 
118         unsafe {
119             __PROCESS_MANAGEMENT_INIT_DONE = true;
120         }
121         kinfo!("Process Manager initialized.");
122     }
123 
124     /// 获取当前进程的pcb
125     pub fn current_pcb() -> Arc<ProcessControlBlock> {
126         if unlikely(unsafe { !__PROCESS_MANAGEMENT_INIT_DONE }) {
127             kerror!("unsafe__PROCESS_MANAGEMENT_INIT_DONE == false");
128             loop {
129                 spin_loop();
130             }
131         }
132         return ProcessControlBlock::arch_current_pcb();
133     }
134 
135     /// 增加当前进程的锁持有计数
136     #[inline(always)]
137     pub fn preempt_disable() {
138         if likely(unsafe { __PROCESS_MANAGEMENT_INIT_DONE }) {
139             ProcessManager::current_pcb().preempt_disable();
140         }
141     }
142 
143     /// 减少当前进程的锁持有计数
144     #[inline(always)]
145     pub fn preempt_enable() {
146         if likely(unsafe { __PROCESS_MANAGEMENT_INIT_DONE }) {
147             ProcessManager::current_pcb().preempt_enable();
148         }
149     }
150 
151     /// 根据pid获取进程的pcb
152     ///
153     /// ## 参数
154     ///
155     /// - `pid` : 进程的pid
156     ///
157     /// ## 返回值
158     ///
159     /// 如果找到了对应的进程,那么返回该进程的pcb,否则返回None
160     pub fn find(pid: Pid) -> Option<Arc<ProcessControlBlock>> {
161         return ALL_PROCESS.lock().as_ref()?.get(&pid).cloned();
162     }
163 
164     /// 向系统中添加一个进程的pcb
165     ///
166     /// ## 参数
167     ///
168     /// - `pcb` : 进程的pcb
169     ///
170     /// ## 返回值
171     ///
172     /// 无
173     pub fn add_pcb(pcb: Arc<ProcessControlBlock>) {
174         ALL_PROCESS
175             .lock()
176             .as_mut()
177             .unwrap()
178             .insert(pcb.pid(), pcb.clone());
179     }
180 
181     /// 唤醒一个进程
182     pub fn wakeup(pcb: &Arc<ProcessControlBlock>) -> Result<(), SystemError> {
183         let _guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
184         let state = pcb.sched_info().state();
185         if state.is_blocked() {
186             let mut writer: RwLockWriteGuard<'_, ProcessSchedulerInfo> = pcb.sched_info_mut();
187             let state = writer.state();
188             if state.is_blocked() {
189                 writer.set_state(ProcessState::Runnable);
190                 // avoid deadlock
191                 drop(writer);
192 
193                 sched_enqueue(pcb.clone(), true);
194                 return Ok(());
195             } else if state.is_exited() {
196                 return Err(SystemError::EINVAL);
197             } else {
198                 return Ok(());
199             }
200         } else if state.is_exited() {
201             return Err(SystemError::EINVAL);
202         } else {
203             return Ok(());
204         }
205     }
206 
207     /// 唤醒暂停的进程
208     pub fn wakeup_stop(pcb: &Arc<ProcessControlBlock>) -> Result<(), SystemError> {
209         let _guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
210         let state = pcb.sched_info().state();
211         if let ProcessState::Stopped = state {
212             let mut writer = pcb.sched_info_mut();
213             let state = writer.state();
214             if let ProcessState::Stopped = state {
215                 writer.set_state(ProcessState::Runnable);
216                 // avoid deadlock
217                 drop(writer);
218 
219                 sched_enqueue(pcb.clone(), true);
220                 return Ok(());
221             } else if state.is_runnable() {
222                 return Ok(());
223             } else {
224                 return Err(SystemError::EINVAL);
225             }
226         } else if state.is_runnable() {
227             return Ok(());
228         } else {
229             return Err(SystemError::EINVAL);
230         }
231     }
232 
233     /// 标志当前进程永久睡眠,但是发起调度的工作,应该由调用者完成
234     ///
235     /// ## 注意
236     ///
237     /// - 进入当前函数之前,不能持有sched_info的锁
238     /// - 进入当前函数之前,必须关闭中断
239     /// - 进入当前函数之后必须保证逻辑的正确性,避免被重复加入调度队列
240     pub fn mark_sleep(interruptable: bool) -> Result<(), SystemError> {
241         assert_eq!(
242             CurrentIrqArch::is_irq_enabled(),
243             false,
244             "interrupt must be disabled before enter ProcessManager::mark_sleep()"
245         );
246 
247         let pcb = ProcessManager::current_pcb();
248         let mut writer = pcb.sched_info_mut_irqsave();
249         if !matches!(writer.state(), ProcessState::Exited(_)) {
250             writer.set_state(ProcessState::Blocked(interruptable));
251             pcb.flags().insert(ProcessFlags::NEED_SCHEDULE);
252             drop(writer);
253 
254             return Ok(());
255         }
256         return Err(SystemError::EINTR);
257     }
258 
259     /// 标志当前进程为停止状态,但是发起调度的工作,应该由调用者完成
260     ///
261     /// ## 注意
262     ///
263     /// - 进入当前函数之前,不能持有sched_info的锁
264     /// - 进入当前函数之前,必须关闭中断
265     pub fn mark_stop() -> Result<(), SystemError> {
266         assert_eq!(
267             CurrentIrqArch::is_irq_enabled(),
268             false,
269             "interrupt must be disabled before enter ProcessManager::mark_stop()"
270         );
271 
272         let pcb = ProcessManager::current_pcb();
273         let mut writer = pcb.sched_info_mut_irqsave();
274         if !matches!(writer.state(), ProcessState::Exited(_)) {
275             writer.set_state(ProcessState::Stopped);
276             pcb.flags().insert(ProcessFlags::NEED_SCHEDULE);
277             drop(writer);
278 
279             return Ok(());
280         }
281         return Err(SystemError::EINTR);
282     }
283     /// 当子进程退出后向父进程发送通知
284     fn exit_notify() {
285         let current = ProcessManager::current_pcb();
286         // 让INIT进程收养所有子进程
287         if current.pid() != Pid(1) {
288             unsafe {
289                 current
290                     .adopt_childen()
291                     .unwrap_or_else(|e| panic!("adopte_childen failed: error: {e:?}"))
292             };
293             let r = current.parent_pcb.read().upgrade();
294             if r.is_none() {
295                 return;
296             }
297             let parent_pcb = r.unwrap();
298             let r = Syscall::kill(parent_pcb.pid(), Signal::SIGCHLD as i32);
299             if r.is_err() {
300                 kwarn!(
301                     "failed to send kill signal to {:?}'s parent pcb {:?}",
302                     current.pid(),
303                     parent_pcb.pid()
304                 );
305             }
306             // todo: 当信号机制重写后,这里需要向父进程发送SIGCHLD信号
307         }
308     }
309 
310     /// 退出当前进程
311     ///
312     /// ## 参数
313     ///
314     /// - `exit_code` : 进程的退出码
315     pub fn exit(exit_code: usize) -> ! {
316         // 关中断
317         let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
318         let pcb = ProcessManager::current_pcb();
319         pcb.sched_info
320             .write()
321             .set_state(ProcessState::Exited(exit_code));
322         pcb.wait_queue.wakeup(Some(ProcessState::Blocked(true)));
323 
324         // 进行进程退出后的工作
325         let thread = pcb.thread.write();
326         if let Some(addr) = thread.set_child_tid {
327             unsafe { clear_user(addr, core::mem::size_of::<i32>()).expect("clear tid failed") };
328         }
329 
330         if let Some(addr) = thread.clear_child_tid {
331             if Arc::strong_count(&pcb.basic().user_vm().expect("User VM Not found")) > 1 {
332                 let _ =
333                     Futex::futex_wake(addr, FutexFlag::FLAGS_MATCH_NONE, 1, FUTEX_BITSET_MATCH_ANY);
334             }
335             unsafe { clear_user(addr, core::mem::size_of::<i32>()).expect("clear tid failed") };
336         }
337 
338         // 如果是vfork出来的进程,则需要处理completion
339         if thread.vfork_done.is_some() {
340             thread.vfork_done.as_ref().unwrap().complete_all();
341         }
342         drop(thread);
343         unsafe { pcb.basic_mut().set_user_vm(None) };
344         drop(pcb);
345         ProcessManager::exit_notify();
346         drop(irq_guard);
347 
348         sched();
349         loop {}
350     }
351 
352     pub unsafe fn release(pid: Pid) {
353         let pcb = ProcessManager::find(pid);
354         if !pcb.is_none() {
355             // let pcb = pcb.unwrap();
356             // 判断该pcb是否在全局没有任何引用
357             // TODO: 当前,pcb的Arc指针存在泄露问题,引用计数不正确,打算在接下来实现debug专用的Arc,方便调试,然后解决这个bug。
358             //          因此目前暂时注释掉,使得能跑
359             // if Arc::strong_count(&pcb) <= 2 {
360             //     drop(pcb);
361             //     ALL_PROCESS.lock().as_mut().unwrap().remove(&pid);
362             // } else {
363             //     // 如果不为1就panic
364             //     let msg = format!("pcb '{:?}' is still referenced, strong count={}",pcb.pid(),  Arc::strong_count(&pcb));
365             //     kerror!("{}", msg);
366             //     panic!()
367             // }
368 
369             ALL_PROCESS.lock().as_mut().unwrap().remove(&pid);
370         }
371     }
372 
373     /// 上下文切换完成后的钩子函数
374     unsafe fn switch_finish_hook() {
375         // kdebug!("switch_finish_hook");
376         let prev_pcb = SWITCH_RESULT
377             .as_mut()
378             .unwrap()
379             .get_mut()
380             .prev_pcb
381             .take()
382             .expect("prev_pcb is None");
383         let next_pcb = SWITCH_RESULT
384             .as_mut()
385             .unwrap()
386             .get_mut()
387             .next_pcb
388             .take()
389             .expect("next_pcb is None");
390 
391         // 由于进程切换前使用了SpinLockGuard::leak(),所以这里需要手动释放锁
392         prev_pcb.arch_info.force_unlock();
393         next_pcb.arch_info.force_unlock();
394     }
395 
396     /// 如果目标进程正在目标CPU上运行,那么就让这个cpu陷入内核态
397     ///
398     /// ## 参数
399     ///
400     /// - `pcb` : 进程的pcb
401     #[allow(dead_code)]
402     pub fn kick(pcb: &Arc<ProcessControlBlock>) {
403         ProcessManager::current_pcb().preempt_disable();
404         let cpu_id = pcb.sched_info().on_cpu();
405 
406         if let Some(cpu_id) = cpu_id {
407             let cpu_id = cpu_id;
408 
409             if pcb.pid() == CPU_EXECUTING.get(cpu_id) {
410                 kick_cpu(cpu_id).expect("ProcessManager::kick(): Failed to kick cpu");
411             }
412         }
413 
414         ProcessManager::current_pcb().preempt_enable();
415     }
416 }
417 
418 /// 上下文切换的钩子函数,当这个函数return的时候,将会发生上下文切换
419 pub unsafe extern "sysv64" fn switch_finish_hook() {
420     ProcessManager::switch_finish_hook();
421 }
422 
423 int_like!(Pid, AtomicPid, usize, AtomicUsize);
424 
425 impl Hash for Pid {
426     fn hash<H: Hasher>(&self, state: &mut H) {
427         self.0.hash(state);
428     }
429 }
430 
431 impl Pid {
432     pub fn to_string(&self) -> String {
433         self.0.to_string()
434     }
435 }
436 
437 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
438 pub enum ProcessState {
439     /// The process is running on a CPU or in a run queue.
440     Runnable,
441     /// The process is waiting for an event to occur.
442     /// 其中的bool表示该等待过程是否可以被打断。
443     /// - 如果该bool为true,那么,硬件中断/信号/其他系统事件都可以打断该等待过程,使得该进程重新进入Runnable状态。
444     /// - 如果该bool为false,那么,这个进程必须被显式的唤醒,才能重新进入Runnable状态。
445     Blocked(bool),
446     /// 进程被信号终止
447     Stopped,
448     /// 进程已经退出,usize表示进程的退出码
449     Exited(usize),
450 }
451 
452 #[allow(dead_code)]
453 impl ProcessState {
454     #[inline(always)]
455     pub fn is_runnable(&self) -> bool {
456         return matches!(self, ProcessState::Runnable);
457     }
458 
459     #[inline(always)]
460     pub fn is_blocked(&self) -> bool {
461         return matches!(self, ProcessState::Blocked(_));
462     }
463 
464     #[inline(always)]
465     pub fn is_exited(&self) -> bool {
466         return matches!(self, ProcessState::Exited(_));
467     }
468 
469     /// Returns `true` if the process state is [`Stopped`].
470     ///
471     /// [`Stopped`]: ProcessState::Stopped
472     #[inline(always)]
473     pub fn is_stopped(&self) -> bool {
474         matches!(self, ProcessState::Stopped)
475     }
476 }
477 
478 bitflags! {
479     /// pcb的标志位
480     pub struct ProcessFlags: usize {
481         /// 当前pcb表示一个内核线程
482         const KTHREAD = 1 << 0;
483         /// 当前进程需要被调度
484         const NEED_SCHEDULE = 1 << 1;
485         /// 进程由于vfork而与父进程存在资源共享
486         const VFORK = 1 << 2;
487         /// 进程不可被冻结
488         const NOFREEZE = 1 << 3;
489         /// 进程正在退出
490         const EXITING = 1 << 4;
491         /// 进程由于接收到终止信号唤醒
492         const WAKEKILL = 1 << 5;
493         /// 进程由于接收到信号而退出.(Killed by a signal)
494         const SIGNALED = 1 << 6;
495         /// 进程需要迁移到其他cpu上
496         const NEED_MIGRATE = 1 << 7;
497     }
498 }
499 
500 #[derive(Debug)]
501 pub struct ProcessControlBlock {
502     /// 当前进程的pid
503     pid: Pid,
504 
505     basic: RwLock<ProcessBasicInfo>,
506     /// 当前进程的自旋锁持有计数
507     preempt_count: AtomicUsize,
508 
509     flags: LockFreeFlags<ProcessFlags>,
510     worker_private: SpinLock<Option<WorkerPrivate>>,
511     /// 进程的内核栈
512     kernel_stack: RwLock<KernelStack>,
513 
514     /// 系统调用栈
515     syscall_stack: RwLock<KernelStack>,
516 
517     /// 与调度相关的信息
518     sched_info: RwLock<ProcessSchedulerInfo>,
519     /// 与处理器架构相关的信息
520     arch_info: SpinLock<ArchPCBInfo>,
521     /// 与信号处理相关的信息(似乎可以是无锁的)
522     sig_info: RwLock<ProcessSignalInfo>,
523     /// 信号处理结构体
524     sig_struct: SpinLock<SignalStruct>,
525 
526     /// 父进程指针
527     parent_pcb: RwLock<Weak<ProcessControlBlock>>,
528 
529     /// 子进程链表
530     children: RwLock<Vec<Pid>>,
531 
532     /// 等待队列
533     wait_queue: WaitQueue,
534 
535     /// 线程信息
536     thread: RwLock<ThreadInfo>,
537 }
538 
539 impl ProcessControlBlock {
540     /// Generate a new pcb.
541     ///
542     /// ## 参数
543     ///
544     /// - `name` : 进程的名字
545     /// - `kstack` : 进程的内核栈
546     ///
547     /// ## 返回值
548     ///
549     /// 返回一个新的pcb
550     pub fn new(name: String, kstack: KernelStack) -> Arc<Self> {
551         return Self::do_create_pcb(name, kstack, false);
552     }
553 
554     /// 创建一个新的idle进程
555     ///
556     /// 请注意,这个函数只能在进程管理初始化的时候调用。
557     pub fn new_idle(cpu_id: u32, kstack: KernelStack) -> Arc<Self> {
558         let name = format!("idle-{}", cpu_id);
559         return Self::do_create_pcb(name, kstack, true);
560     }
561 
562     fn do_create_pcb(name: String, kstack: KernelStack, is_idle: bool) -> Arc<Self> {
563         let (pid, ppid, cwd) = if is_idle {
564             (Pid(0), Pid(0), "/".to_string())
565         } else {
566             (
567                 Self::generate_pid(),
568                 ProcessManager::current_pcb().pid(),
569                 ProcessManager::current_pcb().basic().cwd(),
570             )
571         };
572 
573         let basic_info = ProcessBasicInfo::new(Pid(0), ppid, name, cwd, None);
574         let preempt_count = AtomicUsize::new(0);
575         let flags = unsafe { LockFreeFlags::new(ProcessFlags::empty()) };
576 
577         let sched_info = ProcessSchedulerInfo::new(None);
578         let arch_info = SpinLock::new(ArchPCBInfo::new(&kstack));
579 
580         let ppcb: Weak<ProcessControlBlock> = ProcessManager::find(ppid)
581             .map(|p| Arc::downgrade(&p))
582             .unwrap_or_else(|| Weak::new());
583 
584         let pcb = Self {
585             pid,
586             basic: basic_info,
587             preempt_count,
588             flags,
589             kernel_stack: RwLock::new(kstack),
590             syscall_stack: RwLock::new(KernelStack::new().unwrap()),
591             worker_private: SpinLock::new(None),
592             sched_info,
593             arch_info,
594             sig_info: RwLock::new(ProcessSignalInfo::default()),
595             sig_struct: SpinLock::new(SignalStruct::default()),
596             parent_pcb: RwLock::new(ppcb),
597             children: RwLock::new(Vec::new()),
598             wait_queue: WaitQueue::INIT,
599             thread: RwLock::new(ThreadInfo::new()),
600         };
601 
602         // 初始化系统调用栈
603         pcb.arch_info
604             .lock()
605             .init_syscall_stack(&pcb.syscall_stack.read());
606 
607         let pcb = Arc::new(pcb);
608 
609         // 设置进程的arc指针到内核栈和系统调用栈的最低地址处
610         unsafe {
611             pcb.kernel_stack
612                 .write()
613                 .set_pcb(Arc::downgrade(&pcb))
614                 .unwrap();
615 
616             pcb.syscall_stack
617                 .write()
618                 .set_pcb(Arc::downgrade(&pcb))
619                 .unwrap()
620         };
621 
622         // 将当前pcb加入父进程的子进程哈希表中
623         if pcb.pid() > Pid(1) {
624             if let Some(ppcb_arc) = pcb.parent_pcb.read().upgrade() {
625                 let mut children = ppcb_arc.children.write();
626                 children.push(pcb.pid());
627             } else {
628                 panic!("parent pcb is None");
629             }
630         }
631 
632         return pcb;
633     }
634 
635     /// 生成一个新的pid
636     #[inline(always)]
637     fn generate_pid() -> Pid {
638         static NEXT_PID: AtomicPid = AtomicPid::new(Pid(1));
639         return NEXT_PID.fetch_add(Pid(1), Ordering::SeqCst);
640     }
641 
642     /// 返回当前进程的锁持有计数
643     #[inline(always)]
644     pub fn preempt_count(&self) -> usize {
645         return self.preempt_count.load(Ordering::SeqCst);
646     }
647 
648     /// 增加当前进程的锁持有计数
649     #[inline(always)]
650     pub fn preempt_disable(&self) {
651         self.preempt_count.fetch_add(1, Ordering::SeqCst);
652     }
653 
654     /// 减少当前进程的锁持有计数
655     #[inline(always)]
656     pub fn preempt_enable(&self) {
657         self.preempt_count.fetch_sub(1, Ordering::SeqCst);
658     }
659 
660     #[inline(always)]
661     pub unsafe fn set_preempt_count(&self, count: usize) {
662         self.preempt_count.store(count, Ordering::SeqCst);
663     }
664 
665     #[inline(always)]
666     pub fn flags(&self) -> &mut ProcessFlags {
667         return self.flags.get_mut();
668     }
669 
670     #[inline(always)]
671     pub fn basic(&self) -> RwLockReadGuard<ProcessBasicInfo> {
672         return self.basic.read();
673     }
674 
675     #[inline(always)]
676     pub fn set_name(&self, name: String) {
677         self.basic.write().set_name(name);
678     }
679 
680     #[inline(always)]
681     pub fn basic_mut(&self) -> RwLockWriteGuard<ProcessBasicInfo> {
682         return self.basic.write();
683     }
684 
685     #[inline(always)]
686     pub fn arch_info(&self) -> SpinLockGuard<ArchPCBInfo> {
687         return self.arch_info.lock();
688     }
689 
690     #[inline(always)]
691     pub fn arch_info_irqsave(&self) -> SpinLockGuard<ArchPCBInfo> {
692         return self.arch_info.lock_irqsave();
693     }
694 
695     #[inline(always)]
696     pub fn kernel_stack(&self) -> RwLockReadGuard<KernelStack> {
697         return self.kernel_stack.read();
698     }
699 
700     #[inline(always)]
701     #[allow(dead_code)]
702     pub fn kernel_stack_mut(&self) -> RwLockWriteGuard<KernelStack> {
703         return self.kernel_stack.write();
704     }
705 
706     #[inline(always)]
707     pub fn sched_info(&self) -> RwLockReadGuard<ProcessSchedulerInfo> {
708         return self.sched_info.read();
709     }
710 
711     #[inline(always)]
712     pub fn try_sched_info(&self, times: u8) -> Option<RwLockReadGuard<ProcessSchedulerInfo>> {
713         for _ in 0..times {
714             if let Some(r) = self.sched_info.try_read() {
715                 return Some(r);
716             }
717         }
718 
719         return None;
720     }
721 
722     #[allow(dead_code)]
723     #[inline(always)]
724     pub fn sched_info_irqsave(&self) -> RwLockReadGuard<ProcessSchedulerInfo> {
725         return self.sched_info.read_irqsave();
726     }
727 
728     #[inline(always)]
729     pub fn sched_info_try_upgradeable_irqsave(
730         &self,
731         times: u8,
732     ) -> Option<RwLockUpgradableGuard<ProcessSchedulerInfo>> {
733         for _ in 0..times {
734             if let Some(r) = self.sched_info.try_upgradeable_read_irqsave() {
735                 return Some(r);
736             }
737         }
738         return None;
739     }
740 
741     #[inline(always)]
742     pub fn sched_info_mut(&self) -> RwLockWriteGuard<ProcessSchedulerInfo> {
743         return self.sched_info.write();
744     }
745 
746     #[inline(always)]
747     pub fn sched_info_mut_irqsave(&self) -> RwLockWriteGuard<ProcessSchedulerInfo> {
748         return self.sched_info.write_irqsave();
749     }
750 
751     #[inline(always)]
752     pub fn worker_private(&self) -> SpinLockGuard<Option<WorkerPrivate>> {
753         return self.worker_private.lock();
754     }
755 
756     #[inline(always)]
757     pub fn pid(&self) -> Pid {
758         return self.pid;
759     }
760 
761     /// 获取文件描述符表的Arc指针
762     #[inline(always)]
763     pub fn fd_table(&self) -> Arc<RwLock<FileDescriptorVec>> {
764         return self.basic.read().fd_table().unwrap();
765     }
766 
767     /// 根据文件描述符序号,获取socket对象的Arc指针
768     ///
769     /// ## 参数
770     ///
771     /// - `fd` 文件描述符序号
772     ///
773     /// ## 返回值
774     ///
775     /// Option(&mut Box<dyn Socket>) socket对象的可变引用. 如果文件描述符不是socket,那么返回None
776     pub fn get_socket(&self, fd: i32) -> Option<Arc<SocketInode>> {
777         let binding = ProcessManager::current_pcb().fd_table();
778         let fd_table_guard = binding.read();
779 
780         let f = fd_table_guard.get_file_by_fd(fd)?;
781         drop(fd_table_guard);
782 
783         let guard = f.lock();
784         if guard.file_type() != FileType::Socket {
785             return None;
786         }
787         let socket: Arc<SocketInode> = guard
788             .inode()
789             .downcast_arc::<SocketInode>()
790             .expect("Not a socket inode");
791         return Some(socket);
792     }
793 
794     /// 当前进程退出时,让初始进程收养所有子进程
795     unsafe fn adopt_childen(&self) -> Result<(), SystemError> {
796         match ProcessManager::find(Pid(1)) {
797             Some(init_pcb) => {
798                 let childen_guard = self.children.write();
799                 let mut init_childen_guard = init_pcb.children.write();
800 
801                 childen_guard.iter().for_each(|pid| {
802                     init_childen_guard.push(*pid);
803                 });
804 
805                 return Ok(());
806             }
807             _ => Err(SystemError::ECHILD),
808         }
809     }
810 
811     /// 生成进程的名字
812     pub fn generate_name(program_path: &str, args: &Vec<String>) -> String {
813         let mut name = program_path.to_string();
814         for arg in args {
815             name.push_str(arg);
816             name.push(' ');
817         }
818         return name;
819     }
820 
821     pub fn sig_info(&self) -> RwLockReadGuard<ProcessSignalInfo> {
822         self.sig_info.read()
823     }
824 
825     pub fn try_siginfo(&self, times: u8) -> Option<RwLockReadGuard<ProcessSignalInfo>> {
826         for _ in 0..times {
827             if let Some(r) = self.sig_info.try_read() {
828                 return Some(r);
829             }
830         }
831 
832         return None;
833     }
834 
835     pub fn sig_info_mut(&self) -> RwLockWriteGuard<ProcessSignalInfo> {
836         self.sig_info.write()
837     }
838 
839     pub fn try_siginfo_mut(&self, times: u8) -> Option<RwLockWriteGuard<ProcessSignalInfo>> {
840         for _ in 0..times {
841             if let Some(r) = self.sig_info.try_write() {
842                 return Some(r);
843             }
844         }
845 
846         return None;
847     }
848 
849     pub fn sig_struct(&self) -> SpinLockGuard<SignalStruct> {
850         self.sig_struct.lock()
851     }
852 
853     pub fn try_sig_struct_irq(&self, times: u8) -> Option<SpinLockGuard<SignalStruct>> {
854         for _ in 0..times {
855             if let Ok(r) = self.sig_struct.try_lock_irqsave() {
856                 return Some(r);
857             }
858         }
859 
860         return None;
861     }
862 
863     pub fn sig_struct_irq(&self) -> SpinLockGuard<SignalStruct> {
864         self.sig_struct.lock_irqsave()
865     }
866 }
867 
868 impl Drop for ProcessControlBlock {
869     fn drop(&mut self) {
870         // 在ProcFS中,解除进程的注册
871         procfs_unregister_pid(self.pid())
872             .unwrap_or_else(|e| panic!("procfs_unregister_pid failed: error: {e:?}"));
873 
874         if let Some(ppcb) = self.parent_pcb.read().upgrade() {
875             ppcb.children.write().drain_filter(|pid| *pid == self.pid());
876         }
877     }
878 }
879 
880 /// 线程信息
881 #[derive(Debug)]
882 pub struct ThreadInfo {
883     // 来自用户空间记录用户线程id的地址,在该线程结束时将该地址置0以通知父进程
884     clear_child_tid: Option<VirtAddr>,
885     set_child_tid: Option<VirtAddr>,
886 
887     vfork_done: Option<Arc<Completion>>,
888 }
889 
890 impl ThreadInfo {
891     pub fn new() -> Self {
892         Self {
893             clear_child_tid: None,
894             set_child_tid: None,
895             vfork_done: None,
896         }
897     }
898 }
899 
900 /// 进程的基本信息
901 ///
902 /// 这个结构体保存进程的基本信息,主要是那些不会随着进程的运行而经常改变的信息。
903 #[derive(Debug)]
904 pub struct ProcessBasicInfo {
905     /// 当前进程的进程组id
906     pgid: Pid,
907     /// 当前进程的父进程的pid
908     ppid: Pid,
909     /// 进程的名字
910     name: String,
911 
912     /// 当前进程的工作目录
913     cwd: String,
914 
915     /// 用户地址空间
916     user_vm: Option<Arc<AddressSpace>>,
917 
918     /// 文件描述符表
919     fd_table: Option<Arc<RwLock<FileDescriptorVec>>>,
920 }
921 
922 impl ProcessBasicInfo {
923     pub fn new(
924         pgid: Pid,
925         ppid: Pid,
926         name: String,
927         cwd: String,
928         user_vm: Option<Arc<AddressSpace>>,
929     ) -> RwLock<Self> {
930         let fd_table = Arc::new(RwLock::new(FileDescriptorVec::new()));
931         return RwLock::new(Self {
932             pgid,
933             ppid,
934             name,
935             cwd,
936             user_vm,
937             fd_table: Some(fd_table),
938         });
939     }
940 
941     pub fn pgid(&self) -> Pid {
942         return self.pgid;
943     }
944 
945     pub fn ppid(&self) -> Pid {
946         return self.ppid;
947     }
948 
949     pub fn name(&self) -> &str {
950         return &self.name;
951     }
952 
953     pub fn set_name(&mut self, name: String) {
954         self.name = name;
955     }
956 
957     pub fn cwd(&self) -> String {
958         return self.cwd.clone();
959     }
960     pub fn set_cwd(&mut self, path: String) {
961         return self.cwd = path;
962     }
963 
964     pub fn user_vm(&self) -> Option<Arc<AddressSpace>> {
965         return self.user_vm.clone();
966     }
967 
968     pub unsafe fn set_user_vm(&mut self, user_vm: Option<Arc<AddressSpace>>) {
969         self.user_vm = user_vm;
970     }
971 
972     pub fn fd_table(&self) -> Option<Arc<RwLock<FileDescriptorVec>>> {
973         return self.fd_table.clone();
974     }
975 
976     pub fn set_fd_table(&mut self, fd_table: Option<Arc<RwLock<FileDescriptorVec>>>) {
977         self.fd_table = fd_table;
978     }
979 }
980 
981 #[derive(Debug)]
982 pub struct ProcessSchedulerInfo {
983     /// 当前进程所在的cpu
984     on_cpu: AtomicI32,
985     /// 如果当前进程等待被迁移到另一个cpu核心上(也就是flags中的PF_NEED_MIGRATE被置位),
986     /// 该字段存储要被迁移到的目标处理器核心号
987     migrate_to: AtomicI32,
988 
989     /// 当前进程的状态
990     state: ProcessState,
991     /// 进程的调度策略
992     sched_policy: SchedPolicy,
993     /// 进程的调度优先级
994     priority: SchedPriority,
995     /// 当前进程的虚拟运行时间
996     virtual_runtime: AtomicIsize,
997     /// 由实时调度器管理的时间片
998     rt_time_slice: AtomicIsize,
999 }
1000 
1001 impl ProcessSchedulerInfo {
1002     pub fn new(on_cpu: Option<u32>) -> RwLock<Self> {
1003         let cpu_id = match on_cpu {
1004             Some(cpu_id) => cpu_id as i32,
1005             None => -1,
1006         };
1007         return RwLock::new(Self {
1008             on_cpu: AtomicI32::new(cpu_id),
1009             migrate_to: AtomicI32::new(-1),
1010             state: ProcessState::Blocked(false),
1011             sched_policy: SchedPolicy::CFS,
1012             virtual_runtime: AtomicIsize::new(0),
1013             rt_time_slice: AtomicIsize::new(0),
1014             priority: SchedPriority::new(100).unwrap(),
1015         });
1016     }
1017 
1018     pub fn on_cpu(&self) -> Option<u32> {
1019         let on_cpu = self.on_cpu.load(Ordering::SeqCst);
1020         if on_cpu == -1 {
1021             return None;
1022         } else {
1023             return Some(on_cpu as u32);
1024         }
1025     }
1026 
1027     pub fn set_on_cpu(&self, on_cpu: Option<u32>) {
1028         if let Some(cpu_id) = on_cpu {
1029             self.on_cpu.store(cpu_id as i32, Ordering::SeqCst);
1030         } else {
1031             self.on_cpu.store(-1, Ordering::SeqCst);
1032         }
1033     }
1034 
1035     pub fn migrate_to(&self) -> Option<u32> {
1036         let migrate_to = self.migrate_to.load(Ordering::SeqCst);
1037         if migrate_to == -1 {
1038             return None;
1039         } else {
1040             return Some(migrate_to as u32);
1041         }
1042     }
1043 
1044     pub fn set_migrate_to(&self, migrate_to: Option<u32>) {
1045         if let Some(data) = migrate_to {
1046             self.migrate_to.store(data as i32, Ordering::SeqCst);
1047         } else {
1048             self.migrate_to.store(-1, Ordering::SeqCst)
1049         }
1050     }
1051 
1052     pub fn state(&self) -> ProcessState {
1053         return self.state;
1054     }
1055 
1056     pub fn set_state(&mut self, state: ProcessState) {
1057         self.state = state;
1058     }
1059 
1060     pub fn policy(&self) -> SchedPolicy {
1061         return self.sched_policy;
1062     }
1063 
1064     pub fn virtual_runtime(&self) -> isize {
1065         return self.virtual_runtime.load(Ordering::SeqCst);
1066     }
1067 
1068     pub fn set_virtual_runtime(&self, virtual_runtime: isize) {
1069         self.virtual_runtime
1070             .store(virtual_runtime, Ordering::SeqCst);
1071     }
1072     pub fn increase_virtual_runtime(&self, delta: isize) {
1073         self.virtual_runtime.fetch_add(delta, Ordering::SeqCst);
1074     }
1075 
1076     pub fn rt_time_slice(&self) -> isize {
1077         return self.rt_time_slice.load(Ordering::SeqCst);
1078     }
1079 
1080     pub fn set_rt_time_slice(&self, rt_time_slice: isize) {
1081         self.rt_time_slice.store(rt_time_slice, Ordering::SeqCst);
1082     }
1083 
1084     pub fn increase_rt_time_slice(&self, delta: isize) {
1085         self.rt_time_slice.fetch_add(delta, Ordering::SeqCst);
1086     }
1087 
1088     pub fn priority(&self) -> SchedPriority {
1089         return self.priority;
1090     }
1091 }
1092 
1093 #[derive(Debug, Clone)]
1094 pub struct KernelStack {
1095     stack: Option<AlignedBox<[u8; KernelStack::SIZE], { KernelStack::ALIGN }>>,
1096     /// 标记该内核栈是否可以被释放
1097     can_be_freed: bool,
1098 }
1099 
1100 impl KernelStack {
1101     pub const SIZE: usize = 0x4000;
1102     pub const ALIGN: usize = 0x4000;
1103 
1104     pub fn new() -> Result<Self, SystemError> {
1105         return Ok(Self {
1106             stack: Some(
1107                 AlignedBox::<[u8; KernelStack::SIZE], { KernelStack::ALIGN }>::new_zeroed()?,
1108             ),
1109             can_be_freed: true,
1110         });
1111     }
1112 
1113     /// 根据已有的空间,构造一个内核栈结构体
1114     ///
1115     /// 仅仅用于BSP启动时,为idle进程构造内核栈。其他时候使用这个函数,很可能造成错误!
1116     pub unsafe fn from_existed(base: VirtAddr) -> Result<Self, SystemError> {
1117         if base.is_null() || base.check_aligned(Self::ALIGN) == false {
1118             return Err(SystemError::EFAULT);
1119         }
1120 
1121         return Ok(Self {
1122             stack: Some(
1123                 AlignedBox::<[u8; KernelStack::SIZE], { KernelStack::ALIGN }>::new_unchecked(
1124                     base.data() as *mut [u8; KernelStack::SIZE],
1125                 ),
1126             ),
1127             can_be_freed: false,
1128         });
1129     }
1130 
1131     /// 返回内核栈的起始虚拟地址(低地址)
1132     pub fn start_address(&self) -> VirtAddr {
1133         return VirtAddr::new(self.stack.as_ref().unwrap().as_ptr() as usize);
1134     }
1135 
1136     /// 返回内核栈的结束虚拟地址(高地址)(不包含该地址)
1137     pub fn stack_max_address(&self) -> VirtAddr {
1138         return VirtAddr::new(self.stack.as_ref().unwrap().as_ptr() as usize + Self::SIZE);
1139     }
1140 
1141     pub unsafe fn set_pcb(&mut self, pcb: Weak<ProcessControlBlock>) -> Result<(), SystemError> {
1142         // 将一个Weak<ProcessControlBlock>放到内核栈的最低地址处
1143         let p: *const ProcessControlBlock = Weak::into_raw(pcb);
1144         let stack_bottom_ptr = self.start_address().data() as *mut *const ProcessControlBlock;
1145 
1146         // 如果内核栈的最低地址处已经有了一个pcb,那么,这里就不再设置,直接返回错误
1147         if unlikely(unsafe { !(*stack_bottom_ptr).is_null() }) {
1148             kerror!("kernel stack bottom is not null: {:p}", *stack_bottom_ptr);
1149             return Err(SystemError::EPERM);
1150         }
1151         // 将pcb的地址放到内核栈的最低地址处
1152         unsafe {
1153             *stack_bottom_ptr = p;
1154         }
1155 
1156         return Ok(());
1157     }
1158 
1159     /// 清除内核栈的pcb指针
1160     ///
1161     /// ## 参数
1162     ///
1163     /// - `force` : 如果为true,那么,即使该内核栈的pcb指针不为null,也会被强制清除而不处理Weak指针问题
1164     pub unsafe fn clear_pcb(&mut self, force: bool) {
1165         let stack_bottom_ptr = self.start_address().data() as *mut *const ProcessControlBlock;
1166         if unlikely(unsafe { (*stack_bottom_ptr).is_null() }) {
1167             return;
1168         }
1169 
1170         if !force {
1171             let pcb_ptr: Weak<ProcessControlBlock> = Weak::from_raw(*stack_bottom_ptr);
1172             drop(pcb_ptr);
1173         }
1174 
1175         *stack_bottom_ptr = core::ptr::null();
1176     }
1177 
1178     /// 返回指向当前内核栈pcb的Arc指针
1179     #[allow(dead_code)]
1180     pub unsafe fn pcb(&self) -> Option<Arc<ProcessControlBlock>> {
1181         // 从内核栈的最低地址处取出pcb的地址
1182         let p = self.stack.as_ref().unwrap().as_ptr() as *const ProcessControlBlock;
1183         if unlikely(p.is_null()) {
1184             return None;
1185         }
1186 
1187         // 为了防止内核栈的pcb指针被释放,这里需要将其包装一下,使得Arc的drop不会被调用
1188         let weak_wrapper: ManuallyDrop<Weak<ProcessControlBlock>> =
1189             ManuallyDrop::new(Weak::from_raw(p));
1190 
1191         let new_arc: Arc<ProcessControlBlock> = weak_wrapper.upgrade()?;
1192         return Some(new_arc);
1193     }
1194 }
1195 
1196 impl Drop for KernelStack {
1197     fn drop(&mut self) {
1198         if !self.stack.is_none() {
1199             let pcb_ptr: Weak<ProcessControlBlock> = unsafe {
1200                 Weak::from_raw(self.stack.as_ref().unwrap().as_ptr() as *const ProcessControlBlock)
1201             };
1202             drop(pcb_ptr);
1203         }
1204         // 如果该内核栈不可以被释放,那么,这里就forget,不调用AlignedBox的drop函数
1205         if !self.can_be_freed {
1206             let bx = self.stack.take();
1207             core::mem::forget(bx);
1208         }
1209     }
1210 }
1211 
1212 pub fn process_init() {
1213     ProcessManager::init();
1214 }
1215 
1216 #[derive(Debug)]
1217 pub struct ProcessSignalInfo {
1218     // 当前进程
1219     sig_block: SigSet,
1220     // sig_pending 中存储当前线程要处理的信号
1221     sig_pending: SigPending,
1222     // sig_shared_pending 中存储当前线程所属进程要处理的信号
1223     sig_shared_pending: SigPending,
1224 }
1225 
1226 impl ProcessSignalInfo {
1227     pub fn sig_block(&self) -> &SigSet {
1228         &self.sig_block
1229     }
1230 
1231     pub fn sig_pending(&self) -> &SigPending {
1232         &self.sig_pending
1233     }
1234 
1235     pub fn sig_pending_mut(&mut self) -> &mut SigPending {
1236         &mut self.sig_pending
1237     }
1238 
1239     pub fn sig_block_mut(&mut self) -> &mut SigSet {
1240         &mut self.sig_block
1241     }
1242 
1243     pub fn sig_shared_pending_mut(&mut self) -> &mut SigPending {
1244         &mut self.sig_shared_pending
1245     }
1246 
1247     pub fn sig_shared_pending(&self) -> &SigPending {
1248         &self.sig_shared_pending
1249     }
1250 
1251     /// 从 pcb 的 siginfo中取出下一个要处理的信号,先处理线程信号,再处理进程信号
1252     ///
1253     /// ## 参数
1254     ///
1255     /// - `sig_mask` 被忽略掉的信号
1256     ///
1257     pub fn dequeue_signal(&mut self, sig_mask: &SigSet) -> (Signal, Option<SigInfo>) {
1258         let res = self.sig_pending.dequeue_signal(sig_mask);
1259         if res.0 != Signal::INVALID {
1260             return res;
1261         } else {
1262             return self.sig_shared_pending.dequeue_signal(sig_mask);
1263         }
1264     }
1265 }
1266 
1267 impl Default for ProcessSignalInfo {
1268     fn default() -> Self {
1269         Self {
1270             sig_block: SigSet::empty(),
1271             sig_pending: SigPending::default(),
1272             sig_shared_pending: SigPending::default(),
1273         }
1274     }
1275 }
1276