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