1004e86ffSlogin use core::intrinsics::size_of; 206b09f34Skong 3004e86ffSlogin use alloc::{ 4004e86ffSlogin borrow::ToOwned, 5004e86ffSlogin collections::BTreeMap, 6004e86ffSlogin format, 71496ba7bSLoGin string::String, 8004e86ffSlogin sync::{Arc, Weak}, 9004e86ffSlogin vec::Vec, 10004e86ffSlogin }; 1191e9d4abSLoGin use system_error::SystemError; 12004e86ffSlogin 13004e86ffSlogin use crate::{ 1434e6d6c8Syuyi2439 arch::mm::LockedFrameAllocator, 1502343d0bSLoGin driver::base::device::device_number::DeviceNumber, 16004e86ffSlogin filesystem::vfs::{ 17004e86ffSlogin core::{generate_inode_id, ROOT_INODE}, 18004e86ffSlogin FileType, 19004e86ffSlogin }, 20b087521eSChiichen kerror, kinfo, 21b087521eSChiichen libs::{ 22b087521eSChiichen once::Once, 23b087521eSChiichen spinlock::{SpinLock, SpinLockGuard}, 24b087521eSChiichen }, 254fda81ceSLoGin mm::allocator::page_frame::FrameAllocator, 261496ba7bSLoGin process::{Pid, ProcessManager}, 2778bf93f0SYJwu2023 time::TimeSpec, 28004e86ffSlogin }; 29004e86ffSlogin 30004e86ffSlogin use super::vfs::{ 3178bf93f0SYJwu2023 file::{FileMode, FilePrivateData}, 326b4e7a29SLoGin syscall::ModeType, 3340609970SGnoCiYeH FileSystem, FsInfo, IndexNode, InodeId, Metadata, 34004e86ffSlogin }; 35004e86ffSlogin 368d72b68dSJomo pub mod kmsg; 378d72b68dSJomo pub mod log; 388d72b68dSJomo mod syscall; 398d72b68dSJomo 40004e86ffSlogin /// @brief 进程文件类型 41004e86ffSlogin /// @usage 用于定义进程文件夹下的各类文件类型 42004e86ffSlogin #[derive(Debug)] 43004e86ffSlogin #[repr(u8)] 44004e86ffSlogin pub enum ProcFileType { 45004e86ffSlogin ///展示进程状态信息 46004e86ffSlogin ProcStatus = 0, 4734e6d6c8Syuyi2439 /// meminfo 4834e6d6c8Syuyi2439 ProcMeminfo = 1, 498d72b68dSJomo /// kmsg 508d72b68dSJomo ProcKmsg = 2, 51004e86ffSlogin //todo: 其他文件类型 52004e86ffSlogin ///默认文件类型 53004e86ffSlogin Default, 54004e86ffSlogin } 55004e86ffSlogin 56004e86ffSlogin impl From<u8> for ProcFileType { 57004e86ffSlogin fn from(value: u8) -> Self { 58004e86ffSlogin match value { 59004e86ffSlogin 0 => ProcFileType::ProcStatus, 6034e6d6c8Syuyi2439 1 => ProcFileType::ProcMeminfo, 618d72b68dSJomo 2 => ProcFileType::ProcKmsg, 62004e86ffSlogin _ => ProcFileType::Default, 63004e86ffSlogin } 64004e86ffSlogin } 65004e86ffSlogin } 66004e86ffSlogin /// @brief 节点私有信息结构体 67004e86ffSlogin /// @usage 用于传入各类文件所需的信息 68004e86ffSlogin #[derive(Debug)] 69004e86ffSlogin pub struct InodeInfo { 70004e86ffSlogin ///进程的pid 711496ba7bSLoGin pid: Pid, 72004e86ffSlogin ///文件类型 73004e86ffSlogin ftype: ProcFileType, 74004e86ffSlogin //其他需要传入的信息在此定义 75004e86ffSlogin } 76004e86ffSlogin 77004e86ffSlogin /// @brief procfs的inode名称的最大长度 78004e86ffSlogin const PROCFS_MAX_NAMELEN: usize = 64; 79004e86ffSlogin 80004e86ffSlogin /// @brief procfs文件系统的Inode结构体 81004e86ffSlogin #[derive(Debug)] 82004e86ffSlogin pub struct LockedProcFSInode(SpinLock<ProcFSInode>); 83004e86ffSlogin 84004e86ffSlogin /// @brief procfs文件系统结构体 85004e86ffSlogin #[derive(Debug)] 86004e86ffSlogin pub struct ProcFS { 87004e86ffSlogin /// procfs的root inode 88004e86ffSlogin root_inode: Arc<LockedProcFSInode>, 89004e86ffSlogin } 90004e86ffSlogin 91004e86ffSlogin #[derive(Debug, Clone)] 92004e86ffSlogin pub struct ProcfsFilePrivateData { 93004e86ffSlogin data: Vec<u8>, 94004e86ffSlogin } 95004e86ffSlogin 96004e86ffSlogin impl ProcfsFilePrivateData { 97004e86ffSlogin pub fn new() -> Self { 98004e86ffSlogin return ProcfsFilePrivateData { data: Vec::new() }; 99004e86ffSlogin } 100004e86ffSlogin } 101004e86ffSlogin 102004e86ffSlogin /// @brief procfs文件系统的Inode结构体(不包含锁) 103004e86ffSlogin #[derive(Debug)] 104004e86ffSlogin pub struct ProcFSInode { 105004e86ffSlogin /// 指向父Inode的弱引用 106004e86ffSlogin parent: Weak<LockedProcFSInode>, 107004e86ffSlogin /// 指向自身的弱引用 108004e86ffSlogin self_ref: Weak<LockedProcFSInode>, 109004e86ffSlogin /// 子Inode的B树 110004e86ffSlogin children: BTreeMap<String, Arc<LockedProcFSInode>>, 111004e86ffSlogin /// 当前inode的数据部分 112004e86ffSlogin data: Vec<u8>, 113004e86ffSlogin /// 当前inode的元数据 114004e86ffSlogin metadata: Metadata, 115004e86ffSlogin /// 指向inode所在的文件系统对象的指针 116004e86ffSlogin fs: Weak<ProcFS>, 117004e86ffSlogin /// 储存私有信息 118004e86ffSlogin fdata: InodeInfo, 119004e86ffSlogin } 120004e86ffSlogin 121004e86ffSlogin /// 对ProcFSInode实现获取各类文件信息的函数 122004e86ffSlogin impl ProcFSInode { 123004e86ffSlogin /// @brief 去除Vec中所有的\0,并在结尾添加\0 124004e86ffSlogin #[inline] 125004e86ffSlogin fn trim_string(&self, data: &mut Vec<u8>) { 1261a72a751SLoGin data.retain(|x| *x != 0); 1271a72a751SLoGin 128004e86ffSlogin data.push(0); 129004e86ffSlogin } 130004e86ffSlogin // todo:其他数据获取函数实现 131004e86ffSlogin 132004e86ffSlogin /// @brief 打开status文件 133004e86ffSlogin /// 134676b8ef6SMork fn open_status(&self, pdata: &mut ProcfsFilePrivateData) -> Result<i64, SystemError> { 135004e86ffSlogin // 获取该pid对应的pcb结构体 1361496ba7bSLoGin let pid = self.fdata.pid; 1371496ba7bSLoGin let pcb = ProcessManager::find(pid); 138004e86ffSlogin let pcb = if pcb.is_none() { 139004e86ffSlogin kerror!( 1401496ba7bSLoGin "ProcFS: Cannot find pcb for pid {:?} when opening its 'status' file.", 141004e86ffSlogin pid 142004e86ffSlogin ); 143676b8ef6SMork return Err(SystemError::ESRCH); 144004e86ffSlogin } else { 145004e86ffSlogin pcb.unwrap() 146004e86ffSlogin }; 147004e86ffSlogin // 传入数据 148004e86ffSlogin let pdata: &mut Vec<u8> = &mut pdata.data; 149004e86ffSlogin 150004e86ffSlogin pdata.append( 1511496ba7bSLoGin &mut format!("Name:\t{}", pcb.basic().name()) 152004e86ffSlogin .as_bytes() 153004e86ffSlogin .to_owned(), 154004e86ffSlogin ); 155004e86ffSlogin 1561496ba7bSLoGin let sched_info_guard = pcb.sched_info(); 1570d6cf65aSLoGin let state = sched_info_guard.inner_lock_read_irqsave().state(); 1581496ba7bSLoGin let cpu_id = sched_info_guard 1591496ba7bSLoGin .on_cpu() 160e2841179SLoGin .map(|cpu| cpu.data() as i32) 1611496ba7bSLoGin .unwrap_or(-1); 1621496ba7bSLoGin 1631496ba7bSLoGin let priority = sched_info_guard.priority(); 1641496ba7bSLoGin let vrtime = sched_info_guard.virtual_runtime(); 1651496ba7bSLoGin 1661496ba7bSLoGin pdata.append(&mut format!("\nState:\t{:?}", state).as_bytes().to_owned()); 1671496ba7bSLoGin pdata.append( 1681496ba7bSLoGin &mut format!("\nPid:\t{}", pcb.pid().into()) 1691496ba7bSLoGin .as_bytes() 1701496ba7bSLoGin .to_owned(), 1711496ba7bSLoGin ); 1721496ba7bSLoGin pdata.append( 1731496ba7bSLoGin &mut format!("\nPpid:\t{}", pcb.basic().ppid().into()) 1741496ba7bSLoGin .as_bytes() 1751496ba7bSLoGin .to_owned(), 1761496ba7bSLoGin ); 1771496ba7bSLoGin pdata.append(&mut format!("\ncpu_id:\t{}", cpu_id).as_bytes().to_owned()); 1781496ba7bSLoGin pdata.append( 1791496ba7bSLoGin &mut format!("\npriority:\t{}", priority.data()) 1801496ba7bSLoGin .as_bytes() 1811496ba7bSLoGin .to_owned(), 1821496ba7bSLoGin ); 1831496ba7bSLoGin pdata.append( 1841496ba7bSLoGin &mut format!("\npreempt:\t{}", pcb.preempt_count()) 1851496ba7bSLoGin .as_bytes() 1861496ba7bSLoGin .to_owned(), 1871496ba7bSLoGin ); 1881496ba7bSLoGin pdata.append(&mut format!("\nvrtime:\t{}", vrtime).as_bytes().to_owned()); 1891496ba7bSLoGin 1907b32f508SLoGin if let Some(user_vm) = pcb.basic().user_vm() { 1917b32f508SLoGin let address_space_guard = user_vm.read(); 19240fe15e0SLoGin // todo: 当前进程运行过程中占用内存的峰值 19340fe15e0SLoGin let hiwater_vm: u64 = 0; 19440fe15e0SLoGin // 进程代码段的大小 19540fe15e0SLoGin let text = (address_space_guard.end_code - address_space_guard.start_code) / 1024; 196004e86ffSlogin // 进程数据段的大小 19740fe15e0SLoGin let data = (address_space_guard.end_data - address_space_guard.start_data) / 1024; 19840fe15e0SLoGin drop(address_space_guard); 199004e86ffSlogin pdata.append( 200004e86ffSlogin &mut format!("\nVmPeak:\t{} kB", hiwater_vm) 201004e86ffSlogin .as_bytes() 202004e86ffSlogin .to_owned(), 203004e86ffSlogin ); 204004e86ffSlogin pdata.append(&mut format!("\nVmData:\t{} kB", data).as_bytes().to_owned()); 2051496ba7bSLoGin pdata.append(&mut format!("\nVmExe:\t{} kB", text).as_bytes().to_owned()); 2067b32f508SLoGin } 2077b32f508SLoGin 2081496ba7bSLoGin pdata.append( 2091496ba7bSLoGin &mut format!("\nflags: {:?}\n", pcb.flags().clone()) 2101496ba7bSLoGin .as_bytes() 2111496ba7bSLoGin .to_owned(), 2121496ba7bSLoGin ); 213004e86ffSlogin 214004e86ffSlogin // 去除多余的\0 215004e86ffSlogin self.trim_string(pdata); 216004e86ffSlogin 217004e86ffSlogin return Ok((pdata.len() * size_of::<u8>()) as i64); 218004e86ffSlogin } 219004e86ffSlogin 22034e6d6c8Syuyi2439 /// 打开 meminfo 文件 22134e6d6c8Syuyi2439 fn open_meminfo(&self, pdata: &mut ProcfsFilePrivateData) -> Result<i64, SystemError> { 22234e6d6c8Syuyi2439 // 获取内存信息 2234fda81ceSLoGin let usage = unsafe { LockedFrameAllocator.usage() }; 22434e6d6c8Syuyi2439 22534e6d6c8Syuyi2439 // 传入数据 22634e6d6c8Syuyi2439 let data: &mut Vec<u8> = &mut pdata.data; 22734e6d6c8Syuyi2439 22834e6d6c8Syuyi2439 data.append( 22934e6d6c8Syuyi2439 &mut format!("MemTotal:\t{} kB\n", usage.total().bytes() >> 10) 23034e6d6c8Syuyi2439 .as_bytes() 23134e6d6c8Syuyi2439 .to_owned(), 23234e6d6c8Syuyi2439 ); 23334e6d6c8Syuyi2439 23434e6d6c8Syuyi2439 data.append( 23534e6d6c8Syuyi2439 &mut format!("MemFree:\t{} kB\n", usage.free().bytes() >> 10) 23634e6d6c8Syuyi2439 .as_bytes() 23734e6d6c8Syuyi2439 .to_owned(), 23834e6d6c8Syuyi2439 ); 23934e6d6c8Syuyi2439 24034e6d6c8Syuyi2439 // 去除多余的\0 24134e6d6c8Syuyi2439 self.trim_string(data); 24234e6d6c8Syuyi2439 24334e6d6c8Syuyi2439 return Ok((data.len() * size_of::<u8>()) as i64); 24434e6d6c8Syuyi2439 } 24534e6d6c8Syuyi2439 24634e6d6c8Syuyi2439 /// proc文件系统读取函数 24734e6d6c8Syuyi2439 fn proc_read( 248004e86ffSlogin &self, 249004e86ffSlogin offset: usize, 250004e86ffSlogin len: usize, 251004e86ffSlogin buf: &mut [u8], 252004e86ffSlogin _pdata: &mut ProcfsFilePrivateData, 253676b8ef6SMork ) -> Result<usize, SystemError> { 254004e86ffSlogin let start = _pdata.data.len().min(offset); 255004e86ffSlogin let end = _pdata.data.len().min(offset + len); 256004e86ffSlogin 257004e86ffSlogin // buffer空间不足 258004e86ffSlogin if buf.len() < (end - start) { 259676b8ef6SMork return Err(SystemError::ENOBUFS); 260004e86ffSlogin } 261004e86ffSlogin 262004e86ffSlogin // 拷贝数据 263004e86ffSlogin let src = &_pdata.data[start..end]; 264004e86ffSlogin buf[0..src.len()].copy_from_slice(src); 265004e86ffSlogin return Ok(src.len()); 266004e86ffSlogin } 267004e86ffSlogin } 268004e86ffSlogin 269004e86ffSlogin impl FileSystem for ProcFS { 270004e86ffSlogin fn root_inode(&self) -> Arc<dyn super::vfs::IndexNode> { 271004e86ffSlogin return self.root_inode.clone(); 272004e86ffSlogin } 273004e86ffSlogin 274004e86ffSlogin fn info(&self) -> FsInfo { 275004e86ffSlogin return FsInfo { 276004e86ffSlogin blk_dev_id: 0, 277004e86ffSlogin max_name_len: PROCFS_MAX_NAMELEN, 278004e86ffSlogin }; 279004e86ffSlogin } 280004e86ffSlogin 281004e86ffSlogin fn as_any_ref(&self) -> &dyn core::any::Any { 282004e86ffSlogin self 283004e86ffSlogin } 284004e86ffSlogin } 285004e86ffSlogin 286004e86ffSlogin impl ProcFS { 287004e86ffSlogin pub fn new() -> Arc<Self> { 288004e86ffSlogin // 初始化root inode 289004e86ffSlogin let root: Arc<LockedProcFSInode> = 290004e86ffSlogin Arc::new(LockedProcFSInode(SpinLock::new(ProcFSInode { 291004e86ffSlogin parent: Weak::default(), 292004e86ffSlogin self_ref: Weak::default(), 293004e86ffSlogin children: BTreeMap::new(), 294004e86ffSlogin data: Vec::new(), 295004e86ffSlogin metadata: Metadata { 296004e86ffSlogin dev_id: 0, 297004e86ffSlogin inode_id: generate_inode_id(), 298004e86ffSlogin size: 0, 299004e86ffSlogin blk_size: 0, 300004e86ffSlogin blocks: 0, 301004e86ffSlogin atime: TimeSpec::default(), 302004e86ffSlogin mtime: TimeSpec::default(), 303004e86ffSlogin ctime: TimeSpec::default(), 304004e86ffSlogin file_type: FileType::Dir, 30534e6d6c8Syuyi2439 mode: ModeType::from_bits_truncate(0o555), 306004e86ffSlogin nlinks: 1, 307004e86ffSlogin uid: 0, 308004e86ffSlogin gid: 0, 30902343d0bSLoGin raw_dev: DeviceNumber::default(), 310004e86ffSlogin }, 311004e86ffSlogin fs: Weak::default(), 312004e86ffSlogin fdata: InodeInfo { 3131496ba7bSLoGin pid: Pid::new(0), 314004e86ffSlogin ftype: ProcFileType::Default, 315004e86ffSlogin }, 316004e86ffSlogin }))); 317004e86ffSlogin 318004e86ffSlogin let result: Arc<ProcFS> = Arc::new(ProcFS { root_inode: root }); 319004e86ffSlogin 320004e86ffSlogin // 对root inode加锁,并继续完成初始化工作 321004e86ffSlogin let mut root_guard: SpinLockGuard<ProcFSInode> = result.root_inode.0.lock(); 322004e86ffSlogin root_guard.parent = Arc::downgrade(&result.root_inode); 323004e86ffSlogin root_guard.self_ref = Arc::downgrade(&result.root_inode); 324004e86ffSlogin root_guard.fs = Arc::downgrade(&result); 325004e86ffSlogin // 释放锁 326004e86ffSlogin drop(root_guard); 327004e86ffSlogin 32834e6d6c8Syuyi2439 // 创建meminfo文件 32934e6d6c8Syuyi2439 let inode = result.root_inode(); 33034e6d6c8Syuyi2439 let binding = inode.create( 33134e6d6c8Syuyi2439 "meminfo", 33234e6d6c8Syuyi2439 FileType::File, 33334e6d6c8Syuyi2439 ModeType::from_bits_truncate(0o444), 33434e6d6c8Syuyi2439 ); 33534e6d6c8Syuyi2439 if let Ok(meminfo) = binding { 33634e6d6c8Syuyi2439 let meminfo_file = meminfo 33734e6d6c8Syuyi2439 .as_any_ref() 33834e6d6c8Syuyi2439 .downcast_ref::<LockedProcFSInode>() 33934e6d6c8Syuyi2439 .unwrap(); 34034e6d6c8Syuyi2439 meminfo_file.0.lock().fdata.pid = Pid::new(0); 34134e6d6c8Syuyi2439 meminfo_file.0.lock().fdata.ftype = ProcFileType::ProcMeminfo; 34234e6d6c8Syuyi2439 } else { 34334e6d6c8Syuyi2439 panic!("create meminfo error"); 34434e6d6c8Syuyi2439 } 34534e6d6c8Syuyi2439 3468d72b68dSJomo // 创建kmsg文件 3478d72b68dSJomo let binding = inode.create("kmsg", FileType::File, ModeType::from_bits_truncate(0o444)); 3488d72b68dSJomo if let Ok(kmsg) = binding { 3498d72b68dSJomo let kmsg_file = kmsg 3508d72b68dSJomo .as_any_ref() 3518d72b68dSJomo .downcast_ref::<LockedProcFSInode>() 3528d72b68dSJomo .unwrap(); 3538d72b68dSJomo kmsg_file.0.lock().fdata.pid = Pid::new(1); 3548d72b68dSJomo kmsg_file.0.lock().fdata.ftype = ProcFileType::ProcKmsg; 3558d72b68dSJomo } else { 3568d72b68dSJomo panic!("create ksmg error"); 3578d72b68dSJomo } 3588d72b68dSJomo 359004e86ffSlogin return result; 360004e86ffSlogin } 361004e86ffSlogin 362004e86ffSlogin /// @brief 进程注册函数 363004e86ffSlogin /// @usage 在进程中调用并创建进程对应文件 3641496ba7bSLoGin pub fn register_pid(&self, pid: Pid) -> Result<(), SystemError> { 365004e86ffSlogin // 获取当前inode 36634e6d6c8Syuyi2439 let inode: Arc<dyn IndexNode> = self.root_inode(); 367004e86ffSlogin // 创建对应进程文件夹 36834e6d6c8Syuyi2439 let pid_dir: Arc<dyn IndexNode> = inode.create( 3696b4e7a29SLoGin &pid.to_string(), 3706b4e7a29SLoGin FileType::Dir, 37134e6d6c8Syuyi2439 ModeType::from_bits_truncate(0o555), 3726b4e7a29SLoGin )?; 373004e86ffSlogin // 创建相关文件 374004e86ffSlogin // status文件 37534e6d6c8Syuyi2439 let binding: Arc<dyn IndexNode> = pid_dir.create( 3766b4e7a29SLoGin "status", 3776b4e7a29SLoGin FileType::File, 37834e6d6c8Syuyi2439 ModeType::from_bits_truncate(0o444), 3796b4e7a29SLoGin )?; 38034e6d6c8Syuyi2439 let status_file: &LockedProcFSInode = binding 381004e86ffSlogin .as_any_ref() 382004e86ffSlogin .downcast_ref::<LockedProcFSInode>() 383004e86ffSlogin .unwrap(); 38434e6d6c8Syuyi2439 status_file.0.lock().fdata.pid = pid; 38534e6d6c8Syuyi2439 status_file.0.lock().fdata.ftype = ProcFileType::ProcStatus; 386004e86ffSlogin 387004e86ffSlogin //todo: 创建其他文件 388004e86ffSlogin 389004e86ffSlogin return Ok(()); 390004e86ffSlogin } 391004e86ffSlogin 392004e86ffSlogin /// @brief 解除进程注册 393004e86ffSlogin /// 3941496ba7bSLoGin pub fn unregister_pid(&self, pid: Pid) -> Result<(), SystemError> { 395004e86ffSlogin // 获取当前inode 396004e86ffSlogin let proc: Arc<dyn IndexNode> = self.root_inode(); 397004e86ffSlogin // 获取进程文件夹 3981496ba7bSLoGin let pid_dir: Arc<dyn IndexNode> = proc.find(&pid.to_string())?; 399004e86ffSlogin // 删除进程文件夹下文件 400004e86ffSlogin pid_dir.unlink("status")?; 401004e86ffSlogin 402004e86ffSlogin // 查看进程文件是否还存在 403004e86ffSlogin // let pf= pid_dir.find("status").expect("Cannot find status"); 404004e86ffSlogin 405004e86ffSlogin // 删除进程文件夹 4061496ba7bSLoGin proc.unlink(&pid.to_string())?; 407004e86ffSlogin 408004e86ffSlogin return Ok(()); 409004e86ffSlogin } 410004e86ffSlogin } 411004e86ffSlogin 412004e86ffSlogin impl IndexNode for LockedProcFSInode { 413676b8ef6SMork fn open(&self, data: &mut FilePrivateData, _mode: &FileMode) -> Result<(), SystemError> { 414004e86ffSlogin // 加锁 415004e86ffSlogin let mut inode: SpinLockGuard<ProcFSInode> = self.0.lock(); 416004e86ffSlogin 417004e86ffSlogin // 如果inode类型为文件夹,则直接返回成功 418004e86ffSlogin if let FileType::Dir = inode.metadata.file_type { 419004e86ffSlogin return Ok(()); 420004e86ffSlogin } 421004e86ffSlogin let mut private_data = ProcfsFilePrivateData::new(); 422004e86ffSlogin // 根据文件类型获取相应数据 423004e86ffSlogin let file_size = match inode.fdata.ftype { 424004e86ffSlogin ProcFileType::ProcStatus => inode.open_status(&mut private_data)?, 42534e6d6c8Syuyi2439 ProcFileType::ProcMeminfo => inode.open_meminfo(&mut private_data)?, 426004e86ffSlogin _ => { 427004e86ffSlogin todo!() 428004e86ffSlogin } 429004e86ffSlogin }; 430004e86ffSlogin *data = FilePrivateData::Procfs(private_data); 431004e86ffSlogin // 更新metadata里面的文件大小数值 432004e86ffSlogin inode.metadata.size = file_size; 433004e86ffSlogin 434004e86ffSlogin return Ok(()); 435004e86ffSlogin } 436004e86ffSlogin 437676b8ef6SMork fn close(&self, data: &mut FilePrivateData) -> Result<(), SystemError> { 438004e86ffSlogin let guard: SpinLockGuard<ProcFSInode> = self.0.lock(); 439004e86ffSlogin // 如果inode类型为文件夹,则直接返回成功 440004e86ffSlogin if let FileType::Dir = guard.metadata.file_type { 441004e86ffSlogin return Ok(()); 442004e86ffSlogin } 4431a72a751SLoGin // 释放data 4441a72a751SLoGin *data = FilePrivateData::Procfs(ProcfsFilePrivateData::new()); 4451a72a751SLoGin 446004e86ffSlogin return Ok(()); 447004e86ffSlogin } 448004e86ffSlogin 449004e86ffSlogin fn read_at( 450004e86ffSlogin &self, 451004e86ffSlogin offset: usize, 452004e86ffSlogin len: usize, 453004e86ffSlogin buf: &mut [u8], 454004e86ffSlogin data: &mut FilePrivateData, 455676b8ef6SMork ) -> Result<usize, SystemError> { 456004e86ffSlogin if buf.len() < len { 457676b8ef6SMork return Err(SystemError::EINVAL); 458004e86ffSlogin } 459004e86ffSlogin // 加锁 460004e86ffSlogin let inode: SpinLockGuard<ProcFSInode> = self.0.lock(); 461004e86ffSlogin 462004e86ffSlogin // 检查当前inode是否为一个文件夹,如果是的话,就返回错误 463004e86ffSlogin if inode.metadata.file_type == FileType::Dir { 464676b8ef6SMork return Err(SystemError::EISDIR); 465004e86ffSlogin } 466004e86ffSlogin 467004e86ffSlogin // 获取数据信息 468004e86ffSlogin let private_data = match data { 469004e86ffSlogin FilePrivateData::Procfs(p) => p, 470004e86ffSlogin _ => { 471004e86ffSlogin panic!("ProcFS: FilePrivateData mismatch!"); 472004e86ffSlogin } 473004e86ffSlogin }; 474004e86ffSlogin 475004e86ffSlogin // 根据文件类型读取相应数据 476004e86ffSlogin match inode.fdata.ftype { 47734e6d6c8Syuyi2439 ProcFileType::ProcStatus => return inode.proc_read(offset, len, buf, private_data), 47834e6d6c8Syuyi2439 ProcFileType::ProcMeminfo => return inode.proc_read(offset, len, buf, private_data), 4798d72b68dSJomo ProcFileType::ProcKmsg => (), 480004e86ffSlogin ProcFileType::Default => (), 481004e86ffSlogin }; 482004e86ffSlogin 483004e86ffSlogin // 默认读取 484004e86ffSlogin let start = inode.data.len().min(offset); 485004e86ffSlogin let end = inode.data.len().min(offset + len); 486004e86ffSlogin 487004e86ffSlogin // buffer空间不足 488004e86ffSlogin if buf.len() < (end - start) { 489676b8ef6SMork return Err(SystemError::ENOBUFS); 490004e86ffSlogin } 491004e86ffSlogin 492004e86ffSlogin // 拷贝数据 493004e86ffSlogin let src = &inode.data[start..end]; 494004e86ffSlogin buf[0..src.len()].copy_from_slice(src); 495004e86ffSlogin return Ok(src.len()); 496004e86ffSlogin } 497004e86ffSlogin 498004e86ffSlogin fn write_at( 499004e86ffSlogin &self, 500004e86ffSlogin _offset: usize, 501004e86ffSlogin _len: usize, 502004e86ffSlogin _buf: &[u8], 503004e86ffSlogin _data: &mut FilePrivateData, 504676b8ef6SMork ) -> Result<usize, SystemError> { 50579a452ceShoumkh return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP); 506004e86ffSlogin } 507004e86ffSlogin 508004e86ffSlogin fn fs(&self) -> Arc<dyn FileSystem> { 509004e86ffSlogin return self.0.lock().fs.upgrade().unwrap(); 510004e86ffSlogin } 511004e86ffSlogin 512004e86ffSlogin fn as_any_ref(&self) -> &dyn core::any::Any { 513004e86ffSlogin self 514004e86ffSlogin } 515004e86ffSlogin 516676b8ef6SMork fn metadata(&self) -> Result<Metadata, SystemError> { 517004e86ffSlogin let inode = self.0.lock(); 518004e86ffSlogin let metadata = inode.metadata.clone(); 519004e86ffSlogin 520004e86ffSlogin return Ok(metadata); 521004e86ffSlogin } 522004e86ffSlogin 523676b8ef6SMork fn set_metadata(&self, metadata: &Metadata) -> Result<(), SystemError> { 524004e86ffSlogin let mut inode = self.0.lock(); 525004e86ffSlogin inode.metadata.atime = metadata.atime; 526004e86ffSlogin inode.metadata.mtime = metadata.mtime; 527004e86ffSlogin inode.metadata.ctime = metadata.ctime; 528004e86ffSlogin inode.metadata.mode = metadata.mode; 529004e86ffSlogin inode.metadata.uid = metadata.uid; 530004e86ffSlogin inode.metadata.gid = metadata.gid; 531004e86ffSlogin 532004e86ffSlogin return Ok(()); 533004e86ffSlogin } 534004e86ffSlogin 535676b8ef6SMork fn resize(&self, len: usize) -> Result<(), SystemError> { 536004e86ffSlogin let mut inode = self.0.lock(); 537004e86ffSlogin if inode.metadata.file_type == FileType::File { 538004e86ffSlogin inode.data.resize(len, 0); 539004e86ffSlogin return Ok(()); 540004e86ffSlogin } else { 541676b8ef6SMork return Err(SystemError::EINVAL); 542004e86ffSlogin } 543004e86ffSlogin } 544004e86ffSlogin 545004e86ffSlogin fn create_with_data( 546004e86ffSlogin &self, 547004e86ffSlogin name: &str, 548004e86ffSlogin file_type: FileType, 5496b4e7a29SLoGin mode: ModeType, 550004e86ffSlogin data: usize, 551676b8ef6SMork ) -> Result<Arc<dyn IndexNode>, SystemError> { 552004e86ffSlogin // 获取当前inode 553004e86ffSlogin let mut inode = self.0.lock(); 554004e86ffSlogin // 如果当前inode不是文件夹,则返回 555004e86ffSlogin if inode.metadata.file_type != FileType::Dir { 556676b8ef6SMork return Err(SystemError::ENOTDIR); 557004e86ffSlogin } 558004e86ffSlogin // 如果有重名的,则返回 559004e86ffSlogin if inode.children.contains_key(name) { 560676b8ef6SMork return Err(SystemError::EEXIST); 561004e86ffSlogin } 562004e86ffSlogin 563004e86ffSlogin // 创建inode 564004e86ffSlogin let result: Arc<LockedProcFSInode> = 565004e86ffSlogin Arc::new(LockedProcFSInode(SpinLock::new(ProcFSInode { 566004e86ffSlogin parent: inode.self_ref.clone(), 567004e86ffSlogin self_ref: Weak::default(), 568004e86ffSlogin children: BTreeMap::new(), 569004e86ffSlogin data: Vec::new(), 570004e86ffSlogin metadata: Metadata { 571004e86ffSlogin dev_id: 0, 572004e86ffSlogin inode_id: generate_inode_id(), 573004e86ffSlogin size: 0, 574004e86ffSlogin blk_size: 0, 575004e86ffSlogin blocks: 0, 576004e86ffSlogin atime: TimeSpec::default(), 577004e86ffSlogin mtime: TimeSpec::default(), 578004e86ffSlogin ctime: TimeSpec::default(), 579004e86ffSlogin file_type: file_type, 580004e86ffSlogin mode: mode, 581004e86ffSlogin nlinks: 1, 582004e86ffSlogin uid: 0, 583004e86ffSlogin gid: 0, 58402343d0bSLoGin raw_dev: DeviceNumber::from(data as u32), 585004e86ffSlogin }, 586004e86ffSlogin fs: inode.fs.clone(), 587004e86ffSlogin fdata: InodeInfo { 5881496ba7bSLoGin pid: Pid::new(0), 589004e86ffSlogin ftype: ProcFileType::Default, 590004e86ffSlogin }, 591004e86ffSlogin }))); 592004e86ffSlogin 593004e86ffSlogin // 初始化inode的自引用的weak指针 594004e86ffSlogin result.0.lock().self_ref = Arc::downgrade(&result); 595004e86ffSlogin 596004e86ffSlogin // 将子inode插入父inode的B树中 597004e86ffSlogin inode.children.insert(String::from(name), result.clone()); 598004e86ffSlogin 599004e86ffSlogin return Ok(result); 600004e86ffSlogin } 601004e86ffSlogin 602676b8ef6SMork fn link(&self, name: &str, other: &Arc<dyn IndexNode>) -> Result<(), SystemError> { 603004e86ffSlogin let other: &LockedProcFSInode = other 604004e86ffSlogin .downcast_ref::<LockedProcFSInode>() 605676b8ef6SMork .ok_or(SystemError::EPERM)?; 606004e86ffSlogin let mut inode: SpinLockGuard<ProcFSInode> = self.0.lock(); 607004e86ffSlogin let mut other_locked: SpinLockGuard<ProcFSInode> = other.0.lock(); 608004e86ffSlogin 609004e86ffSlogin // 如果当前inode不是文件夹,那么报错 610004e86ffSlogin if inode.metadata.file_type != FileType::Dir { 611676b8ef6SMork return Err(SystemError::ENOTDIR); 612004e86ffSlogin } 613004e86ffSlogin 614004e86ffSlogin // 如果另一个inode是文件夹,那么也报错 615004e86ffSlogin if other_locked.metadata.file_type == FileType::Dir { 616676b8ef6SMork return Err(SystemError::EISDIR); 617004e86ffSlogin } 618004e86ffSlogin 619004e86ffSlogin // 如果当前文件夹下已经有同名文件,也报错。 620004e86ffSlogin if inode.children.contains_key(name) { 621676b8ef6SMork return Err(SystemError::EEXIST); 622004e86ffSlogin } 623004e86ffSlogin 624004e86ffSlogin inode 625004e86ffSlogin .children 626004e86ffSlogin .insert(String::from(name), other_locked.self_ref.upgrade().unwrap()); 627004e86ffSlogin 628004e86ffSlogin // 增加硬链接计数 629004e86ffSlogin other_locked.metadata.nlinks += 1; 630004e86ffSlogin return Ok(()); 631004e86ffSlogin } 632004e86ffSlogin 633676b8ef6SMork fn unlink(&self, name: &str) -> Result<(), SystemError> { 634004e86ffSlogin let mut inode: SpinLockGuard<ProcFSInode> = self.0.lock(); 635004e86ffSlogin // 如果当前inode不是目录,那么也没有子目录/文件的概念了,因此要求当前inode的类型是目录 636004e86ffSlogin if inode.metadata.file_type != FileType::Dir { 637676b8ef6SMork return Err(SystemError::ENOTDIR); 638004e86ffSlogin } 639*9e481b3bSTTaq 640004e86ffSlogin // 不允许删除当前文件夹,也不允许删除上一个目录 641004e86ffSlogin if name == "." || name == ".." { 642676b8ef6SMork return Err(SystemError::ENOTEMPTY); 643004e86ffSlogin } 644004e86ffSlogin 645004e86ffSlogin // 获得要删除的文件的inode 646676b8ef6SMork let to_delete = inode.children.get(name).ok_or(SystemError::ENOENT)?; 647*9e481b3bSTTaq 648004e86ffSlogin // 减少硬链接计数 649004e86ffSlogin to_delete.0.lock().metadata.nlinks -= 1; 650*9e481b3bSTTaq 651004e86ffSlogin // 在当前目录中删除这个子目录项 652004e86ffSlogin inode.children.remove(name); 653*9e481b3bSTTaq 654004e86ffSlogin return Ok(()); 655004e86ffSlogin } 656004e86ffSlogin 657*9e481b3bSTTaq fn move_to( 658004e86ffSlogin &self, 659004e86ffSlogin _old_name: &str, 660004e86ffSlogin _target: &Arc<dyn IndexNode>, 661004e86ffSlogin _new_name: &str, 662676b8ef6SMork ) -> Result<(), SystemError> { 66379a452ceShoumkh return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP); 664004e86ffSlogin } 665004e86ffSlogin 666676b8ef6SMork fn find(&self, name: &str) -> Result<Arc<dyn IndexNode>, SystemError> { 667004e86ffSlogin let inode = self.0.lock(); 668004e86ffSlogin 669004e86ffSlogin if inode.metadata.file_type != FileType::Dir { 670676b8ef6SMork return Err(SystemError::ENOTDIR); 671004e86ffSlogin } 672004e86ffSlogin 673004e86ffSlogin match name { 674004e86ffSlogin "" | "." => { 675676b8ef6SMork return Ok(inode.self_ref.upgrade().ok_or(SystemError::ENOENT)?); 676004e86ffSlogin } 677004e86ffSlogin 678004e86ffSlogin ".." => { 679676b8ef6SMork return Ok(inode.parent.upgrade().ok_or(SystemError::ENOENT)?); 680004e86ffSlogin } 681004e86ffSlogin name => { 682004e86ffSlogin // 在子目录项中查找 683676b8ef6SMork return Ok(inode.children.get(name).ok_or(SystemError::ENOENT)?.clone()); 684004e86ffSlogin } 685004e86ffSlogin } 686004e86ffSlogin } 687004e86ffSlogin 688676b8ef6SMork fn get_entry_name(&self, ino: InodeId) -> Result<String, SystemError> { 689004e86ffSlogin let inode: SpinLockGuard<ProcFSInode> = self.0.lock(); 690004e86ffSlogin if inode.metadata.file_type != FileType::Dir { 691676b8ef6SMork return Err(SystemError::ENOTDIR); 692004e86ffSlogin } 693004e86ffSlogin 6946b4e7a29SLoGin match ino.into() { 695004e86ffSlogin 0 => { 696004e86ffSlogin return Ok(String::from(".")); 697004e86ffSlogin } 698004e86ffSlogin 1 => { 699004e86ffSlogin return Ok(String::from("..")); 700004e86ffSlogin } 701004e86ffSlogin ino => { 702004e86ffSlogin // 暴力遍历所有的children,判断inode id是否相同 703004e86ffSlogin // TODO: 优化这里,这个地方性能很差! 704004e86ffSlogin let mut key: Vec<String> = inode 705004e86ffSlogin .children 706004e86ffSlogin .keys() 7076b4e7a29SLoGin .filter(|k| { 7086b4e7a29SLoGin inode 7096b4e7a29SLoGin .children 7106b4e7a29SLoGin .get(*k) 7116b4e7a29SLoGin .unwrap() 7126b4e7a29SLoGin .0 7136b4e7a29SLoGin .lock() 7146b4e7a29SLoGin .metadata 7156b4e7a29SLoGin .inode_id 7166b4e7a29SLoGin .into() 7176b4e7a29SLoGin == ino 7186b4e7a29SLoGin }) 719004e86ffSlogin .cloned() 720004e86ffSlogin .collect(); 721004e86ffSlogin 722004e86ffSlogin match key.len() { 723676b8ef6SMork 0=>{return Err(SystemError::ENOENT);} 724004e86ffSlogin 1=>{return Ok(key.remove(0));} 7256b4e7a29SLoGin _ => panic!("Procfs get_entry_name: key.len()={key_len}>1, current inode_id={inode_id:?}, to find={to_find:?}", key_len=key.len(), inode_id = inode.metadata.inode_id, to_find=ino) 726004e86ffSlogin } 727004e86ffSlogin } 728004e86ffSlogin } 729004e86ffSlogin } 730004e86ffSlogin 731676b8ef6SMork fn list(&self) -> Result<Vec<String>, SystemError> { 732004e86ffSlogin let info = self.metadata()?; 733004e86ffSlogin if info.file_type != FileType::Dir { 734676b8ef6SMork return Err(SystemError::ENOTDIR); 735004e86ffSlogin } 736004e86ffSlogin 737004e86ffSlogin let mut keys: Vec<String> = Vec::new(); 738004e86ffSlogin keys.push(String::from(".")); 739004e86ffSlogin keys.push(String::from("..")); 740004e86ffSlogin keys.append(&mut self.0.lock().children.keys().cloned().collect()); 741004e86ffSlogin 742004e86ffSlogin return Ok(keys); 743004e86ffSlogin } 744004e86ffSlogin } 745004e86ffSlogin 746004e86ffSlogin /// @brief 向procfs注册进程 7471496ba7bSLoGin pub fn procfs_register_pid(pid: Pid) -> Result<(), SystemError> { 748004e86ffSlogin let procfs_inode = ROOT_INODE().find("proc")?; 749004e86ffSlogin 750004e86ffSlogin let procfs_inode = procfs_inode 751004e86ffSlogin .downcast_ref::<LockedProcFSInode>() 752004e86ffSlogin .expect("Failed to find procfs' root inode"); 753004e86ffSlogin let fs = procfs_inode.fs(); 754004e86ffSlogin let procfs: &ProcFS = fs.as_any_ref().downcast_ref::<ProcFS>().unwrap(); 755004e86ffSlogin 756004e86ffSlogin // 调用注册函数 757004e86ffSlogin procfs.register_pid(pid)?; 758004e86ffSlogin 759004e86ffSlogin return Ok(()); 760004e86ffSlogin } 761004e86ffSlogin 762004e86ffSlogin /// @brief 在ProcFS中,解除进程的注册 7631496ba7bSLoGin pub fn procfs_unregister_pid(pid: Pid) -> Result<(), SystemError> { 764004e86ffSlogin // 获取procfs实例 765004e86ffSlogin let procfs_inode: Arc<dyn IndexNode> = ROOT_INODE().find("proc")?; 766004e86ffSlogin 767004e86ffSlogin let procfs_inode: &LockedProcFSInode = procfs_inode 768004e86ffSlogin .downcast_ref::<LockedProcFSInode>() 769004e86ffSlogin .expect("Failed to find procfs' root inode"); 770004e86ffSlogin let fs: Arc<dyn FileSystem> = procfs_inode.fs(); 771004e86ffSlogin let procfs: &ProcFS = fs.as_any_ref().downcast_ref::<ProcFS>().unwrap(); 772004e86ffSlogin 773004e86ffSlogin // 调用解除注册函数 774004e86ffSlogin return procfs.unregister_pid(pid); 775004e86ffSlogin } 776b087521eSChiichen 777b087521eSChiichen pub fn procfs_init() -> Result<(), SystemError> { 778b087521eSChiichen static INIT: Once = Once::new(); 779b087521eSChiichen let mut result = None; 780b087521eSChiichen INIT.call_once(|| { 781b087521eSChiichen kinfo!("Initializing ProcFS..."); 78234e6d6c8Syuyi2439 // 创建 procfs 实例 783b087521eSChiichen let procfs: Arc<ProcFS> = ProcFS::new(); 784b087521eSChiichen 78534e6d6c8Syuyi2439 // procfs 挂载 786b087521eSChiichen let _t = ROOT_INODE() 787b087521eSChiichen .find("proc") 788b087521eSChiichen .expect("Cannot find /proc") 789b087521eSChiichen .mount(procfs) 790b087521eSChiichen .expect("Failed to mount proc"); 791b087521eSChiichen kinfo!("ProcFS mounted."); 792b087521eSChiichen result = Some(Ok(())); 793b087521eSChiichen }); 794b087521eSChiichen 795b087521eSChiichen return result.unwrap(); 796b087521eSChiichen } 797