xref: /DragonOS/kernel/src/process/mod.rs (revision a03c4f9dee5705207325c56629c0ccd219168f10)
1 use core::{
2     hash::{Hash, Hasher},
3     intrinsics::{likely, unlikely},
4     mem::ManuallyDrop,
5     sync::atomic::{compiler_fence, AtomicBool, AtomicI32, AtomicIsize, AtomicUsize, Ordering},
6 };
7 
8 use alloc::{
9     string::{String, ToString},
10     sync::{Arc, Weak},
11     vec::Vec,
12 };
13 use hashbrown::HashMap;
14 
15 use crate::{
16     arch::{process::ArchPCBInfo, sched::sched, CurrentIrqArch},
17     exception::InterruptArch,
18     filesystem::{
19         procfs::procfs_unregister_pid,
20         vfs::{file::FileDescriptorVec, FileType},
21     },
22     kdebug, kinfo,
23     libs::{
24         align::AlignedBox,
25         casting::DowncastArc,
26         rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard},
27         spinlock::{SpinLock, SpinLockGuard},
28         wait_queue::WaitQueue,
29     },
30     mm::{percpu::PerCpuVar, set_INITIAL_PROCESS_ADDRESS_SPACE, ucontext::AddressSpace, VirtAddr},
31     net::socket::SocketInode,
32     sched::{
33         core::{sched_enqueue, CPU_EXECUTING},
34         SchedPolicy, SchedPriority,
35     },
36     smp::kick_cpu,
37     syscall::SystemError,
38 };
39 
40 use self::kthread::WorkerPrivate;
41 
42 pub mod abi;
43 pub mod c_adapter;
44 pub mod exec;
45 pub mod fork;
46 pub mod idle;
47 pub mod init;
48 pub mod kthread;
49 pub mod process;
50 pub mod syscall;
51 
52 /// 系统中所有进程的pcb
53 static ALL_PROCESS: SpinLock<Option<HashMap<Pid, Arc<ProcessControlBlock>>>> = SpinLock::new(None);
54 
55 pub static mut SWITCH_RESULT: Option<PerCpuVar<SwitchResult>> = None;
56 
57 /// 一个只改变1次的全局变量,标志进程管理器是否已经初始化完成
58 static mut __PROCESS_MANAGEMENT_INIT_DONE: bool = false;
59 
60 #[derive(Debug)]
61 pub struct SwitchResult {
62     pub prev_pcb: Option<Arc<ProcessControlBlock>>,
63     pub next_pcb: Option<Arc<ProcessControlBlock>>,
64 }
65 
66 impl SwitchResult {
67     pub fn new() -> Self {
68         Self {
69             prev_pcb: None,
70             next_pcb: None,
71         }
72     }
73 }
74 
75 #[derive(Debug)]
76 pub struct ProcessManager;
77 impl ProcessManager {
78     fn init() {
79         static INIT_FLAG: AtomicBool = AtomicBool::new(false);
80         if INIT_FLAG
81             .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
82             .is_err()
83         {
84             panic!("ProcessManager has been initialized!");
85         }
86 
87         unsafe {
88             compiler_fence(Ordering::SeqCst);
89             kdebug!("To create address space for INIT process.");
90             // test_buddy();
91             set_INITIAL_PROCESS_ADDRESS_SPACE(
92                 AddressSpace::new(true).expect("Failed to create address space for INIT process."),
93             );
94             kdebug!("INIT process address space created.");
95             compiler_fence(Ordering::SeqCst);
96         };
97 
98         ALL_PROCESS.lock().replace(HashMap::new());
99         Self::arch_init();
100         kdebug!("process arch init done.");
101         Self::init_idle();
102         kdebug!("process idle init done.");
103 
104         unsafe {
105             __PROCESS_MANAGEMENT_INIT_DONE = true;
106         }
107         kinfo!("Process Manager initialized.");
108     }
109 
110     /// 获取当前进程的pcb
111     pub fn current_pcb() -> Arc<ProcessControlBlock> {
112         return ProcessControlBlock::arch_current_pcb();
113     }
114 
115     /// 增加当前进程的锁持有计数
116     #[inline(always)]
117     pub fn preempt_disable() {
118         if likely(unsafe { __PROCESS_MANAGEMENT_INIT_DONE }) {
119             ProcessManager::current_pcb().preempt_disable();
120         }
121     }
122 
123     /// 减少当前进程的锁持有计数
124     #[inline(always)]
125     pub fn preempt_enable() {
126         if likely(unsafe { __PROCESS_MANAGEMENT_INIT_DONE }) {
127             ProcessManager::current_pcb().preempt_enable();
128         }
129     }
130 
131     /// 根据pid获取进程的pcb
132     ///
133     /// ## 参数
134     ///
135     /// - `pid` : 进程的pid
136     ///
137     /// ## 返回值
138     ///
139     /// 如果找到了对应的进程,那么返回该进程的pcb,否则返回None
140     pub fn find(pid: Pid) -> Option<Arc<ProcessControlBlock>> {
141         return ALL_PROCESS.lock().as_ref()?.get(&pid).cloned();
142     }
143 
144     /// 向系统中添加一个进程的pcb
145     ///
146     /// ## 参数
147     ///
148     /// - `pcb` : 进程的pcb
149     ///
150     /// ## 返回值
151     ///
152     /// 无
153     pub fn add_pcb(pcb: Arc<ProcessControlBlock>) {
154         ALL_PROCESS
155             .lock()
156             .as_mut()
157             .unwrap()
158             .insert(pcb.pid(), pcb.clone());
159     }
160 
161     /// 唤醒一个进程
162     pub fn wakeup(pcb: &Arc<ProcessControlBlock>) -> Result<(), SystemError> {
163         let _guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
164         let state = pcb.sched_info().state();
165         if state.is_blocked() {
166             let mut writer = pcb.sched_info_mut();
167             let state = writer.state();
168             if state.is_blocked() {
169                 writer.set_state(ProcessState::Runnable);
170                 // avoid deadlock
171                 drop(writer);
172 
173                 sched_enqueue(pcb.clone(), true);
174                 return Ok(());
175             } else if state.is_exited() {
176                 return Err(SystemError::EINVAL);
177             } else {
178                 return Ok(());
179             }
180         } else if state.is_exited() {
181             return Err(SystemError::EINVAL);
182         } else {
183             return Ok(());
184         }
185     }
186 
187     /// 标志当前进程永久睡眠,但是发起调度的工作,应该由调用者完成
188     ///
189     /// ## 注意
190     ///
191     /// - 进入当前函数之前,不能持有sched_info的锁
192     /// - 进入当前函数之前,必须关闭中断
193     pub fn mark_sleep(interruptable: bool) -> Result<(), SystemError> {
194         assert_eq!(
195             CurrentIrqArch::is_irq_enabled(),
196             false,
197             "interrupt must be disabled before enter ProcessManager::mark_sleep()"
198         );
199 
200         let pcb = ProcessManager::current_pcb();
201         let mut writer = pcb.sched_info_mut_irqsave();
202         if writer.state() != ProcessState::Exited(0) {
203             writer.set_state(ProcessState::Blocked(interruptable));
204             pcb.flags().insert(ProcessFlags::NEED_SCHEDULE);
205             drop(writer);
206 
207             return Ok(());
208         }
209         return Err(SystemError::EINTR);
210     }
211 
212     /// 当子进程退出后向父进程发送通知
213     fn exit_notify() {
214         let current = ProcessManager::current_pcb();
215         // 让INIT进程收养所有子进程
216         if current.pid() != Pid(1) {
217             unsafe {
218                 current
219                     .adopt_childen()
220                     .unwrap_or_else(|e| panic!("adopte_childen failed: error: {e:?}"))
221             };
222             // todo: 当信号机制重写后,这里需要向父进程发送SIGCHLD信号
223         }
224     }
225 
226     /// 退出当前进程
227     ///
228     /// ## 参数
229     ///
230     /// - `exit_code` : 进程的退出码
231     pub fn exit(exit_code: usize) -> ! {
232         // 关中断
233         let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
234         let pcb = ProcessManager::current_pcb();
235         pcb.sched_info
236             .write()
237             .set_state(ProcessState::Exited(exit_code));
238         pcb.wait_queue.wakeup(Some(ProcessState::Blocked(true)));
239         drop(pcb);
240         ProcessManager::exit_notify();
241         drop(irq_guard);
242         sched();
243         loop {}
244     }
245 
246     pub unsafe fn release(pid: Pid) {
247         let pcb = ProcessManager::find(pid);
248         if !pcb.is_none() {
249             let pcb = pcb.unwrap();
250             // 判断该pcb是否在全局没有任何引用
251             if Arc::strong_count(&pcb) <= 1 {
252                 drop(pcb);
253                 ALL_PROCESS.lock().as_mut().unwrap().remove(&pid);
254             } else {
255                 // 如果不为1就panic
256                 panic!("pcb is still referenced");
257             }
258         }
259     }
260 
261     /// 上下文切换完成后的钩子函数
262     unsafe fn switch_finish_hook() {
263         // kdebug!("switch_finish_hook");
264         let prev_pcb = SWITCH_RESULT
265             .as_mut()
266             .unwrap()
267             .get_mut()
268             .prev_pcb
269             .take()
270             .expect("prev_pcb is None");
271         let next_pcb = SWITCH_RESULT
272             .as_mut()
273             .unwrap()
274             .get_mut()
275             .next_pcb
276             .take()
277             .expect("next_pcb is None");
278 
279         // 由于进程切换前使用了SpinLockGuard::leak(),所以这里需要手动释放锁
280         prev_pcb.arch_info.force_unlock();
281         next_pcb.arch_info.force_unlock();
282     }
283 
284     /// 如果目标进程正在目标CPU上运行,那么就让这个cpu陷入内核态
285     ///
286     /// ## 参数
287     ///
288     /// - `pcb` : 进程的pcb
289     #[allow(dead_code)]
290     pub fn kick(pcb: &Arc<ProcessControlBlock>) {
291         ProcessManager::current_pcb().preempt_disable();
292         let cpu_id = pcb.sched_info().on_cpu();
293 
294         if let Some(cpu_id) = cpu_id {
295             let cpu_id = cpu_id;
296 
297             if pcb.pid() == CPU_EXECUTING.get(cpu_id) {
298                 kick_cpu(cpu_id).expect("ProcessManager::kick(): Failed to kick cpu");
299             }
300         }
301 
302         ProcessManager::current_pcb().preempt_enable();
303     }
304 }
305 
306 /// 上下文切换的钩子函数,当这个函数return的时候,将会发生上下文切换
307 pub unsafe extern "sysv64" fn switch_finish_hook() {
308     ProcessManager::switch_finish_hook();
309 }
310 
311 int_like!(Pid, AtomicPid, usize, AtomicUsize);
312 
313 impl Hash for Pid {
314     fn hash<H: Hasher>(&self, state: &mut H) {
315         self.0.hash(state);
316     }
317 }
318 
319 impl Pid {
320     pub fn to_string(&self) -> String {
321         self.0.to_string()
322     }
323 }
324 
325 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
326 pub enum ProcessState {
327     /// The process is running on a CPU or in a run queue.
328     Runnable,
329     /// The process is waiting for an event to occur.
330     /// 其中的bool表示该等待过程是否可以被打断。
331     /// - 如果该bool为true,那么,硬件中断/信号/其他系统事件都可以打断该等待过程,使得该进程重新进入Runnable状态。
332     /// - 如果该bool为false,那么,这个进程必须被显式的唤醒,才能重新进入Runnable状态。
333     Blocked(bool),
334     /// 进程被信号终止
335     // Stopped(SignalNumber),
336     /// 进程已经退出,usize表示进程的退出码
337     Exited(usize),
338 }
339 
340 #[allow(dead_code)]
341 impl ProcessState {
342     #[inline(always)]
343     pub fn is_runnable(&self) -> bool {
344         return matches!(self, ProcessState::Runnable);
345     }
346 
347     #[inline(always)]
348     pub fn is_blocked(&self) -> bool {
349         return matches!(self, ProcessState::Blocked(_));
350     }
351 
352     #[inline(always)]
353     pub fn is_exited(&self) -> bool {
354         return matches!(self, ProcessState::Exited(_));
355     }
356 }
357 
358 bitflags! {
359     /// pcb的标志位
360     pub struct ProcessFlags: usize {
361         /// 当前pcb表示一个内核线程
362         const KTHREAD = 1 << 0;
363         /// 当前进程需要被调度
364         const NEED_SCHEDULE = 1 << 1;
365         /// 进程由于vfork而与父进程存在资源共享
366         const VFORK = 1 << 2;
367         /// 进程不可被冻结
368         const NOFREEZE = 1 << 3;
369         /// 进程正在退出
370         const EXITING = 1 << 4;
371         /// 进程由于接收到终止信号唤醒
372         const WAKEKILL = 1 << 5;
373         /// 进程由于接收到信号而退出.(Killed by a signal)
374         const SIGNALED = 1 << 6;
375         /// 进程需要迁移到其他cpu上
376         const NEED_MIGRATE = 1 << 7;
377     }
378 }
379 
380 #[derive(Debug)]
381 pub struct ProcessControlBlock {
382     /// 当前进程的pid
383     pid: Pid,
384 
385     basic: RwLock<ProcessBasicInfo>,
386     /// 当前进程的自旋锁持有计数
387     preempt_count: AtomicUsize,
388 
389     flags: SpinLock<ProcessFlags>,
390     worker_private: SpinLock<Option<WorkerPrivate>>,
391     /// 进程的内核栈
392     kernel_stack: RwLock<KernelStack>,
393 
394     /// 与调度相关的信息
395     sched_info: RwLock<ProcessSchedulerInfo>,
396     /// 与处理器架构相关的信息
397     arch_info: SpinLock<ArchPCBInfo>,
398 
399     /// 父进程指针
400     parent_pcb: RwLock<Weak<ProcessControlBlock>>,
401 
402     /// 子进程链表
403     children: RwLock<HashMap<Pid, Arc<ProcessControlBlock>>>,
404 
405     /// 等待队列
406     wait_queue: WaitQueue,
407 }
408 
409 impl ProcessControlBlock {
410     /// Generate a new pcb.
411     ///
412     /// ## 参数
413     ///
414     /// - `name` : 进程的名字
415     /// - `kstack` : 进程的内核栈
416     ///
417     /// ## 返回值
418     ///
419     /// 返回一个新的pcb
420     pub fn new(name: String, kstack: KernelStack) -> Arc<Self> {
421         return Self::do_create_pcb(name, kstack, false);
422     }
423 
424     /// 创建一个新的idle进程
425     ///
426     /// 请注意,这个函数只能在进程管理初始化的时候调用。
427     pub fn new_idle(cpu_id: u32, kstack: KernelStack) -> Arc<Self> {
428         let name = format!("idle-{}", cpu_id);
429         return Self::do_create_pcb(name, kstack, true);
430     }
431 
432     fn do_create_pcb(name: String, kstack: KernelStack, is_idle: bool) -> Arc<Self> {
433         let (pid, ppid, cwd) = if is_idle {
434             (Pid(0), Pid(0), "/".to_string())
435         } else {
436             (
437                 Self::generate_pid(),
438                 ProcessManager::current_pcb().pid(),
439                 ProcessManager::current_pcb().basic().cwd(),
440             )
441         };
442 
443         let basic_info = ProcessBasicInfo::new(Pid(0), ppid, name, cwd, None);
444         let preempt_count = AtomicUsize::new(0);
445         let flags = SpinLock::new(ProcessFlags::empty());
446 
447         let sched_info = ProcessSchedulerInfo::new(None);
448         let arch_info = SpinLock::new(ArchPCBInfo::new(Some(&kstack)));
449 
450         let ppcb: Weak<ProcessControlBlock> = ProcessManager::find(ppid)
451             .map(|p| Arc::downgrade(&p))
452             .unwrap_or_else(|| Weak::new());
453 
454         let pcb = Self {
455             pid,
456             basic: basic_info,
457             preempt_count,
458             flags,
459             kernel_stack: RwLock::new(kstack),
460             worker_private: SpinLock::new(None),
461             sched_info,
462             arch_info,
463             parent_pcb: RwLock::new(ppcb),
464             children: RwLock::new(HashMap::new()),
465             wait_queue: WaitQueue::INIT,
466         };
467 
468         let pcb = Arc::new(pcb);
469 
470         // 设置进程的arc指针到内核栈的最低地址处
471         unsafe { pcb.kernel_stack.write().set_pcb(Arc::clone(&pcb)).unwrap() };
472 
473         // 将当前pcb加入父进程的子进程哈希表中
474         if pcb.pid() > Pid(1) {
475             if let Some(ppcb_arc) = pcb.parent_pcb.read().upgrade() {
476                 let mut children = ppcb_arc.children.write();
477                 children.insert(pcb.pid(), pcb.clone());
478             } else {
479                 panic!("parent pcb is None");
480             }
481         }
482 
483         return pcb;
484     }
485 
486     /// 生成一个新的pid
487     #[inline(always)]
488     fn generate_pid() -> Pid {
489         static NEXT_PID: AtomicPid = AtomicPid::new(Pid(1));
490         return NEXT_PID.fetch_add(Pid(1), Ordering::SeqCst);
491     }
492 
493     /// 返回当前进程的锁持有计数
494     #[inline(always)]
495     pub fn preempt_count(&self) -> usize {
496         return self.preempt_count.load(Ordering::SeqCst);
497     }
498 
499     /// 增加当前进程的锁持有计数
500     #[inline(always)]
501     pub fn preempt_disable(&self) {
502         self.preempt_count.fetch_add(1, Ordering::SeqCst);
503     }
504 
505     /// 减少当前进程的锁持有计数
506     #[inline(always)]
507     pub fn preempt_enable(&self) {
508         self.preempt_count.fetch_sub(1, Ordering::SeqCst);
509     }
510 
511     #[inline(always)]
512     pub unsafe fn set_preempt_count(&self, count: usize) {
513         self.preempt_count.store(count, Ordering::SeqCst);
514     }
515 
516     #[inline(always)]
517     pub fn flags(&self) -> SpinLockGuard<ProcessFlags> {
518         return self.flags.lock();
519     }
520 
521     #[inline(always)]
522     pub fn basic(&self) -> RwLockReadGuard<ProcessBasicInfo> {
523         return self.basic.read();
524     }
525 
526     #[inline(always)]
527     pub fn set_name(&self, name: String) {
528         self.basic.write().set_name(name);
529     }
530 
531     #[inline(always)]
532     pub fn basic_mut(&self) -> RwLockWriteGuard<ProcessBasicInfo> {
533         return self.basic.write();
534     }
535 
536     #[inline(always)]
537     pub fn arch_info(&self) -> SpinLockGuard<ArchPCBInfo> {
538         return self.arch_info.lock();
539     }
540 
541     #[inline(always)]
542     pub fn arch_info_irqsave(&self) -> SpinLockGuard<ArchPCBInfo> {
543         return self.arch_info.lock_irqsave();
544     }
545 
546     #[inline(always)]
547     pub fn kernel_stack(&self) -> RwLockReadGuard<KernelStack> {
548         return self.kernel_stack.read();
549     }
550 
551     #[inline(always)]
552     #[allow(dead_code)]
553     pub fn kernel_stack_mut(&self) -> RwLockWriteGuard<KernelStack> {
554         return self.kernel_stack.write();
555     }
556 
557     #[inline(always)]
558     pub fn sched_info(&self) -> RwLockReadGuard<ProcessSchedulerInfo> {
559         return self.sched_info.read();
560     }
561 
562     #[inline(always)]
563     pub fn sched_info_mut(&self) -> RwLockWriteGuard<ProcessSchedulerInfo> {
564         return self.sched_info.write();
565     }
566 
567     #[inline(always)]
568     pub fn sched_info_mut_irqsave(&self) -> RwLockWriteGuard<ProcessSchedulerInfo> {
569         return self.sched_info.write_irqsave();
570     }
571 
572     #[inline(always)]
573     pub fn worker_private(&self) -> SpinLockGuard<Option<WorkerPrivate>> {
574         return self.worker_private.lock();
575     }
576 
577     #[inline(always)]
578     pub fn pid(&self) -> Pid {
579         return self.pid;
580     }
581 
582     /// 获取文件描述符表的Arc指针
583     #[inline(always)]
584     pub fn fd_table(&self) -> Arc<RwLock<FileDescriptorVec>> {
585         return self.basic.read().fd_table().unwrap();
586     }
587 
588     /// 根据文件描述符序号,获取socket对象的Arc指针
589     ///
590     /// ## 参数
591     ///
592     /// - `fd` 文件描述符序号
593     ///
594     /// ## 返回值
595     ///
596     /// Option(&mut Box<dyn Socket>) socket对象的可变引用. 如果文件描述符不是socket,那么返回None
597     pub fn get_socket(&self, fd: i32) -> Option<Arc<SocketInode>> {
598         let binding = ProcessManager::current_pcb().fd_table();
599         let fd_table_guard = binding.read();
600 
601         let f = fd_table_guard.get_file_by_fd(fd)?;
602         drop(fd_table_guard);
603 
604         let guard = f.lock();
605         if guard.file_type() != FileType::Socket {
606             return None;
607         }
608         let socket: Arc<SocketInode> = guard
609             .inode()
610             .downcast_arc::<SocketInode>()
611             .expect("Not a socket inode");
612         return Some(socket);
613     }
614 
615     /// 当前进程退出时,让初始进程收养所有子进程
616     unsafe fn adopt_childen(&self) -> Result<(), SystemError> {
617         match ProcessManager::find(Pid(1)) {
618             Some(init_pcb) => {
619                 let mut childen_guard = self.children.write();
620                 let mut init_childen_guard = init_pcb.children.write();
621 
622                 childen_guard.drain().for_each(|(pid, child)| {
623                     init_childen_guard.insert(pid, child);
624                 });
625 
626                 return Ok(());
627             }
628             _ => Err(SystemError::ECHILD),
629         }
630     }
631 
632     /// 生成进程的名字
633     pub fn generate_name(program_path: &str, args: &Vec<String>) -> String {
634         let mut name = program_path.to_string();
635         for arg in args {
636             name.push_str(arg);
637             name.push(' ');
638         }
639         return name;
640     }
641 }
642 
643 impl Drop for ProcessControlBlock {
644     fn drop(&mut self) {
645         // 在ProcFS中,解除进程的注册
646         procfs_unregister_pid(self.pid())
647             .unwrap_or_else(|e| panic!("procfs_unregister_pid failed: error: {e:?}"));
648 
649         if let Some(ppcb) = self.parent_pcb.read().upgrade() {
650             ppcb.children.write().remove(&self.pid());
651         }
652 
653         unsafe { ProcessManager::release(self.pid()) };
654     }
655 }
656 /// 进程的基本信息
657 ///
658 /// 这个结构体保存进程的基本信息,主要是那些不会随着进程的运行而经常改变的信息。
659 #[derive(Debug)]
660 pub struct ProcessBasicInfo {
661     /// 当前进程的进程组id
662     pgid: Pid,
663     /// 当前进程的父进程的pid
664     ppid: Pid,
665     /// 进程的名字
666     name: String,
667 
668     /// 当前进程的工作目录
669     cwd: String,
670 
671     /// 用户地址空间
672     user_vm: Option<Arc<AddressSpace>>,
673 
674     /// 文件描述符表
675     fd_table: Option<Arc<RwLock<FileDescriptorVec>>>,
676 }
677 
678 impl ProcessBasicInfo {
679     pub fn new(
680         pgid: Pid,
681         ppid: Pid,
682         name: String,
683         cwd: String,
684         user_vm: Option<Arc<AddressSpace>>,
685     ) -> RwLock<Self> {
686         let fd_table = Arc::new(RwLock::new(FileDescriptorVec::new()));
687         return RwLock::new(Self {
688             pgid,
689             ppid,
690             name,
691             cwd,
692             user_vm,
693             fd_table: Some(fd_table),
694         });
695     }
696 
697     pub fn pgid(&self) -> Pid {
698         return self.pgid;
699     }
700 
701     pub fn ppid(&self) -> Pid {
702         return self.ppid;
703     }
704 
705     pub fn name(&self) -> &str {
706         return &self.name;
707     }
708 
709     pub fn set_name(&mut self, name: String) {
710         self.name = name;
711     }
712 
713     pub fn cwd(&self) -> String {
714         return self.cwd.clone();
715     }
716     pub fn set_cwd(&mut self, path: String) {
717         return self.cwd = path;
718     }
719 
720     pub fn user_vm(&self) -> Option<Arc<AddressSpace>> {
721         return self.user_vm.clone();
722     }
723 
724     pub unsafe fn set_user_vm(&mut self, user_vm: Option<Arc<AddressSpace>>) {
725         self.user_vm = user_vm;
726     }
727 
728     pub fn fd_table(&self) -> Option<Arc<RwLock<FileDescriptorVec>>> {
729         return self.fd_table.clone();
730     }
731 
732     pub fn set_fd_table(&mut self, fd_table: Option<Arc<RwLock<FileDescriptorVec>>>) {
733         self.fd_table = fd_table;
734     }
735 }
736 
737 #[derive(Debug)]
738 pub struct ProcessSchedulerInfo {
739     /// 当前进程所在的cpu
740     on_cpu: AtomicI32,
741     /// 如果当前进程等待被迁移到另一个cpu核心上(也就是flags中的PF_NEED_MIGRATE被置位),
742     /// 该字段存储要被迁移到的目标处理器核心号
743     migrate_to: AtomicI32,
744 
745     /// 当前进程的状态
746     state: ProcessState,
747     /// 进程的调度策略
748     sched_policy: SchedPolicy,
749     /// 进程的调度优先级
750     priority: SchedPriority,
751     /// 当前进程的虚拟运行时间
752     virtual_runtime: AtomicIsize,
753     /// 由实时调度器管理的时间片
754     rt_time_slice: AtomicIsize,
755 }
756 
757 impl ProcessSchedulerInfo {
758     pub fn new(on_cpu: Option<u32>) -> RwLock<Self> {
759         let cpu_id = match on_cpu {
760             Some(cpu_id) => cpu_id as i32,
761             None => -1,
762         };
763         return RwLock::new(Self {
764             on_cpu: AtomicI32::new(cpu_id),
765             migrate_to: AtomicI32::new(-1),
766             state: ProcessState::Blocked(false),
767             sched_policy: SchedPolicy::CFS,
768             virtual_runtime: AtomicIsize::new(0),
769             rt_time_slice: AtomicIsize::new(0),
770             priority: SchedPriority::new(100).unwrap(),
771         });
772     }
773 
774     pub fn on_cpu(&self) -> Option<u32> {
775         let on_cpu = self.on_cpu.load(Ordering::SeqCst);
776         if on_cpu == -1 {
777             return None;
778         } else {
779             return Some(on_cpu as u32);
780         }
781     }
782 
783     pub fn set_on_cpu(&self, on_cpu: Option<u32>) {
784         if let Some(cpu_id) = on_cpu {
785             self.on_cpu.store(cpu_id as i32, Ordering::SeqCst);
786         } else {
787             self.on_cpu.store(-1, Ordering::SeqCst);
788         }
789     }
790 
791     pub fn migrate_to(&self) -> Option<u32> {
792         let migrate_to = self.migrate_to.load(Ordering::SeqCst);
793         if migrate_to == -1 {
794             return None;
795         } else {
796             return Some(migrate_to as u32);
797         }
798     }
799 
800     pub fn set_migrate_to(&self, migrate_to: Option<u32>) {
801         if let Some(data) = migrate_to {
802             self.migrate_to.store(data as i32, Ordering::SeqCst);
803         } else {
804             self.migrate_to.store(-1, Ordering::SeqCst)
805         }
806     }
807 
808     pub fn state(&self) -> ProcessState {
809         return self.state;
810     }
811 
812     fn set_state(&mut self, state: ProcessState) {
813         self.state = state;
814     }
815 
816     pub fn policy(&self) -> SchedPolicy {
817         return self.sched_policy;
818     }
819 
820     pub fn virtual_runtime(&self) -> isize {
821         return self.virtual_runtime.load(Ordering::SeqCst);
822     }
823 
824     pub fn set_virtual_runtime(&self, virtual_runtime: isize) {
825         self.virtual_runtime
826             .store(virtual_runtime, Ordering::SeqCst);
827     }
828     pub fn increase_virtual_runtime(&self, delta: isize) {
829         self.virtual_runtime.fetch_add(delta, Ordering::SeqCst);
830     }
831 
832     pub fn rt_time_slice(&self) -> isize {
833         return self.rt_time_slice.load(Ordering::SeqCst);
834     }
835 
836     pub fn set_rt_time_slice(&self, rt_time_slice: isize) {
837         self.rt_time_slice.store(rt_time_slice, Ordering::SeqCst);
838     }
839 
840     pub fn increase_rt_time_slice(&self, delta: isize) {
841         self.rt_time_slice.fetch_add(delta, Ordering::SeqCst);
842     }
843 
844     pub fn priority(&self) -> SchedPriority {
845         return self.priority;
846     }
847 }
848 
849 #[derive(Debug)]
850 pub struct KernelStack {
851     stack: Option<AlignedBox<[u8; KernelStack::SIZE], { KernelStack::ALIGN }>>,
852     /// 标记该内核栈是否可以被释放
853     can_be_freed: bool,
854 }
855 
856 impl KernelStack {
857     pub const SIZE: usize = 0x4000;
858     pub const ALIGN: usize = 0x4000;
859 
860     pub fn new() -> Result<Self, SystemError> {
861         return Ok(Self {
862             stack: Some(
863                 AlignedBox::<[u8; KernelStack::SIZE], { KernelStack::ALIGN }>::new_zeroed()?,
864             ),
865             can_be_freed: true,
866         });
867     }
868 
869     /// 根据已有的空间,构造一个内核栈结构体
870     ///
871     /// 仅仅用于BSP启动时,为idle进程构造内核栈。其他时候使用这个函数,很可能造成错误!
872     pub unsafe fn from_existed(base: VirtAddr) -> Result<Self, SystemError> {
873         if base.is_null() || base.check_aligned(Self::ALIGN) == false {
874             return Err(SystemError::EFAULT);
875         }
876 
877         return Ok(Self {
878             stack: Some(
879                 AlignedBox::<[u8; KernelStack::SIZE], { KernelStack::ALIGN }>::new_unchecked(
880                     base.data() as *mut [u8; KernelStack::SIZE],
881                 ),
882             ),
883             can_be_freed: false,
884         });
885     }
886 
887     /// 返回内核栈的起始虚拟地址(低地址)
888     pub fn start_address(&self) -> VirtAddr {
889         return VirtAddr::new(self.stack.as_ref().unwrap().as_ptr() as usize);
890     }
891 
892     /// 返回内核栈的结束虚拟地址(高地址)(不包含该地址)
893     pub fn stack_max_address(&self) -> VirtAddr {
894         return VirtAddr::new(self.stack.as_ref().unwrap().as_ptr() as usize + Self::SIZE);
895     }
896 
897     pub unsafe fn set_pcb(&mut self, pcb: Arc<ProcessControlBlock>) -> Result<(), SystemError> {
898         // 将一个Arc<ProcessControlBlock>放到内核栈的最低地址处
899         let p: *const ProcessControlBlock = Arc::into_raw(pcb);
900         let stack_bottom_ptr = self.start_address().data() as *mut *const ProcessControlBlock;
901 
902         // 如果内核栈的最低地址处已经有了一个pcb,那么,这里就不再设置,直接返回错误
903         if unlikely(unsafe { !(*stack_bottom_ptr).is_null() }) {
904             return Err(SystemError::EPERM);
905         }
906         // 将pcb的地址放到内核栈的最低地址处
907         unsafe {
908             *stack_bottom_ptr = p;
909         }
910 
911         return Ok(());
912     }
913 
914     /// 返回指向当前内核栈pcb的Arc指针
915     #[allow(dead_code)]
916     pub unsafe fn pcb(&self) -> Option<Arc<ProcessControlBlock>> {
917         // 从内核栈的最低地址处取出pcb的地址
918         let p = self.stack.as_ref().unwrap().as_ptr() as *const ProcessControlBlock;
919         if unlikely(p.is_null()) {
920             return None;
921         }
922 
923         // 为了防止内核栈的pcb指针被释放,这里需要将其包装一下,使得Arc的drop不会被调用
924         let arc_wrapper: ManuallyDrop<Arc<ProcessControlBlock>> =
925             ManuallyDrop::new(Arc::from_raw(p));
926 
927         let new_arc: Arc<ProcessControlBlock> = Arc::clone(&arc_wrapper);
928         return Some(new_arc);
929     }
930 }
931 
932 impl Drop for KernelStack {
933     fn drop(&mut self) {
934         if !self.stack.is_none() {
935             let pcb_ptr: Arc<ProcessControlBlock> = unsafe {
936                 Arc::from_raw(self.stack.as_ref().unwrap().as_ptr() as *const ProcessControlBlock)
937             };
938             drop(pcb_ptr);
939         }
940         // 如果该内核栈不可以被释放,那么,这里就forget,不调用AlignedBox的drop函数
941         if !self.can_be_freed {
942             let bx = self.stack.take();
943             core::mem::forget(bx);
944         }
945     }
946 }
947 
948 pub fn process_init() {
949     ProcessManager::init();
950 }
951