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