xref: /DragonOS/kernel/src/process/mod.rs (revision d14e28a8a9b023ee8df7c2e8eee43e523134dbb2)
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     #[inline(never)]
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         const RANDOMIZE = 1 << 8;
526     }
527 }
528 
529 #[derive(Debug)]
530 pub struct ProcessControlBlock {
531     /// 当前进程的pid
532     pid: Pid,
533     /// 当前进程的线程组id(这个值在同一个线程组内永远不变)
534     tgid: Pid,
535 
536     basic: RwLock<ProcessBasicInfo>,
537     /// 当前进程的自旋锁持有计数
538     preempt_count: AtomicUsize,
539 
540     flags: LockFreeFlags<ProcessFlags>,
541     worker_private: SpinLock<Option<WorkerPrivate>>,
542     /// 进程的内核栈
543     kernel_stack: RwLock<KernelStack>,
544 
545     /// 系统调用栈
546     syscall_stack: RwLock<KernelStack>,
547 
548     /// 与调度相关的信息
549     sched_info: ProcessSchedulerInfo,
550     /// 与处理器架构相关的信息
551     arch_info: SpinLock<ArchPCBInfo>,
552     /// 与信号处理相关的信息(似乎可以是无锁的)
553     sig_info: RwLock<ProcessSignalInfo>,
554     /// 信号处理结构体
555     sig_struct: SpinLock<SignalStruct>,
556     /// 退出信号S
557     exit_signal: AtomicSignal,
558 
559     /// 父进程指针
560     parent_pcb: RwLock<Weak<ProcessControlBlock>>,
561     /// 真实父进程指针
562     real_parent_pcb: RwLock<Weak<ProcessControlBlock>>,
563 
564     /// 子进程链表
565     children: RwLock<Vec<Pid>>,
566 
567     /// 等待队列
568     wait_queue: WaitQueue,
569 
570     /// 线程信息
571     thread: RwLock<ThreadInfo>,
572 }
573 
574 impl ProcessControlBlock {
575     /// Generate a new pcb.
576     ///
577     /// ## 参数
578     ///
579     /// - `name` : 进程的名字
580     /// - `kstack` : 进程的内核栈
581     ///
582     /// ## 返回值
583     ///
584     /// 返回一个新的pcb
585     pub fn new(name: String, kstack: KernelStack) -> Arc<Self> {
586         return Self::do_create_pcb(name, kstack, false);
587     }
588 
589     /// 创建一个新的idle进程
590     ///
591     /// 请注意,这个函数只能在进程管理初始化的时候调用。
592     pub fn new_idle(cpu_id: u32, kstack: KernelStack) -> Arc<Self> {
593         let name = format!("idle-{}", cpu_id);
594         return Self::do_create_pcb(name, kstack, true);
595     }
596 
597     #[inline(never)]
598     fn do_create_pcb(name: String, kstack: KernelStack, is_idle: bool) -> Arc<Self> {
599         let (pid, ppid, cwd) = if is_idle {
600             (Pid(0), Pid(0), "/".to_string())
601         } else {
602             let ppid = ProcessManager::current_pcb().pid();
603             let cwd = ProcessManager::current_pcb().basic().cwd();
604             (Self::generate_pid(), ppid, cwd)
605         };
606 
607         let basic_info = ProcessBasicInfo::new(Pid(0), ppid, name, cwd, None);
608         let preempt_count = AtomicUsize::new(0);
609         let flags = unsafe { LockFreeFlags::new(ProcessFlags::empty()) };
610 
611         let sched_info = ProcessSchedulerInfo::new(None);
612         let arch_info = SpinLock::new(ArchPCBInfo::new(&kstack));
613 
614         let ppcb: Weak<ProcessControlBlock> = ProcessManager::find(ppid)
615             .map(|p| Arc::downgrade(&p))
616             .unwrap_or_else(|| Weak::new());
617 
618         let pcb = Self {
619             pid,
620             tgid: pid,
621             basic: basic_info,
622             preempt_count,
623             flags,
624             kernel_stack: RwLock::new(kstack),
625             syscall_stack: RwLock::new(KernelStack::new().unwrap()),
626             worker_private: SpinLock::new(None),
627             sched_info,
628             arch_info,
629             sig_info: RwLock::new(ProcessSignalInfo::default()),
630             sig_struct: SpinLock::new(SignalStruct::new()),
631             exit_signal: AtomicSignal::new(Signal::SIGCHLD),
632             parent_pcb: RwLock::new(ppcb.clone()),
633             real_parent_pcb: RwLock::new(ppcb),
634             children: RwLock::new(Vec::new()),
635             wait_queue: WaitQueue::INIT,
636             thread: RwLock::new(ThreadInfo::new()),
637         };
638 
639         // 初始化系统调用栈
640         #[cfg(target_arch = "x86_64")]
641         pcb.arch_info
642             .lock()
643             .init_syscall_stack(&pcb.syscall_stack.read());
644 
645         let pcb = Arc::new(pcb);
646 
647         // 设置进程的arc指针到内核栈和系统调用栈的最低地址处
648         unsafe {
649             pcb.kernel_stack
650                 .write()
651                 .set_pcb(Arc::downgrade(&pcb))
652                 .unwrap();
653 
654             pcb.syscall_stack
655                 .write()
656                 .set_pcb(Arc::downgrade(&pcb))
657                 .unwrap()
658         };
659 
660         // 将当前pcb加入父进程的子进程哈希表中
661         if pcb.pid() > Pid(1) {
662             if let Some(ppcb_arc) = pcb.parent_pcb.read().upgrade() {
663                 let mut children = ppcb_arc.children.write_irqsave();
664                 children.push(pcb.pid());
665             } else {
666                 panic!("parent pcb is None");
667             }
668         }
669 
670         return pcb;
671     }
672 
673     /// 生成一个新的pid
674     #[inline(always)]
675     fn generate_pid() -> Pid {
676         static NEXT_PID: AtomicPid = AtomicPid::new(Pid(1));
677         return NEXT_PID.fetch_add(Pid(1), Ordering::SeqCst);
678     }
679 
680     /// 返回当前进程的锁持有计数
681     #[inline(always)]
682     pub fn preempt_count(&self) -> usize {
683         return self.preempt_count.load(Ordering::SeqCst);
684     }
685 
686     /// 增加当前进程的锁持有计数
687     #[inline(always)]
688     pub fn preempt_disable(&self) {
689         self.preempt_count.fetch_add(1, Ordering::SeqCst);
690     }
691 
692     /// 减少当前进程的锁持有计数
693     #[inline(always)]
694     pub fn preempt_enable(&self) {
695         self.preempt_count.fetch_sub(1, Ordering::SeqCst);
696     }
697 
698     #[inline(always)]
699     pub unsafe fn set_preempt_count(&self, count: usize) {
700         self.preempt_count.store(count, Ordering::SeqCst);
701     }
702 
703     #[inline(always)]
704     pub fn flags(&self) -> &mut ProcessFlags {
705         return self.flags.get_mut();
706     }
707 
708     /// 请注意,这个值能在中断上下文中读取,但不能被中断上下文修改
709     /// 否则会导致死锁
710     #[inline(always)]
711     pub fn basic(&self) -> RwLockReadGuard<ProcessBasicInfo> {
712         return self.basic.read();
713     }
714 
715     #[inline(always)]
716     pub fn set_name(&self, name: String) {
717         self.basic.write().set_name(name);
718     }
719 
720     #[inline(always)]
721     pub fn basic_mut(&self) -> RwLockWriteGuard<ProcessBasicInfo> {
722         return self.basic.write_irqsave();
723     }
724 
725     /// # 获取arch info的锁,同时关闭中断
726     #[inline(always)]
727     pub fn arch_info_irqsave(&self) -> SpinLockGuard<ArchPCBInfo> {
728         return self.arch_info.lock_irqsave();
729     }
730 
731     /// # 获取arch info的锁,但是不关闭中断
732     ///
733     /// 由于arch info在进程切换的时候会使用到,
734     /// 因此在中断上下文外,获取arch info 而不irqsave是不安全的.
735     ///
736     /// 只能在以下情况下使用这个函数:
737     /// - 在中断上下文中(中断已经禁用),获取arch info的锁。
738     /// - 刚刚创建新的pcb
739     #[inline(always)]
740     pub unsafe fn arch_info(&self) -> SpinLockGuard<ArchPCBInfo> {
741         return self.arch_info.lock();
742     }
743 
744     #[inline(always)]
745     pub fn kernel_stack(&self) -> RwLockReadGuard<KernelStack> {
746         return self.kernel_stack.read();
747     }
748 
749     #[inline(always)]
750     #[allow(dead_code)]
751     pub fn kernel_stack_mut(&self) -> RwLockWriteGuard<KernelStack> {
752         return self.kernel_stack.write();
753     }
754 
755     #[inline(always)]
756     pub fn sched_info(&self) -> &ProcessSchedulerInfo {
757         return &self.sched_info;
758     }
759 
760     #[inline(always)]
761     pub fn worker_private(&self) -> SpinLockGuard<Option<WorkerPrivate>> {
762         return self.worker_private.lock();
763     }
764 
765     #[inline(always)]
766     pub fn pid(&self) -> Pid {
767         return self.pid;
768     }
769 
770     #[inline(always)]
771     pub fn tgid(&self) -> Pid {
772         return self.tgid;
773     }
774 
775     /// 获取文件描述符表的Arc指针
776     #[inline(always)]
777     pub fn fd_table(&self) -> Arc<RwLock<FileDescriptorVec>> {
778         return self.basic.read().fd_table().unwrap();
779     }
780 
781     /// 根据文件描述符序号,获取socket对象的Arc指针
782     ///
783     /// ## 参数
784     ///
785     /// - `fd` 文件描述符序号
786     ///
787     /// ## 返回值
788     ///
789     /// Option(&mut Box<dyn Socket>) socket对象的可变引用. 如果文件描述符不是socket,那么返回None
790     pub fn get_socket(&self, fd: i32) -> Option<Arc<SocketInode>> {
791         let binding = ProcessManager::current_pcb().fd_table();
792         let fd_table_guard = binding.read();
793 
794         let f = fd_table_guard.get_file_by_fd(fd)?;
795         drop(fd_table_guard);
796 
797         let guard = f.lock();
798         if guard.file_type() != FileType::Socket {
799             return None;
800         }
801         let socket: Arc<SocketInode> = guard
802             .inode()
803             .downcast_arc::<SocketInode>()
804             .expect("Not a socket inode");
805         return Some(socket);
806     }
807 
808     /// 当前进程退出时,让初始进程收养所有子进程
809     unsafe fn adopt_childen(&self) -> Result<(), SystemError> {
810         match ProcessManager::find(Pid(1)) {
811             Some(init_pcb) => {
812                 let childen_guard = self.children.write();
813                 let mut init_childen_guard = init_pcb.children.write();
814 
815                 childen_guard.iter().for_each(|pid| {
816                     init_childen_guard.push(*pid);
817                 });
818 
819                 return Ok(());
820             }
821             _ => Err(SystemError::ECHILD),
822         }
823     }
824 
825     /// 生成进程的名字
826     pub fn generate_name(program_path: &str, args: &Vec<String>) -> String {
827         let mut name = program_path.to_string();
828         for arg in args {
829             name.push(' ');
830             name.push_str(arg);
831         }
832         return name;
833     }
834 
835     pub fn sig_info(&self) -> RwLockReadGuard<ProcessSignalInfo> {
836         self.sig_info.read()
837     }
838 
839     pub fn sig_info_irqsave(&self) -> RwLockReadGuard<ProcessSignalInfo> {
840         self.sig_info.read_irqsave()
841     }
842 
843     pub fn try_siginfo(&self, times: u8) -> Option<RwLockReadGuard<ProcessSignalInfo>> {
844         for _ in 0..times {
845             if let Some(r) = self.sig_info.try_read() {
846                 return Some(r);
847             }
848         }
849 
850         return None;
851     }
852 
853     pub fn sig_info_mut(&self) -> RwLockWriteGuard<ProcessSignalInfo> {
854         self.sig_info.write_irqsave()
855     }
856 
857     pub fn try_siginfo_mut(&self, times: u8) -> Option<RwLockWriteGuard<ProcessSignalInfo>> {
858         for _ in 0..times {
859             if let Some(r) = self.sig_info.try_write() {
860                 return Some(r);
861             }
862         }
863 
864         return None;
865     }
866 
867     pub fn sig_struct(&self) -> SpinLockGuard<SignalStruct> {
868         self.sig_struct.lock()
869     }
870 
871     pub fn try_sig_struct_irq(&self, times: u8) -> Option<SpinLockGuard<SignalStruct>> {
872         for _ in 0..times {
873             if let Ok(r) = self.sig_struct.try_lock_irqsave() {
874                 return Some(r);
875             }
876         }
877 
878         return None;
879     }
880 
881     pub fn sig_struct_irqsave(&self) -> SpinLockGuard<SignalStruct> {
882         self.sig_struct.lock_irqsave()
883     }
884 }
885 
886 impl Drop for ProcessControlBlock {
887     fn drop(&mut self) {
888         // 在ProcFS中,解除进程的注册
889         procfs_unregister_pid(self.pid())
890             .unwrap_or_else(|e| panic!("procfs_unregister_pid failed: error: {e:?}"));
891 
892         if let Some(ppcb) = self.parent_pcb.read().upgrade() {
893             ppcb.children.write().retain(|pid| *pid != self.pid());
894         }
895     }
896 }
897 
898 /// 线程信息
899 #[derive(Debug)]
900 pub struct ThreadInfo {
901     // 来自用户空间记录用户线程id的地址,在该线程结束时将该地址置0以通知父进程
902     clear_child_tid: Option<VirtAddr>,
903     set_child_tid: Option<VirtAddr>,
904 
905     vfork_done: Option<Arc<Completion>>,
906     /// 线程组的组长
907     group_leader: Weak<ProcessControlBlock>,
908 }
909 
910 impl ThreadInfo {
911     pub fn new() -> Self {
912         Self {
913             clear_child_tid: None,
914             set_child_tid: None,
915             vfork_done: None,
916             group_leader: Weak::default(),
917         }
918     }
919 
920     pub fn group_leader(&self) -> Option<Arc<ProcessControlBlock>> {
921         return self.group_leader.upgrade();
922     }
923 }
924 
925 /// 进程的基本信息
926 ///
927 /// 这个结构体保存进程的基本信息,主要是那些不会随着进程的运行而经常改变的信息。
928 #[derive(Debug)]
929 pub struct ProcessBasicInfo {
930     /// 当前进程的进程组id
931     pgid: Pid,
932     /// 当前进程的父进程的pid
933     ppid: Pid,
934     /// 进程的名字
935     name: String,
936 
937     /// 当前进程的工作目录
938     cwd: String,
939 
940     /// 用户地址空间
941     user_vm: Option<Arc<AddressSpace>>,
942 
943     /// 文件描述符表
944     fd_table: Option<Arc<RwLock<FileDescriptorVec>>>,
945 }
946 
947 impl ProcessBasicInfo {
948     #[inline(never)]
949     pub fn new(
950         pgid: Pid,
951         ppid: Pid,
952         name: String,
953         cwd: String,
954         user_vm: Option<Arc<AddressSpace>>,
955     ) -> RwLock<Self> {
956         let fd_table = Arc::new(RwLock::new(FileDescriptorVec::new()));
957         return RwLock::new(Self {
958             pgid,
959             ppid,
960             name,
961             cwd,
962             user_vm,
963             fd_table: Some(fd_table),
964         });
965     }
966 
967     pub fn pgid(&self) -> Pid {
968         return self.pgid;
969     }
970 
971     pub fn ppid(&self) -> Pid {
972         return self.ppid;
973     }
974 
975     pub fn name(&self) -> &str {
976         return &self.name;
977     }
978 
979     pub fn set_name(&mut self, name: String) {
980         self.name = name;
981     }
982 
983     pub fn cwd(&self) -> String {
984         return self.cwd.clone();
985     }
986     pub fn set_cwd(&mut self, path: String) {
987         return self.cwd = path;
988     }
989 
990     pub fn user_vm(&self) -> Option<Arc<AddressSpace>> {
991         return self.user_vm.clone();
992     }
993 
994     pub unsafe fn set_user_vm(&mut self, user_vm: Option<Arc<AddressSpace>>) {
995         self.user_vm = user_vm;
996     }
997 
998     pub fn fd_table(&self) -> Option<Arc<RwLock<FileDescriptorVec>>> {
999         return self.fd_table.clone();
1000     }
1001 
1002     pub fn set_fd_table(&mut self, fd_table: Option<Arc<RwLock<FileDescriptorVec>>>) {
1003         self.fd_table = fd_table;
1004     }
1005 }
1006 
1007 #[derive(Debug)]
1008 pub struct ProcessSchedulerInfo {
1009     /// 当前进程所在的cpu
1010     on_cpu: AtomicI32,
1011     /// 如果当前进程等待被迁移到另一个cpu核心上(也就是flags中的PF_NEED_MIGRATE被置位),
1012     /// 该字段存储要被迁移到的目标处理器核心号
1013     migrate_to: AtomicI32,
1014     inner_locked: RwLock<InnerSchedInfo>,
1015     /// 进程的调度优先级
1016     priority: SchedPriority,
1017     /// 当前进程的虚拟运行时间
1018     virtual_runtime: AtomicIsize,
1019     /// 由实时调度器管理的时间片
1020     rt_time_slice: AtomicIsize,
1021 }
1022 
1023 #[derive(Debug)]
1024 pub struct InnerSchedInfo {
1025     /// 当前进程的状态
1026     state: ProcessState,
1027     /// 进程的调度策略
1028     sched_policy: SchedPolicy,
1029 }
1030 
1031 impl InnerSchedInfo {
1032     pub fn state(&self) -> ProcessState {
1033         return self.state;
1034     }
1035 
1036     pub fn set_state(&mut self, state: ProcessState) {
1037         self.state = state;
1038     }
1039 
1040     pub fn policy(&self) -> SchedPolicy {
1041         return self.sched_policy;
1042     }
1043 }
1044 
1045 impl ProcessSchedulerInfo {
1046     #[inline(never)]
1047     pub fn new(on_cpu: Option<u32>) -> Self {
1048         let cpu_id = match on_cpu {
1049             Some(cpu_id) => cpu_id as i32,
1050             None => -1,
1051         };
1052         return Self {
1053             on_cpu: AtomicI32::new(cpu_id),
1054             migrate_to: AtomicI32::new(-1),
1055             inner_locked: RwLock::new(InnerSchedInfo {
1056                 state: ProcessState::Blocked(false),
1057                 sched_policy: SchedPolicy::CFS,
1058             }),
1059             virtual_runtime: AtomicIsize::new(0),
1060             rt_time_slice: AtomicIsize::new(0),
1061             priority: SchedPriority::new(100).unwrap(),
1062         };
1063     }
1064 
1065     pub fn on_cpu(&self) -> Option<u32> {
1066         let on_cpu = self.on_cpu.load(Ordering::SeqCst);
1067         if on_cpu == -1 {
1068             return None;
1069         } else {
1070             return Some(on_cpu as u32);
1071         }
1072     }
1073 
1074     pub fn set_on_cpu(&self, on_cpu: Option<u32>) {
1075         if let Some(cpu_id) = on_cpu {
1076             self.on_cpu.store(cpu_id as i32, Ordering::SeqCst);
1077         } else {
1078             self.on_cpu.store(-1, Ordering::SeqCst);
1079         }
1080     }
1081 
1082     pub fn migrate_to(&self) -> Option<u32> {
1083         let migrate_to = self.migrate_to.load(Ordering::SeqCst);
1084         if migrate_to == -1 {
1085             return None;
1086         } else {
1087             return Some(migrate_to as u32);
1088         }
1089     }
1090 
1091     pub fn set_migrate_to(&self, migrate_to: Option<u32>) {
1092         if let Some(data) = migrate_to {
1093             self.migrate_to.store(data as i32, Ordering::SeqCst);
1094         } else {
1095             self.migrate_to.store(-1, Ordering::SeqCst)
1096         }
1097     }
1098 
1099     pub fn inner_lock_write_irqsave(&self) -> RwLockWriteGuard<InnerSchedInfo> {
1100         return self.inner_locked.write_irqsave();
1101     }
1102 
1103     pub fn inner_lock_read_irqsave(&self) -> RwLockReadGuard<InnerSchedInfo> {
1104         return self.inner_locked.read_irqsave();
1105     }
1106 
1107     pub fn inner_lock_try_read_irqsave(
1108         &self,
1109         times: u8,
1110     ) -> Option<RwLockReadGuard<InnerSchedInfo>> {
1111         for _ in 0..times {
1112             if let Some(r) = self.inner_locked.try_read_irqsave() {
1113                 return Some(r);
1114             }
1115         }
1116 
1117         return None;
1118     }
1119 
1120     pub fn inner_lock_try_upgradable_read_irqsave(
1121         &self,
1122         times: u8,
1123     ) -> Option<RwLockUpgradableGuard<InnerSchedInfo>> {
1124         for _ in 0..times {
1125             if let Some(r) = self.inner_locked.try_upgradeable_read_irqsave() {
1126                 return Some(r);
1127             }
1128         }
1129 
1130         return None;
1131     }
1132 
1133     pub fn virtual_runtime(&self) -> isize {
1134         return self.virtual_runtime.load(Ordering::SeqCst);
1135     }
1136 
1137     pub fn set_virtual_runtime(&self, virtual_runtime: isize) {
1138         self.virtual_runtime
1139             .store(virtual_runtime, Ordering::SeqCst);
1140     }
1141     pub fn increase_virtual_runtime(&self, delta: isize) {
1142         self.virtual_runtime.fetch_add(delta, Ordering::SeqCst);
1143     }
1144 
1145     pub fn rt_time_slice(&self) -> isize {
1146         return self.rt_time_slice.load(Ordering::SeqCst);
1147     }
1148 
1149     pub fn set_rt_time_slice(&self, rt_time_slice: isize) {
1150         self.rt_time_slice.store(rt_time_slice, Ordering::SeqCst);
1151     }
1152 
1153     pub fn increase_rt_time_slice(&self, delta: isize) {
1154         self.rt_time_slice.fetch_add(delta, Ordering::SeqCst);
1155     }
1156 
1157     pub fn priority(&self) -> SchedPriority {
1158         return self.priority;
1159     }
1160 }
1161 
1162 #[derive(Debug, Clone)]
1163 pub struct KernelStack {
1164     stack: Option<AlignedBox<[u8; KernelStack::SIZE], { KernelStack::ALIGN }>>,
1165     /// 标记该内核栈是否可以被释放
1166     can_be_freed: bool,
1167 }
1168 
1169 impl KernelStack {
1170     pub const SIZE: usize = 0x4000;
1171     pub const ALIGN: usize = 0x4000;
1172 
1173     pub fn new() -> Result<Self, SystemError> {
1174         return Ok(Self {
1175             stack: Some(
1176                 AlignedBox::<[u8; KernelStack::SIZE], { KernelStack::ALIGN }>::new_zeroed()?,
1177             ),
1178             can_be_freed: true,
1179         });
1180     }
1181 
1182     /// 根据已有的空间,构造一个内核栈结构体
1183     ///
1184     /// 仅仅用于BSP启动时,为idle进程构造内核栈。其他时候使用这个函数,很可能造成错误!
1185     pub unsafe fn from_existed(base: VirtAddr) -> Result<Self, SystemError> {
1186         if base.is_null() || base.check_aligned(Self::ALIGN) == false {
1187             return Err(SystemError::EFAULT);
1188         }
1189 
1190         return Ok(Self {
1191             stack: Some(
1192                 AlignedBox::<[u8; KernelStack::SIZE], { KernelStack::ALIGN }>::new_unchecked(
1193                     base.data() as *mut [u8; KernelStack::SIZE],
1194                 ),
1195             ),
1196             can_be_freed: false,
1197         });
1198     }
1199 
1200     /// 返回内核栈的起始虚拟地址(低地址)
1201     pub fn start_address(&self) -> VirtAddr {
1202         return VirtAddr::new(self.stack.as_ref().unwrap().as_ptr() as usize);
1203     }
1204 
1205     /// 返回内核栈的结束虚拟地址(高地址)(不包含该地址)
1206     pub fn stack_max_address(&self) -> VirtAddr {
1207         return VirtAddr::new(self.stack.as_ref().unwrap().as_ptr() as usize + Self::SIZE);
1208     }
1209 
1210     pub unsafe fn set_pcb(&mut self, pcb: Weak<ProcessControlBlock>) -> Result<(), SystemError> {
1211         // 将一个Weak<ProcessControlBlock>放到内核栈的最低地址处
1212         let p: *const ProcessControlBlock = Weak::into_raw(pcb);
1213         let stack_bottom_ptr = self.start_address().data() as *mut *const ProcessControlBlock;
1214 
1215         // 如果内核栈的最低地址处已经有了一个pcb,那么,这里就不再设置,直接返回错误
1216         if unlikely(unsafe { !(*stack_bottom_ptr).is_null() }) {
1217             kerror!("kernel stack bottom is not null: {:p}", *stack_bottom_ptr);
1218             return Err(SystemError::EPERM);
1219         }
1220         // 将pcb的地址放到内核栈的最低地址处
1221         unsafe {
1222             *stack_bottom_ptr = p;
1223         }
1224 
1225         return Ok(());
1226     }
1227 
1228     /// 清除内核栈的pcb指针
1229     ///
1230     /// ## 参数
1231     ///
1232     /// - `force` : 如果为true,那么,即使该内核栈的pcb指针不为null,也会被强制清除而不处理Weak指针问题
1233     pub unsafe fn clear_pcb(&mut self, force: bool) {
1234         let stack_bottom_ptr = self.start_address().data() as *mut *const ProcessControlBlock;
1235         if unlikely(unsafe { (*stack_bottom_ptr).is_null() }) {
1236             return;
1237         }
1238 
1239         if !force {
1240             let pcb_ptr: Weak<ProcessControlBlock> = Weak::from_raw(*stack_bottom_ptr);
1241             drop(pcb_ptr);
1242         }
1243 
1244         *stack_bottom_ptr = core::ptr::null();
1245     }
1246 
1247     /// 返回指向当前内核栈pcb的Arc指针
1248     #[allow(dead_code)]
1249     pub unsafe fn pcb(&self) -> Option<Arc<ProcessControlBlock>> {
1250         // 从内核栈的最低地址处取出pcb的地址
1251         let p = self.stack.as_ref().unwrap().as_ptr() as *const *const ProcessControlBlock;
1252         if unlikely(unsafe { (*p).is_null() }) {
1253             return None;
1254         }
1255 
1256         // 为了防止内核栈的pcb指针被释放,这里需要将其包装一下,使得Arc的drop不会被调用
1257         let weak_wrapper: ManuallyDrop<Weak<ProcessControlBlock>> =
1258             ManuallyDrop::new(Weak::from_raw(*p));
1259 
1260         let new_arc: Arc<ProcessControlBlock> = weak_wrapper.upgrade()?;
1261         return Some(new_arc);
1262     }
1263 }
1264 
1265 impl Drop for KernelStack {
1266     fn drop(&mut self) {
1267         if !self.stack.is_none() {
1268             let ptr = self.stack.as_ref().unwrap().as_ptr() as *const *const ProcessControlBlock;
1269             if unsafe { !(*ptr).is_null() } {
1270                 let pcb_ptr: Weak<ProcessControlBlock> = unsafe { Weak::from_raw(*ptr) };
1271                 drop(pcb_ptr);
1272             }
1273         }
1274         // 如果该内核栈不可以被释放,那么,这里就forget,不调用AlignedBox的drop函数
1275         if !self.can_be_freed {
1276             let bx = self.stack.take();
1277             core::mem::forget(bx);
1278         }
1279     }
1280 }
1281 
1282 pub fn process_init() {
1283     ProcessManager::init();
1284 }
1285 
1286 #[derive(Debug)]
1287 pub struct ProcessSignalInfo {
1288     // 当前进程
1289     sig_block: SigSet,
1290     // sig_pending 中存储当前线程要处理的信号
1291     sig_pending: SigPending,
1292     // sig_shared_pending 中存储当前线程所属进程要处理的信号
1293     sig_shared_pending: SigPending,
1294 }
1295 
1296 impl ProcessSignalInfo {
1297     pub fn sig_block(&self) -> &SigSet {
1298         &self.sig_block
1299     }
1300 
1301     pub fn sig_pending(&self) -> &SigPending {
1302         &self.sig_pending
1303     }
1304 
1305     pub fn sig_pending_mut(&mut self) -> &mut SigPending {
1306         &mut self.sig_pending
1307     }
1308 
1309     pub fn sig_block_mut(&mut self) -> &mut SigSet {
1310         &mut self.sig_block
1311     }
1312 
1313     pub fn sig_shared_pending_mut(&mut self) -> &mut SigPending {
1314         &mut self.sig_shared_pending
1315     }
1316 
1317     pub fn sig_shared_pending(&self) -> &SigPending {
1318         &self.sig_shared_pending
1319     }
1320 
1321     /// 从 pcb 的 siginfo中取出下一个要处理的信号,先处理线程信号,再处理进程信号
1322     ///
1323     /// ## 参数
1324     ///
1325     /// - `sig_mask` 被忽略掉的信号
1326     ///
1327     pub fn dequeue_signal(&mut self, sig_mask: &SigSet) -> (Signal, Option<SigInfo>) {
1328         let res = self.sig_pending.dequeue_signal(sig_mask);
1329         if res.0 != Signal::INVALID {
1330             return res;
1331         } else {
1332             return self.sig_shared_pending.dequeue_signal(sig_mask);
1333         }
1334     }
1335 }
1336 
1337 impl Default for ProcessSignalInfo {
1338     fn default() -> Self {
1339         Self {
1340             sig_block: SigSet::empty(),
1341             sig_pending: SigPending::default(),
1342             sig_shared_pending: SigPending::default(),
1343         }
1344     }
1345 }
1346