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