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