mod.rs 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088
  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. string::{String, ToString},
  11. sync::{Arc, Weak},
  12. vec::Vec,
  13. };
  14. use cred::INIT_CRED;
  15. use hashbrown::HashMap;
  16. use log::{debug, error, info, warn};
  17. use pid::{alloc_pid, Pid, PidLink, PidType};
  18. use process_group::Pgid;
  19. use system_error::SystemError;
  20. use crate::{
  21. arch::{
  22. cpu::current_cpu_id,
  23. ipc::signal::{AtomicSignal, SigSet, Signal},
  24. process::ArchPCBInfo,
  25. CurrentIrqArch,
  26. },
  27. driver::tty::tty_core::TtyCore,
  28. exception::InterruptArch,
  29. filesystem::{
  30. fs::FsStruct,
  31. procfs::procfs_unregister_pid,
  32. vfs::{file::FileDescriptorVec, FileType, IndexNode},
  33. },
  34. ipc::{
  35. signal::RestartBlock,
  36. signal_types::{SigInfo, SigPending, SignalFlags, 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. rwlock::{RwLock, RwLockReadGuard, RwLockUpgradableGuard, RwLockWriteGuard},
  47. spinlock::{SpinLock, SpinLockGuard},
  48. wait_queue::WaitQueue,
  49. },
  50. mm::{
  51. percpu::{PerCpu, PerCpuVar},
  52. set_IDLE_PROCESS_ADDRESS_SPACE,
  53. ucontext::AddressSpace,
  54. PhysAddr, VirtAddr,
  55. },
  56. net::socket::SocketInode,
  57. sched::{
  58. completion::Completion, cpu_rq, fair::FairSchedEntity, prio::MAX_PRIO, DequeueFlag,
  59. EnqueueFlag, OnRq, SchedMode, WakeupFlags, __schedule,
  60. },
  61. smp::{
  62. core::smp_get_processor_id,
  63. cpu::{AtomicProcessorId, ProcessorId},
  64. kick_cpu,
  65. },
  66. syscall::user_access::clear_user,
  67. };
  68. use timer::AlarmTimer;
  69. use self::{cred::Cred, kthread::WorkerPrivate};
  70. use crate::process::namespace::nsproxy::NsProxy;
  71. pub mod abi;
  72. pub mod cred;
  73. pub mod exec;
  74. pub mod execve;
  75. pub mod exit;
  76. pub mod fork;
  77. pub mod geteuid;
  78. pub mod idle;
  79. pub mod kthread;
  80. pub mod namespace;
  81. pub mod pid;
  82. pub mod process_group;
  83. pub mod resource;
  84. pub mod session;
  85. pub mod signal;
  86. pub mod stdio;
  87. pub mod syscall;
  88. pub mod timer;
  89. pub mod utils;
  90. /// 系统中所有进程的pcb
  91. static ALL_PROCESS: SpinLock<Option<HashMap<RawPid, Arc<ProcessControlBlock>>>> =
  92. SpinLock::new(None);
  93. pub static mut PROCESS_SWITCH_RESULT: Option<PerCpuVar<SwitchResult>> = None;
  94. /// 一个只改变1次的全局变量,标志进程管理器是否已经初始化完成
  95. static mut __PROCESS_MANAGEMENT_INIT_DONE: bool = false;
  96. pub struct SwitchResult {
  97. pub prev_pcb: Option<Arc<ProcessControlBlock>>,
  98. pub next_pcb: Option<Arc<ProcessControlBlock>>,
  99. }
  100. impl SwitchResult {
  101. pub fn new() -> Self {
  102. Self {
  103. prev_pcb: None,
  104. next_pcb: None,
  105. }
  106. }
  107. }
  108. #[derive(Debug)]
  109. pub struct ProcessManager;
  110. impl ProcessManager {
  111. #[inline(never)]
  112. fn init() {
  113. static INIT_FLAG: AtomicBool = AtomicBool::new(false);
  114. if INIT_FLAG
  115. .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
  116. .is_err()
  117. {
  118. panic!("ProcessManager has been initialized!");
  119. }
  120. unsafe {
  121. compiler_fence(Ordering::SeqCst);
  122. debug!("To create address space for INIT process.");
  123. // test_buddy();
  124. set_IDLE_PROCESS_ADDRESS_SPACE(
  125. AddressSpace::new(true).expect("Failed to create address space for INIT process."),
  126. );
  127. debug!("INIT process address space created.");
  128. compiler_fence(Ordering::SeqCst);
  129. };
  130. ALL_PROCESS.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() -> RawPid {
  167. if unlikely(unsafe { !__PROCESS_MANAGEMENT_INIT_DONE }) {
  168. return RawPid(0);
  169. }
  170. return ProcessManager::current_pcb().raw_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: RawPid) -> 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.raw_pid(), pcb.clone());
  213. }
  214. /// ### 获取所有进程的pid
  215. pub fn get_all_processes() -> Vec<RawPid> {
  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. #[inline(never)]
  340. fn exit_notify() {
  341. let current = ProcessManager::current_pcb();
  342. // 让INIT进程收养所有子进程
  343. if current.raw_pid() != RawPid(1) {
  344. unsafe {
  345. current
  346. .adopt_childen()
  347. .unwrap_or_else(|e| panic!("adopte_childen failed: error: {e:?}"))
  348. };
  349. let r = current.parent_pcb.read_irqsave().upgrade();
  350. if r.is_none() {
  351. return;
  352. }
  353. let parent_pcb = r.unwrap();
  354. let r = crate::ipc::kill::kill_process_by_pcb(parent_pcb.clone(), Signal::SIGCHLD);
  355. if let Err(e) = r {
  356. warn!(
  357. "failed to send kill signal to {:?}'s parent pcb {:?}: {:?}",
  358. current.raw_pid(),
  359. parent_pcb.raw_pid(),
  360. e
  361. );
  362. }
  363. // todo: 这里还需要根据线程组的信息,决定信号的发送
  364. }
  365. }
  366. /// 退出当前进程
  367. ///
  368. /// ## 参数
  369. ///
  370. /// - `exit_code` : 进程的退出码
  371. ///
  372. /// ## 注意
  373. /// 对于正常退出的进程,状态码应该先左移八位,以便用户态读取的时候正常返回退出码;而对于被信号终止的进程,状态码则是最低七位,无需进行移位操作。
  374. ///
  375. /// 因此注意,传入的`exit_code`应该是已经完成了移位操作的
  376. pub fn exit(exit_code: usize) -> ! {
  377. // 检查是否是init进程尝试退出,如果是则产生panic
  378. let current_pcb = ProcessManager::current_pcb();
  379. if current_pcb.raw_pid() == RawPid(1) {
  380. log::error!(
  381. "Init process (pid=1) attempted to exit with code {}. This should not happen and indicates a serious system error.",
  382. exit_code
  383. );
  384. loop {
  385. spin_loop();
  386. }
  387. }
  388. drop(current_pcb);
  389. // 关中断
  390. let _irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
  391. let pid: Arc<Pid>;
  392. let raw_pid = ProcessManager::current_pid();
  393. {
  394. let pcb = ProcessManager::current_pcb();
  395. pid = pcb.pid();
  396. pcb.sched_info
  397. .inner_lock_write_irqsave()
  398. .set_state(ProcessState::Exited(exit_code));
  399. pcb.wait_queue.mark_dead();
  400. pcb.wait_queue.wakeup_all(Some(ProcessState::Blocked(true)));
  401. let rq = cpu_rq(smp_get_processor_id().data() as usize);
  402. let (rq, guard) = rq.self_lock();
  403. rq.deactivate_task(
  404. pcb.clone(),
  405. DequeueFlag::DEQUEUE_SLEEP | DequeueFlag::DEQUEUE_NOCLOCK,
  406. );
  407. drop(guard);
  408. // 进行进程退出后的工作
  409. let thread = pcb.thread.write_irqsave();
  410. if let Some(addr) = thread.clear_child_tid {
  411. if Arc::strong_count(&pcb.basic().user_vm().expect("User VM Not found")) > 1 {
  412. let _ = Futex::futex_wake(
  413. addr,
  414. FutexFlag::FLAGS_MATCH_NONE,
  415. 1,
  416. FUTEX_BITSET_MATCH_ANY,
  417. );
  418. }
  419. unsafe { clear_user(addr, core::mem::size_of::<i32>()).expect("clear tid failed") };
  420. }
  421. compiler_fence(Ordering::SeqCst);
  422. RobustListHead::exit_robust_list(pcb.clone());
  423. // 如果是vfork出来的进程,则需要处理completion
  424. if thread.vfork_done.is_some() {
  425. thread.vfork_done.as_ref().unwrap().complete_all();
  426. }
  427. drop(thread);
  428. unsafe { pcb.basic_mut().set_user_vm(None) };
  429. pcb.exit_files();
  430. // TODO 由于未实现进程组,tty记录的前台进程组等于当前进程,故退出前要置空
  431. // 后续相关逻辑需要在SYS_EXIT_GROUP系统调用中实现
  432. if let Some(tty) = pcb.sig_info_irqsave().tty() {
  433. // 临时解决方案!!! 临时解决方案!!! 引入进程组之后,要重写这个更新前台进程组的逻辑
  434. let mut g = tty.core().contorl_info_irqsave();
  435. if g.pgid == Some(pid) {
  436. g.pgid = None;
  437. }
  438. }
  439. pcb.sig_info_mut().set_tty(None);
  440. drop(pcb);
  441. ProcessManager::exit_notify();
  442. }
  443. __schedule(SchedMode::SM_NONE);
  444. error!("raw_pid {raw_pid:?} exited but sched again!");
  445. #[allow(clippy::empty_loop)]
  446. loop {
  447. spin_loop();
  448. }
  449. }
  450. /// 从全局进程列表中删除一个进程
  451. ///
  452. /// # 参数
  453. ///
  454. /// - `pid` : 进程的**全局** pid
  455. pub(super) unsafe fn release(pid: RawPid) {
  456. let pcb = ProcessManager::find(pid);
  457. if pcb.is_some() {
  458. // log::debug!("release pid {}", pid);
  459. // let pcb = pcb.unwrap();
  460. // 判断该pcb是否在全局没有任何引用
  461. // TODO: 当前,pcb的Arc指针存在泄露问题,引用计数不正确,打算在接下来实现debug专用的Arc,方便调试,然后解决这个bug。
  462. // 因此目前暂时注释掉,使得能跑
  463. // if Arc::strong_count(&pcb) <= 2 {
  464. // drop(pcb);
  465. // ALL_PROCESS.lock().as_mut().unwrap().remove(&pid);
  466. // } else {
  467. // // 如果不为1就panic
  468. // let msg = format!("pcb '{:?}' is still referenced, strong count={}",pcb.pid(), Arc::strong_count(&pcb));
  469. // error!("{}", msg);
  470. // panic!()
  471. // }
  472. ALL_PROCESS.lock_irqsave().as_mut().unwrap().remove(&pid);
  473. }
  474. }
  475. /// 上下文切换完成后的钩子函数
  476. unsafe fn switch_finish_hook() {
  477. // debug!("switch_finish_hook");
  478. let prev_pcb = PROCESS_SWITCH_RESULT
  479. .as_mut()
  480. .unwrap()
  481. .get_mut()
  482. .prev_pcb
  483. .take()
  484. .expect("prev_pcb is None");
  485. let next_pcb = PROCESS_SWITCH_RESULT
  486. .as_mut()
  487. .unwrap()
  488. .get_mut()
  489. .next_pcb
  490. .take()
  491. .expect("next_pcb is None");
  492. // 由于进程切换前使用了SpinLockGuard::leak(),所以这里需要手动释放锁
  493. fence(Ordering::SeqCst);
  494. prev_pcb.arch_info.force_unlock();
  495. fence(Ordering::SeqCst);
  496. next_pcb.arch_info.force_unlock();
  497. fence(Ordering::SeqCst);
  498. }
  499. /// 如果目标进程正在目标CPU上运行,那么就让这个cpu陷入内核态
  500. ///
  501. /// ## 参数
  502. ///
  503. /// - `pcb` : 进程的pcb
  504. #[allow(dead_code)]
  505. pub fn kick(pcb: &Arc<ProcessControlBlock>) {
  506. ProcessManager::current_pcb().preempt_disable();
  507. let cpu_id = pcb.sched_info().on_cpu();
  508. if let Some(cpu_id) = cpu_id {
  509. if pcb.raw_pid() == cpu_rq(cpu_id.data() as usize).current().raw_pid() {
  510. kick_cpu(cpu_id).expect("ProcessManager::kick(): Failed to kick cpu");
  511. }
  512. }
  513. ProcessManager::current_pcb().preempt_enable();
  514. }
  515. }
  516. /// 上下文切换的钩子函数,当这个函数return的时候,将会发生上下文切换
  517. #[cfg(target_arch = "x86_64")]
  518. #[inline(never)]
  519. pub unsafe extern "sysv64" fn switch_finish_hook() {
  520. ProcessManager::switch_finish_hook();
  521. }
  522. #[cfg(target_arch = "riscv64")]
  523. #[inline(always)]
  524. pub unsafe fn switch_finish_hook() {
  525. ProcessManager::switch_finish_hook();
  526. }
  527. int_like!(RawPid, AtomicRawPid, usize, AtomicUsize);
  528. impl fmt::Display for RawPid {
  529. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  530. write!(f, "{}", self.0)
  531. }
  532. }
  533. impl RawPid {
  534. /// 该RawPid暂未分配,待会会初始化它。
  535. /// 这个状态只应当出现在进程/线程创建的过程中
  536. pub const UNASSIGNED: RawPid = RawPid(usize::MAX - 1);
  537. pub const MAX_VALID: RawPid = RawPid(usize::MAX - 32);
  538. pub fn is_valid(&self) -> bool {
  539. self.0 >= Self::MAX_VALID.0
  540. }
  541. }
  542. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  543. pub enum ProcessState {
  544. /// The process is running on a CPU or in a run queue.
  545. Runnable,
  546. /// The process is waiting for an event to occur.
  547. /// 其中的bool表示该等待过程是否可以被打断。
  548. /// - 如果该bool为true,那么,硬件中断/信号/其他系统事件都可以打断该等待过程,使得该进程重新进入Runnable状态。
  549. /// - 如果该bool为false,那么,这个进程必须被显式的唤醒,才能重新进入Runnable状态。
  550. Blocked(bool),
  551. /// 进程被信号终止
  552. Stopped,
  553. /// 进程已经退出,usize表示进程的退出码
  554. Exited(usize),
  555. }
  556. #[allow(dead_code)]
  557. impl ProcessState {
  558. #[inline(always)]
  559. pub fn is_runnable(&self) -> bool {
  560. return matches!(self, ProcessState::Runnable);
  561. }
  562. #[inline(always)]
  563. pub fn is_blocked(&self) -> bool {
  564. return matches!(self, ProcessState::Blocked(_));
  565. }
  566. #[inline(always)]
  567. pub fn is_blocked_interruptable(&self) -> bool {
  568. return matches!(self, ProcessState::Blocked(true));
  569. }
  570. /// Returns `true` if the process state is [`Exited`].
  571. #[inline(always)]
  572. pub fn is_exited(&self) -> bool {
  573. return matches!(self, ProcessState::Exited(_));
  574. }
  575. /// Returns `true` if the process state is [`Stopped`].
  576. ///
  577. /// [`Stopped`]: ProcessState::Stopped
  578. #[inline(always)]
  579. pub fn is_stopped(&self) -> bool {
  580. matches!(self, ProcessState::Stopped)
  581. }
  582. /// Returns exit code if the process state is [`Exited`].
  583. #[inline(always)]
  584. pub fn exit_code(&self) -> Option<usize> {
  585. match self {
  586. ProcessState::Exited(code) => Some(*code),
  587. _ => None,
  588. }
  589. }
  590. }
  591. bitflags! {
  592. /// pcb的标志位
  593. pub struct ProcessFlags: usize {
  594. /// 当前pcb表示一个内核线程
  595. const KTHREAD = 1 << 0;
  596. /// 当前进程需要被调度
  597. const NEED_SCHEDULE = 1 << 1;
  598. /// 进程由于vfork而与父进程存在资源共享
  599. const VFORK = 1 << 2;
  600. /// 进程不可被冻结
  601. const NOFREEZE = 1 << 3;
  602. /// 进程正在退出
  603. const EXITING = 1 << 4;
  604. /// 进程由于接收到终止信号唤醒
  605. const WAKEKILL = 1 << 5;
  606. /// 进程由于接收到信号而退出.(Killed by a signal)
  607. const SIGNALED = 1 << 6;
  608. /// 进程需要迁移到其他cpu上
  609. const NEED_MIGRATE = 1 << 7;
  610. /// 随机化的虚拟地址空间,主要用于动态链接器的加载
  611. const RANDOMIZE = 1 << 8;
  612. /// 进程有未处理的信号(这是一个用于快速判断的标志位)
  613. /// 相当于Linux的TIF_SIGPENDING
  614. const HAS_PENDING_SIGNAL = 1 << 9;
  615. /// 进程需要恢复之前保存的信号掩码
  616. const RESTORE_SIG_MASK = 1 << 10;
  617. /// Forked but didn't exec
  618. const FORKNOEXEC = 1 << 11;
  619. }
  620. }
  621. impl ProcessFlags {
  622. pub const fn exit_to_user_mode_work(&self) -> Self {
  623. Self::from_bits_truncate(self.bits & (Self::HAS_PENDING_SIGNAL.bits))
  624. }
  625. /// 测试并清除标志位
  626. ///
  627. /// ## 参数
  628. ///
  629. /// - `rhs` : 需要测试并清除的标志位
  630. ///
  631. /// ## 返回值
  632. ///
  633. /// 如果标志位在清除前是置位的,则返回 `true`,否则返回 `false`
  634. pub const fn test_and_clear(&mut self, rhs: Self) -> bool {
  635. let r = (self.bits & rhs.bits) != 0;
  636. self.bits &= !rhs.bits;
  637. r
  638. }
  639. }
  640. #[derive(Debug)]
  641. pub struct ProcessControlBlock {
  642. /// 当前进程的pid
  643. pid: RawPid,
  644. /// 当前进程的线程组id(这个值在同一个线程组内永远不变)
  645. tgid: RawPid,
  646. thread_pid: RwLock<Option<Arc<Pid>>>,
  647. /// PID链接数组
  648. pid_links: [PidLink; PidType::PIDTYPE_MAX],
  649. /// namespace代理
  650. nsproxy: RwLock<Arc<NsProxy>>,
  651. basic: RwLock<ProcessBasicInfo>,
  652. /// 当前进程的自旋锁持有计数
  653. preempt_count: AtomicUsize,
  654. flags: LockFreeFlags<ProcessFlags>,
  655. worker_private: SpinLock<Option<WorkerPrivate>>,
  656. /// 进程的内核栈
  657. kernel_stack: RwLock<KernelStack>,
  658. /// 系统调用栈
  659. syscall_stack: RwLock<KernelStack>,
  660. /// 与调度相关的信息
  661. sched_info: ProcessSchedulerInfo,
  662. /// 与处理器架构相关的信息
  663. arch_info: SpinLock<ArchPCBInfo>,
  664. /// 与信号处理相关的信息(似乎可以是无锁的)
  665. sig_info: RwLock<ProcessSignalInfo>,
  666. /// 信号处理结构体
  667. sig_struct: SpinLock<SignalStruct>,
  668. /// 退出信号S
  669. exit_signal: AtomicSignal,
  670. /// 父进程指针
  671. parent_pcb: RwLock<Weak<ProcessControlBlock>>,
  672. /// 真实父进程指针
  673. real_parent_pcb: RwLock<Weak<ProcessControlBlock>>,
  674. /// 子进程链表
  675. children: RwLock<Vec<RawPid>>,
  676. /// 等待队列
  677. wait_queue: WaitQueue,
  678. /// 线程信息
  679. thread: RwLock<ThreadInfo>,
  680. /// 进程文件系统的状态
  681. fs: RwLock<Arc<FsStruct>>,
  682. ///闹钟定时器
  683. alarm_timer: SpinLock<Option<AlarmTimer>>,
  684. /// 进程的robust lock列表
  685. robust_list: RwLock<Option<RobustListHead>>,
  686. /// 进程作为主体的凭证集
  687. cred: SpinLock<Arc<Cred>>,
  688. self_ref: Weak<ProcessControlBlock>,
  689. restart_block: SpinLock<Option<RestartBlock>>,
  690. /// 进程的可执行文件路径
  691. executable_path: RwLock<String>,
  692. }
  693. impl ProcessControlBlock {
  694. /// Generate a new pcb.
  695. ///
  696. /// ## 参数
  697. ///
  698. /// - `name` : 进程的名字
  699. /// - `kstack` : 进程的内核栈
  700. ///
  701. /// ## 返回值
  702. ///
  703. /// 返回一个新的pcb
  704. pub fn new(name: String, kstack: KernelStack) -> Arc<Self> {
  705. return Self::do_create_pcb(name, kstack, false);
  706. }
  707. /// 创建一个新的idle进程
  708. ///
  709. /// 请注意,这个函数只能在进程管理初始化的时候调用。
  710. pub fn new_idle(cpu_id: u32, kstack: KernelStack) -> Arc<Self> {
  711. let name = format!("idle-{}", cpu_id);
  712. return Self::do_create_pcb(name, kstack, true);
  713. }
  714. /// # 函数的功能
  715. ///
  716. /// 返回此函数是否是内核进程
  717. ///
  718. /// # 返回值
  719. ///
  720. /// 若进程是内核进程则返回true 否则返回false
  721. pub fn is_kthread(&self) -> bool {
  722. return matches!(self.flags(), &mut ProcessFlags::KTHREAD);
  723. }
  724. #[inline(never)]
  725. fn do_create_pcb(name: String, kstack: KernelStack, is_idle: bool) -> Arc<Self> {
  726. // 初始化namespace代理
  727. let nsproxy = if is_idle {
  728. // idle进程使用root namespace
  729. NsProxy::new_root()
  730. } else {
  731. // 其他进程继承父进程的namespace
  732. ProcessManager::current_pcb().nsproxy().clone()
  733. };
  734. let (raw_pid, ppid, cwd, cred, tty): (
  735. RawPid,
  736. RawPid,
  737. String,
  738. Arc<Cred>,
  739. Option<Arc<TtyCore>>,
  740. ) = if is_idle {
  741. let cred = INIT_CRED.clone();
  742. (RawPid(0), RawPid(0), "/".to_string(), cred, None)
  743. } else {
  744. let ppid = ProcessManager::current_pcb().task_pid_vnr();
  745. let cred = ProcessManager::current_pcb().cred();
  746. if cred.cap_ambient != cred.cap_permitted || cred.cap_ambient != cred.cap_effective {
  747. todo!("create a new cred for child.")
  748. // cred.cap_permitted = cred.cap_ambient;
  749. // cred.cap_effective = cred.cap_ambient;
  750. }
  751. let cwd = ProcessManager::current_pcb().basic().cwd();
  752. let tty = ProcessManager::current_pcb().sig_info_irqsave().tty();
  753. // Here, UNASSIGNED is used to represent an unallocated pid,
  754. // which will be allocated later in `copy_process`.
  755. let raw_pid = RawPid::UNASSIGNED;
  756. (raw_pid, ppid, cwd, cred, tty)
  757. };
  758. let basic_info = ProcessBasicInfo::new(ppid, name.clone(), cwd, None);
  759. let preempt_count = AtomicUsize::new(0);
  760. let flags = unsafe { LockFreeFlags::new(ProcessFlags::empty()) };
  761. let sched_info = ProcessSchedulerInfo::new(None);
  762. let ppcb: Weak<ProcessControlBlock> = ProcessManager::find_task_by_vpid(ppid)
  763. .map(|p| Arc::downgrade(&p))
  764. .unwrap_or_default();
  765. // 使用 Arc::new_cyclic 避免在栈上创建巨大的结构体
  766. let pcb = Arc::new_cyclic(|weak| {
  767. let arch_info = SpinLock::new(ArchPCBInfo::new(&kstack));
  768. let pcb = Self {
  769. pid: raw_pid,
  770. tgid: raw_pid,
  771. thread_pid: RwLock::new(None),
  772. pid_links: core::array::from_fn(|_| PidLink::default()),
  773. nsproxy: RwLock::new(nsproxy),
  774. basic: basic_info,
  775. preempt_count,
  776. flags,
  777. kernel_stack: RwLock::new(kstack),
  778. syscall_stack: RwLock::new(KernelStack::new().unwrap()),
  779. worker_private: SpinLock::new(None),
  780. sched_info,
  781. arch_info,
  782. sig_info: RwLock::new(ProcessSignalInfo::default()),
  783. sig_struct: SpinLock::new(SignalStruct::new()),
  784. exit_signal: AtomicSignal::new(Signal::SIGCHLD),
  785. parent_pcb: RwLock::new(ppcb.clone()),
  786. real_parent_pcb: RwLock::new(ppcb),
  787. children: RwLock::new(Vec::new()),
  788. wait_queue: WaitQueue::default(),
  789. thread: RwLock::new(ThreadInfo::new()),
  790. fs: RwLock::new(Arc::new(FsStruct::new())),
  791. alarm_timer: SpinLock::new(None),
  792. robust_list: RwLock::new(None),
  793. cred: SpinLock::new(cred),
  794. self_ref: weak.clone(),
  795. restart_block: SpinLock::new(None),
  796. executable_path: RwLock::new(name),
  797. };
  798. pcb.sig_info.write().set_tty(tty);
  799. // 初始化系统调用栈
  800. #[cfg(target_arch = "x86_64")]
  801. pcb.arch_info
  802. .lock()
  803. .init_syscall_stack(&pcb.syscall_stack.read());
  804. pcb
  805. });
  806. pcb.sched_info()
  807. .sched_entity()
  808. .force_mut()
  809. .set_pcb(Arc::downgrade(&pcb));
  810. // 设置进程的arc指针到内核栈和系统调用栈的最低地址处
  811. unsafe {
  812. pcb.kernel_stack
  813. .write()
  814. .set_pcb(Arc::downgrade(&pcb))
  815. .unwrap();
  816. pcb.syscall_stack
  817. .write()
  818. .set_pcb(Arc::downgrade(&pcb))
  819. .unwrap()
  820. };
  821. return pcb;
  822. }
  823. /// 返回当前进程的锁持有计数
  824. #[inline(always)]
  825. pub fn preempt_count(&self) -> usize {
  826. return self.preempt_count.load(Ordering::SeqCst);
  827. }
  828. /// 增加当前进程的锁持有计数
  829. #[inline(always)]
  830. pub fn preempt_disable(&self) {
  831. self.preempt_count.fetch_add(1, Ordering::SeqCst);
  832. }
  833. /// 减少当前进程的锁持有计数
  834. #[inline(always)]
  835. pub fn preempt_enable(&self) {
  836. self.preempt_count.fetch_sub(1, Ordering::SeqCst);
  837. }
  838. #[inline(always)]
  839. pub unsafe fn set_preempt_count(&self, count: usize) {
  840. self.preempt_count.store(count, Ordering::SeqCst);
  841. }
  842. #[inline(always)]
  843. pub fn contain_child(&self, pid: &RawPid) -> bool {
  844. let children = self.children.read();
  845. return children.contains(pid);
  846. }
  847. #[inline(always)]
  848. pub fn flags(&self) -> &mut ProcessFlags {
  849. return self.flags.get_mut();
  850. }
  851. /// 请注意,这个值能在中断上下文中读取,但不能被中断上下文修改
  852. /// 否则会导致死锁
  853. #[inline(always)]
  854. pub fn basic(&self) -> RwLockReadGuard<ProcessBasicInfo> {
  855. return self.basic.read_irqsave();
  856. }
  857. #[inline(always)]
  858. pub fn set_name(&self, name: String) {
  859. self.basic.write().set_name(name);
  860. }
  861. #[inline(always)]
  862. pub fn basic_mut(&self) -> RwLockWriteGuard<ProcessBasicInfo> {
  863. return self.basic.write_irqsave();
  864. }
  865. /// # 获取arch info的锁,同时关闭中断
  866. #[inline(always)]
  867. pub fn arch_info_irqsave(&self) -> SpinLockGuard<ArchPCBInfo> {
  868. return self.arch_info.lock_irqsave();
  869. }
  870. /// # 获取arch info的锁,但是不关闭中断
  871. ///
  872. /// 由于arch info在进程切换的时候会使用到,
  873. /// 因此在中断上下文外,获取arch info 而不irqsave是不安全的.
  874. ///
  875. /// 只能在以下情况下使用这个函数:
  876. /// - 在中断上下文中(中断已经禁用),获取arch info的锁。
  877. /// - 刚刚创建新的pcb
  878. #[inline(always)]
  879. pub unsafe fn arch_info(&self) -> SpinLockGuard<ArchPCBInfo> {
  880. return self.arch_info.lock();
  881. }
  882. #[inline(always)]
  883. pub fn kernel_stack(&self) -> RwLockReadGuard<KernelStack> {
  884. return self.kernel_stack.read();
  885. }
  886. pub unsafe fn kernel_stack_force_ref(&self) -> &KernelStack {
  887. self.kernel_stack.force_get_ref()
  888. }
  889. #[inline(always)]
  890. #[allow(dead_code)]
  891. pub fn kernel_stack_mut(&self) -> RwLockWriteGuard<KernelStack> {
  892. return self.kernel_stack.write();
  893. }
  894. #[inline(always)]
  895. pub fn sched_info(&self) -> &ProcessSchedulerInfo {
  896. return &self.sched_info;
  897. }
  898. #[inline(always)]
  899. pub fn worker_private(&self) -> SpinLockGuard<Option<WorkerPrivate>> {
  900. return self.worker_private.lock();
  901. }
  902. #[inline(always)]
  903. pub fn raw_pid(&self) -> RawPid {
  904. return self.pid;
  905. }
  906. #[inline(always)]
  907. pub fn fs_struct(&self) -> Arc<FsStruct> {
  908. self.fs.read().clone()
  909. }
  910. pub fn fs_struct_mut(&self) -> RwLockWriteGuard<Arc<FsStruct>> {
  911. self.fs.write()
  912. }
  913. pub fn pwd_inode(&self) -> Arc<dyn IndexNode> {
  914. self.fs.read().pwd()
  915. }
  916. /// 获取文件描述符表的Arc指针
  917. #[inline(always)]
  918. pub fn fd_table(&self) -> Arc<RwLock<FileDescriptorVec>> {
  919. return self.basic.read().try_fd_table().unwrap();
  920. }
  921. #[inline(always)]
  922. pub fn cred(&self) -> Arc<Cred> {
  923. self.cred.lock().clone()
  924. }
  925. pub fn set_execute_path(&self, path: String) {
  926. *self.executable_path.write() = path;
  927. }
  928. pub fn execute_path(&self) -> String {
  929. self.executable_path.read().clone()
  930. }
  931. pub fn real_parent_pcb(&self) -> Option<Arc<ProcessControlBlock>> {
  932. return self.real_parent_pcb.read_irqsave().upgrade();
  933. }
  934. /// 判断当前进程是否是全局的init进程
  935. pub fn is_global_init(&self) -> bool {
  936. self.task_tgid_vnr().unwrap() == RawPid(1)
  937. }
  938. /// 根据文件描述符序号,获取socket对象的Arc指针
  939. ///
  940. /// ## 参数
  941. ///
  942. /// - `fd` 文件描述符序号
  943. ///
  944. /// ## 返回值
  945. ///
  946. /// Option(&mut Box<dyn Socket>) socket对象的可变引用. 如果文件描述符不是socket,那么返回None
  947. pub fn get_socket(&self, fd: i32) -> Option<Arc<SocketInode>> {
  948. let binding = ProcessManager::current_pcb().fd_table();
  949. let fd_table_guard = binding.read();
  950. let f = fd_table_guard.get_file_by_fd(fd)?;
  951. drop(fd_table_guard);
  952. if f.file_type() != FileType::Socket {
  953. return None;
  954. }
  955. let socket: Arc<SocketInode> = f
  956. .inode()
  957. .downcast_arc::<SocketInode>()
  958. .expect("Not a socket inode");
  959. return Some(socket);
  960. }
  961. /// 当前进程退出时,让初始进程收养所有子进程
  962. unsafe fn adopt_childen(&self) -> Result<(), SystemError> {
  963. match ProcessManager::find_task_by_vpid(RawPid(1)) {
  964. Some(init_pcb) => {
  965. let childen_guard = self.children.write();
  966. if Arc::ptr_eq(&self.self_ref.upgrade().unwrap(), &init_pcb) {
  967. // 当前进程是namespace的init进程,由父进程所在的pidns的init进程去收养子进程
  968. if let Some(parent_pcb) = self.real_parent_pcb() {
  969. assert!(
  970. !Arc::ptr_eq(&parent_pcb, &init_pcb),
  971. "adopt_childen: parent_pcb is init_pcb, pid: {}",
  972. self.raw_pid()
  973. );
  974. let parent_init = ProcessManager::find_task_by_pid_ns(
  975. RawPid(1),
  976. &parent_pcb.active_pid_ns(),
  977. );
  978. if parent_init.is_none() {
  979. log::warn!(
  980. "adopt_childen: parent_init is None, pid: {}",
  981. self.raw_pid()
  982. );
  983. return Ok(());
  984. }
  985. let parent_init = parent_init.unwrap();
  986. let mut parent_children_guard = parent_init.children.write();
  987. childen_guard.iter().for_each(|pid| {
  988. log::debug!(
  989. "adopt_childen: pid {} is adopted by parent init pid {}",
  990. pid,
  991. parent_init.raw_pid()
  992. );
  993. parent_children_guard.push(*pid);
  994. });
  995. return Ok(());
  996. } else {
  997. log::warn!("adopt_childen: parent_pcb is None, pid: {}", self.raw_pid());
  998. return Ok(());
  999. }
  1000. }
  1001. let mut init_childen_guard = init_pcb.children.write();
  1002. childen_guard.iter().for_each(|pid| {
  1003. log::debug!(
  1004. "adopt_childen: pid {} is adopted by init pid {}",
  1005. pid,
  1006. init_pcb.raw_pid()
  1007. );
  1008. init_childen_guard.push(*pid);
  1009. });
  1010. return Ok(());
  1011. }
  1012. _ => Err(SystemError::ECHILD),
  1013. }
  1014. }
  1015. /// 生成进程的名字
  1016. pub fn generate_name(program_path: &str) -> String {
  1017. // Extract just the basename from the program path
  1018. let name = program_path.split('/').last().unwrap_or(program_path);
  1019. name.to_string()
  1020. }
  1021. pub fn sig_info_irqsave(&self) -> RwLockReadGuard<ProcessSignalInfo> {
  1022. self.sig_info.read_irqsave()
  1023. }
  1024. pub fn sig_info_upgradable(&self) -> RwLockUpgradableGuard<ProcessSignalInfo> {
  1025. self.sig_info.upgradeable_read_irqsave()
  1026. }
  1027. pub fn try_siginfo_irqsave(&self, times: u8) -> Option<RwLockReadGuard<ProcessSignalInfo>> {
  1028. for _ in 0..times {
  1029. if let Some(r) = self.sig_info.try_read_irqsave() {
  1030. return Some(r);
  1031. }
  1032. }
  1033. return None;
  1034. }
  1035. pub fn sig_info_mut(&self) -> RwLockWriteGuard<ProcessSignalInfo> {
  1036. self.sig_info.write_irqsave()
  1037. }
  1038. pub fn try_siginfo_mut(&self, times: u8) -> Option<RwLockWriteGuard<ProcessSignalInfo>> {
  1039. for _ in 0..times {
  1040. if let Some(r) = self.sig_info.try_write_irqsave() {
  1041. return Some(r);
  1042. }
  1043. }
  1044. return None;
  1045. }
  1046. /// 判断当前进程是否有未处理的信号
  1047. pub fn has_pending_signal(&self) -> bool {
  1048. let sig_info = self.sig_info_irqsave();
  1049. let has_pending = sig_info.sig_pending().has_pending();
  1050. drop(sig_info);
  1051. return has_pending;
  1052. }
  1053. /// 根据 pcb 的 flags 判断当前进程是否有未处理的信号
  1054. pub fn has_pending_signal_fast(&self) -> bool {
  1055. self.flags.get().contains(ProcessFlags::HAS_PENDING_SIGNAL)
  1056. }
  1057. /// 检查当前进程是否有未被阻塞的待处理信号。
  1058. ///
  1059. /// 注:该函数较慢,因此需要与 has_pending_signal_fast 一起使用。
  1060. pub fn has_pending_not_masked_signal(&self) -> bool {
  1061. let sig_info = self.sig_info_irqsave();
  1062. let blocked: SigSet = *sig_info.sig_blocked();
  1063. let mut pending: SigSet = sig_info.sig_pending().signal();
  1064. drop(sig_info);
  1065. pending.remove(blocked);
  1066. // log::debug!(
  1067. // "pending and not masked:{:?}, masked: {:?}",
  1068. // pending,
  1069. // blocked
  1070. // );
  1071. let has_not_masked = !pending.is_empty();
  1072. return has_not_masked;
  1073. }
  1074. pub fn sig_struct(&self) -> SpinLockGuard<SignalStruct> {
  1075. self.sig_struct.lock_irqsave()
  1076. }
  1077. pub fn try_sig_struct_irqsave(&self, times: u8) -> Option<SpinLockGuard<SignalStruct>> {
  1078. for _ in 0..times {
  1079. if let Ok(r) = self.sig_struct.try_lock_irqsave() {
  1080. return Some(r);
  1081. }
  1082. }
  1083. return None;
  1084. }
  1085. pub fn sig_struct_irqsave(&self) -> SpinLockGuard<SignalStruct> {
  1086. self.sig_struct.lock_irqsave()
  1087. }
  1088. #[inline(always)]
  1089. pub fn get_robust_list(&self) -> RwLockReadGuard<Option<RobustListHead>> {
  1090. return self.robust_list.read_irqsave();
  1091. }
  1092. #[inline(always)]
  1093. pub fn set_robust_list(&self, new_robust_list: Option<RobustListHead>) {
  1094. *self.robust_list.write_irqsave() = new_robust_list;
  1095. }
  1096. pub fn alarm_timer_irqsave(&self) -> SpinLockGuard<Option<AlarmTimer>> {
  1097. return self.alarm_timer.lock_irqsave();
  1098. }
  1099. /// Exit fd table when process exit
  1100. fn exit_files(&self) {
  1101. // 关闭文件描述符表
  1102. // 这里这样写的原因是避免某些inode在关闭时需要访问当前进程的basic,导致死锁
  1103. let mut guard = self.basic.write_irqsave();
  1104. let old = guard.set_fd_table(None);
  1105. drop(guard);
  1106. drop(old)
  1107. }
  1108. pub fn children_read_irqsave(&self) -> RwLockReadGuard<Vec<RawPid>> {
  1109. self.children.read_irqsave()
  1110. }
  1111. pub fn threads_read_irqsave(&self) -> RwLockReadGuard<ThreadInfo> {
  1112. self.thread.read_irqsave()
  1113. }
  1114. pub fn threads_write_irqsave(&self) -> RwLockWriteGuard<ThreadInfo> {
  1115. self.thread.write_irqsave()
  1116. }
  1117. pub fn restart_block(&self) -> SpinLockGuard<Option<RestartBlock>> {
  1118. self.restart_block.lock()
  1119. }
  1120. pub fn set_restart_fn(
  1121. &self,
  1122. restart_block: Option<RestartBlock>,
  1123. ) -> Result<usize, SystemError> {
  1124. *self.restart_block.lock() = restart_block;
  1125. return Err(SystemError::ERESTART_RESTARTBLOCK);
  1126. }
  1127. pub fn parent_pcb(&self) -> Option<Arc<ProcessControlBlock>> {
  1128. self.parent_pcb.read().upgrade()
  1129. }
  1130. pub fn is_exited(&self) -> bool {
  1131. self.sched_info
  1132. .inner_lock_read_irqsave()
  1133. .state()
  1134. .is_exited()
  1135. }
  1136. pub fn exit_code(&self) -> Option<usize> {
  1137. self.sched_info
  1138. .inner_lock_read_irqsave()
  1139. .state()
  1140. .exit_code()
  1141. }
  1142. /// 获取进程的namespace代理
  1143. pub fn nsproxy(&self) -> Arc<NsProxy> {
  1144. self.nsproxy.read().clone()
  1145. }
  1146. /// 设置进程的namespace代理
  1147. ///
  1148. /// ## 参数
  1149. /// - `nsproxy` : 新的namespace代理
  1150. ///
  1151. /// ## 返回值
  1152. /// 返回旧的namespace代理
  1153. pub fn set_nsproxy(&self, nsproxy: Arc<NsProxy>) -> Arc<NsProxy> {
  1154. let mut guard = self.nsproxy.write();
  1155. let old = guard.clone();
  1156. *guard = nsproxy;
  1157. return old;
  1158. }
  1159. pub fn is_thread_group_leader(&self) -> bool {
  1160. self.exit_signal.load(Ordering::SeqCst) != Signal::INVALID
  1161. }
  1162. }
  1163. impl Drop for ProcessControlBlock {
  1164. fn drop(&mut self) {
  1165. let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
  1166. // log::debug!("Drop ProcessControlBlock: pid: {}", self.raw_pid(),);
  1167. self.__exit_signal();
  1168. // 在ProcFS中,解除进程的注册
  1169. procfs_unregister_pid(self.raw_pid())
  1170. .unwrap_or_else(|e: SystemError| panic!("procfs_unregister_pid failed: error: {e:?}"));
  1171. if let Some(ppcb) = self.parent_pcb.read_irqsave().upgrade() {
  1172. ppcb.children
  1173. .write_irqsave()
  1174. .retain(|pid| *pid != self.raw_pid());
  1175. }
  1176. // log::debug!("Drop pid: {:?}", self.pid());
  1177. drop(irq_guard);
  1178. }
  1179. }
  1180. /// 线程信息
  1181. #[derive(Debug)]
  1182. pub struct ThreadInfo {
  1183. // 来自用户空间记录用户线程id的地址,在该线程结束时将该地址置0以通知父进程
  1184. clear_child_tid: Option<VirtAddr>,
  1185. set_child_tid: Option<VirtAddr>,
  1186. vfork_done: Option<Arc<Completion>>,
  1187. /// 线程组的组长
  1188. group_leader: Weak<ProcessControlBlock>,
  1189. /// 当前线程为组长时,该字段存储组内所有线程的pcb
  1190. group_tasks: Vec<Weak<ProcessControlBlock>>,
  1191. }
  1192. impl Default for ThreadInfo {
  1193. fn default() -> Self {
  1194. Self::new()
  1195. }
  1196. }
  1197. impl ThreadInfo {
  1198. pub fn new() -> Self {
  1199. Self {
  1200. clear_child_tid: None,
  1201. set_child_tid: None,
  1202. vfork_done: None,
  1203. group_leader: Weak::default(),
  1204. group_tasks: Vec::new(),
  1205. }
  1206. }
  1207. pub fn group_leader(&self) -> Option<Arc<ProcessControlBlock>> {
  1208. return self.group_leader.upgrade();
  1209. }
  1210. pub fn thread_group_empty(&self) -> bool {
  1211. let group_leader = self.group_leader();
  1212. if let Some(leader) = group_leader {
  1213. if Arc::ptr_eq(&leader, &ProcessManager::current_pcb()) {
  1214. return self.group_tasks.is_empty();
  1215. }
  1216. return false;
  1217. }
  1218. return true;
  1219. }
  1220. }
  1221. /// 进程的基本信息
  1222. ///
  1223. /// 这个结构体保存进程的基本信息,主要是那些不会随着进程的运行而经常改变的信息。
  1224. #[derive(Debug)]
  1225. pub struct ProcessBasicInfo {
  1226. /// 当前进程的父进程的pid
  1227. ppid: RawPid,
  1228. /// 进程的名字
  1229. name: String,
  1230. /// 当前进程的工作目录
  1231. cwd: String,
  1232. /// 用户地址空间
  1233. user_vm: Option<Arc<AddressSpace>>,
  1234. /// 文件描述符表
  1235. fd_table: Option<Arc<RwLock<FileDescriptorVec>>>,
  1236. }
  1237. impl ProcessBasicInfo {
  1238. #[inline(never)]
  1239. pub fn new(
  1240. ppid: RawPid,
  1241. name: String,
  1242. cwd: String,
  1243. user_vm: Option<Arc<AddressSpace>>,
  1244. ) -> RwLock<Self> {
  1245. let fd_table = Arc::new(RwLock::new(FileDescriptorVec::new()));
  1246. return RwLock::new(Self {
  1247. ppid,
  1248. name,
  1249. cwd,
  1250. user_vm,
  1251. fd_table: Some(fd_table),
  1252. });
  1253. }
  1254. pub fn ppid(&self) -> RawPid {
  1255. return self.ppid;
  1256. }
  1257. pub fn name(&self) -> &str {
  1258. return &self.name;
  1259. }
  1260. pub fn set_name(&mut self, name: String) {
  1261. self.name = name;
  1262. }
  1263. pub fn cwd(&self) -> String {
  1264. return self.cwd.clone();
  1265. }
  1266. pub fn set_cwd(&mut self, path: String) {
  1267. return self.cwd = path;
  1268. }
  1269. pub fn user_vm(&self) -> Option<Arc<AddressSpace>> {
  1270. return self.user_vm.clone();
  1271. }
  1272. pub unsafe fn set_user_vm(&mut self, user_vm: Option<Arc<AddressSpace>>) {
  1273. self.user_vm = user_vm;
  1274. }
  1275. pub fn try_fd_table(&self) -> Option<Arc<RwLock<FileDescriptorVec>>> {
  1276. return self.fd_table.clone();
  1277. }
  1278. pub fn set_fd_table(
  1279. &mut self,
  1280. fd_table: Option<Arc<RwLock<FileDescriptorVec>>>,
  1281. ) -> Option<Arc<RwLock<FileDescriptorVec>>> {
  1282. let old = self.fd_table.take();
  1283. self.fd_table = fd_table;
  1284. return old;
  1285. }
  1286. }
  1287. #[derive(Debug)]
  1288. pub struct ProcessSchedulerInfo {
  1289. /// 当前进程所在的cpu
  1290. on_cpu: AtomicProcessorId,
  1291. /// 如果当前进程等待被迁移到另一个cpu核心上(也就是flags中的PF_NEED_MIGRATE被置位),
  1292. /// 该字段存储要被迁移到的目标处理器核心号
  1293. // migrate_to: AtomicProcessorId,
  1294. inner_locked: RwLock<InnerSchedInfo>,
  1295. /// 进程的调度优先级
  1296. // priority: SchedPriority,
  1297. /// 当前进程的虚拟运行时间
  1298. // virtual_runtime: AtomicIsize,
  1299. /// 由实时调度器管理的时间片
  1300. // rt_time_slice: AtomicIsize,
  1301. pub sched_stat: RwLock<SchedInfo>,
  1302. /// 调度策略
  1303. pub sched_policy: RwLock<crate::sched::SchedPolicy>,
  1304. /// cfs调度实体
  1305. pub sched_entity: Arc<FairSchedEntity>,
  1306. pub on_rq: SpinLock<OnRq>,
  1307. pub prio_data: RwLock<PrioData>,
  1308. }
  1309. #[derive(Debug, Default)]
  1310. #[allow(dead_code)]
  1311. pub struct SchedInfo {
  1312. /// 记录任务在特定 CPU 上运行的次数
  1313. pub pcount: usize,
  1314. /// 记录任务等待在运行队列上的时间
  1315. pub run_delay: usize,
  1316. /// 记录任务上次在 CPU 上运行的时间戳
  1317. pub last_arrival: u64,
  1318. /// 记录任务上次被加入到运行队列中的时间戳
  1319. pub last_queued: u64,
  1320. }
  1321. #[derive(Debug)]
  1322. #[allow(dead_code)]
  1323. pub struct PrioData {
  1324. pub prio: i32,
  1325. pub static_prio: i32,
  1326. pub normal_prio: i32,
  1327. }
  1328. impl Default for PrioData {
  1329. fn default() -> Self {
  1330. Self {
  1331. prio: MAX_PRIO - 20,
  1332. static_prio: MAX_PRIO - 20,
  1333. normal_prio: MAX_PRIO - 20,
  1334. }
  1335. }
  1336. }
  1337. #[derive(Debug)]
  1338. pub struct InnerSchedInfo {
  1339. /// 当前进程的状态
  1340. state: ProcessState,
  1341. /// 进程的调度策略
  1342. sleep: bool,
  1343. }
  1344. impl InnerSchedInfo {
  1345. pub fn state(&self) -> ProcessState {
  1346. return self.state;
  1347. }
  1348. pub fn set_state(&mut self, state: ProcessState) {
  1349. self.state = state;
  1350. }
  1351. pub fn set_sleep(&mut self) {
  1352. self.sleep = true;
  1353. }
  1354. pub fn set_wakeup(&mut self) {
  1355. self.sleep = false;
  1356. }
  1357. pub fn is_mark_sleep(&self) -> bool {
  1358. self.sleep
  1359. }
  1360. }
  1361. impl ProcessSchedulerInfo {
  1362. #[inline(never)]
  1363. pub fn new(on_cpu: Option<ProcessorId>) -> Self {
  1364. let cpu_id = on_cpu.unwrap_or(ProcessorId::INVALID);
  1365. return Self {
  1366. on_cpu: AtomicProcessorId::new(cpu_id),
  1367. // migrate_to: AtomicProcessorId::new(ProcessorId::INVALID),
  1368. inner_locked: RwLock::new(InnerSchedInfo {
  1369. state: ProcessState::Blocked(false),
  1370. sleep: false,
  1371. }),
  1372. // virtual_runtime: AtomicIsize::new(0),
  1373. // rt_time_slice: AtomicIsize::new(0),
  1374. // priority: SchedPriority::new(100).unwrap(),
  1375. sched_stat: RwLock::new(SchedInfo::default()),
  1376. sched_policy: RwLock::new(crate::sched::SchedPolicy::CFS),
  1377. sched_entity: FairSchedEntity::new(),
  1378. on_rq: SpinLock::new(OnRq::None),
  1379. prio_data: RwLock::new(PrioData::default()),
  1380. };
  1381. }
  1382. pub fn sched_entity(&self) -> Arc<FairSchedEntity> {
  1383. return self.sched_entity.clone();
  1384. }
  1385. pub fn on_cpu(&self) -> Option<ProcessorId> {
  1386. let on_cpu = self.on_cpu.load(Ordering::SeqCst);
  1387. if on_cpu == ProcessorId::INVALID {
  1388. return None;
  1389. } else {
  1390. return Some(on_cpu);
  1391. }
  1392. }
  1393. pub fn set_on_cpu(&self, on_cpu: Option<ProcessorId>) {
  1394. if let Some(cpu_id) = on_cpu {
  1395. self.on_cpu.store(cpu_id, Ordering::SeqCst);
  1396. } else {
  1397. self.on_cpu.store(ProcessorId::INVALID, Ordering::SeqCst);
  1398. }
  1399. }
  1400. // pub fn migrate_to(&self) -> Option<ProcessorId> {
  1401. // let migrate_to = self.migrate_to.load(Ordering::SeqCst);
  1402. // if migrate_to == ProcessorId::INVALID {
  1403. // return None;
  1404. // } else {
  1405. // return Some(migrate_to);
  1406. // }
  1407. // }
  1408. // pub fn set_migrate_to(&self, migrate_to: Option<ProcessorId>) {
  1409. // if let Some(data) = migrate_to {
  1410. // self.migrate_to.store(data, Ordering::SeqCst);
  1411. // } else {
  1412. // self.migrate_to
  1413. // .store(ProcessorId::INVALID, Ordering::SeqCst)
  1414. // }
  1415. // }
  1416. pub fn inner_lock_write_irqsave(&self) -> RwLockWriteGuard<InnerSchedInfo> {
  1417. return self.inner_locked.write_irqsave();
  1418. }
  1419. pub fn inner_lock_read_irqsave(&self) -> RwLockReadGuard<InnerSchedInfo> {
  1420. return self.inner_locked.read_irqsave();
  1421. }
  1422. // pub fn inner_lock_try_read_irqsave(
  1423. // &self,
  1424. // times: u8,
  1425. // ) -> Option<RwLockReadGuard<InnerSchedInfo>> {
  1426. // for _ in 0..times {
  1427. // if let Some(r) = self.inner_locked.try_read_irqsave() {
  1428. // return Some(r);
  1429. // }
  1430. // }
  1431. // return None;
  1432. // }
  1433. // pub fn inner_lock_try_upgradable_read_irqsave(
  1434. // &self,
  1435. // times: u8,
  1436. // ) -> Option<RwLockUpgradableGuard<InnerSchedInfo>> {
  1437. // for _ in 0..times {
  1438. // if let Some(r) = self.inner_locked.try_upgradeable_read_irqsave() {
  1439. // return Some(r);
  1440. // }
  1441. // }
  1442. // return None;
  1443. // }
  1444. // pub fn virtual_runtime(&self) -> isize {
  1445. // return self.virtual_runtime.load(Ordering::SeqCst);
  1446. // }
  1447. // pub fn set_virtual_runtime(&self, virtual_runtime: isize) {
  1448. // self.virtual_runtime
  1449. // .store(virtual_runtime, Ordering::SeqCst);
  1450. // }
  1451. // pub fn increase_virtual_runtime(&self, delta: isize) {
  1452. // self.virtual_runtime.fetch_add(delta, Ordering::SeqCst);
  1453. // }
  1454. // pub fn rt_time_slice(&self) -> isize {
  1455. // return self.rt_time_slice.load(Ordering::SeqCst);
  1456. // }
  1457. // pub fn set_rt_time_slice(&self, rt_time_slice: isize) {
  1458. // self.rt_time_slice.store(rt_time_slice, Ordering::SeqCst);
  1459. // }
  1460. // pub fn increase_rt_time_slice(&self, delta: isize) {
  1461. // self.rt_time_slice.fetch_add(delta, Ordering::SeqCst);
  1462. // }
  1463. pub fn policy(&self) -> crate::sched::SchedPolicy {
  1464. return *self.sched_policy.read_irqsave();
  1465. }
  1466. }
  1467. #[derive(Debug)]
  1468. pub struct KernelStack {
  1469. stack: Option<AlignedBox<[u8; KernelStack::SIZE], { KernelStack::ALIGN }>>,
  1470. /// 标记该内核栈是否可以被释放
  1471. ty: KernelStackType,
  1472. }
  1473. #[derive(Debug)]
  1474. pub enum KernelStackType {
  1475. KernelSpace(VirtAddr, PhysAddr),
  1476. Static,
  1477. Dynamic,
  1478. }
  1479. // 为什么需要这个锁?
  1480. // alloc_from_kernel_space 使用该函数分配内核栈时,如果该函数被中断打断,
  1481. // 而切换的任务使用dealloc_from_kernel_space回收内核栈,对
  1482. // KernelMapper的可变引用获取将会失败造成错误
  1483. static KSTACK_LOCK: SpinLock<()> = SpinLock::new(());
  1484. unsafe fn alloc_from_kernel_space() -> (VirtAddr, PhysAddr) {
  1485. use crate::arch::MMArch;
  1486. use crate::mm::allocator::page_frame::{allocate_page_frames, PageFrameCount};
  1487. use crate::mm::kernel_mapper::KernelMapper;
  1488. use crate::mm::page::EntryFlags;
  1489. use crate::mm::MemoryManagementArch;
  1490. // Layout
  1491. // ---------------
  1492. // | KernelStack |
  1493. // | guard page | size == KernelStack::SIZE
  1494. // | KernelStack |
  1495. // | guard page |
  1496. // | .......... |
  1497. // ---------------
  1498. let _guard = KSTACK_LOCK.try_lock_irqsave().unwrap();
  1499. let need_size = KernelStack::SIZE * 2;
  1500. let page_num = PageFrameCount::new(need_size.div_ceil(MMArch::PAGE_SIZE).next_power_of_two());
  1501. let (paddr, _count) = allocate_page_frames(page_num).expect("kernel stack alloc failed");
  1502. let guard_vaddr = MMArch::phys_2_virt(paddr).unwrap();
  1503. let _kstack_paddr = paddr + KernelStack::SIZE;
  1504. let kstack_vaddr = guard_vaddr + KernelStack::SIZE;
  1505. core::ptr::write_bytes(kstack_vaddr.data() as *mut u8, 0, KernelStack::SIZE);
  1506. let guard_flags = EntryFlags::new();
  1507. let mut kernel_mapper = KernelMapper::lock();
  1508. let kernel_mapper = kernel_mapper.as_mut().unwrap();
  1509. for i in 0..KernelStack::SIZE / MMArch::PAGE_SIZE {
  1510. let guard_page_vaddr = guard_vaddr + i * MMArch::PAGE_SIZE;
  1511. // Map the guard page
  1512. let flusher = kernel_mapper.remap(guard_page_vaddr, guard_flags).unwrap();
  1513. flusher.flush();
  1514. }
  1515. // unsafe {
  1516. // log::debug!(
  1517. // "trigger kernel stack guard page :{:#x}",
  1518. // (kstack_vaddr.data() - 8)
  1519. // );
  1520. // let guard_ptr = (kstack_vaddr.data() - 8) as *mut usize;
  1521. // guard_ptr.write(0xfff); // Invalid
  1522. // }
  1523. // log::info!(
  1524. // "[kernel stack alloc]: virt: {:#x}, phy: {:#x}",
  1525. // kstack_vaddr.data(),
  1526. // _kstack_paddr.data()
  1527. // );
  1528. (guard_vaddr, paddr)
  1529. }
  1530. unsafe fn dealloc_from_kernel_space(vaddr: VirtAddr, paddr: PhysAddr) {
  1531. use crate::arch::mm::kernel_page_flags;
  1532. use crate::arch::MMArch;
  1533. use crate::mm::allocator::page_frame::{deallocate_page_frames, PageFrameCount, PhysPageFrame};
  1534. use crate::mm::kernel_mapper::KernelMapper;
  1535. use crate::mm::MemoryManagementArch;
  1536. let _guard = KSTACK_LOCK.try_lock_irqsave().unwrap();
  1537. let need_size = KernelStack::SIZE * 2;
  1538. let page_num = PageFrameCount::new(need_size.div_ceil(MMArch::PAGE_SIZE).next_power_of_two());
  1539. // log::info!(
  1540. // "[kernel stack dealloc]: virt: {:#x}, phy: {:#x}",
  1541. // vaddr.data(),
  1542. // paddr.data()
  1543. // );
  1544. let mut kernel_mapper = KernelMapper::lock();
  1545. let kernel_mapper = kernel_mapper.as_mut().unwrap();
  1546. // restore the guard page flags
  1547. for i in 0..KernelStack::SIZE / MMArch::PAGE_SIZE {
  1548. let guard_page_vaddr = vaddr + i * MMArch::PAGE_SIZE;
  1549. let flusher = kernel_mapper
  1550. .remap(guard_page_vaddr, kernel_page_flags(vaddr))
  1551. .unwrap();
  1552. flusher.flush();
  1553. }
  1554. // release the physical page
  1555. unsafe { deallocate_page_frames(PhysPageFrame::new(paddr), page_num) };
  1556. }
  1557. impl KernelStack {
  1558. pub const SIZE: usize = 0x8000;
  1559. pub const ALIGN: usize = 0x8000;
  1560. pub fn new() -> Result<Self, SystemError> {
  1561. if cfg!(feature = "kstack_protect") {
  1562. unsafe {
  1563. let (kstack_vaddr, kstack_paddr) = alloc_from_kernel_space();
  1564. let real_kstack_vaddr = kstack_vaddr + KernelStack::SIZE;
  1565. Ok(Self {
  1566. stack: Some(
  1567. AlignedBox::<[u8; KernelStack::SIZE], { KernelStack::ALIGN }>::new_unchecked(
  1568. real_kstack_vaddr.data() as *mut [u8; KernelStack::SIZE],
  1569. ),
  1570. ),
  1571. ty: KernelStackType::KernelSpace(kstack_vaddr, kstack_paddr),
  1572. })
  1573. }
  1574. } else {
  1575. Ok(Self {
  1576. stack: Some(
  1577. AlignedBox::<[u8; KernelStack::SIZE], { KernelStack::ALIGN }>::new_zeroed()?,
  1578. ),
  1579. ty: KernelStackType::Dynamic,
  1580. })
  1581. }
  1582. }
  1583. /// 根据已有的空间,构造一个内核栈结构体
  1584. ///
  1585. /// 仅仅用于BSP启动时,为idle进程构造内核栈。其他时候使用这个函数,很可能造成错误!
  1586. pub unsafe fn from_existed(base: VirtAddr) -> Result<Self, SystemError> {
  1587. if base.is_null() || !base.check_aligned(Self::ALIGN) {
  1588. return Err(SystemError::EFAULT);
  1589. }
  1590. Ok(Self {
  1591. stack: Some(
  1592. AlignedBox::<[u8; KernelStack::SIZE], { KernelStack::ALIGN }>::new_unchecked(
  1593. base.data() as *mut [u8; KernelStack::SIZE],
  1594. ),
  1595. ),
  1596. ty: KernelStackType::Static,
  1597. })
  1598. }
  1599. pub fn guard_page_address(&self) -> Option<VirtAddr> {
  1600. match self.ty {
  1601. KernelStackType::KernelSpace(kstack_virt_addr, _) => {
  1602. return Some(kstack_virt_addr);
  1603. }
  1604. _ => {
  1605. // 静态内核栈和动态内核栈没有guard page
  1606. return None;
  1607. }
  1608. }
  1609. }
  1610. pub fn guard_page_size(&self) -> Option<usize> {
  1611. match self.ty {
  1612. KernelStackType::KernelSpace(_, _) => {
  1613. return Some(KernelStack::SIZE);
  1614. }
  1615. _ => {
  1616. // 静态内核栈和动态内核栈没有guard page
  1617. return None;
  1618. }
  1619. }
  1620. }
  1621. /// 返回内核栈的起始虚拟地址(低地址)
  1622. pub fn start_address(&self) -> VirtAddr {
  1623. return VirtAddr::new(self.stack.as_ref().unwrap().as_ptr() as usize);
  1624. }
  1625. /// 返回内核栈的结束虚拟地址(高地址)(不包含该地址)
  1626. pub fn stack_max_address(&self) -> VirtAddr {
  1627. return VirtAddr::new(self.stack.as_ref().unwrap().as_ptr() as usize + Self::SIZE);
  1628. }
  1629. pub unsafe fn set_pcb(&mut self, pcb: Weak<ProcessControlBlock>) -> Result<(), SystemError> {
  1630. // 将一个Weak<ProcessControlBlock>放到内核栈的最低地址处
  1631. let p: *const ProcessControlBlock = Weak::into_raw(pcb);
  1632. let stack_bottom_ptr = self.start_address().data() as *mut *const ProcessControlBlock;
  1633. // 如果内核栈的最低地址处已经有了一个pcb,那么,这里就不再设置,直接返回错误
  1634. if unlikely(unsafe { !(*stack_bottom_ptr).is_null() }) {
  1635. error!("kernel stack bottom is not null: {:p}", *stack_bottom_ptr);
  1636. return Err(SystemError::EPERM);
  1637. }
  1638. // 将pcb的地址放到内核栈的最低地址处
  1639. unsafe {
  1640. *stack_bottom_ptr = p;
  1641. }
  1642. return Ok(());
  1643. }
  1644. /// 清除内核栈的pcb指针
  1645. ///
  1646. /// ## 参数
  1647. ///
  1648. /// - `force` : 如果为true,那么,即使该内核栈的pcb指针不为null,也会被强制清除而不处理Weak指针问题
  1649. pub unsafe fn clear_pcb(&mut self, force: bool) {
  1650. let stack_bottom_ptr = self.start_address().data() as *mut *const ProcessControlBlock;
  1651. if unlikely(unsafe { (*stack_bottom_ptr).is_null() }) {
  1652. return;
  1653. }
  1654. if !force {
  1655. let pcb_ptr: Weak<ProcessControlBlock> = Weak::from_raw(*stack_bottom_ptr);
  1656. drop(pcb_ptr);
  1657. }
  1658. *stack_bottom_ptr = core::ptr::null();
  1659. }
  1660. /// 返回指向当前内核栈pcb的Arc指针
  1661. #[allow(dead_code)]
  1662. pub unsafe fn pcb(&self) -> Option<Arc<ProcessControlBlock>> {
  1663. // 从内核栈的最低地址处取出pcb的地址
  1664. let p = self.stack.as_ref().unwrap().as_ptr() as *const *const ProcessControlBlock;
  1665. if unlikely(unsafe { (*p).is_null() }) {
  1666. return None;
  1667. }
  1668. // 为了防止内核栈的pcb指针被释放,这里需要将其包装一下,使得Arc的drop不会被调用
  1669. let weak_wrapper: ManuallyDrop<Weak<ProcessControlBlock>> =
  1670. ManuallyDrop::new(Weak::from_raw(*p));
  1671. let new_arc: Arc<ProcessControlBlock> = weak_wrapper.upgrade()?;
  1672. return Some(new_arc);
  1673. }
  1674. }
  1675. impl Drop for KernelStack {
  1676. fn drop(&mut self) {
  1677. if self.stack.is_some() {
  1678. let ptr = self.stack.as_ref().unwrap().as_ptr() as *const *const ProcessControlBlock;
  1679. if unsafe { !(*ptr).is_null() } {
  1680. let pcb_ptr: Weak<ProcessControlBlock> = unsafe { Weak::from_raw(*ptr) };
  1681. drop(pcb_ptr);
  1682. }
  1683. }
  1684. match self.ty {
  1685. KernelStackType::KernelSpace(kstack_virt_addr, kstack_phy_addr) => {
  1686. // 释放内核栈
  1687. unsafe {
  1688. dealloc_from_kernel_space(kstack_virt_addr, kstack_phy_addr);
  1689. }
  1690. let bx = self.stack.take();
  1691. core::mem::forget(bx);
  1692. }
  1693. KernelStackType::Static => {
  1694. let bx = self.stack.take();
  1695. core::mem::forget(bx);
  1696. }
  1697. KernelStackType::Dynamic => {}
  1698. }
  1699. }
  1700. }
  1701. pub fn process_init() {
  1702. ProcessManager::init();
  1703. }
  1704. #[derive(Debug)]
  1705. pub struct ProcessSignalInfo {
  1706. // 当前进程被屏蔽的信号
  1707. sig_blocked: SigSet,
  1708. // 暂存旧信号,用于恢复
  1709. saved_sigmask: SigSet,
  1710. // sig_pending 中存储当前线程要处理的信号
  1711. sig_pending: SigPending,
  1712. // sig_shared_pending 中存储当前线程所属进程要处理的信号
  1713. sig_shared_pending: SigPending,
  1714. flags: SignalFlags,
  1715. // 当前进程对应的tty
  1716. tty: Option<Arc<TtyCore>>,
  1717. has_child_subreaper: bool,
  1718. /// 标记当前进程是否是一个“子进程收割者”
  1719. ///
  1720. /// todo: 在prctl里面实现设置这个标志位的功能
  1721. is_child_subreaper: bool,
  1722. /// boolean value for session group leader
  1723. pub is_session_leader: bool,
  1724. }
  1725. impl ProcessSignalInfo {
  1726. pub fn sig_blocked(&self) -> &SigSet {
  1727. &self.sig_blocked
  1728. }
  1729. pub fn sig_pending(&self) -> &SigPending {
  1730. &self.sig_pending
  1731. }
  1732. pub fn sig_pending_mut(&mut self) -> &mut SigPending {
  1733. &mut self.sig_pending
  1734. }
  1735. pub fn sig_block_mut(&mut self) -> &mut SigSet {
  1736. &mut self.sig_blocked
  1737. }
  1738. pub fn saved_sigmask(&self) -> &SigSet {
  1739. &self.saved_sigmask
  1740. }
  1741. pub fn saved_sigmask_mut(&mut self) -> &mut SigSet {
  1742. &mut self.saved_sigmask
  1743. }
  1744. pub fn sig_shared_pending_mut(&mut self) -> &mut SigPending {
  1745. &mut self.sig_shared_pending
  1746. }
  1747. pub fn sig_shared_pending(&self) -> &SigPending {
  1748. &self.sig_shared_pending
  1749. }
  1750. pub fn tty(&self) -> Option<Arc<TtyCore>> {
  1751. self.tty.clone()
  1752. }
  1753. pub fn set_tty(&mut self, tty: Option<Arc<TtyCore>>) {
  1754. self.tty = tty;
  1755. }
  1756. pub fn flags(&self) -> SignalFlags {
  1757. self.flags
  1758. }
  1759. /// 从 pcb 的 siginfo中取出下一个要处理的信号,先处理线程信号,再处理进程信号
  1760. ///
  1761. /// ## 参数
  1762. ///
  1763. /// - `sig_mask` 被忽略掉的信号
  1764. ///
  1765. pub fn dequeue_signal(
  1766. &mut self,
  1767. sig_mask: &SigSet,
  1768. pcb: &Arc<ProcessControlBlock>,
  1769. ) -> (Signal, Option<SigInfo>) {
  1770. let res = self.sig_pending.dequeue_signal(sig_mask);
  1771. pcb.recalc_sigpending(Some(self));
  1772. if res.0 != Signal::INVALID {
  1773. return res;
  1774. } else {
  1775. let res = self.sig_shared_pending.dequeue_signal(sig_mask);
  1776. pcb.recalc_sigpending(Some(self));
  1777. return res;
  1778. }
  1779. }
  1780. pub fn has_child_subreaper(&self) -> bool {
  1781. self.has_child_subreaper
  1782. }
  1783. pub fn set_has_child_subreaper(&mut self, has_child_subreaper: bool) {
  1784. self.has_child_subreaper = has_child_subreaper;
  1785. }
  1786. pub fn is_child_subreaper(&self) -> bool {
  1787. self.is_child_subreaper
  1788. }
  1789. pub fn set_is_child_subreaper(&mut self, is_child_subreaper: bool) {
  1790. self.is_child_subreaper = is_child_subreaper;
  1791. }
  1792. }
  1793. impl Default for ProcessSignalInfo {
  1794. fn default() -> Self {
  1795. Self {
  1796. sig_blocked: SigSet::empty(),
  1797. saved_sigmask: SigSet::empty(),
  1798. sig_pending: SigPending::default(),
  1799. sig_shared_pending: SigPending::default(),
  1800. tty: None,
  1801. has_child_subreaper: false,
  1802. is_child_subreaper: false,
  1803. is_session_leader: false,
  1804. flags: SignalFlags::empty(),
  1805. }
  1806. }
  1807. }