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