xref: /DragonOS/kernel/src/process/mod.rs (revision be8cdf4b8edcd9579572672411f4489039dea313)
1 use core::{
2     hash::{Hash, Hasher},
3     hint::spin_loop,
4     intrinsics::{likely, unlikely},
5     mem::ManuallyDrop,
6     sync::atomic::{compiler_fence, AtomicBool, AtomicI32, AtomicIsize, AtomicUsize, Ordering},
7 };
8 
9 use alloc::{
10     string::{String, ToString},
11     sync::{Arc, Weak},
12     vec::Vec,
13 };
14 use hashbrown::HashMap;
15 
16 use crate::{
17     arch::{
18         ipc::signal::{AtomicSignal, SigSet, Signal},
19         process::ArchPCBInfo,
20         sched::sched,
21         CurrentIrqArch,
22     },
23     exception::InterruptArch,
24     filesystem::{
25         procfs::procfs_unregister_pid,
26         vfs::{file::FileDescriptorVec, FileType},
27     },
28     ipc::signal_types::{SigInfo, SigPending, SignalStruct},
29     kdebug, kinfo,
30     libs::{
31         align::AlignedBox,
32         casting::DowncastArc,
33         futex::{
34             constant::{FutexFlag, FUTEX_BITSET_MATCH_ANY},
35             futex::Futex,
36         },
37         lock_free_flags::LockFreeFlags,
38         rwlock::{RwLock, RwLockReadGuard, RwLockUpgradableGuard, RwLockWriteGuard},
39         spinlock::{SpinLock, SpinLockGuard},
40         wait_queue::WaitQueue,
41     },
42     mm::{percpu::PerCpuVar, set_INITIAL_PROCESS_ADDRESS_SPACE, ucontext::AddressSpace, VirtAddr},
43     net::socket::SocketInode,
44     sched::{
45         completion::Completion,
46         core::{sched_enqueue, CPU_EXECUTING},
47         SchedPolicy, SchedPriority,
48     },
49     smp::kick_cpu,
50     syscall::{user_access::clear_user, Syscall, SystemError},
51 };
52 
53 use self::kthread::WorkerPrivate;
54 
55 pub mod abi;
56 pub mod c_adapter;
57 pub mod exec;
58 pub mod fork;
59 pub mod idle;
60 pub mod init;
61 pub mod kthread;
62 pub mod pid;
63 pub mod process;
64 pub mod resource;
65 pub mod syscall;
66 
67 /// 系统中所有进程的pcb
68 static ALL_PROCESS: SpinLock<Option<HashMap<Pid, Arc<ProcessControlBlock>>>> = SpinLock::new(None);
69 
70 pub static mut SWITCH_RESULT: Option<PerCpuVar<SwitchResult>> = None;
71 
72 /// 一个只改变1次的全局变量,标志进程管理器是否已经初始化完成
73 static mut __PROCESS_MANAGEMENT_INIT_DONE: bool = false;
74 
75 #[derive(Debug)]
76 pub struct SwitchResult {
77     pub prev_pcb: Option<Arc<ProcessControlBlock>>,
78     pub next_pcb: Option<Arc<ProcessControlBlock>>,
79 }
80 
81 impl SwitchResult {
82     pub fn new() -> Self {
83         Self {
84             prev_pcb: None,
85             next_pcb: None,
86         }
87     }
88 }
89 
90 #[derive(Debug)]
91 pub struct ProcessManager;
92 impl ProcessManager {
93     fn init() {
94         static INIT_FLAG: AtomicBool = AtomicBool::new(false);
95         if INIT_FLAG
96             .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
97             .is_err()
98         {
99             panic!("ProcessManager has been initialized!");
100         }
101 
102         unsafe {
103             compiler_fence(Ordering::SeqCst);
104             kdebug!("To create address space for INIT process.");
105             // test_buddy();
106             set_INITIAL_PROCESS_ADDRESS_SPACE(
107                 AddressSpace::new(true).expect("Failed to create address space for INIT process."),
108             );
109             kdebug!("INIT process address space created.");
110             compiler_fence(Ordering::SeqCst);
111         };
112 
113         ALL_PROCESS.lock().replace(HashMap::new());
114         Self::arch_init();
115         kdebug!("process arch init done.");
116         Self::init_idle();
117         kdebug!("process idle init done.");
118 
119         unsafe {
120             __PROCESS_MANAGEMENT_INIT_DONE = true;
121         }
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().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()
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().state();
191         if state.is_blocked() {
192             let mut writer: RwLockWriteGuard<'_, ProcessSchedulerInfo> = pcb.sched_info_mut();
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().state();
217         if let ProcessState::Stopped = state {
218             let mut writer = pcb.sched_info_mut();
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_mut_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_mut_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         let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
325         let pcb = ProcessManager::current_pcb();
326         pcb.sched_info
327             .write()
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         drop(irq_guard);
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().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 pub unsafe extern "sysv64" fn switch_finish_hook() {
427     ProcessManager::switch_finish_hook();
428 }
429 
430 int_like!(Pid, AtomicPid, usize, AtomicUsize);
431 
432 impl Hash for Pid {
433     fn hash<H: Hasher>(&self, state: &mut H) {
434         self.0.hash(state);
435     }
436 }
437 
438 impl Pid {
439     pub fn to_string(&self) -> String {
440         self.0.to_string()
441     }
442 }
443 
444 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
445 pub enum ProcessState {
446     /// The process is running on a CPU or in a run queue.
447     Runnable,
448     /// The process is waiting for an event to occur.
449     /// 其中的bool表示该等待过程是否可以被打断。
450     /// - 如果该bool为true,那么,硬件中断/信号/其他系统事件都可以打断该等待过程,使得该进程重新进入Runnable状态。
451     /// - 如果该bool为false,那么,这个进程必须被显式的唤醒,才能重新进入Runnable状态。
452     Blocked(bool),
453     /// 进程被信号终止
454     Stopped,
455     /// 进程已经退出,usize表示进程的退出码
456     Exited(usize),
457 }
458 
459 #[allow(dead_code)]
460 impl ProcessState {
461     #[inline(always)]
462     pub fn is_runnable(&self) -> bool {
463         return matches!(self, ProcessState::Runnable);
464     }
465 
466     #[inline(always)]
467     pub fn is_blocked(&self) -> bool {
468         return matches!(self, ProcessState::Blocked(_));
469     }
470 
471     #[inline(always)]
472     pub fn is_blocked_interruptable(&self) -> bool {
473         return matches!(self, ProcessState::Blocked(true));
474     }
475 
476     #[inline(always)]
477     pub fn is_exited(&self) -> bool {
478         return matches!(self, ProcessState::Exited(_));
479     }
480 
481     /// Returns `true` if the process state is [`Stopped`].
482     ///
483     /// [`Stopped`]: ProcessState::Stopped
484     #[inline(always)]
485     pub fn is_stopped(&self) -> bool {
486         matches!(self, ProcessState::Stopped)
487     }
488 }
489 
490 bitflags! {
491     /// pcb的标志位
492     pub struct ProcessFlags: usize {
493         /// 当前pcb表示一个内核线程
494         const KTHREAD = 1 << 0;
495         /// 当前进程需要被调度
496         const NEED_SCHEDULE = 1 << 1;
497         /// 进程由于vfork而与父进程存在资源共享
498         const VFORK = 1 << 2;
499         /// 进程不可被冻结
500         const NOFREEZE = 1 << 3;
501         /// 进程正在退出
502         const EXITING = 1 << 4;
503         /// 进程由于接收到终止信号唤醒
504         const WAKEKILL = 1 << 5;
505         /// 进程由于接收到信号而退出.(Killed by a signal)
506         const SIGNALED = 1 << 6;
507         /// 进程需要迁移到其他cpu上
508         const NEED_MIGRATE = 1 << 7;
509     }
510 }
511 
512 #[derive(Debug)]
513 pub struct ProcessControlBlock {
514     /// 当前进程的pid
515     pid: Pid,
516     /// 当前进程的线程组id(这个值在同一个线程组内永远不变)
517     tgid: Pid,
518 
519     basic: RwLock<ProcessBasicInfo>,
520     /// 当前进程的自旋锁持有计数
521     preempt_count: AtomicUsize,
522 
523     flags: LockFreeFlags<ProcessFlags>,
524     worker_private: SpinLock<Option<WorkerPrivate>>,
525     /// 进程的内核栈
526     kernel_stack: RwLock<KernelStack>,
527 
528     /// 系统调用栈
529     syscall_stack: RwLock<KernelStack>,
530 
531     /// 与调度相关的信息
532     sched_info: RwLock<ProcessSchedulerInfo>,
533     /// 与处理器架构相关的信息
534     arch_info: SpinLock<ArchPCBInfo>,
535     /// 与信号处理相关的信息(似乎可以是无锁的)
536     sig_info: RwLock<ProcessSignalInfo>,
537     /// 信号处理结构体
538     sig_struct: SpinLock<SignalStruct>,
539     /// 退出信号S
540     exit_signal: AtomicSignal,
541 
542     /// 父进程指针
543     parent_pcb: RwLock<Weak<ProcessControlBlock>>,
544     /// 真实父进程指针
545     real_parent_pcb: RwLock<Weak<ProcessControlBlock>>,
546 
547     /// 子进程链表
548     children: RwLock<Vec<Pid>>,
549 
550     /// 等待队列
551     wait_queue: WaitQueue,
552 
553     /// 线程信息
554     thread: RwLock<ThreadInfo>,
555 }
556 
557 impl ProcessControlBlock {
558     /// Generate a new pcb.
559     ///
560     /// ## 参数
561     ///
562     /// - `name` : 进程的名字
563     /// - `kstack` : 进程的内核栈
564     ///
565     /// ## 返回值
566     ///
567     /// 返回一个新的pcb
568     pub fn new(name: String, kstack: KernelStack) -> Arc<Self> {
569         return Self::do_create_pcb(name, kstack, false);
570     }
571 
572     /// 创建一个新的idle进程
573     ///
574     /// 请注意,这个函数只能在进程管理初始化的时候调用。
575     pub fn new_idle(cpu_id: u32, kstack: KernelStack) -> Arc<Self> {
576         let name = format!("idle-{}", cpu_id);
577         return Self::do_create_pcb(name, kstack, true);
578     }
579 
580     fn do_create_pcb(name: String, kstack: KernelStack, is_idle: bool) -> Arc<Self> {
581         let (pid, ppid, cwd) = if is_idle {
582             (Pid(0), Pid(0), "/".to_string())
583         } else {
584             (
585                 Self::generate_pid(),
586                 ProcessManager::current_pcb().pid(),
587                 ProcessManager::current_pcb().basic().cwd(),
588             )
589         };
590 
591         let basic_info = ProcessBasicInfo::new(Pid(0), ppid, name, cwd, None);
592         let preempt_count = AtomicUsize::new(0);
593         let flags = unsafe { LockFreeFlags::new(ProcessFlags::empty()) };
594 
595         let sched_info = ProcessSchedulerInfo::new(None);
596         let arch_info = SpinLock::new(ArchPCBInfo::new(&kstack));
597 
598         let ppcb: Weak<ProcessControlBlock> = ProcessManager::find(ppid)
599             .map(|p| Arc::downgrade(&p))
600             .unwrap_or_else(|| Weak::new());
601 
602         let pcb = Self {
603             pid,
604             tgid: pid,
605             basic: basic_info,
606             preempt_count,
607             flags,
608             kernel_stack: RwLock::new(kstack),
609             syscall_stack: RwLock::new(KernelStack::new().unwrap()),
610             worker_private: SpinLock::new(None),
611             sched_info,
612             arch_info,
613             sig_info: RwLock::new(ProcessSignalInfo::default()),
614             sig_struct: SpinLock::new(SignalStruct::default()),
615             exit_signal: AtomicSignal::new(Signal::SIGCHLD),
616             parent_pcb: RwLock::new(ppcb.clone()),
617             real_parent_pcb: RwLock::new(ppcb),
618             children: RwLock::new(Vec::new()),
619             wait_queue: WaitQueue::INIT,
620             thread: RwLock::new(ThreadInfo::new()),
621         };
622 
623         // 初始化系统调用栈
624         pcb.arch_info
625             .lock()
626             .init_syscall_stack(&pcb.syscall_stack.read());
627 
628         let pcb = Arc::new(pcb);
629 
630         // 设置进程的arc指针到内核栈和系统调用栈的最低地址处
631         unsafe {
632             pcb.kernel_stack
633                 .write()
634                 .set_pcb(Arc::downgrade(&pcb))
635                 .unwrap();
636 
637             pcb.syscall_stack
638                 .write()
639                 .set_pcb(Arc::downgrade(&pcb))
640                 .unwrap()
641         };
642 
643         // 将当前pcb加入父进程的子进程哈希表中
644         if pcb.pid() > Pid(1) {
645             if let Some(ppcb_arc) = pcb.parent_pcb.read().upgrade() {
646                 let mut children = ppcb_arc.children.write();
647                 children.push(pcb.pid());
648             } else {
649                 panic!("parent pcb is None");
650             }
651         }
652 
653         return pcb;
654     }
655 
656     /// 生成一个新的pid
657     #[inline(always)]
658     fn generate_pid() -> Pid {
659         static NEXT_PID: AtomicPid = AtomicPid::new(Pid(1));
660         return NEXT_PID.fetch_add(Pid(1), Ordering::SeqCst);
661     }
662 
663     /// 返回当前进程的锁持有计数
664     #[inline(always)]
665     pub fn preempt_count(&self) -> usize {
666         return self.preempt_count.load(Ordering::SeqCst);
667     }
668 
669     /// 增加当前进程的锁持有计数
670     #[inline(always)]
671     pub fn preempt_disable(&self) {
672         self.preempt_count.fetch_add(1, Ordering::SeqCst);
673     }
674 
675     /// 减少当前进程的锁持有计数
676     #[inline(always)]
677     pub fn preempt_enable(&self) {
678         self.preempt_count.fetch_sub(1, Ordering::SeqCst);
679     }
680 
681     #[inline(always)]
682     pub unsafe fn set_preempt_count(&self, count: usize) {
683         self.preempt_count.store(count, Ordering::SeqCst);
684     }
685 
686     #[inline(always)]
687     pub fn flags(&self) -> &mut ProcessFlags {
688         return self.flags.get_mut();
689     }
690 
691     #[inline(always)]
692     pub fn basic(&self) -> RwLockReadGuard<ProcessBasicInfo> {
693         return self.basic.read();
694     }
695 
696     #[inline(always)]
697     pub fn set_name(&self, name: String) {
698         self.basic.write().set_name(name);
699     }
700 
701     #[inline(always)]
702     pub fn basic_mut(&self) -> RwLockWriteGuard<ProcessBasicInfo> {
703         return self.basic.write();
704     }
705 
706     #[inline(always)]
707     pub fn arch_info(&self) -> SpinLockGuard<ArchPCBInfo> {
708         return self.arch_info.lock();
709     }
710 
711     #[inline(always)]
712     pub fn arch_info_irqsave(&self) -> SpinLockGuard<ArchPCBInfo> {
713         return self.arch_info.lock_irqsave();
714     }
715 
716     #[inline(always)]
717     pub fn kernel_stack(&self) -> RwLockReadGuard<KernelStack> {
718         return self.kernel_stack.read();
719     }
720 
721     #[inline(always)]
722     #[allow(dead_code)]
723     pub fn kernel_stack_mut(&self) -> RwLockWriteGuard<KernelStack> {
724         return self.kernel_stack.write();
725     }
726 
727     #[inline(always)]
728     pub fn sched_info(&self) -> RwLockReadGuard<ProcessSchedulerInfo> {
729         return self.sched_info.read();
730     }
731 
732     #[inline(always)]
733     pub fn try_sched_info(&self, times: u8) -> Option<RwLockReadGuard<ProcessSchedulerInfo>> {
734         for _ in 0..times {
735             if let Some(r) = self.sched_info.try_read() {
736                 return Some(r);
737             }
738         }
739 
740         return None;
741     }
742 
743     #[allow(dead_code)]
744     #[inline(always)]
745     pub fn sched_info_irqsave(&self) -> RwLockReadGuard<ProcessSchedulerInfo> {
746         return self.sched_info.read_irqsave();
747     }
748 
749     #[inline(always)]
750     pub fn sched_info_try_upgradeable_irqsave(
751         &self,
752         times: u8,
753     ) -> Option<RwLockUpgradableGuard<ProcessSchedulerInfo>> {
754         for _ in 0..times {
755             if let Some(r) = self.sched_info.try_upgradeable_read_irqsave() {
756                 return Some(r);
757             }
758         }
759         return None;
760     }
761 
762     #[inline(always)]
763     pub fn sched_info_mut(&self) -> RwLockWriteGuard<ProcessSchedulerInfo> {
764         return self.sched_info.write();
765     }
766 
767     #[inline(always)]
768     pub fn sched_info_mut_irqsave(&self) -> RwLockWriteGuard<ProcessSchedulerInfo> {
769         return self.sched_info.write_irqsave();
770     }
771 
772     #[inline(always)]
773     pub fn worker_private(&self) -> SpinLockGuard<Option<WorkerPrivate>> {
774         return self.worker_private.lock();
775     }
776 
777     #[inline(always)]
778     pub fn pid(&self) -> Pid {
779         return self.pid;
780     }
781 
782     #[inline(always)]
783     pub fn tgid(&self) -> Pid {
784         return self.tgid;
785     }
786 
787     /// 获取文件描述符表的Arc指针
788     #[inline(always)]
789     pub fn fd_table(&self) -> Arc<RwLock<FileDescriptorVec>> {
790         return self.basic.read().fd_table().unwrap();
791     }
792 
793     /// 根据文件描述符序号,获取socket对象的Arc指针
794     ///
795     /// ## 参数
796     ///
797     /// - `fd` 文件描述符序号
798     ///
799     /// ## 返回值
800     ///
801     /// Option(&mut Box<dyn Socket>) socket对象的可变引用. 如果文件描述符不是socket,那么返回None
802     pub fn get_socket(&self, fd: i32) -> Option<Arc<SocketInode>> {
803         let binding = ProcessManager::current_pcb().fd_table();
804         let fd_table_guard = binding.read();
805 
806         let f = fd_table_guard.get_file_by_fd(fd)?;
807         drop(fd_table_guard);
808 
809         let guard = f.lock();
810         if guard.file_type() != FileType::Socket {
811             return None;
812         }
813         let socket: Arc<SocketInode> = guard
814             .inode()
815             .downcast_arc::<SocketInode>()
816             .expect("Not a socket inode");
817         return Some(socket);
818     }
819 
820     /// 当前进程退出时,让初始进程收养所有子进程
821     unsafe fn adopt_childen(&self) -> Result<(), SystemError> {
822         match ProcessManager::find(Pid(1)) {
823             Some(init_pcb) => {
824                 let childen_guard = self.children.write();
825                 let mut init_childen_guard = init_pcb.children.write();
826 
827                 childen_guard.iter().for_each(|pid| {
828                     init_childen_guard.push(*pid);
829                 });
830 
831                 return Ok(());
832             }
833             _ => Err(SystemError::ECHILD),
834         }
835     }
836 
837     /// 生成进程的名字
838     pub fn generate_name(program_path: &str, args: &Vec<String>) -> String {
839         let mut name = program_path.to_string();
840         for arg in args {
841             name.push_str(arg);
842             name.push(' ');
843         }
844         return name;
845     }
846 
847     pub fn sig_info(&self) -> RwLockReadGuard<ProcessSignalInfo> {
848         self.sig_info.read()
849     }
850 
851     pub fn try_siginfo(&self, times: u8) -> Option<RwLockReadGuard<ProcessSignalInfo>> {
852         for _ in 0..times {
853             if let Some(r) = self.sig_info.try_read() {
854                 return Some(r);
855             }
856         }
857 
858         return None;
859     }
860 
861     pub fn sig_info_mut(&self) -> RwLockWriteGuard<ProcessSignalInfo> {
862         self.sig_info.write()
863     }
864 
865     pub fn try_siginfo_mut(&self, times: u8) -> Option<RwLockWriteGuard<ProcessSignalInfo>> {
866         for _ in 0..times {
867             if let Some(r) = self.sig_info.try_write() {
868                 return Some(r);
869             }
870         }
871 
872         return None;
873     }
874 
875     pub fn sig_struct(&self) -> SpinLockGuard<SignalStruct> {
876         self.sig_struct.lock()
877     }
878 
879     pub fn try_sig_struct_irq(&self, times: u8) -> Option<SpinLockGuard<SignalStruct>> {
880         for _ in 0..times {
881             if let Ok(r) = self.sig_struct.try_lock_irqsave() {
882                 return Some(r);
883             }
884         }
885 
886         return None;
887     }
888 
889     pub fn sig_struct_irq(&self) -> SpinLockGuard<SignalStruct> {
890         self.sig_struct.lock_irqsave()
891     }
892 }
893 
894 impl Drop for ProcessControlBlock {
895     fn drop(&mut self) {
896         // 在ProcFS中,解除进程的注册
897         procfs_unregister_pid(self.pid())
898             .unwrap_or_else(|e| panic!("procfs_unregister_pid failed: error: {e:?}"));
899 
900         if let Some(ppcb) = self.parent_pcb.read().upgrade() {
901             ppcb.children.write().drain_filter(|pid| *pid == self.pid());
902         }
903     }
904 }
905 
906 /// 线程信息
907 #[derive(Debug)]
908 pub struct ThreadInfo {
909     // 来自用户空间记录用户线程id的地址,在该线程结束时将该地址置0以通知父进程
910     clear_child_tid: Option<VirtAddr>,
911     set_child_tid: Option<VirtAddr>,
912 
913     vfork_done: Option<Arc<Completion>>,
914     /// 线程组的组长
915     group_leader: Weak<ProcessControlBlock>,
916 }
917 
918 impl ThreadInfo {
919     pub fn new() -> Self {
920         Self {
921             clear_child_tid: None,
922             set_child_tid: None,
923             vfork_done: None,
924             group_leader: Weak::default(),
925         }
926     }
927 
928     pub fn group_leader(&self) -> Option<Arc<ProcessControlBlock>> {
929         return self.group_leader.upgrade();
930     }
931 }
932 
933 /// 进程的基本信息
934 ///
935 /// 这个结构体保存进程的基本信息,主要是那些不会随着进程的运行而经常改变的信息。
936 #[derive(Debug)]
937 pub struct ProcessBasicInfo {
938     /// 当前进程的进程组id
939     pgid: Pid,
940     /// 当前进程的父进程的pid
941     ppid: Pid,
942     /// 进程的名字
943     name: String,
944 
945     /// 当前进程的工作目录
946     cwd: String,
947 
948     /// 用户地址空间
949     user_vm: Option<Arc<AddressSpace>>,
950 
951     /// 文件描述符表
952     fd_table: Option<Arc<RwLock<FileDescriptorVec>>>,
953 }
954 
955 impl ProcessBasicInfo {
956     pub fn new(
957         pgid: Pid,
958         ppid: Pid,
959         name: String,
960         cwd: String,
961         user_vm: Option<Arc<AddressSpace>>,
962     ) -> RwLock<Self> {
963         let fd_table = Arc::new(RwLock::new(FileDescriptorVec::new()));
964         return RwLock::new(Self {
965             pgid,
966             ppid,
967             name,
968             cwd,
969             user_vm,
970             fd_table: Some(fd_table),
971         });
972     }
973 
974     pub fn pgid(&self) -> Pid {
975         return self.pgid;
976     }
977 
978     pub fn ppid(&self) -> Pid {
979         return self.ppid;
980     }
981 
982     pub fn name(&self) -> &str {
983         return &self.name;
984     }
985 
986     pub fn set_name(&mut self, name: String) {
987         self.name = name;
988     }
989 
990     pub fn cwd(&self) -> String {
991         return self.cwd.clone();
992     }
993     pub fn set_cwd(&mut self, path: String) {
994         return self.cwd = path;
995     }
996 
997     pub fn user_vm(&self) -> Option<Arc<AddressSpace>> {
998         return self.user_vm.clone();
999     }
1000 
1001     pub unsafe fn set_user_vm(&mut self, user_vm: Option<Arc<AddressSpace>>) {
1002         self.user_vm = user_vm;
1003     }
1004 
1005     pub fn fd_table(&self) -> Option<Arc<RwLock<FileDescriptorVec>>> {
1006         return self.fd_table.clone();
1007     }
1008 
1009     pub fn set_fd_table(&mut self, fd_table: Option<Arc<RwLock<FileDescriptorVec>>>) {
1010         self.fd_table = fd_table;
1011     }
1012 }
1013 
1014 #[derive(Debug)]
1015 pub struct ProcessSchedulerInfo {
1016     /// 当前进程所在的cpu
1017     on_cpu: AtomicI32,
1018     /// 如果当前进程等待被迁移到另一个cpu核心上(也就是flags中的PF_NEED_MIGRATE被置位),
1019     /// 该字段存储要被迁移到的目标处理器核心号
1020     migrate_to: AtomicI32,
1021 
1022     /// 当前进程的状态
1023     state: ProcessState,
1024     /// 进程的调度策略
1025     sched_policy: SchedPolicy,
1026     /// 进程的调度优先级
1027     priority: SchedPriority,
1028     /// 当前进程的虚拟运行时间
1029     virtual_runtime: AtomicIsize,
1030     /// 由实时调度器管理的时间片
1031     rt_time_slice: AtomicIsize,
1032 }
1033 
1034 impl ProcessSchedulerInfo {
1035     pub fn new(on_cpu: Option<u32>) -> RwLock<Self> {
1036         let cpu_id = match on_cpu {
1037             Some(cpu_id) => cpu_id as i32,
1038             None => -1,
1039         };
1040         return RwLock::new(Self {
1041             on_cpu: AtomicI32::new(cpu_id),
1042             migrate_to: AtomicI32::new(-1),
1043             state: ProcessState::Blocked(false),
1044             sched_policy: SchedPolicy::CFS,
1045             virtual_runtime: AtomicIsize::new(0),
1046             rt_time_slice: AtomicIsize::new(0),
1047             priority: SchedPriority::new(100).unwrap(),
1048         });
1049     }
1050 
1051     pub fn on_cpu(&self) -> Option<u32> {
1052         let on_cpu = self.on_cpu.load(Ordering::SeqCst);
1053         if on_cpu == -1 {
1054             return None;
1055         } else {
1056             return Some(on_cpu as u32);
1057         }
1058     }
1059 
1060     pub fn set_on_cpu(&self, on_cpu: Option<u32>) {
1061         if let Some(cpu_id) = on_cpu {
1062             self.on_cpu.store(cpu_id as i32, Ordering::SeqCst);
1063         } else {
1064             self.on_cpu.store(-1, Ordering::SeqCst);
1065         }
1066     }
1067 
1068     pub fn migrate_to(&self) -> Option<u32> {
1069         let migrate_to = self.migrate_to.load(Ordering::SeqCst);
1070         if migrate_to == -1 {
1071             return None;
1072         } else {
1073             return Some(migrate_to as u32);
1074         }
1075     }
1076 
1077     pub fn set_migrate_to(&self, migrate_to: Option<u32>) {
1078         if let Some(data) = migrate_to {
1079             self.migrate_to.store(data as i32, Ordering::SeqCst);
1080         } else {
1081             self.migrate_to.store(-1, Ordering::SeqCst)
1082         }
1083     }
1084 
1085     pub fn state(&self) -> ProcessState {
1086         return self.state;
1087     }
1088 
1089     pub fn set_state(&mut self, state: ProcessState) {
1090         self.state = state;
1091     }
1092 
1093     pub fn policy(&self) -> SchedPolicy {
1094         return self.sched_policy;
1095     }
1096 
1097     pub fn virtual_runtime(&self) -> isize {
1098         return self.virtual_runtime.load(Ordering::SeqCst);
1099     }
1100 
1101     pub fn set_virtual_runtime(&self, virtual_runtime: isize) {
1102         self.virtual_runtime
1103             .store(virtual_runtime, Ordering::SeqCst);
1104     }
1105     pub fn increase_virtual_runtime(&self, delta: isize) {
1106         self.virtual_runtime.fetch_add(delta, Ordering::SeqCst);
1107     }
1108 
1109     pub fn rt_time_slice(&self) -> isize {
1110         return self.rt_time_slice.load(Ordering::SeqCst);
1111     }
1112 
1113     pub fn set_rt_time_slice(&self, rt_time_slice: isize) {
1114         self.rt_time_slice.store(rt_time_slice, Ordering::SeqCst);
1115     }
1116 
1117     pub fn increase_rt_time_slice(&self, delta: isize) {
1118         self.rt_time_slice.fetch_add(delta, Ordering::SeqCst);
1119     }
1120 
1121     pub fn priority(&self) -> SchedPriority {
1122         return self.priority;
1123     }
1124 }
1125 
1126 #[derive(Debug, Clone)]
1127 pub struct KernelStack {
1128     stack: Option<AlignedBox<[u8; KernelStack::SIZE], { KernelStack::ALIGN }>>,
1129     /// 标记该内核栈是否可以被释放
1130     can_be_freed: bool,
1131 }
1132 
1133 impl KernelStack {
1134     pub const SIZE: usize = 0x4000;
1135     pub const ALIGN: usize = 0x4000;
1136 
1137     pub fn new() -> Result<Self, SystemError> {
1138         return Ok(Self {
1139             stack: Some(
1140                 AlignedBox::<[u8; KernelStack::SIZE], { KernelStack::ALIGN }>::new_zeroed()?,
1141             ),
1142             can_be_freed: true,
1143         });
1144     }
1145 
1146     /// 根据已有的空间,构造一个内核栈结构体
1147     ///
1148     /// 仅仅用于BSP启动时,为idle进程构造内核栈。其他时候使用这个函数,很可能造成错误!
1149     pub unsafe fn from_existed(base: VirtAddr) -> Result<Self, SystemError> {
1150         if base.is_null() || base.check_aligned(Self::ALIGN) == false {
1151             return Err(SystemError::EFAULT);
1152         }
1153 
1154         return Ok(Self {
1155             stack: Some(
1156                 AlignedBox::<[u8; KernelStack::SIZE], { KernelStack::ALIGN }>::new_unchecked(
1157                     base.data() as *mut [u8; KernelStack::SIZE],
1158                 ),
1159             ),
1160             can_be_freed: false,
1161         });
1162     }
1163 
1164     /// 返回内核栈的起始虚拟地址(低地址)
1165     pub fn start_address(&self) -> VirtAddr {
1166         return VirtAddr::new(self.stack.as_ref().unwrap().as_ptr() as usize);
1167     }
1168 
1169     /// 返回内核栈的结束虚拟地址(高地址)(不包含该地址)
1170     pub fn stack_max_address(&self) -> VirtAddr {
1171         return VirtAddr::new(self.stack.as_ref().unwrap().as_ptr() as usize + Self::SIZE);
1172     }
1173 
1174     pub unsafe fn set_pcb(&mut self, pcb: Weak<ProcessControlBlock>) -> Result<(), SystemError> {
1175         // 将一个Weak<ProcessControlBlock>放到内核栈的最低地址处
1176         let p: *const ProcessControlBlock = Weak::into_raw(pcb);
1177         let stack_bottom_ptr = self.start_address().data() as *mut *const ProcessControlBlock;
1178 
1179         // 如果内核栈的最低地址处已经有了一个pcb,那么,这里就不再设置,直接返回错误
1180         if unlikely(unsafe { !(*stack_bottom_ptr).is_null() }) {
1181             kerror!("kernel stack bottom is not null: {:p}", *stack_bottom_ptr);
1182             return Err(SystemError::EPERM);
1183         }
1184         // 将pcb的地址放到内核栈的最低地址处
1185         unsafe {
1186             *stack_bottom_ptr = p;
1187         }
1188 
1189         return Ok(());
1190     }
1191 
1192     /// 清除内核栈的pcb指针
1193     ///
1194     /// ## 参数
1195     ///
1196     /// - `force` : 如果为true,那么,即使该内核栈的pcb指针不为null,也会被强制清除而不处理Weak指针问题
1197     pub unsafe fn clear_pcb(&mut self, force: bool) {
1198         let stack_bottom_ptr = self.start_address().data() as *mut *const ProcessControlBlock;
1199         if unlikely(unsafe { (*stack_bottom_ptr).is_null() }) {
1200             return;
1201         }
1202 
1203         if !force {
1204             let pcb_ptr: Weak<ProcessControlBlock> = Weak::from_raw(*stack_bottom_ptr);
1205             drop(pcb_ptr);
1206         }
1207 
1208         *stack_bottom_ptr = core::ptr::null();
1209     }
1210 
1211     /// 返回指向当前内核栈pcb的Arc指针
1212     #[allow(dead_code)]
1213     pub unsafe fn pcb(&self) -> Option<Arc<ProcessControlBlock>> {
1214         // 从内核栈的最低地址处取出pcb的地址
1215         let p = self.stack.as_ref().unwrap().as_ptr() as *const ProcessControlBlock;
1216         if unlikely(p.is_null()) {
1217             return None;
1218         }
1219 
1220         // 为了防止内核栈的pcb指针被释放,这里需要将其包装一下,使得Arc的drop不会被调用
1221         let weak_wrapper: ManuallyDrop<Weak<ProcessControlBlock>> =
1222             ManuallyDrop::new(Weak::from_raw(p));
1223 
1224         let new_arc: Arc<ProcessControlBlock> = weak_wrapper.upgrade()?;
1225         return Some(new_arc);
1226     }
1227 }
1228 
1229 impl Drop for KernelStack {
1230     fn drop(&mut self) {
1231         if !self.stack.is_none() {
1232             let pcb_ptr: Weak<ProcessControlBlock> = unsafe {
1233                 Weak::from_raw(self.stack.as_ref().unwrap().as_ptr() as *const ProcessControlBlock)
1234             };
1235             drop(pcb_ptr);
1236         }
1237         // 如果该内核栈不可以被释放,那么,这里就forget,不调用AlignedBox的drop函数
1238         if !self.can_be_freed {
1239             let bx = self.stack.take();
1240             core::mem::forget(bx);
1241         }
1242     }
1243 }
1244 
1245 pub fn process_init() {
1246     ProcessManager::init();
1247 }
1248 
1249 #[derive(Debug)]
1250 pub struct ProcessSignalInfo {
1251     // 当前进程
1252     sig_block: SigSet,
1253     // sig_pending 中存储当前线程要处理的信号
1254     sig_pending: SigPending,
1255     // sig_shared_pending 中存储当前线程所属进程要处理的信号
1256     sig_shared_pending: SigPending,
1257 }
1258 
1259 impl ProcessSignalInfo {
1260     pub fn sig_block(&self) -> &SigSet {
1261         &self.sig_block
1262     }
1263 
1264     pub fn sig_pending(&self) -> &SigPending {
1265         &self.sig_pending
1266     }
1267 
1268     pub fn sig_pending_mut(&mut self) -> &mut SigPending {
1269         &mut self.sig_pending
1270     }
1271 
1272     pub fn sig_block_mut(&mut self) -> &mut SigSet {
1273         &mut self.sig_block
1274     }
1275 
1276     pub fn sig_shared_pending_mut(&mut self) -> &mut SigPending {
1277         &mut self.sig_shared_pending
1278     }
1279 
1280     pub fn sig_shared_pending(&self) -> &SigPending {
1281         &self.sig_shared_pending
1282     }
1283 
1284     /// 从 pcb 的 siginfo中取出下一个要处理的信号,先处理线程信号,再处理进程信号
1285     ///
1286     /// ## 参数
1287     ///
1288     /// - `sig_mask` 被忽略掉的信号
1289     ///
1290     pub fn dequeue_signal(&mut self, sig_mask: &SigSet) -> (Signal, Option<SigInfo>) {
1291         let res = self.sig_pending.dequeue_signal(sig_mask);
1292         if res.0 != Signal::INVALID {
1293             return res;
1294         } else {
1295             return self.sig_shared_pending.dequeue_signal(sig_mask);
1296         }
1297     }
1298 }
1299 
1300 impl Default for ProcessSignalInfo {
1301     fn default() -> Self {
1302         Self {
1303             sig_block: SigSet::empty(),
1304             sig_pending: SigPending::default(),
1305             sig_shared_pending: SigPending::default(),
1306         }
1307     }
1308 }
1309