mod.rs 55 KB

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