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