mod.rs 46 KB

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