mod.rs 47 KB

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