mod.rs 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564
  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. // TODO 由于未实现进程组,tty记录的前台进程组等于当前进程,故退出前要置空
  383. // 后续相关逻辑需要在SYS_EXIT_GROUP系统调用中实现
  384. if let Some(tty) = pcb.sig_info_irqsave().tty() {
  385. tty.core().contorl_info_irqsave().pgid = None;
  386. }
  387. pcb.sig_info_mut().set_tty(None);
  388. drop(pcb);
  389. ProcessManager::exit_notify();
  390. // unsafe { CurrentIrqArch::interrupt_enable() };
  391. __schedule(SchedMode::SM_NONE);
  392. error!("pid {pid:?} exited but sched again!");
  393. #[allow(clippy::empty_loop)]
  394. loop {
  395. spin_loop();
  396. }
  397. }
  398. pub unsafe fn release(pid: Pid) {
  399. let pcb = ProcessManager::find(pid);
  400. if pcb.is_some() {
  401. // let pcb = pcb.unwrap();
  402. // 判断该pcb是否在全局没有任何引用
  403. // TODO: 当前,pcb的Arc指针存在泄露问题,引用计数不正确,打算在接下来实现debug专用的Arc,方便调试,然后解决这个bug。
  404. // 因此目前暂时注释掉,使得能跑
  405. // if Arc::strong_count(&pcb) <= 2 {
  406. // drop(pcb);
  407. // ALL_PROCESS.lock().as_mut().unwrap().remove(&pid);
  408. // } else {
  409. // // 如果不为1就panic
  410. // let msg = format!("pcb '{:?}' is still referenced, strong count={}",pcb.pid(), Arc::strong_count(&pcb));
  411. // error!("{}", msg);
  412. // panic!()
  413. // }
  414. ALL_PROCESS.lock_irqsave().as_mut().unwrap().remove(&pid);
  415. }
  416. }
  417. /// 上下文切换完成后的钩子函数
  418. unsafe fn switch_finish_hook() {
  419. // debug!("switch_finish_hook");
  420. let prev_pcb = PROCESS_SWITCH_RESULT
  421. .as_mut()
  422. .unwrap()
  423. .get_mut()
  424. .prev_pcb
  425. .take()
  426. .expect("prev_pcb is None");
  427. let next_pcb = PROCESS_SWITCH_RESULT
  428. .as_mut()
  429. .unwrap()
  430. .get_mut()
  431. .next_pcb
  432. .take()
  433. .expect("next_pcb is None");
  434. // 由于进程切换前使用了SpinLockGuard::leak(),所以这里需要手动释放锁
  435. fence(Ordering::SeqCst);
  436. prev_pcb.arch_info.force_unlock();
  437. fence(Ordering::SeqCst);
  438. next_pcb.arch_info.force_unlock();
  439. fence(Ordering::SeqCst);
  440. }
  441. /// 如果目标进程正在目标CPU上运行,那么就让这个cpu陷入内核态
  442. ///
  443. /// ## 参数
  444. ///
  445. /// - `pcb` : 进程的pcb
  446. #[allow(dead_code)]
  447. pub fn kick(pcb: &Arc<ProcessControlBlock>) {
  448. ProcessManager::current_pcb().preempt_disable();
  449. let cpu_id = pcb.sched_info().on_cpu();
  450. if let Some(cpu_id) = cpu_id {
  451. if pcb.pid() == cpu_rq(cpu_id.data() as usize).current().pid() {
  452. kick_cpu(cpu_id).expect("ProcessManager::kick(): Failed to kick cpu");
  453. }
  454. }
  455. ProcessManager::current_pcb().preempt_enable();
  456. }
  457. }
  458. /// 上下文切换的钩子函数,当这个函数return的时候,将会发生上下文切换
  459. #[cfg(target_arch = "x86_64")]
  460. #[inline(never)]
  461. pub unsafe extern "sysv64" fn switch_finish_hook() {
  462. ProcessManager::switch_finish_hook();
  463. }
  464. #[cfg(target_arch = "riscv64")]
  465. #[inline(always)]
  466. pub unsafe fn switch_finish_hook() {
  467. ProcessManager::switch_finish_hook();
  468. }
  469. int_like!(Pid, AtomicPid, usize, AtomicUsize);
  470. impl fmt::Display for Pid {
  471. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  472. write!(f, "{}", self.0)
  473. }
  474. }
  475. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  476. pub enum ProcessState {
  477. /// The process is running on a CPU or in a run queue.
  478. Runnable,
  479. /// The process is waiting for an event to occur.
  480. /// 其中的bool表示该等待过程是否可以被打断。
  481. /// - 如果该bool为true,那么,硬件中断/信号/其他系统事件都可以打断该等待过程,使得该进程重新进入Runnable状态。
  482. /// - 如果该bool为false,那么,这个进程必须被显式的唤醒,才能重新进入Runnable状态。
  483. Blocked(bool),
  484. /// 进程被信号终止
  485. Stopped,
  486. /// 进程已经退出,usize表示进程的退出码
  487. Exited(usize),
  488. }
  489. #[allow(dead_code)]
  490. impl ProcessState {
  491. #[inline(always)]
  492. pub fn is_runnable(&self) -> bool {
  493. return matches!(self, ProcessState::Runnable);
  494. }
  495. #[inline(always)]
  496. pub fn is_blocked(&self) -> bool {
  497. return matches!(self, ProcessState::Blocked(_));
  498. }
  499. #[inline(always)]
  500. pub fn is_blocked_interruptable(&self) -> bool {
  501. return matches!(self, ProcessState::Blocked(true));
  502. }
  503. /// Returns `true` if the process state is [`Exited`].
  504. #[inline(always)]
  505. pub fn is_exited(&self) -> bool {
  506. return matches!(self, ProcessState::Exited(_));
  507. }
  508. /// Returns `true` if the process state is [`Stopped`].
  509. ///
  510. /// [`Stopped`]: ProcessState::Stopped
  511. #[inline(always)]
  512. pub fn is_stopped(&self) -> bool {
  513. matches!(self, ProcessState::Stopped)
  514. }
  515. /// Returns exit code if the process state is [`Exited`].
  516. #[inline(always)]
  517. pub fn exit_code(&self) -> Option<usize> {
  518. match self {
  519. ProcessState::Exited(code) => Some(*code),
  520. _ => None,
  521. }
  522. }
  523. }
  524. bitflags! {
  525. /// pcb的标志位
  526. pub struct ProcessFlags: usize {
  527. /// 当前pcb表示一个内核线程
  528. const KTHREAD = 1 << 0;
  529. /// 当前进程需要被调度
  530. const NEED_SCHEDULE = 1 << 1;
  531. /// 进程由于vfork而与父进程存在资源共享
  532. const VFORK = 1 << 2;
  533. /// 进程不可被冻结
  534. const NOFREEZE = 1 << 3;
  535. /// 进程正在退出
  536. const EXITING = 1 << 4;
  537. /// 进程由于接收到终止信号唤醒
  538. const WAKEKILL = 1 << 5;
  539. /// 进程由于接收到信号而退出.(Killed by a signal)
  540. const SIGNALED = 1 << 6;
  541. /// 进程需要迁移到其他cpu上
  542. const NEED_MIGRATE = 1 << 7;
  543. /// 随机化的虚拟地址空间,主要用于动态链接器的加载
  544. const RANDOMIZE = 1 << 8;
  545. }
  546. }
  547. #[derive(Debug)]
  548. pub struct ProcessControlBlock {
  549. /// 当前进程的pid
  550. pid: Pid,
  551. /// 当前进程的线程组id(这个值在同一个线程组内永远不变)
  552. tgid: Pid,
  553. basic: RwLock<ProcessBasicInfo>,
  554. /// 当前进程的自旋锁持有计数
  555. preempt_count: AtomicUsize,
  556. flags: LockFreeFlags<ProcessFlags>,
  557. worker_private: SpinLock<Option<WorkerPrivate>>,
  558. /// 进程的内核栈
  559. kernel_stack: RwLock<KernelStack>,
  560. /// 系统调用栈
  561. syscall_stack: RwLock<KernelStack>,
  562. /// 与调度相关的信息
  563. sched_info: ProcessSchedulerInfo,
  564. /// 与处理器架构相关的信息
  565. arch_info: SpinLock<ArchPCBInfo>,
  566. /// 与信号处理相关的信息(似乎可以是无锁的)
  567. sig_info: RwLock<ProcessSignalInfo>,
  568. /// 信号处理结构体
  569. sig_struct: SpinLock<SignalStruct>,
  570. /// 退出信号S
  571. exit_signal: AtomicSignal,
  572. /// 父进程指针
  573. parent_pcb: RwLock<Weak<ProcessControlBlock>>,
  574. /// 真实父进程指针
  575. real_parent_pcb: RwLock<Weak<ProcessControlBlock>>,
  576. /// 子进程链表
  577. children: RwLock<Vec<Pid>>,
  578. /// 等待队列
  579. wait_queue: WaitQueue,
  580. /// 线程信息
  581. thread: RwLock<ThreadInfo>,
  582. ///闹钟定时器
  583. alarm_timer: SpinLock<Option<AlarmTimer>>,
  584. /// 进程的robust lock列表
  585. robust_list: RwLock<Option<RobustListHead>>,
  586. /// 进程作为主体的凭证集
  587. cred: SpinLock<Cred>,
  588. }
  589. impl ProcessControlBlock {
  590. /// Generate a new pcb.
  591. ///
  592. /// ## 参数
  593. ///
  594. /// - `name` : 进程的名字
  595. /// - `kstack` : 进程的内核栈
  596. ///
  597. /// ## 返回值
  598. ///
  599. /// 返回一个新的pcb
  600. pub fn new(name: String, kstack: KernelStack) -> Arc<Self> {
  601. return Self::do_create_pcb(name, kstack, false);
  602. }
  603. /// 创建一个新的idle进程
  604. ///
  605. /// 请注意,这个函数只能在进程管理初始化的时候调用。
  606. pub fn new_idle(cpu_id: u32, kstack: KernelStack) -> Arc<Self> {
  607. let name = format!("idle-{}", cpu_id);
  608. return Self::do_create_pcb(name, kstack, true);
  609. }
  610. /// # 函数的功能
  611. ///
  612. /// 返回此函数是否是内核进程
  613. ///
  614. /// # 返回值
  615. ///
  616. /// 若进程是内核进程则返回true 否则返回false
  617. pub fn is_kthread(&self) -> bool {
  618. return matches!(self.flags(), &mut ProcessFlags::KTHREAD);
  619. }
  620. #[inline(never)]
  621. fn do_create_pcb(name: String, kstack: KernelStack, is_idle: bool) -> Arc<Self> {
  622. let (pid, ppid, cwd, cred) = if is_idle {
  623. let cred = INIT_CRED.clone();
  624. (Pid(0), Pid(0), "/".to_string(), cred)
  625. } else {
  626. let ppid = ProcessManager::current_pcb().pid();
  627. let mut cred = ProcessManager::current_pcb().cred();
  628. cred.cap_permitted = cred.cap_ambient;
  629. cred.cap_effective = cred.cap_ambient;
  630. let cwd = ProcessManager::current_pcb().basic().cwd();
  631. (Self::generate_pid(), ppid, cwd, cred)
  632. };
  633. let basic_info = ProcessBasicInfo::new(Pid(0), ppid, Pid(0), name, cwd, None);
  634. let preempt_count = AtomicUsize::new(0);
  635. let flags = unsafe { LockFreeFlags::new(ProcessFlags::empty()) };
  636. let sched_info = ProcessSchedulerInfo::new(None);
  637. let arch_info = SpinLock::new(ArchPCBInfo::new(&kstack));
  638. let ppcb: Weak<ProcessControlBlock> = ProcessManager::find(ppid)
  639. .map(|p| Arc::downgrade(&p))
  640. .unwrap_or_default();
  641. let pcb = Self {
  642. pid,
  643. tgid: pid,
  644. basic: basic_info,
  645. preempt_count,
  646. flags,
  647. kernel_stack: RwLock::new(kstack),
  648. syscall_stack: RwLock::new(KernelStack::new().unwrap()),
  649. worker_private: SpinLock::new(None),
  650. sched_info,
  651. arch_info,
  652. sig_info: RwLock::new(ProcessSignalInfo::default()),
  653. sig_struct: SpinLock::new(SignalStruct::new()),
  654. exit_signal: AtomicSignal::new(Signal::SIGCHLD),
  655. parent_pcb: RwLock::new(ppcb.clone()),
  656. real_parent_pcb: RwLock::new(ppcb),
  657. children: RwLock::new(Vec::new()),
  658. wait_queue: WaitQueue::default(),
  659. thread: RwLock::new(ThreadInfo::new()),
  660. alarm_timer: SpinLock::new(None),
  661. robust_list: RwLock::new(None),
  662. cred: SpinLock::new(cred),
  663. };
  664. // 初始化系统调用栈
  665. #[cfg(target_arch = "x86_64")]
  666. pcb.arch_info
  667. .lock()
  668. .init_syscall_stack(&pcb.syscall_stack.read());
  669. let pcb = Arc::new(pcb);
  670. pcb.sched_info()
  671. .sched_entity()
  672. .force_mut()
  673. .set_pcb(Arc::downgrade(&pcb));
  674. // 设置进程的arc指针到内核栈和系统调用栈的最低地址处
  675. unsafe {
  676. pcb.kernel_stack
  677. .write()
  678. .set_pcb(Arc::downgrade(&pcb))
  679. .unwrap();
  680. pcb.syscall_stack
  681. .write()
  682. .set_pcb(Arc::downgrade(&pcb))
  683. .unwrap()
  684. };
  685. // 将当前pcb加入父进程的子进程哈希表中
  686. if pcb.pid() > Pid(1) {
  687. if let Some(ppcb_arc) = pcb.parent_pcb.read_irqsave().upgrade() {
  688. let mut children = ppcb_arc.children.write_irqsave();
  689. children.push(pcb.pid());
  690. } else {
  691. panic!("parent pcb is None");
  692. }
  693. }
  694. return pcb;
  695. }
  696. /// 生成一个新的pid
  697. #[inline(always)]
  698. fn generate_pid() -> Pid {
  699. static NEXT_PID: AtomicPid = AtomicPid::new(Pid(1));
  700. return NEXT_PID.fetch_add(Pid(1), Ordering::SeqCst);
  701. }
  702. /// 返回当前进程的锁持有计数
  703. #[inline(always)]
  704. pub fn preempt_count(&self) -> usize {
  705. return self.preempt_count.load(Ordering::SeqCst);
  706. }
  707. /// 增加当前进程的锁持有计数
  708. #[inline(always)]
  709. pub fn preempt_disable(&self) {
  710. self.preempt_count.fetch_add(1, Ordering::SeqCst);
  711. }
  712. /// 减少当前进程的锁持有计数
  713. #[inline(always)]
  714. pub fn preempt_enable(&self) {
  715. self.preempt_count.fetch_sub(1, Ordering::SeqCst);
  716. }
  717. #[inline(always)]
  718. pub unsafe fn set_preempt_count(&self, count: usize) {
  719. self.preempt_count.store(count, Ordering::SeqCst);
  720. }
  721. #[inline(always)]
  722. pub fn flags(&self) -> &mut ProcessFlags {
  723. return self.flags.get_mut();
  724. }
  725. /// 请注意,这个值能在中断上下文中读取,但不能被中断上下文修改
  726. /// 否则会导致死锁
  727. #[inline(always)]
  728. pub fn basic(&self) -> RwLockReadGuard<ProcessBasicInfo> {
  729. return self.basic.read_irqsave();
  730. }
  731. #[inline(always)]
  732. pub fn set_name(&self, name: String) {
  733. self.basic.write().set_name(name);
  734. }
  735. #[inline(always)]
  736. pub fn basic_mut(&self) -> RwLockWriteGuard<ProcessBasicInfo> {
  737. return self.basic.write_irqsave();
  738. }
  739. /// # 获取arch info的锁,同时关闭中断
  740. #[inline(always)]
  741. pub fn arch_info_irqsave(&self) -> SpinLockGuard<ArchPCBInfo> {
  742. return self.arch_info.lock_irqsave();
  743. }
  744. /// # 获取arch info的锁,但是不关闭中断
  745. ///
  746. /// 由于arch info在进程切换的时候会使用到,
  747. /// 因此在中断上下文外,获取arch info 而不irqsave是不安全的.
  748. ///
  749. /// 只能在以下情况下使用这个函数:
  750. /// - 在中断上下文中(中断已经禁用),获取arch info的锁。
  751. /// - 刚刚创建新的pcb
  752. #[inline(always)]
  753. pub unsafe fn arch_info(&self) -> SpinLockGuard<ArchPCBInfo> {
  754. return self.arch_info.lock();
  755. }
  756. #[inline(always)]
  757. pub fn kernel_stack(&self) -> RwLockReadGuard<KernelStack> {
  758. return self.kernel_stack.read();
  759. }
  760. pub unsafe fn kernel_stack_force_ref(&self) -> &KernelStack {
  761. self.kernel_stack.force_get_ref()
  762. }
  763. #[inline(always)]
  764. #[allow(dead_code)]
  765. pub fn kernel_stack_mut(&self) -> RwLockWriteGuard<KernelStack> {
  766. return self.kernel_stack.write();
  767. }
  768. #[inline(always)]
  769. pub fn sched_info(&self) -> &ProcessSchedulerInfo {
  770. return &self.sched_info;
  771. }
  772. #[inline(always)]
  773. pub fn worker_private(&self) -> SpinLockGuard<Option<WorkerPrivate>> {
  774. return self.worker_private.lock();
  775. }
  776. #[inline(always)]
  777. pub fn pid(&self) -> Pid {
  778. return self.pid;
  779. }
  780. #[inline(always)]
  781. pub fn tgid(&self) -> Pid {
  782. return self.tgid;
  783. }
  784. /// 获取文件描述符表的Arc指针
  785. #[inline(always)]
  786. pub fn fd_table(&self) -> Arc<RwLock<FileDescriptorVec>> {
  787. return self.basic.read().fd_table().unwrap();
  788. }
  789. #[inline(always)]
  790. pub fn cred(&self) -> Cred {
  791. self.cred.lock().clone()
  792. }
  793. /// 根据文件描述符序号,获取socket对象的Arc指针
  794. ///
  795. /// ## 参数
  796. ///
  797. /// - `fd` 文件描述符序号
  798. ///
  799. /// ## 返回值
  800. ///
  801. /// Option(&mut Box<dyn Socket>) socket对象的可变引用. 如果文件描述符不是socket,那么返回None
  802. pub fn get_socket(&self, fd: i32) -> Option<Arc<SocketInode>> {
  803. let binding = ProcessManager::current_pcb().fd_table();
  804. let fd_table_guard = binding.read();
  805. let f = fd_table_guard.get_file_by_fd(fd)?;
  806. drop(fd_table_guard);
  807. if f.file_type() != FileType::Socket {
  808. return None;
  809. }
  810. let socket: Arc<SocketInode> = f
  811. .inode()
  812. .downcast_arc::<SocketInode>()
  813. .expect("Not a socket inode");
  814. return Some(socket);
  815. }
  816. /// 当前进程退出时,让初始进程收养所有子进程
  817. unsafe fn adopt_childen(&self) -> Result<(), SystemError> {
  818. match ProcessManager::find(Pid(1)) {
  819. Some(init_pcb) => {
  820. let childen_guard = self.children.write();
  821. let mut init_childen_guard = init_pcb.children.write();
  822. childen_guard.iter().for_each(|pid| {
  823. init_childen_guard.push(*pid);
  824. });
  825. return Ok(());
  826. }
  827. _ => Err(SystemError::ECHILD),
  828. }
  829. }
  830. /// 生成进程的名字
  831. pub fn generate_name(program_path: &str, args: &Vec<CString>) -> String {
  832. let mut name = program_path.to_string();
  833. for arg in args {
  834. name.push(' ');
  835. name.push_str(arg.to_string_lossy().as_ref());
  836. }
  837. return name;
  838. }
  839. pub fn sig_info_irqsave(&self) -> RwLockReadGuard<ProcessSignalInfo> {
  840. self.sig_info.read_irqsave()
  841. }
  842. pub fn try_siginfo_irqsave(&self, times: u8) -> Option<RwLockReadGuard<ProcessSignalInfo>> {
  843. for _ in 0..times {
  844. if let Some(r) = self.sig_info.try_read_irqsave() {
  845. return Some(r);
  846. }
  847. }
  848. return None;
  849. }
  850. pub fn sig_info_mut(&self) -> RwLockWriteGuard<ProcessSignalInfo> {
  851. self.sig_info.write_irqsave()
  852. }
  853. pub fn try_siginfo_mut(&self, times: u8) -> Option<RwLockWriteGuard<ProcessSignalInfo>> {
  854. for _ in 0..times {
  855. if let Some(r) = self.sig_info.try_write_irqsave() {
  856. return Some(r);
  857. }
  858. }
  859. return None;
  860. }
  861. /// 判断当前进程是否有未处理的信号
  862. pub fn has_pending_signal(&self) -> bool {
  863. let sig_info = self.sig_info_irqsave();
  864. let has_pending = sig_info.sig_pending().has_pending();
  865. drop(sig_info);
  866. return has_pending;
  867. }
  868. pub fn sig_struct(&self) -> SpinLockGuard<SignalStruct> {
  869. self.sig_struct.lock_irqsave()
  870. }
  871. pub fn try_sig_struct_irqsave(&self, times: u8) -> Option<SpinLockGuard<SignalStruct>> {
  872. for _ in 0..times {
  873. if let Ok(r) = self.sig_struct.try_lock_irqsave() {
  874. return Some(r);
  875. }
  876. }
  877. return None;
  878. }
  879. pub fn sig_struct_irqsave(&self) -> SpinLockGuard<SignalStruct> {
  880. self.sig_struct.lock_irqsave()
  881. }
  882. #[inline(always)]
  883. pub fn get_robust_list(&self) -> RwLockReadGuard<Option<RobustListHead>> {
  884. return self.robust_list.read_irqsave();
  885. }
  886. #[inline(always)]
  887. pub fn set_robust_list(&self, new_robust_list: Option<RobustListHead>) {
  888. *self.robust_list.write_irqsave() = new_robust_list;
  889. }
  890. pub fn alarm_timer_irqsave(&self) -> SpinLockGuard<Option<AlarmTimer>> {
  891. return self.alarm_timer.lock_irqsave();
  892. }
  893. }
  894. impl Drop for ProcessControlBlock {
  895. fn drop(&mut self) {
  896. let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
  897. // 在ProcFS中,解除进程的注册
  898. procfs_unregister_pid(self.pid())
  899. .unwrap_or_else(|e| panic!("procfs_unregister_pid failed: error: {e:?}"));
  900. if let Some(ppcb) = self.parent_pcb.read_irqsave().upgrade() {
  901. ppcb.children
  902. .write_irqsave()
  903. .retain(|pid| *pid != self.pid());
  904. }
  905. drop(irq_guard);
  906. }
  907. }
  908. /// 线程信息
  909. #[derive(Debug)]
  910. pub struct ThreadInfo {
  911. // 来自用户空间记录用户线程id的地址,在该线程结束时将该地址置0以通知父进程
  912. clear_child_tid: Option<VirtAddr>,
  913. set_child_tid: Option<VirtAddr>,
  914. vfork_done: Option<Arc<Completion>>,
  915. /// 线程组的组长
  916. group_leader: Weak<ProcessControlBlock>,
  917. }
  918. impl ThreadInfo {
  919. pub fn new() -> Self {
  920. Self {
  921. clear_child_tid: None,
  922. set_child_tid: None,
  923. vfork_done: None,
  924. group_leader: Weak::default(),
  925. }
  926. }
  927. pub fn group_leader(&self) -> Option<Arc<ProcessControlBlock>> {
  928. return self.group_leader.upgrade();
  929. }
  930. }
  931. /// 进程的基本信息
  932. ///
  933. /// 这个结构体保存进程的基本信息,主要是那些不会随着进程的运行而经常改变的信息。
  934. #[derive(Debug)]
  935. pub struct ProcessBasicInfo {
  936. /// 当前进程的进程组id
  937. pgid: Pid,
  938. /// 当前进程的父进程的pid
  939. ppid: Pid,
  940. /// 当前进程所属会话id
  941. sid: Pid,
  942. /// 进程的名字
  943. name: String,
  944. /// 当前进程的工作目录
  945. cwd: String,
  946. /// 用户地址空间
  947. user_vm: Option<Arc<AddressSpace>>,
  948. /// 文件描述符表
  949. fd_table: Option<Arc<RwLock<FileDescriptorVec>>>,
  950. }
  951. impl ProcessBasicInfo {
  952. #[inline(never)]
  953. pub fn new(
  954. pgid: Pid,
  955. ppid: Pid,
  956. sid: Pid,
  957. name: String,
  958. cwd: String,
  959. user_vm: Option<Arc<AddressSpace>>,
  960. ) -> RwLock<Self> {
  961. let fd_table = Arc::new(RwLock::new(FileDescriptorVec::new()));
  962. return RwLock::new(Self {
  963. pgid,
  964. ppid,
  965. sid,
  966. name,
  967. cwd,
  968. user_vm,
  969. fd_table: Some(fd_table),
  970. });
  971. }
  972. pub fn pgid(&self) -> Pid {
  973. return self.pgid;
  974. }
  975. pub fn ppid(&self) -> Pid {
  976. return self.ppid;
  977. }
  978. pub fn sid(&self) -> Pid {
  979. return self.sid;
  980. }
  981. pub fn name(&self) -> &str {
  982. return &self.name;
  983. }
  984. pub fn set_name(&mut self, name: String) {
  985. self.name = name;
  986. }
  987. pub fn cwd(&self) -> String {
  988. return self.cwd.clone();
  989. }
  990. pub fn set_cwd(&mut self, path: String) {
  991. return self.cwd = path;
  992. }
  993. pub fn user_vm(&self) -> Option<Arc<AddressSpace>> {
  994. return self.user_vm.clone();
  995. }
  996. pub unsafe fn set_user_vm(&mut self, user_vm: Option<Arc<AddressSpace>>) {
  997. self.user_vm = user_vm;
  998. }
  999. pub fn fd_table(&self) -> Option<Arc<RwLock<FileDescriptorVec>>> {
  1000. return self.fd_table.clone();
  1001. }
  1002. pub fn set_fd_table(&mut self, fd_table: Option<Arc<RwLock<FileDescriptorVec>>>) {
  1003. self.fd_table = fd_table;
  1004. }
  1005. }
  1006. #[derive(Debug)]
  1007. pub struct ProcessSchedulerInfo {
  1008. /// 当前进程所在的cpu
  1009. on_cpu: AtomicProcessorId,
  1010. /// 如果当前进程等待被迁移到另一个cpu核心上(也就是flags中的PF_NEED_MIGRATE被置位),
  1011. /// 该字段存储要被迁移到的目标处理器核心号
  1012. // migrate_to: AtomicProcessorId,
  1013. inner_locked: RwLock<InnerSchedInfo>,
  1014. /// 进程的调度优先级
  1015. // priority: SchedPriority,
  1016. /// 当前进程的虚拟运行时间
  1017. // virtual_runtime: AtomicIsize,
  1018. /// 由实时调度器管理的时间片
  1019. // rt_time_slice: AtomicIsize,
  1020. pub sched_stat: RwLock<SchedInfo>,
  1021. /// 调度策略
  1022. pub sched_policy: RwLock<crate::sched::SchedPolicy>,
  1023. /// cfs调度实体
  1024. pub sched_entity: Arc<FairSchedEntity>,
  1025. pub on_rq: SpinLock<OnRq>,
  1026. pub prio_data: RwLock<PrioData>,
  1027. }
  1028. #[derive(Debug, Default)]
  1029. #[allow(dead_code)]
  1030. pub struct SchedInfo {
  1031. /// 记录任务在特定 CPU 上运行的次数
  1032. pub pcount: usize,
  1033. /// 记录任务等待在运行队列上的时间
  1034. pub run_delay: usize,
  1035. /// 记录任务上次在 CPU 上运行的时间戳
  1036. pub last_arrival: u64,
  1037. /// 记录任务上次被加入到运行队列中的时间戳
  1038. pub last_queued: u64,
  1039. }
  1040. #[derive(Debug)]
  1041. #[allow(dead_code)]
  1042. pub struct PrioData {
  1043. pub prio: i32,
  1044. pub static_prio: i32,
  1045. pub normal_prio: i32,
  1046. }
  1047. impl Default for PrioData {
  1048. fn default() -> Self {
  1049. Self {
  1050. prio: MAX_PRIO - 20,
  1051. static_prio: MAX_PRIO - 20,
  1052. normal_prio: MAX_PRIO - 20,
  1053. }
  1054. }
  1055. }
  1056. #[derive(Debug)]
  1057. pub struct InnerSchedInfo {
  1058. /// 当前进程的状态
  1059. state: ProcessState,
  1060. /// 进程的调度策略
  1061. sleep: bool,
  1062. }
  1063. impl InnerSchedInfo {
  1064. pub fn state(&self) -> ProcessState {
  1065. return self.state;
  1066. }
  1067. pub fn set_state(&mut self, state: ProcessState) {
  1068. self.state = state;
  1069. }
  1070. pub fn set_sleep(&mut self) {
  1071. self.sleep = true;
  1072. }
  1073. pub fn set_wakeup(&mut self) {
  1074. self.sleep = false;
  1075. }
  1076. pub fn is_mark_sleep(&self) -> bool {
  1077. self.sleep
  1078. }
  1079. }
  1080. impl ProcessSchedulerInfo {
  1081. #[inline(never)]
  1082. pub fn new(on_cpu: Option<ProcessorId>) -> Self {
  1083. let cpu_id = on_cpu.unwrap_or(ProcessorId::INVALID);
  1084. return Self {
  1085. on_cpu: AtomicProcessorId::new(cpu_id),
  1086. // migrate_to: AtomicProcessorId::new(ProcessorId::INVALID),
  1087. inner_locked: RwLock::new(InnerSchedInfo {
  1088. state: ProcessState::Blocked(false),
  1089. sleep: false,
  1090. }),
  1091. // virtual_runtime: AtomicIsize::new(0),
  1092. // rt_time_slice: AtomicIsize::new(0),
  1093. // priority: SchedPriority::new(100).unwrap(),
  1094. sched_stat: RwLock::new(SchedInfo::default()),
  1095. sched_policy: RwLock::new(crate::sched::SchedPolicy::CFS),
  1096. sched_entity: FairSchedEntity::new(),
  1097. on_rq: SpinLock::new(OnRq::None),
  1098. prio_data: RwLock::new(PrioData::default()),
  1099. };
  1100. }
  1101. pub fn sched_entity(&self) -> Arc<FairSchedEntity> {
  1102. return self.sched_entity.clone();
  1103. }
  1104. pub fn on_cpu(&self) -> Option<ProcessorId> {
  1105. let on_cpu = self.on_cpu.load(Ordering::SeqCst);
  1106. if on_cpu == ProcessorId::INVALID {
  1107. return None;
  1108. } else {
  1109. return Some(on_cpu);
  1110. }
  1111. }
  1112. pub fn set_on_cpu(&self, on_cpu: Option<ProcessorId>) {
  1113. if let Some(cpu_id) = on_cpu {
  1114. self.on_cpu.store(cpu_id, Ordering::SeqCst);
  1115. } else {
  1116. self.on_cpu.store(ProcessorId::INVALID, Ordering::SeqCst);
  1117. }
  1118. }
  1119. // pub fn migrate_to(&self) -> Option<ProcessorId> {
  1120. // let migrate_to = self.migrate_to.load(Ordering::SeqCst);
  1121. // if migrate_to == ProcessorId::INVALID {
  1122. // return None;
  1123. // } else {
  1124. // return Some(migrate_to);
  1125. // }
  1126. // }
  1127. // pub fn set_migrate_to(&self, migrate_to: Option<ProcessorId>) {
  1128. // if let Some(data) = migrate_to {
  1129. // self.migrate_to.store(data, Ordering::SeqCst);
  1130. // } else {
  1131. // self.migrate_to
  1132. // .store(ProcessorId::INVALID, Ordering::SeqCst)
  1133. // }
  1134. // }
  1135. pub fn inner_lock_write_irqsave(&self) -> RwLockWriteGuard<InnerSchedInfo> {
  1136. return self.inner_locked.write_irqsave();
  1137. }
  1138. pub fn inner_lock_read_irqsave(&self) -> RwLockReadGuard<InnerSchedInfo> {
  1139. return self.inner_locked.read_irqsave();
  1140. }
  1141. // pub fn inner_lock_try_read_irqsave(
  1142. // &self,
  1143. // times: u8,
  1144. // ) -> Option<RwLockReadGuard<InnerSchedInfo>> {
  1145. // for _ in 0..times {
  1146. // if let Some(r) = self.inner_locked.try_read_irqsave() {
  1147. // return Some(r);
  1148. // }
  1149. // }
  1150. // return None;
  1151. // }
  1152. // pub fn inner_lock_try_upgradable_read_irqsave(
  1153. // &self,
  1154. // times: u8,
  1155. // ) -> Option<RwLockUpgradableGuard<InnerSchedInfo>> {
  1156. // for _ in 0..times {
  1157. // if let Some(r) = self.inner_locked.try_upgradeable_read_irqsave() {
  1158. // return Some(r);
  1159. // }
  1160. // }
  1161. // return None;
  1162. // }
  1163. // pub fn virtual_runtime(&self) -> isize {
  1164. // return self.virtual_runtime.load(Ordering::SeqCst);
  1165. // }
  1166. // pub fn set_virtual_runtime(&self, virtual_runtime: isize) {
  1167. // self.virtual_runtime
  1168. // .store(virtual_runtime, Ordering::SeqCst);
  1169. // }
  1170. // pub fn increase_virtual_runtime(&self, delta: isize) {
  1171. // self.virtual_runtime.fetch_add(delta, Ordering::SeqCst);
  1172. // }
  1173. // pub fn rt_time_slice(&self) -> isize {
  1174. // return self.rt_time_slice.load(Ordering::SeqCst);
  1175. // }
  1176. // pub fn set_rt_time_slice(&self, rt_time_slice: isize) {
  1177. // self.rt_time_slice.store(rt_time_slice, Ordering::SeqCst);
  1178. // }
  1179. // pub fn increase_rt_time_slice(&self, delta: isize) {
  1180. // self.rt_time_slice.fetch_add(delta, Ordering::SeqCst);
  1181. // }
  1182. pub fn policy(&self) -> crate::sched::SchedPolicy {
  1183. return *self.sched_policy.read_irqsave();
  1184. }
  1185. }
  1186. #[derive(Debug, Clone)]
  1187. pub struct KernelStack {
  1188. stack: Option<AlignedBox<[u8; KernelStack::SIZE], { KernelStack::ALIGN }>>,
  1189. /// 标记该内核栈是否可以被释放
  1190. can_be_freed: bool,
  1191. }
  1192. impl KernelStack {
  1193. pub const SIZE: usize = 0x4000;
  1194. pub const ALIGN: usize = 0x4000;
  1195. pub fn new() -> Result<Self, SystemError> {
  1196. return Ok(Self {
  1197. stack: Some(
  1198. AlignedBox::<[u8; KernelStack::SIZE], { KernelStack::ALIGN }>::new_zeroed()?,
  1199. ),
  1200. can_be_freed: true,
  1201. });
  1202. }
  1203. /// 根据已有的空间,构造一个内核栈结构体
  1204. ///
  1205. /// 仅仅用于BSP启动时,为idle进程构造内核栈。其他时候使用这个函数,很可能造成错误!
  1206. pub unsafe fn from_existed(base: VirtAddr) -> Result<Self, SystemError> {
  1207. if base.is_null() || !base.check_aligned(Self::ALIGN) {
  1208. return Err(SystemError::EFAULT);
  1209. }
  1210. return Ok(Self {
  1211. stack: Some(
  1212. AlignedBox::<[u8; KernelStack::SIZE], { KernelStack::ALIGN }>::new_unchecked(
  1213. base.data() as *mut [u8; KernelStack::SIZE],
  1214. ),
  1215. ),
  1216. can_be_freed: false,
  1217. });
  1218. }
  1219. /// 返回内核栈的起始虚拟地址(低地址)
  1220. pub fn start_address(&self) -> VirtAddr {
  1221. return VirtAddr::new(self.stack.as_ref().unwrap().as_ptr() as usize);
  1222. }
  1223. /// 返回内核栈的结束虚拟地址(高地址)(不包含该地址)
  1224. pub fn stack_max_address(&self) -> VirtAddr {
  1225. return VirtAddr::new(self.stack.as_ref().unwrap().as_ptr() as usize + Self::SIZE);
  1226. }
  1227. pub unsafe fn set_pcb(&mut self, pcb: Weak<ProcessControlBlock>) -> Result<(), SystemError> {
  1228. // 将一个Weak<ProcessControlBlock>放到内核栈的最低地址处
  1229. let p: *const ProcessControlBlock = Weak::into_raw(pcb);
  1230. let stack_bottom_ptr = self.start_address().data() as *mut *const ProcessControlBlock;
  1231. // 如果内核栈的最低地址处已经有了一个pcb,那么,这里就不再设置,直接返回错误
  1232. if unlikely(unsafe { !(*stack_bottom_ptr).is_null() }) {
  1233. error!("kernel stack bottom is not null: {:p}", *stack_bottom_ptr);
  1234. return Err(SystemError::EPERM);
  1235. }
  1236. // 将pcb的地址放到内核栈的最低地址处
  1237. unsafe {
  1238. *stack_bottom_ptr = p;
  1239. }
  1240. return Ok(());
  1241. }
  1242. /// 清除内核栈的pcb指针
  1243. ///
  1244. /// ## 参数
  1245. ///
  1246. /// - `force` : 如果为true,那么,即使该内核栈的pcb指针不为null,也会被强制清除而不处理Weak指针问题
  1247. pub unsafe fn clear_pcb(&mut self, force: bool) {
  1248. let stack_bottom_ptr = self.start_address().data() as *mut *const ProcessControlBlock;
  1249. if unlikely(unsafe { (*stack_bottom_ptr).is_null() }) {
  1250. return;
  1251. }
  1252. if !force {
  1253. let pcb_ptr: Weak<ProcessControlBlock> = Weak::from_raw(*stack_bottom_ptr);
  1254. drop(pcb_ptr);
  1255. }
  1256. *stack_bottom_ptr = core::ptr::null();
  1257. }
  1258. /// 返回指向当前内核栈pcb的Arc指针
  1259. #[allow(dead_code)]
  1260. pub unsafe fn pcb(&self) -> Option<Arc<ProcessControlBlock>> {
  1261. // 从内核栈的最低地址处取出pcb的地址
  1262. let p = self.stack.as_ref().unwrap().as_ptr() as *const *const ProcessControlBlock;
  1263. if unlikely(unsafe { (*p).is_null() }) {
  1264. return None;
  1265. }
  1266. // 为了防止内核栈的pcb指针被释放,这里需要将其包装一下,使得Arc的drop不会被调用
  1267. let weak_wrapper: ManuallyDrop<Weak<ProcessControlBlock>> =
  1268. ManuallyDrop::new(Weak::from_raw(*p));
  1269. let new_arc: Arc<ProcessControlBlock> = weak_wrapper.upgrade()?;
  1270. return Some(new_arc);
  1271. }
  1272. }
  1273. impl Drop for KernelStack {
  1274. fn drop(&mut self) {
  1275. if self.stack.is_some() {
  1276. let ptr = self.stack.as_ref().unwrap().as_ptr() as *const *const ProcessControlBlock;
  1277. if unsafe { !(*ptr).is_null() } {
  1278. let pcb_ptr: Weak<ProcessControlBlock> = unsafe { Weak::from_raw(*ptr) };
  1279. drop(pcb_ptr);
  1280. }
  1281. }
  1282. // 如果该内核栈不可以被释放,那么,这里就forget,不调用AlignedBox的drop函数
  1283. if !self.can_be_freed {
  1284. let bx = self.stack.take();
  1285. core::mem::forget(bx);
  1286. }
  1287. }
  1288. }
  1289. pub fn process_init() {
  1290. ProcessManager::init();
  1291. }
  1292. #[derive(Debug)]
  1293. pub struct ProcessSignalInfo {
  1294. // 当前进程
  1295. sig_block: SigSet,
  1296. // sig_pending 中存储当前线程要处理的信号
  1297. sig_pending: SigPending,
  1298. // sig_shared_pending 中存储当前线程所属进程要处理的信号
  1299. sig_shared_pending: SigPending,
  1300. // 当前进程对应的tty
  1301. tty: Option<Arc<TtyCore>>,
  1302. }
  1303. impl ProcessSignalInfo {
  1304. pub fn sig_block(&self) -> &SigSet {
  1305. &self.sig_block
  1306. }
  1307. pub fn sig_pending(&self) -> &SigPending {
  1308. &self.sig_pending
  1309. }
  1310. pub fn sig_pending_mut(&mut self) -> &mut SigPending {
  1311. &mut self.sig_pending
  1312. }
  1313. pub fn sig_block_mut(&mut self) -> &mut SigSet {
  1314. &mut self.sig_block
  1315. }
  1316. pub fn sig_shared_pending_mut(&mut self) -> &mut SigPending {
  1317. &mut self.sig_shared_pending
  1318. }
  1319. pub fn sig_shared_pending(&self) -> &SigPending {
  1320. &self.sig_shared_pending
  1321. }
  1322. pub fn tty(&self) -> Option<Arc<TtyCore>> {
  1323. self.tty.clone()
  1324. }
  1325. pub fn set_tty(&mut self, tty: Option<Arc<TtyCore>>) {
  1326. self.tty = tty;
  1327. }
  1328. /// 从 pcb 的 siginfo中取出下一个要处理的信号,先处理线程信号,再处理进程信号
  1329. ///
  1330. /// ## 参数
  1331. ///
  1332. /// - `sig_mask` 被忽略掉的信号
  1333. ///
  1334. pub fn dequeue_signal(&mut self, sig_mask: &SigSet) -> (Signal, Option<SigInfo>) {
  1335. let res = self.sig_pending.dequeue_signal(sig_mask);
  1336. if res.0 != Signal::INVALID {
  1337. return res;
  1338. } else {
  1339. return self.sig_shared_pending.dequeue_signal(sig_mask);
  1340. }
  1341. }
  1342. }
  1343. impl Default for ProcessSignalInfo {
  1344. fn default() -> Self {
  1345. Self {
  1346. sig_block: SigSet::empty(),
  1347. sig_pending: SigPending::default(),
  1348. sig_shared_pending: SigPending::default(),
  1349. tty: None,
  1350. }
  1351. }
  1352. }