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