mod.rs 45 KB

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