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