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