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