xref: /DragonOS/kernel/src/process/mod.rs (revision f9fe30be89e89499aad4ef52b4648986bef5a7d8)
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 
426         // TODO 由于未实现进程组,tty记录的前台进程组等于当前进程,故退出前要置空
427         // 后续相关逻辑需要在SYS_EXIT_GROUP系统调用中实现
428         pcb.sig_info_irqsave()
429             .tty()
430             .unwrap()
431             .core()
432             .contorl_info_irqsave()
433             .pgid = None;
434         pcb.sig_info_mut().set_tty(None);
435 
436         drop(pcb);
437         ProcessManager::exit_notify();
438         // unsafe { CurrentIrqArch::interrupt_enable() };
439         __schedule(SchedMode::SM_NONE);
440         error!("pid {pid:?} exited but sched again!");
441         #[allow(clippy::empty_loop)]
442         loop {
443             spin_loop();
444         }
445     }
446 
447     pub unsafe fn release(pid: Pid) {
448         let pcb = ProcessManager::find(pid);
449         if pcb.is_some() {
450             // let pcb = pcb.unwrap();
451             // 判断该pcb是否在全局没有任何引用
452             // TODO: 当前,pcb的Arc指针存在泄露问题,引用计数不正确,打算在接下来实现debug专用的Arc,方便调试,然后解决这个bug。
453             //          因此目前暂时注释掉,使得能跑
454             // if Arc::strong_count(&pcb) <= 2 {
455             //     drop(pcb);
456             //     ALL_PROCESS.lock().as_mut().unwrap().remove(&pid);
457             // } else {
458             //     // 如果不为1就panic
459             //     let msg = format!("pcb '{:?}' is still referenced, strong count={}",pcb.pid(),  Arc::strong_count(&pcb));
460             //     error!("{}", msg);
461             //     panic!()
462             // }
463 
464             ALL_PROCESS.lock_irqsave().as_mut().unwrap().remove(&pid);
465         }
466     }
467 
468     /// 上下文切换完成后的钩子函数
469     unsafe fn switch_finish_hook() {
470         // debug!("switch_finish_hook");
471         let prev_pcb = PROCESS_SWITCH_RESULT
472             .as_mut()
473             .unwrap()
474             .get_mut()
475             .prev_pcb
476             .take()
477             .expect("prev_pcb is None");
478         let next_pcb = PROCESS_SWITCH_RESULT
479             .as_mut()
480             .unwrap()
481             .get_mut()
482             .next_pcb
483             .take()
484             .expect("next_pcb is None");
485 
486         // 由于进程切换前使用了SpinLockGuard::leak(),所以这里需要手动释放锁
487         fence(Ordering::SeqCst);
488 
489         prev_pcb.arch_info.force_unlock();
490         fence(Ordering::SeqCst);
491 
492         next_pcb.arch_info.force_unlock();
493         fence(Ordering::SeqCst);
494     }
495 
496     /// 如果目标进程正在目标CPU上运行,那么就让这个cpu陷入内核态
497     ///
498     /// ## 参数
499     ///
500     /// - `pcb` : 进程的pcb
501     #[allow(dead_code)]
502     pub fn kick(pcb: &Arc<ProcessControlBlock>) {
503         ProcessManager::current_pcb().preempt_disable();
504         let cpu_id = pcb.sched_info().on_cpu();
505 
506         if let Some(cpu_id) = cpu_id {
507             if pcb.pid() == cpu_rq(cpu_id.data() as usize).current().pid() {
508                 kick_cpu(cpu_id).expect("ProcessManager::kick(): Failed to kick cpu");
509             }
510         }
511 
512         ProcessManager::current_pcb().preempt_enable();
513     }
514 }
515 
516 /// 上下文切换的钩子函数,当这个函数return的时候,将会发生上下文切换
517 #[cfg(target_arch = "x86_64")]
518 #[inline(never)]
519 pub unsafe extern "sysv64" fn switch_finish_hook() {
520     ProcessManager::switch_finish_hook();
521 }
522 #[cfg(target_arch = "riscv64")]
523 #[inline(always)]
524 pub unsafe fn switch_finish_hook() {
525     ProcessManager::switch_finish_hook();
526 }
527 
528 int_like!(Pid, AtomicPid, usize, AtomicUsize);
529 
530 impl fmt::Display for Pid {
531     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
532         write!(f, "{}", self.0)
533     }
534 }
535 
536 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
537 pub enum ProcessState {
538     /// The process is running on a CPU or in a run queue.
539     Runnable,
540     /// The process is waiting for an event to occur.
541     /// 其中的bool表示该等待过程是否可以被打断。
542     /// - 如果该bool为true,那么,硬件中断/信号/其他系统事件都可以打断该等待过程,使得该进程重新进入Runnable状态。
543     /// - 如果该bool为false,那么,这个进程必须被显式的唤醒,才能重新进入Runnable状态。
544     Blocked(bool),
545     /// 进程被信号终止
546     Stopped,
547     /// 进程已经退出,usize表示进程的退出码
548     Exited(usize),
549 }
550 
551 #[allow(dead_code)]
552 impl ProcessState {
553     #[inline(always)]
554     pub fn is_runnable(&self) -> bool {
555         return matches!(self, ProcessState::Runnable);
556     }
557 
558     #[inline(always)]
559     pub fn is_blocked(&self) -> bool {
560         return matches!(self, ProcessState::Blocked(_));
561     }
562 
563     #[inline(always)]
564     pub fn is_blocked_interruptable(&self) -> bool {
565         return matches!(self, ProcessState::Blocked(true));
566     }
567 
568     /// Returns `true` if the process state is [`Exited`].
569     #[inline(always)]
570     pub fn is_exited(&self) -> bool {
571         return matches!(self, ProcessState::Exited(_));
572     }
573 
574     /// Returns `true` if the process state is [`Stopped`].
575     ///
576     /// [`Stopped`]: ProcessState::Stopped
577     #[inline(always)]
578     pub fn is_stopped(&self) -> bool {
579         matches!(self, ProcessState::Stopped)
580     }
581 
582     /// Returns exit code if the process state is [`Exited`].
583     #[inline(always)]
584     pub fn exit_code(&self) -> Option<usize> {
585         match self {
586             ProcessState::Exited(code) => Some(*code),
587             _ => None,
588         }
589     }
590 }
591 
592 bitflags! {
593     /// pcb的标志位
594     pub struct ProcessFlags: usize {
595         /// 当前pcb表示一个内核线程
596         const KTHREAD = 1 << 0;
597         /// 当前进程需要被调度
598         const NEED_SCHEDULE = 1 << 1;
599         /// 进程由于vfork而与父进程存在资源共享
600         const VFORK = 1 << 2;
601         /// 进程不可被冻结
602         const NOFREEZE = 1 << 3;
603         /// 进程正在退出
604         const EXITING = 1 << 4;
605         /// 进程由于接收到终止信号唤醒
606         const WAKEKILL = 1 << 5;
607         /// 进程由于接收到信号而退出.(Killed by a signal)
608         const SIGNALED = 1 << 6;
609         /// 进程需要迁移到其他cpu上
610         const NEED_MIGRATE = 1 << 7;
611         /// 随机化的虚拟地址空间,主要用于动态链接器的加载
612         const RANDOMIZE = 1 << 8;
613     }
614 }
615 
616 #[derive(Debug)]
617 pub struct ProcessControlBlock {
618     /// 当前进程的pid
619     pid: Pid,
620     /// 当前进程的线程组id(这个值在同一个线程组内永远不变)
621     tgid: Pid,
622 
623     basic: RwLock<ProcessBasicInfo>,
624     /// 当前进程的自旋锁持有计数
625     preempt_count: AtomicUsize,
626 
627     flags: LockFreeFlags<ProcessFlags>,
628     worker_private: SpinLock<Option<WorkerPrivate>>,
629     /// 进程的内核栈
630     kernel_stack: RwLock<KernelStack>,
631 
632     /// 系统调用栈
633     syscall_stack: RwLock<KernelStack>,
634 
635     /// 与调度相关的信息
636     sched_info: ProcessSchedulerInfo,
637     /// 与处理器架构相关的信息
638     arch_info: SpinLock<ArchPCBInfo>,
639     /// 与信号处理相关的信息(似乎可以是无锁的)
640     sig_info: RwLock<ProcessSignalInfo>,
641     /// 信号处理结构体
642     sig_struct: SpinLock<SignalStruct>,
643     /// 退出信号S
644     exit_signal: AtomicSignal,
645 
646     /// 父进程指针
647     parent_pcb: RwLock<Weak<ProcessControlBlock>>,
648     /// 真实父进程指针
649     real_parent_pcb: RwLock<Weak<ProcessControlBlock>>,
650 
651     /// 子进程链表
652     children: RwLock<Vec<Pid>>,
653 
654     /// 等待队列
655     wait_queue: WaitQueue,
656 
657     /// 线程信息
658     thread: RwLock<ThreadInfo>,
659 
660     ///闹钟定时器
661     alarm_timer: SpinLock<Option<AlarmTimer>>,
662 
663     /// 进程的robust lock列表
664     robust_list: RwLock<Option<RobustListHead>>,
665 
666     /// 进程作为主体的凭证集
667     cred: SpinLock<Cred>,
668 }
669 
670 impl ProcessControlBlock {
671     /// Generate a new pcb.
672     ///
673     /// ## 参数
674     ///
675     /// - `name` : 进程的名字
676     /// - `kstack` : 进程的内核栈
677     ///
678     /// ## 返回值
679     ///
680     /// 返回一个新的pcb
681     pub fn new(name: String, kstack: KernelStack) -> Arc<Self> {
682         return Self::do_create_pcb(name, kstack, false);
683     }
684 
685     /// 创建一个新的idle进程
686     ///
687     /// 请注意,这个函数只能在进程管理初始化的时候调用。
688     pub fn new_idle(cpu_id: u32, kstack: KernelStack) -> Arc<Self> {
689         let name = format!("idle-{}", cpu_id);
690         return Self::do_create_pcb(name, kstack, true);
691     }
692 
693     /// # 函数的功能
694     ///
695     /// 返回此函数是否是内核进程
696     ///
697     /// # 返回值
698     ///
699     /// 若进程是内核进程则返回true 否则返回false
700     pub fn is_kthread(&self) -> bool {
701         return matches!(self.flags(), &mut ProcessFlags::KTHREAD);
702     }
703 
704     #[inline(never)]
705     fn do_create_pcb(name: String, kstack: KernelStack, is_idle: bool) -> Arc<Self> {
706         let (pid, ppid, cwd, cred) = if is_idle {
707             let cred = INIT_CRED.clone();
708             (Pid(0), Pid(0), "/".to_string(), cred)
709         } else {
710             let ppid = ProcessManager::current_pcb().pid();
711             let mut cred = ProcessManager::current_pcb().cred();
712             cred.cap_permitted = cred.cap_ambient;
713             cred.cap_effective = cred.cap_ambient;
714             let cwd = ProcessManager::current_pcb().basic().cwd();
715             (Self::generate_pid(), ppid, cwd, cred)
716         };
717 
718         let basic_info = ProcessBasicInfo::new(Pid(0), ppid, Pid(0), name, cwd, None);
719         let preempt_count = AtomicUsize::new(0);
720         let flags = unsafe { LockFreeFlags::new(ProcessFlags::empty()) };
721 
722         let sched_info = ProcessSchedulerInfo::new(None);
723         let arch_info = SpinLock::new(ArchPCBInfo::new(&kstack));
724 
725         let ppcb: Weak<ProcessControlBlock> = ProcessManager::find(ppid)
726             .map(|p| Arc::downgrade(&p))
727             .unwrap_or_default();
728 
729         let pcb = Self {
730             pid,
731             tgid: pid,
732             basic: basic_info,
733             preempt_count,
734             flags,
735             kernel_stack: RwLock::new(kstack),
736             syscall_stack: RwLock::new(KernelStack::new().unwrap()),
737             worker_private: SpinLock::new(None),
738             sched_info,
739             arch_info,
740             sig_info: RwLock::new(ProcessSignalInfo::default()),
741             sig_struct: SpinLock::new(SignalStruct::new()),
742             exit_signal: AtomicSignal::new(Signal::SIGCHLD),
743             parent_pcb: RwLock::new(ppcb.clone()),
744             real_parent_pcb: RwLock::new(ppcb),
745             children: RwLock::new(Vec::new()),
746             wait_queue: WaitQueue::default(),
747             thread: RwLock::new(ThreadInfo::new()),
748             alarm_timer: SpinLock::new(None),
749             robust_list: RwLock::new(None),
750             cred: SpinLock::new(cred),
751         };
752 
753         // 初始化系统调用栈
754         #[cfg(target_arch = "x86_64")]
755         pcb.arch_info
756             .lock()
757             .init_syscall_stack(&pcb.syscall_stack.read());
758 
759         let pcb = Arc::new(pcb);
760 
761         pcb.sched_info()
762             .sched_entity()
763             .force_mut()
764             .set_pcb(Arc::downgrade(&pcb));
765         // 设置进程的arc指针到内核栈和系统调用栈的最低地址处
766         unsafe {
767             pcb.kernel_stack
768                 .write()
769                 .set_pcb(Arc::downgrade(&pcb))
770                 .unwrap();
771 
772             pcb.syscall_stack
773                 .write()
774                 .set_pcb(Arc::downgrade(&pcb))
775                 .unwrap()
776         };
777 
778         // 将当前pcb加入父进程的子进程哈希表中
779         if pcb.pid() > Pid(1) {
780             if let Some(ppcb_arc) = pcb.parent_pcb.read_irqsave().upgrade() {
781                 let mut children = ppcb_arc.children.write_irqsave();
782                 children.push(pcb.pid());
783             } else {
784                 panic!("parent pcb is None");
785             }
786         }
787 
788         return pcb;
789     }
790 
791     /// 生成一个新的pid
792     #[inline(always)]
793     fn generate_pid() -> Pid {
794         static NEXT_PID: AtomicPid = AtomicPid::new(Pid(1));
795         return NEXT_PID.fetch_add(Pid(1), Ordering::SeqCst);
796     }
797 
798     /// 返回当前进程的锁持有计数
799     #[inline(always)]
800     pub fn preempt_count(&self) -> usize {
801         return self.preempt_count.load(Ordering::SeqCst);
802     }
803 
804     /// 增加当前进程的锁持有计数
805     #[inline(always)]
806     pub fn preempt_disable(&self) {
807         self.preempt_count.fetch_add(1, Ordering::SeqCst);
808     }
809 
810     /// 减少当前进程的锁持有计数
811     #[inline(always)]
812     pub fn preempt_enable(&self) {
813         self.preempt_count.fetch_sub(1, Ordering::SeqCst);
814     }
815 
816     #[inline(always)]
817     pub unsafe fn set_preempt_count(&self, count: usize) {
818         self.preempt_count.store(count, Ordering::SeqCst);
819     }
820 
821     #[inline(always)]
822     pub fn flags(&self) -> &mut ProcessFlags {
823         return self.flags.get_mut();
824     }
825 
826     /// 请注意,这个值能在中断上下文中读取,但不能被中断上下文修改
827     /// 否则会导致死锁
828     #[inline(always)]
829     pub fn basic(&self) -> RwLockReadGuard<ProcessBasicInfo> {
830         return self.basic.read_irqsave();
831     }
832 
833     #[inline(always)]
834     pub fn set_name(&self, name: String) {
835         self.basic.write().set_name(name);
836     }
837 
838     #[inline(always)]
839     pub fn basic_mut(&self) -> RwLockWriteGuard<ProcessBasicInfo> {
840         return self.basic.write_irqsave();
841     }
842 
843     /// # 获取arch info的锁,同时关闭中断
844     #[inline(always)]
845     pub fn arch_info_irqsave(&self) -> SpinLockGuard<ArchPCBInfo> {
846         return self.arch_info.lock_irqsave();
847     }
848 
849     /// # 获取arch info的锁,但是不关闭中断
850     ///
851     /// 由于arch info在进程切换的时候会使用到,
852     /// 因此在中断上下文外,获取arch info 而不irqsave是不安全的.
853     ///
854     /// 只能在以下情况下使用这个函数:
855     /// - 在中断上下文中(中断已经禁用),获取arch info的锁。
856     /// - 刚刚创建新的pcb
857     #[inline(always)]
858     pub unsafe fn arch_info(&self) -> SpinLockGuard<ArchPCBInfo> {
859         return self.arch_info.lock();
860     }
861 
862     #[inline(always)]
863     pub fn kernel_stack(&self) -> RwLockReadGuard<KernelStack> {
864         return self.kernel_stack.read();
865     }
866 
867     pub unsafe fn kernel_stack_force_ref(&self) -> &KernelStack {
868         self.kernel_stack.force_get_ref()
869     }
870 
871     #[inline(always)]
872     #[allow(dead_code)]
873     pub fn kernel_stack_mut(&self) -> RwLockWriteGuard<KernelStack> {
874         return self.kernel_stack.write();
875     }
876 
877     #[inline(always)]
878     pub fn sched_info(&self) -> &ProcessSchedulerInfo {
879         return &self.sched_info;
880     }
881 
882     #[inline(always)]
883     pub fn worker_private(&self) -> SpinLockGuard<Option<WorkerPrivate>> {
884         return self.worker_private.lock();
885     }
886 
887     #[inline(always)]
888     pub fn pid(&self) -> Pid {
889         return self.pid;
890     }
891 
892     #[inline(always)]
893     pub fn tgid(&self) -> Pid {
894         return self.tgid;
895     }
896 
897     /// 获取文件描述符表的Arc指针
898     #[inline(always)]
899     pub fn fd_table(&self) -> Arc<RwLock<FileDescriptorVec>> {
900         return self.basic.read().fd_table().unwrap();
901     }
902 
903     #[inline(always)]
904     pub fn cred(&self) -> Cred {
905         self.cred.lock().clone()
906     }
907 
908     /// 根据文件描述符序号,获取socket对象的Arc指针
909     ///
910     /// ## 参数
911     ///
912     /// - `fd` 文件描述符序号
913     ///
914     /// ## 返回值
915     ///
916     /// Option(&mut Box<dyn Socket>) socket对象的可变引用. 如果文件描述符不是socket,那么返回None
917     pub fn get_socket(&self, fd: i32) -> Option<Arc<SocketInode>> {
918         let binding = ProcessManager::current_pcb().fd_table();
919         let fd_table_guard = binding.read();
920 
921         let f = fd_table_guard.get_file_by_fd(fd)?;
922         drop(fd_table_guard);
923 
924         if f.file_type() != FileType::Socket {
925             return None;
926         }
927         let socket: Arc<SocketInode> = f
928             .inode()
929             .downcast_arc::<SocketInode>()
930             .expect("Not a socket inode");
931         return Some(socket);
932     }
933 
934     /// 当前进程退出时,让初始进程收养所有子进程
935     unsafe fn adopt_childen(&self) -> Result<(), SystemError> {
936         match ProcessManager::find(Pid(1)) {
937             Some(init_pcb) => {
938                 let childen_guard = self.children.write();
939                 let mut init_childen_guard = init_pcb.children.write();
940 
941                 childen_guard.iter().for_each(|pid| {
942                     init_childen_guard.push(*pid);
943                 });
944 
945                 return Ok(());
946             }
947             _ => Err(SystemError::ECHILD),
948         }
949     }
950 
951     /// 生成进程的名字
952     pub fn generate_name(program_path: &str, args: &Vec<CString>) -> String {
953         let mut name = program_path.to_string();
954         for arg in args {
955             name.push(' ');
956             name.push_str(arg.to_string_lossy().as_ref());
957         }
958         return name;
959     }
960 
961     pub fn sig_info_irqsave(&self) -> RwLockReadGuard<ProcessSignalInfo> {
962         self.sig_info.read_irqsave()
963     }
964 
965     pub fn try_siginfo_irqsave(&self, times: u8) -> Option<RwLockReadGuard<ProcessSignalInfo>> {
966         for _ in 0..times {
967             if let Some(r) = self.sig_info.try_read_irqsave() {
968                 return Some(r);
969             }
970         }
971 
972         return None;
973     }
974 
975     pub fn sig_info_mut(&self) -> RwLockWriteGuard<ProcessSignalInfo> {
976         self.sig_info.write_irqsave()
977     }
978 
979     pub fn try_siginfo_mut(&self, times: u8) -> Option<RwLockWriteGuard<ProcessSignalInfo>> {
980         for _ in 0..times {
981             if let Some(r) = self.sig_info.try_write_irqsave() {
982                 return Some(r);
983             }
984         }
985 
986         return None;
987     }
988 
989     /// 判断当前进程是否有未处理的信号
990     pub fn has_pending_signal(&self) -> bool {
991         let sig_info = self.sig_info_irqsave();
992         let has_pending = sig_info.sig_pending().has_pending();
993         drop(sig_info);
994         return has_pending;
995     }
996 
997     pub fn sig_struct(&self) -> SpinLockGuard<SignalStruct> {
998         self.sig_struct.lock_irqsave()
999     }
1000 
1001     pub fn try_sig_struct_irqsave(&self, times: u8) -> Option<SpinLockGuard<SignalStruct>> {
1002         for _ in 0..times {
1003             if let Ok(r) = self.sig_struct.try_lock_irqsave() {
1004                 return Some(r);
1005             }
1006         }
1007 
1008         return None;
1009     }
1010 
1011     pub fn sig_struct_irqsave(&self) -> SpinLockGuard<SignalStruct> {
1012         self.sig_struct.lock_irqsave()
1013     }
1014 
1015     #[inline(always)]
1016     pub fn get_robust_list(&self) -> RwLockReadGuard<Option<RobustListHead>> {
1017         return self.robust_list.read_irqsave();
1018     }
1019 
1020     #[inline(always)]
1021     pub fn set_robust_list(&self, new_robust_list: Option<RobustListHead>) {
1022         *self.robust_list.write_irqsave() = new_robust_list;
1023     }
1024 
1025     pub fn alarm_timer_irqsave(&self) -> SpinLockGuard<Option<AlarmTimer>> {
1026         return self.alarm_timer.lock_irqsave();
1027     }
1028 }
1029 
1030 impl Drop for ProcessControlBlock {
1031     fn drop(&mut self) {
1032         let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
1033         // 在ProcFS中,解除进程的注册
1034         procfs_unregister_pid(self.pid())
1035             .unwrap_or_else(|e| panic!("procfs_unregister_pid failed: error: {e:?}"));
1036 
1037         if let Some(ppcb) = self.parent_pcb.read_irqsave().upgrade() {
1038             ppcb.children
1039                 .write_irqsave()
1040                 .retain(|pid| *pid != self.pid());
1041         }
1042 
1043         drop(irq_guard);
1044     }
1045 }
1046 
1047 /// 线程信息
1048 #[derive(Debug)]
1049 pub struct ThreadInfo {
1050     // 来自用户空间记录用户线程id的地址,在该线程结束时将该地址置0以通知父进程
1051     clear_child_tid: Option<VirtAddr>,
1052     set_child_tid: Option<VirtAddr>,
1053 
1054     vfork_done: Option<Arc<Completion>>,
1055     /// 线程组的组长
1056     group_leader: Weak<ProcessControlBlock>,
1057 }
1058 
1059 impl ThreadInfo {
1060     pub fn new() -> Self {
1061         Self {
1062             clear_child_tid: None,
1063             set_child_tid: None,
1064             vfork_done: None,
1065             group_leader: Weak::default(),
1066         }
1067     }
1068 
1069     pub fn group_leader(&self) -> Option<Arc<ProcessControlBlock>> {
1070         return self.group_leader.upgrade();
1071     }
1072 }
1073 
1074 /// 进程的基本信息
1075 ///
1076 /// 这个结构体保存进程的基本信息,主要是那些不会随着进程的运行而经常改变的信息。
1077 #[derive(Debug)]
1078 pub struct ProcessBasicInfo {
1079     /// 当前进程的进程组id
1080     pgid: Pid,
1081     /// 当前进程的父进程的pid
1082     ppid: Pid,
1083     /// 当前进程所属会话id
1084     sid: Pid,
1085     /// 进程的名字
1086     name: String,
1087 
1088     /// 当前进程的工作目录
1089     cwd: String,
1090 
1091     /// 用户地址空间
1092     user_vm: Option<Arc<AddressSpace>>,
1093 
1094     /// 文件描述符表
1095     fd_table: Option<Arc<RwLock<FileDescriptorVec>>>,
1096 }
1097 
1098 impl ProcessBasicInfo {
1099     #[inline(never)]
1100     pub fn new(
1101         pgid: Pid,
1102         ppid: Pid,
1103         sid: Pid,
1104         name: String,
1105         cwd: String,
1106         user_vm: Option<Arc<AddressSpace>>,
1107     ) -> RwLock<Self> {
1108         let fd_table = Arc::new(RwLock::new(FileDescriptorVec::new()));
1109         return RwLock::new(Self {
1110             pgid,
1111             ppid,
1112             sid,
1113             name,
1114             cwd,
1115             user_vm,
1116             fd_table: Some(fd_table),
1117         });
1118     }
1119 
1120     pub fn pgid(&self) -> Pid {
1121         return self.pgid;
1122     }
1123 
1124     pub fn ppid(&self) -> Pid {
1125         return self.ppid;
1126     }
1127 
1128     pub fn sid(&self) -> Pid {
1129         return self.sid;
1130     }
1131 
1132     pub fn name(&self) -> &str {
1133         return &self.name;
1134     }
1135 
1136     pub fn set_name(&mut self, name: String) {
1137         self.name = name;
1138     }
1139 
1140     pub fn cwd(&self) -> String {
1141         return self.cwd.clone();
1142     }
1143     pub fn set_cwd(&mut self, path: String) {
1144         return self.cwd = path;
1145     }
1146 
1147     pub fn user_vm(&self) -> Option<Arc<AddressSpace>> {
1148         return self.user_vm.clone();
1149     }
1150 
1151     pub unsafe fn set_user_vm(&mut self, user_vm: Option<Arc<AddressSpace>>) {
1152         self.user_vm = user_vm;
1153     }
1154 
1155     pub fn fd_table(&self) -> Option<Arc<RwLock<FileDescriptorVec>>> {
1156         return self.fd_table.clone();
1157     }
1158 
1159     pub fn set_fd_table(&mut self, fd_table: Option<Arc<RwLock<FileDescriptorVec>>>) {
1160         self.fd_table = fd_table;
1161     }
1162 }
1163 
1164 #[derive(Debug)]
1165 pub struct ProcessSchedulerInfo {
1166     /// 当前进程所在的cpu
1167     on_cpu: AtomicProcessorId,
1168     /// 如果当前进程等待被迁移到另一个cpu核心上(也就是flags中的PF_NEED_MIGRATE被置位),
1169     /// 该字段存储要被迁移到的目标处理器核心号
1170     // migrate_to: AtomicProcessorId,
1171     inner_locked: RwLock<InnerSchedInfo>,
1172     /// 进程的调度优先级
1173     // priority: SchedPriority,
1174     /// 当前进程的虚拟运行时间
1175     // virtual_runtime: AtomicIsize,
1176     /// 由实时调度器管理的时间片
1177     // rt_time_slice: AtomicIsize,
1178     pub sched_stat: RwLock<SchedInfo>,
1179     /// 调度策略
1180     pub sched_policy: RwLock<crate::sched::SchedPolicy>,
1181     /// cfs调度实体
1182     pub sched_entity: Arc<FairSchedEntity>,
1183     pub on_rq: SpinLock<OnRq>,
1184 
1185     pub prio_data: RwLock<PrioData>,
1186 }
1187 
1188 #[derive(Debug, Default)]
1189 #[allow(dead_code)]
1190 pub struct SchedInfo {
1191     /// 记录任务在特定 CPU 上运行的次数
1192     pub pcount: usize,
1193     /// 记录任务等待在运行队列上的时间
1194     pub run_delay: usize,
1195     /// 记录任务上次在 CPU 上运行的时间戳
1196     pub last_arrival: u64,
1197     /// 记录任务上次被加入到运行队列中的时间戳
1198     pub last_queued: u64,
1199 }
1200 
1201 #[derive(Debug)]
1202 #[allow(dead_code)]
1203 pub struct PrioData {
1204     pub prio: i32,
1205     pub static_prio: i32,
1206     pub normal_prio: i32,
1207 }
1208 
1209 impl Default for PrioData {
1210     fn default() -> Self {
1211         Self {
1212             prio: MAX_PRIO - 20,
1213             static_prio: MAX_PRIO - 20,
1214             normal_prio: MAX_PRIO - 20,
1215         }
1216     }
1217 }
1218 
1219 #[derive(Debug)]
1220 pub struct InnerSchedInfo {
1221     /// 当前进程的状态
1222     state: ProcessState,
1223     /// 进程的调度策略
1224     sleep: bool,
1225 }
1226 
1227 impl InnerSchedInfo {
1228     pub fn state(&self) -> ProcessState {
1229         return self.state;
1230     }
1231 
1232     pub fn set_state(&mut self, state: ProcessState) {
1233         self.state = state;
1234     }
1235 
1236     pub fn set_sleep(&mut self) {
1237         self.sleep = true;
1238     }
1239 
1240     pub fn set_wakeup(&mut self) {
1241         self.sleep = false;
1242     }
1243 
1244     pub fn is_mark_sleep(&self) -> bool {
1245         self.sleep
1246     }
1247 }
1248 
1249 impl ProcessSchedulerInfo {
1250     #[inline(never)]
1251     pub fn new(on_cpu: Option<ProcessorId>) -> Self {
1252         let cpu_id = on_cpu.unwrap_or(ProcessorId::INVALID);
1253         return Self {
1254             on_cpu: AtomicProcessorId::new(cpu_id),
1255             // migrate_to: AtomicProcessorId::new(ProcessorId::INVALID),
1256             inner_locked: RwLock::new(InnerSchedInfo {
1257                 state: ProcessState::Blocked(false),
1258                 sleep: false,
1259             }),
1260             // virtual_runtime: AtomicIsize::new(0),
1261             // rt_time_slice: AtomicIsize::new(0),
1262             // priority: SchedPriority::new(100).unwrap(),
1263             sched_stat: RwLock::new(SchedInfo::default()),
1264             sched_policy: RwLock::new(crate::sched::SchedPolicy::CFS),
1265             sched_entity: FairSchedEntity::new(),
1266             on_rq: SpinLock::new(OnRq::None),
1267             prio_data: RwLock::new(PrioData::default()),
1268         };
1269     }
1270 
1271     pub fn sched_entity(&self) -> Arc<FairSchedEntity> {
1272         return self.sched_entity.clone();
1273     }
1274 
1275     pub fn on_cpu(&self) -> Option<ProcessorId> {
1276         let on_cpu = self.on_cpu.load(Ordering::SeqCst);
1277         if on_cpu == ProcessorId::INVALID {
1278             return None;
1279         } else {
1280             return Some(on_cpu);
1281         }
1282     }
1283 
1284     pub fn set_on_cpu(&self, on_cpu: Option<ProcessorId>) {
1285         if let Some(cpu_id) = on_cpu {
1286             self.on_cpu.store(cpu_id, Ordering::SeqCst);
1287         } else {
1288             self.on_cpu.store(ProcessorId::INVALID, Ordering::SeqCst);
1289         }
1290     }
1291 
1292     // pub fn migrate_to(&self) -> Option<ProcessorId> {
1293     //     let migrate_to = self.migrate_to.load(Ordering::SeqCst);
1294     //     if migrate_to == ProcessorId::INVALID {
1295     //         return None;
1296     //     } else {
1297     //         return Some(migrate_to);
1298     //     }
1299     // }
1300 
1301     // pub fn set_migrate_to(&self, migrate_to: Option<ProcessorId>) {
1302     //     if let Some(data) = migrate_to {
1303     //         self.migrate_to.store(data, Ordering::SeqCst);
1304     //     } else {
1305     //         self.migrate_to
1306     //             .store(ProcessorId::INVALID, Ordering::SeqCst)
1307     //     }
1308     // }
1309 
1310     pub fn inner_lock_write_irqsave(&self) -> RwLockWriteGuard<InnerSchedInfo> {
1311         return self.inner_locked.write_irqsave();
1312     }
1313 
1314     pub fn inner_lock_read_irqsave(&self) -> RwLockReadGuard<InnerSchedInfo> {
1315         return self.inner_locked.read_irqsave();
1316     }
1317 
1318     // pub fn inner_lock_try_read_irqsave(
1319     //     &self,
1320     //     times: u8,
1321     // ) -> Option<RwLockReadGuard<InnerSchedInfo>> {
1322     //     for _ in 0..times {
1323     //         if let Some(r) = self.inner_locked.try_read_irqsave() {
1324     //             return Some(r);
1325     //         }
1326     //     }
1327 
1328     //     return None;
1329     // }
1330 
1331     // pub fn inner_lock_try_upgradable_read_irqsave(
1332     //     &self,
1333     //     times: u8,
1334     // ) -> Option<RwLockUpgradableGuard<InnerSchedInfo>> {
1335     //     for _ in 0..times {
1336     //         if let Some(r) = self.inner_locked.try_upgradeable_read_irqsave() {
1337     //             return Some(r);
1338     //         }
1339     //     }
1340 
1341     //     return None;
1342     // }
1343 
1344     // pub fn virtual_runtime(&self) -> isize {
1345     //     return self.virtual_runtime.load(Ordering::SeqCst);
1346     // }
1347 
1348     // pub fn set_virtual_runtime(&self, virtual_runtime: isize) {
1349     //     self.virtual_runtime
1350     //         .store(virtual_runtime, Ordering::SeqCst);
1351     // }
1352     // pub fn increase_virtual_runtime(&self, delta: isize) {
1353     //     self.virtual_runtime.fetch_add(delta, Ordering::SeqCst);
1354     // }
1355 
1356     // pub fn rt_time_slice(&self) -> isize {
1357     //     return self.rt_time_slice.load(Ordering::SeqCst);
1358     // }
1359 
1360     // pub fn set_rt_time_slice(&self, rt_time_slice: isize) {
1361     //     self.rt_time_slice.store(rt_time_slice, Ordering::SeqCst);
1362     // }
1363 
1364     // pub fn increase_rt_time_slice(&self, delta: isize) {
1365     //     self.rt_time_slice.fetch_add(delta, Ordering::SeqCst);
1366     // }
1367 
1368     pub fn policy(&self) -> crate::sched::SchedPolicy {
1369         return *self.sched_policy.read_irqsave();
1370     }
1371 }
1372 
1373 #[derive(Debug, Clone)]
1374 pub struct KernelStack {
1375     stack: Option<AlignedBox<[u8; KernelStack::SIZE], { KernelStack::ALIGN }>>,
1376     /// 标记该内核栈是否可以被释放
1377     can_be_freed: bool,
1378 }
1379 
1380 impl KernelStack {
1381     pub const SIZE: usize = 0x4000;
1382     pub const ALIGN: usize = 0x4000;
1383 
1384     pub fn new() -> Result<Self, SystemError> {
1385         return Ok(Self {
1386             stack: Some(
1387                 AlignedBox::<[u8; KernelStack::SIZE], { KernelStack::ALIGN }>::new_zeroed()?,
1388             ),
1389             can_be_freed: true,
1390         });
1391     }
1392 
1393     /// 根据已有的空间,构造一个内核栈结构体
1394     ///
1395     /// 仅仅用于BSP启动时,为idle进程构造内核栈。其他时候使用这个函数,很可能造成错误!
1396     pub unsafe fn from_existed(base: VirtAddr) -> Result<Self, SystemError> {
1397         if base.is_null() || !base.check_aligned(Self::ALIGN) {
1398             return Err(SystemError::EFAULT);
1399         }
1400 
1401         return Ok(Self {
1402             stack: Some(
1403                 AlignedBox::<[u8; KernelStack::SIZE], { KernelStack::ALIGN }>::new_unchecked(
1404                     base.data() as *mut [u8; KernelStack::SIZE],
1405                 ),
1406             ),
1407             can_be_freed: false,
1408         });
1409     }
1410 
1411     /// 返回内核栈的起始虚拟地址(低地址)
1412     pub fn start_address(&self) -> VirtAddr {
1413         return VirtAddr::new(self.stack.as_ref().unwrap().as_ptr() as usize);
1414     }
1415 
1416     /// 返回内核栈的结束虚拟地址(高地址)(不包含该地址)
1417     pub fn stack_max_address(&self) -> VirtAddr {
1418         return VirtAddr::new(self.stack.as_ref().unwrap().as_ptr() as usize + Self::SIZE);
1419     }
1420 
1421     pub unsafe fn set_pcb(&mut self, pcb: Weak<ProcessControlBlock>) -> Result<(), SystemError> {
1422         // 将一个Weak<ProcessControlBlock>放到内核栈的最低地址处
1423         let p: *const ProcessControlBlock = Weak::into_raw(pcb);
1424         let stack_bottom_ptr = self.start_address().data() as *mut *const ProcessControlBlock;
1425 
1426         // 如果内核栈的最低地址处已经有了一个pcb,那么,这里就不再设置,直接返回错误
1427         if unlikely(unsafe { !(*stack_bottom_ptr).is_null() }) {
1428             error!("kernel stack bottom is not null: {:p}", *stack_bottom_ptr);
1429             return Err(SystemError::EPERM);
1430         }
1431         // 将pcb的地址放到内核栈的最低地址处
1432         unsafe {
1433             *stack_bottom_ptr = p;
1434         }
1435 
1436         return Ok(());
1437     }
1438 
1439     /// 清除内核栈的pcb指针
1440     ///
1441     /// ## 参数
1442     ///
1443     /// - `force` : 如果为true,那么,即使该内核栈的pcb指针不为null,也会被强制清除而不处理Weak指针问题
1444     pub unsafe fn clear_pcb(&mut self, force: bool) {
1445         let stack_bottom_ptr = self.start_address().data() as *mut *const ProcessControlBlock;
1446         if unlikely(unsafe { (*stack_bottom_ptr).is_null() }) {
1447             return;
1448         }
1449 
1450         if !force {
1451             let pcb_ptr: Weak<ProcessControlBlock> = Weak::from_raw(*stack_bottom_ptr);
1452             drop(pcb_ptr);
1453         }
1454 
1455         *stack_bottom_ptr = core::ptr::null();
1456     }
1457 
1458     /// 返回指向当前内核栈pcb的Arc指针
1459     #[allow(dead_code)]
1460     pub unsafe fn pcb(&self) -> Option<Arc<ProcessControlBlock>> {
1461         // 从内核栈的最低地址处取出pcb的地址
1462         let p = self.stack.as_ref().unwrap().as_ptr() as *const *const ProcessControlBlock;
1463         if unlikely(unsafe { (*p).is_null() }) {
1464             return None;
1465         }
1466 
1467         // 为了防止内核栈的pcb指针被释放,这里需要将其包装一下,使得Arc的drop不会被调用
1468         let weak_wrapper: ManuallyDrop<Weak<ProcessControlBlock>> =
1469             ManuallyDrop::new(Weak::from_raw(*p));
1470 
1471         let new_arc: Arc<ProcessControlBlock> = weak_wrapper.upgrade()?;
1472         return Some(new_arc);
1473     }
1474 }
1475 
1476 impl Drop for KernelStack {
1477     fn drop(&mut self) {
1478         if self.stack.is_some() {
1479             let ptr = self.stack.as_ref().unwrap().as_ptr() as *const *const ProcessControlBlock;
1480             if unsafe { !(*ptr).is_null() } {
1481                 let pcb_ptr: Weak<ProcessControlBlock> = unsafe { Weak::from_raw(*ptr) };
1482                 drop(pcb_ptr);
1483             }
1484         }
1485         // 如果该内核栈不可以被释放,那么,这里就forget,不调用AlignedBox的drop函数
1486         if !self.can_be_freed {
1487             let bx = self.stack.take();
1488             core::mem::forget(bx);
1489         }
1490     }
1491 }
1492 
1493 pub fn process_init() {
1494     ProcessManager::init();
1495 }
1496 
1497 #[derive(Debug)]
1498 pub struct ProcessSignalInfo {
1499     // 当前进程
1500     sig_block: SigSet,
1501     // sig_pending 中存储当前线程要处理的信号
1502     sig_pending: SigPending,
1503     // sig_shared_pending 中存储当前线程所属进程要处理的信号
1504     sig_shared_pending: SigPending,
1505     // 当前进程对应的tty
1506     tty: Option<Arc<TtyCore>>,
1507 }
1508 
1509 impl ProcessSignalInfo {
1510     pub fn sig_block(&self) -> &SigSet {
1511         &self.sig_block
1512     }
1513 
1514     pub fn sig_pending(&self) -> &SigPending {
1515         &self.sig_pending
1516     }
1517 
1518     pub fn sig_pending_mut(&mut self) -> &mut SigPending {
1519         &mut self.sig_pending
1520     }
1521 
1522     pub fn sig_block_mut(&mut self) -> &mut SigSet {
1523         &mut self.sig_block
1524     }
1525 
1526     pub fn sig_shared_pending_mut(&mut self) -> &mut SigPending {
1527         &mut self.sig_shared_pending
1528     }
1529 
1530     pub fn sig_shared_pending(&self) -> &SigPending {
1531         &self.sig_shared_pending
1532     }
1533 
1534     pub fn tty(&self) -> Option<Arc<TtyCore>> {
1535         self.tty.clone()
1536     }
1537 
1538     pub fn set_tty(&mut self, tty: Option<Arc<TtyCore>>) {
1539         self.tty = tty;
1540     }
1541 
1542     /// 从 pcb 的 siginfo中取出下一个要处理的信号,先处理线程信号,再处理进程信号
1543     ///
1544     /// ## 参数
1545     ///
1546     /// - `sig_mask` 被忽略掉的信号
1547     ///
1548     pub fn dequeue_signal(&mut self, sig_mask: &SigSet) -> (Signal, Option<SigInfo>) {
1549         let res = self.sig_pending.dequeue_signal(sig_mask);
1550         if res.0 != Signal::INVALID {
1551             return res;
1552         } else {
1553             return self.sig_shared_pending.dequeue_signal(sig_mask);
1554         }
1555     }
1556 }
1557 
1558 impl Default for ProcessSignalInfo {
1559     fn default() -> Self {
1560         Self {
1561             sig_block: SigSet::empty(),
1562             sig_pending: SigPending::default(),
1563             sig_shared_pending: SigPending::default(),
1564             tty: None,
1565         }
1566     }
1567 }
1568