mod.rs 51 KB

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