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