mod.rs 55 KB

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