1004e86ffSlogin use core::intrinsics::size_of; 206b09f34Skong 3004e86ffSlogin use alloc::{ 4004e86ffSlogin borrow::ToOwned, 5004e86ffSlogin collections::BTreeMap, 6004e86ffSlogin format, 7b5b571e0SLoGin string::{String, ToString}, 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, 23597ecc08STTaq rwlock::RwLock, 24b087521eSChiichen spinlock::{SpinLock, SpinLockGuard}, 25b087521eSChiichen }, 264fda81ceSLoGin mm::allocator::page_frame::FrameAllocator, 271496ba7bSLoGin process::{Pid, ProcessManager}, 2878bf93f0SYJwu2023 time::TimeSpec, 29004e86ffSlogin }; 30004e86ffSlogin 31004e86ffSlogin use super::vfs::{ 3278bf93f0SYJwu2023 file::{FileMode, FilePrivateData}, 336b4e7a29SLoGin syscall::ModeType, 34597ecc08STTaq FileSystem, FsInfo, IndexNode, InodeId, Magic, Metadata, SuperBlock, 35004e86ffSlogin }; 36004e86ffSlogin 378d72b68dSJomo pub mod kmsg; 388d72b68dSJomo pub mod log; 398d72b68dSJomo mod syscall; 408d72b68dSJomo 41004e86ffSlogin /// @brief 进程文件类型 42004e86ffSlogin /// @usage 用于定义进程文件夹下的各类文件类型 43004e86ffSlogin #[derive(Debug)] 44004e86ffSlogin #[repr(u8)] 45004e86ffSlogin pub enum ProcFileType { 46004e86ffSlogin ///展示进程状态信息 47004e86ffSlogin ProcStatus = 0, 4834e6d6c8Syuyi2439 /// meminfo 4934e6d6c8Syuyi2439 ProcMeminfo = 1, 508d72b68dSJomo /// kmsg 518d72b68dSJomo ProcKmsg = 2, 52004e86ffSlogin //todo: 其他文件类型 53004e86ffSlogin ///默认文件类型 54004e86ffSlogin Default, 55004e86ffSlogin } 56004e86ffSlogin 57004e86ffSlogin impl From<u8> for ProcFileType { 58004e86ffSlogin fn from(value: u8) -> Self { 59004e86ffSlogin match value { 60004e86ffSlogin 0 => ProcFileType::ProcStatus, 6134e6d6c8Syuyi2439 1 => ProcFileType::ProcMeminfo, 628d72b68dSJomo 2 => ProcFileType::ProcKmsg, 63004e86ffSlogin _ => ProcFileType::Default, 64004e86ffSlogin } 65004e86ffSlogin } 66004e86ffSlogin } 67004e86ffSlogin /// @brief 节点私有信息结构体 68004e86ffSlogin /// @usage 用于传入各类文件所需的信息 69004e86ffSlogin #[derive(Debug)] 70004e86ffSlogin pub struct InodeInfo { 71004e86ffSlogin ///进程的pid 721496ba7bSLoGin pid: Pid, 73004e86ffSlogin ///文件类型 74004e86ffSlogin ftype: ProcFileType, 75004e86ffSlogin //其他需要传入的信息在此定义 76004e86ffSlogin } 77004e86ffSlogin 78004e86ffSlogin /// @brief procfs的inode名称的最大长度 79004e86ffSlogin const PROCFS_MAX_NAMELEN: usize = 64; 80597ecc08STTaq const PROCFS_BLOCK_SIZE: u64 = 512; 81004e86ffSlogin /// @brief procfs文件系统的Inode结构体 82004e86ffSlogin #[derive(Debug)] 83004e86ffSlogin pub struct LockedProcFSInode(SpinLock<ProcFSInode>); 84004e86ffSlogin 85004e86ffSlogin /// @brief procfs文件系统结构体 86004e86ffSlogin #[derive(Debug)] 87004e86ffSlogin pub struct ProcFS { 88004e86ffSlogin /// procfs的root inode 89004e86ffSlogin root_inode: Arc<LockedProcFSInode>, 90597ecc08STTaq super_block: RwLock<SuperBlock>, 91004e86ffSlogin } 92004e86ffSlogin 93004e86ffSlogin #[derive(Debug, Clone)] 94004e86ffSlogin pub struct ProcfsFilePrivateData { 95004e86ffSlogin data: Vec<u8>, 96004e86ffSlogin } 97004e86ffSlogin 98004e86ffSlogin impl ProcfsFilePrivateData { 99004e86ffSlogin pub fn new() -> Self { 100004e86ffSlogin return ProcfsFilePrivateData { data: Vec::new() }; 101004e86ffSlogin } 102004e86ffSlogin } 103004e86ffSlogin 104b5b571e0SLoGin impl Default for ProcfsFilePrivateData { 105b5b571e0SLoGin fn default() -> Self { 106b5b571e0SLoGin Self::new() 107b5b571e0SLoGin } 108b5b571e0SLoGin } 109b5b571e0SLoGin 110004e86ffSlogin /// @brief procfs文件系统的Inode结构体(不包含锁) 111004e86ffSlogin #[derive(Debug)] 112004e86ffSlogin pub struct ProcFSInode { 113004e86ffSlogin /// 指向父Inode的弱引用 114004e86ffSlogin parent: Weak<LockedProcFSInode>, 115004e86ffSlogin /// 指向自身的弱引用 116004e86ffSlogin self_ref: Weak<LockedProcFSInode>, 117004e86ffSlogin /// 子Inode的B树 118004e86ffSlogin children: BTreeMap<String, Arc<LockedProcFSInode>>, 119004e86ffSlogin /// 当前inode的数据部分 120004e86ffSlogin data: Vec<u8>, 121004e86ffSlogin /// 当前inode的元数据 122004e86ffSlogin metadata: Metadata, 123004e86ffSlogin /// 指向inode所在的文件系统对象的指针 124004e86ffSlogin fs: Weak<ProcFS>, 125004e86ffSlogin /// 储存私有信息 126004e86ffSlogin fdata: InodeInfo, 127004e86ffSlogin } 128004e86ffSlogin 129004e86ffSlogin /// 对ProcFSInode实现获取各类文件信息的函数 130004e86ffSlogin impl ProcFSInode { 131004e86ffSlogin /// @brief 去除Vec中所有的\0,并在结尾添加\0 132004e86ffSlogin #[inline] 133004e86ffSlogin fn trim_string(&self, data: &mut Vec<u8>) { 1341a72a751SLoGin data.retain(|x| *x != 0); 1351a72a751SLoGin 136004e86ffSlogin data.push(0); 137004e86ffSlogin } 138004e86ffSlogin // todo:其他数据获取函数实现 139004e86ffSlogin 140004e86ffSlogin /// @brief 打开status文件 141004e86ffSlogin /// 142676b8ef6SMork fn open_status(&self, pdata: &mut ProcfsFilePrivateData) -> Result<i64, SystemError> { 143004e86ffSlogin // 获取该pid对应的pcb结构体 1441496ba7bSLoGin let pid = self.fdata.pid; 1451496ba7bSLoGin let pcb = ProcessManager::find(pid); 146b5b571e0SLoGin let pcb = if let Some(pcb) = pcb { 147b5b571e0SLoGin pcb 148b5b571e0SLoGin } else { 149004e86ffSlogin kerror!( 1501496ba7bSLoGin "ProcFS: Cannot find pcb for pid {:?} when opening its 'status' file.", 151004e86ffSlogin pid 152004e86ffSlogin ); 153676b8ef6SMork return Err(SystemError::ESRCH); 154004e86ffSlogin }; 155004e86ffSlogin // 传入数据 156004e86ffSlogin let pdata: &mut Vec<u8> = &mut pdata.data; 157004e86ffSlogin 158004e86ffSlogin pdata.append( 1591496ba7bSLoGin &mut format!("Name:\t{}", pcb.basic().name()) 160004e86ffSlogin .as_bytes() 161004e86ffSlogin .to_owned(), 162004e86ffSlogin ); 163004e86ffSlogin 1641496ba7bSLoGin let sched_info_guard = pcb.sched_info(); 1650d6cf65aSLoGin let state = sched_info_guard.inner_lock_read_irqsave().state(); 1661496ba7bSLoGin let cpu_id = sched_info_guard 1671496ba7bSLoGin .on_cpu() 168e2841179SLoGin .map(|cpu| cpu.data() as i32) 1691496ba7bSLoGin .unwrap_or(-1); 1701496ba7bSLoGin 171*f0c87a89SGnoCiYeH let priority = sched_info_guard.policy(); 172*f0c87a89SGnoCiYeH let vrtime = sched_info_guard.sched_entity.vruntime; 1731496ba7bSLoGin 1741496ba7bSLoGin pdata.append(&mut format!("\nState:\t{:?}", state).as_bytes().to_owned()); 1751496ba7bSLoGin pdata.append( 1761496ba7bSLoGin &mut format!("\nPid:\t{}", pcb.pid().into()) 1771496ba7bSLoGin .as_bytes() 1781496ba7bSLoGin .to_owned(), 1791496ba7bSLoGin ); 1801496ba7bSLoGin pdata.append( 1811496ba7bSLoGin &mut format!("\nPpid:\t{}", pcb.basic().ppid().into()) 1821496ba7bSLoGin .as_bytes() 1831496ba7bSLoGin .to_owned(), 1841496ba7bSLoGin ); 1851496ba7bSLoGin pdata.append(&mut format!("\ncpu_id:\t{}", cpu_id).as_bytes().to_owned()); 186*f0c87a89SGnoCiYeH pdata.append(&mut format!("\npriority:\t{:?}", priority).as_bytes().to_owned()); 1871496ba7bSLoGin pdata.append( 1881496ba7bSLoGin &mut format!("\npreempt:\t{}", pcb.preempt_count()) 1891496ba7bSLoGin .as_bytes() 1901496ba7bSLoGin .to_owned(), 1911496ba7bSLoGin ); 1921496ba7bSLoGin pdata.append(&mut format!("\nvrtime:\t{}", vrtime).as_bytes().to_owned()); 1931496ba7bSLoGin 1947b32f508SLoGin if let Some(user_vm) = pcb.basic().user_vm() { 1957b32f508SLoGin let address_space_guard = user_vm.read(); 19640fe15e0SLoGin // todo: 当前进程运行过程中占用内存的峰值 19740fe15e0SLoGin let hiwater_vm: u64 = 0; 19840fe15e0SLoGin // 进程代码段的大小 19940fe15e0SLoGin let text = (address_space_guard.end_code - address_space_guard.start_code) / 1024; 200004e86ffSlogin // 进程数据段的大小 20140fe15e0SLoGin let data = (address_space_guard.end_data - address_space_guard.start_data) / 1024; 20240fe15e0SLoGin drop(address_space_guard); 203004e86ffSlogin pdata.append( 204004e86ffSlogin &mut format!("\nVmPeak:\t{} kB", hiwater_vm) 205004e86ffSlogin .as_bytes() 206004e86ffSlogin .to_owned(), 207004e86ffSlogin ); 208004e86ffSlogin pdata.append(&mut format!("\nVmData:\t{} kB", data).as_bytes().to_owned()); 2091496ba7bSLoGin pdata.append(&mut format!("\nVmExe:\t{} kB", text).as_bytes().to_owned()); 2107b32f508SLoGin } 2117b32f508SLoGin 2121496ba7bSLoGin pdata.append( 2131496ba7bSLoGin &mut format!("\nflags: {:?}\n", pcb.flags().clone()) 2141496ba7bSLoGin .as_bytes() 2151496ba7bSLoGin .to_owned(), 2161496ba7bSLoGin ); 217004e86ffSlogin 218004e86ffSlogin // 去除多余的\0 219004e86ffSlogin self.trim_string(pdata); 220004e86ffSlogin 221004e86ffSlogin return Ok((pdata.len() * size_of::<u8>()) as i64); 222004e86ffSlogin } 223004e86ffSlogin 22434e6d6c8Syuyi2439 /// 打开 meminfo 文件 22534e6d6c8Syuyi2439 fn open_meminfo(&self, pdata: &mut ProcfsFilePrivateData) -> Result<i64, SystemError> { 22634e6d6c8Syuyi2439 // 获取内存信息 2274fda81ceSLoGin let usage = unsafe { LockedFrameAllocator.usage() }; 22834e6d6c8Syuyi2439 22934e6d6c8Syuyi2439 // 传入数据 23034e6d6c8Syuyi2439 let data: &mut Vec<u8> = &mut pdata.data; 23134e6d6c8Syuyi2439 23234e6d6c8Syuyi2439 data.append( 23334e6d6c8Syuyi2439 &mut format!("MemTotal:\t{} kB\n", usage.total().bytes() >> 10) 23434e6d6c8Syuyi2439 .as_bytes() 23534e6d6c8Syuyi2439 .to_owned(), 23634e6d6c8Syuyi2439 ); 23734e6d6c8Syuyi2439 23834e6d6c8Syuyi2439 data.append( 23934e6d6c8Syuyi2439 &mut format!("MemFree:\t{} kB\n", usage.free().bytes() >> 10) 24034e6d6c8Syuyi2439 .as_bytes() 24134e6d6c8Syuyi2439 .to_owned(), 24234e6d6c8Syuyi2439 ); 24334e6d6c8Syuyi2439 24434e6d6c8Syuyi2439 // 去除多余的\0 24534e6d6c8Syuyi2439 self.trim_string(data); 24634e6d6c8Syuyi2439 24734e6d6c8Syuyi2439 return Ok((data.len() * size_of::<u8>()) as i64); 24834e6d6c8Syuyi2439 } 24934e6d6c8Syuyi2439 25034e6d6c8Syuyi2439 /// proc文件系统读取函数 25134e6d6c8Syuyi2439 fn proc_read( 252004e86ffSlogin &self, 253004e86ffSlogin offset: usize, 254004e86ffSlogin len: usize, 255004e86ffSlogin buf: &mut [u8], 2569430523bSyuyi2439 pdata: &mut ProcfsFilePrivateData, 257676b8ef6SMork ) -> Result<usize, SystemError> { 2589430523bSyuyi2439 let start = pdata.data.len().min(offset); 2599430523bSyuyi2439 let end = pdata.data.len().min(offset + len); 260004e86ffSlogin 261004e86ffSlogin // buffer空间不足 262004e86ffSlogin if buf.len() < (end - start) { 263676b8ef6SMork return Err(SystemError::ENOBUFS); 264004e86ffSlogin } 265004e86ffSlogin 266004e86ffSlogin // 拷贝数据 2679430523bSyuyi2439 let src = &pdata.data[start..end]; 268004e86ffSlogin buf[0..src.len()].copy_from_slice(src); 269004e86ffSlogin return Ok(src.len()); 270004e86ffSlogin } 271004e86ffSlogin } 272004e86ffSlogin 273004e86ffSlogin impl FileSystem for ProcFS { 274004e86ffSlogin fn root_inode(&self) -> Arc<dyn super::vfs::IndexNode> { 275004e86ffSlogin return self.root_inode.clone(); 276004e86ffSlogin } 277004e86ffSlogin 278004e86ffSlogin fn info(&self) -> FsInfo { 279004e86ffSlogin return FsInfo { 280004e86ffSlogin blk_dev_id: 0, 281004e86ffSlogin max_name_len: PROCFS_MAX_NAMELEN, 282004e86ffSlogin }; 283004e86ffSlogin } 284004e86ffSlogin 285004e86ffSlogin fn as_any_ref(&self) -> &dyn core::any::Any { 286004e86ffSlogin self 287004e86ffSlogin } 2881d37ca6dSDonkey Kane fn name(&self) -> &str { 2891d37ca6dSDonkey Kane "procfs" 2901d37ca6dSDonkey Kane } 291597ecc08STTaq 292597ecc08STTaq fn super_block(&self) -> SuperBlock { 293597ecc08STTaq self.super_block.read().clone() 294597ecc08STTaq } 295004e86ffSlogin } 296004e86ffSlogin 297004e86ffSlogin impl ProcFS { 298004e86ffSlogin pub fn new() -> Arc<Self> { 299597ecc08STTaq let super_block = SuperBlock::new( 300597ecc08STTaq Magic::PROC_MAGIC, 301597ecc08STTaq PROCFS_BLOCK_SIZE, 302597ecc08STTaq PROCFS_MAX_NAMELEN as u64, 303597ecc08STTaq ); 304004e86ffSlogin // 初始化root inode 305004e86ffSlogin let root: Arc<LockedProcFSInode> = 306004e86ffSlogin Arc::new(LockedProcFSInode(SpinLock::new(ProcFSInode { 307004e86ffSlogin parent: Weak::default(), 308004e86ffSlogin self_ref: Weak::default(), 309004e86ffSlogin children: BTreeMap::new(), 310004e86ffSlogin data: Vec::new(), 311004e86ffSlogin metadata: Metadata { 312004e86ffSlogin dev_id: 0, 313004e86ffSlogin inode_id: generate_inode_id(), 314004e86ffSlogin size: 0, 315004e86ffSlogin blk_size: 0, 316004e86ffSlogin blocks: 0, 317004e86ffSlogin atime: TimeSpec::default(), 318004e86ffSlogin mtime: TimeSpec::default(), 319004e86ffSlogin ctime: TimeSpec::default(), 320004e86ffSlogin file_type: FileType::Dir, 32134e6d6c8Syuyi2439 mode: ModeType::from_bits_truncate(0o555), 322004e86ffSlogin nlinks: 1, 323004e86ffSlogin uid: 0, 324004e86ffSlogin gid: 0, 32502343d0bSLoGin raw_dev: DeviceNumber::default(), 326004e86ffSlogin }, 327004e86ffSlogin fs: Weak::default(), 328004e86ffSlogin fdata: InodeInfo { 3291496ba7bSLoGin pid: Pid::new(0), 330004e86ffSlogin ftype: ProcFileType::Default, 331004e86ffSlogin }, 332004e86ffSlogin }))); 333004e86ffSlogin 334597ecc08STTaq let result: Arc<ProcFS> = Arc::new(ProcFS { 335597ecc08STTaq root_inode: root, 336597ecc08STTaq super_block: RwLock::new(super_block), 337597ecc08STTaq }); 338004e86ffSlogin 339004e86ffSlogin // 对root inode加锁,并继续完成初始化工作 340004e86ffSlogin let mut root_guard: SpinLockGuard<ProcFSInode> = result.root_inode.0.lock(); 341004e86ffSlogin root_guard.parent = Arc::downgrade(&result.root_inode); 342004e86ffSlogin root_guard.self_ref = Arc::downgrade(&result.root_inode); 343004e86ffSlogin root_guard.fs = Arc::downgrade(&result); 344004e86ffSlogin // 释放锁 345004e86ffSlogin drop(root_guard); 346004e86ffSlogin 34734e6d6c8Syuyi2439 // 创建meminfo文件 34834e6d6c8Syuyi2439 let inode = result.root_inode(); 34934e6d6c8Syuyi2439 let binding = inode.create( 35034e6d6c8Syuyi2439 "meminfo", 35134e6d6c8Syuyi2439 FileType::File, 35234e6d6c8Syuyi2439 ModeType::from_bits_truncate(0o444), 35334e6d6c8Syuyi2439 ); 35434e6d6c8Syuyi2439 if let Ok(meminfo) = binding { 35534e6d6c8Syuyi2439 let meminfo_file = meminfo 35634e6d6c8Syuyi2439 .as_any_ref() 35734e6d6c8Syuyi2439 .downcast_ref::<LockedProcFSInode>() 35834e6d6c8Syuyi2439 .unwrap(); 35934e6d6c8Syuyi2439 meminfo_file.0.lock().fdata.pid = Pid::new(0); 36034e6d6c8Syuyi2439 meminfo_file.0.lock().fdata.ftype = ProcFileType::ProcMeminfo; 36134e6d6c8Syuyi2439 } else { 36234e6d6c8Syuyi2439 panic!("create meminfo error"); 36334e6d6c8Syuyi2439 } 36434e6d6c8Syuyi2439 3658d72b68dSJomo // 创建kmsg文件 3668d72b68dSJomo let binding = inode.create("kmsg", FileType::File, ModeType::from_bits_truncate(0o444)); 3678d72b68dSJomo if let Ok(kmsg) = binding { 3688d72b68dSJomo let kmsg_file = kmsg 3698d72b68dSJomo .as_any_ref() 3708d72b68dSJomo .downcast_ref::<LockedProcFSInode>() 3718d72b68dSJomo .unwrap(); 3728d72b68dSJomo kmsg_file.0.lock().fdata.pid = Pid::new(1); 3738d72b68dSJomo kmsg_file.0.lock().fdata.ftype = ProcFileType::ProcKmsg; 3748d72b68dSJomo } else { 3758d72b68dSJomo panic!("create ksmg error"); 3768d72b68dSJomo } 3778d72b68dSJomo 378004e86ffSlogin return result; 379004e86ffSlogin } 380004e86ffSlogin 381004e86ffSlogin /// @brief 进程注册函数 382004e86ffSlogin /// @usage 在进程中调用并创建进程对应文件 3831496ba7bSLoGin pub fn register_pid(&self, pid: Pid) -> Result<(), SystemError> { 384004e86ffSlogin // 获取当前inode 38534e6d6c8Syuyi2439 let inode: Arc<dyn IndexNode> = self.root_inode(); 386004e86ffSlogin // 创建对应进程文件夹 38734e6d6c8Syuyi2439 let pid_dir: Arc<dyn IndexNode> = inode.create( 3886b4e7a29SLoGin &pid.to_string(), 3896b4e7a29SLoGin FileType::Dir, 39034e6d6c8Syuyi2439 ModeType::from_bits_truncate(0o555), 3916b4e7a29SLoGin )?; 392004e86ffSlogin // 创建相关文件 393004e86ffSlogin // status文件 39434e6d6c8Syuyi2439 let binding: Arc<dyn IndexNode> = pid_dir.create( 3956b4e7a29SLoGin "status", 3966b4e7a29SLoGin FileType::File, 39734e6d6c8Syuyi2439 ModeType::from_bits_truncate(0o444), 3986b4e7a29SLoGin )?; 39934e6d6c8Syuyi2439 let status_file: &LockedProcFSInode = binding 400004e86ffSlogin .as_any_ref() 401004e86ffSlogin .downcast_ref::<LockedProcFSInode>() 402004e86ffSlogin .unwrap(); 40334e6d6c8Syuyi2439 status_file.0.lock().fdata.pid = pid; 40434e6d6c8Syuyi2439 status_file.0.lock().fdata.ftype = ProcFileType::ProcStatus; 405004e86ffSlogin 406004e86ffSlogin //todo: 创建其他文件 407004e86ffSlogin 408004e86ffSlogin return Ok(()); 409004e86ffSlogin } 410004e86ffSlogin 411004e86ffSlogin /// @brief 解除进程注册 412004e86ffSlogin /// 4131496ba7bSLoGin pub fn unregister_pid(&self, pid: Pid) -> Result<(), SystemError> { 414004e86ffSlogin // 获取当前inode 415004e86ffSlogin let proc: Arc<dyn IndexNode> = self.root_inode(); 416004e86ffSlogin // 获取进程文件夹 4171496ba7bSLoGin let pid_dir: Arc<dyn IndexNode> = proc.find(&pid.to_string())?; 418004e86ffSlogin // 删除进程文件夹下文件 419004e86ffSlogin pid_dir.unlink("status")?; 420004e86ffSlogin 421004e86ffSlogin // 查看进程文件是否还存在 422004e86ffSlogin // let pf= pid_dir.find("status").expect("Cannot find status"); 423004e86ffSlogin 424004e86ffSlogin // 删除进程文件夹 4251496ba7bSLoGin proc.unlink(&pid.to_string())?; 426004e86ffSlogin 427004e86ffSlogin return Ok(()); 428004e86ffSlogin } 429004e86ffSlogin } 430004e86ffSlogin 431004e86ffSlogin impl IndexNode for LockedProcFSInode { 432dfe53cf0SGnoCiYeH fn open( 433dfe53cf0SGnoCiYeH &self, 434dfe53cf0SGnoCiYeH mut data: SpinLockGuard<FilePrivateData>, 435dfe53cf0SGnoCiYeH _mode: &FileMode, 436dfe53cf0SGnoCiYeH ) -> Result<(), SystemError> { 437004e86ffSlogin // 加锁 438004e86ffSlogin let mut inode: SpinLockGuard<ProcFSInode> = self.0.lock(); 439004e86ffSlogin 440004e86ffSlogin // 如果inode类型为文件夹,则直接返回成功 441004e86ffSlogin if let FileType::Dir = inode.metadata.file_type { 442004e86ffSlogin return Ok(()); 443004e86ffSlogin } 444004e86ffSlogin let mut private_data = ProcfsFilePrivateData::new(); 445004e86ffSlogin // 根据文件类型获取相应数据 446004e86ffSlogin let file_size = match inode.fdata.ftype { 447004e86ffSlogin ProcFileType::ProcStatus => inode.open_status(&mut private_data)?, 44834e6d6c8Syuyi2439 ProcFileType::ProcMeminfo => inode.open_meminfo(&mut private_data)?, 449004e86ffSlogin _ => { 450004e86ffSlogin todo!() 451004e86ffSlogin } 452004e86ffSlogin }; 453004e86ffSlogin *data = FilePrivateData::Procfs(private_data); 454004e86ffSlogin // 更新metadata里面的文件大小数值 455004e86ffSlogin inode.metadata.size = file_size; 456004e86ffSlogin 457004e86ffSlogin return Ok(()); 458004e86ffSlogin } 459004e86ffSlogin 460dfe53cf0SGnoCiYeH fn close(&self, mut data: SpinLockGuard<FilePrivateData>) -> Result<(), SystemError> { 461004e86ffSlogin let guard: SpinLockGuard<ProcFSInode> = self.0.lock(); 462004e86ffSlogin // 如果inode类型为文件夹,则直接返回成功 463004e86ffSlogin if let FileType::Dir = guard.metadata.file_type { 464004e86ffSlogin return Ok(()); 465004e86ffSlogin } 4661a72a751SLoGin // 释放data 4671a72a751SLoGin *data = FilePrivateData::Procfs(ProcfsFilePrivateData::new()); 4681a72a751SLoGin 469004e86ffSlogin return Ok(()); 470004e86ffSlogin } 471004e86ffSlogin 472004e86ffSlogin fn read_at( 473004e86ffSlogin &self, 474004e86ffSlogin offset: usize, 475004e86ffSlogin len: usize, 476004e86ffSlogin buf: &mut [u8], 477dfe53cf0SGnoCiYeH data: SpinLockGuard<FilePrivateData>, 478676b8ef6SMork ) -> Result<usize, SystemError> { 479004e86ffSlogin if buf.len() < len { 480676b8ef6SMork return Err(SystemError::EINVAL); 481004e86ffSlogin } 482004e86ffSlogin // 加锁 483004e86ffSlogin let inode: SpinLockGuard<ProcFSInode> = self.0.lock(); 484004e86ffSlogin 485004e86ffSlogin // 检查当前inode是否为一个文件夹,如果是的话,就返回错误 486004e86ffSlogin if inode.metadata.file_type == FileType::Dir { 487676b8ef6SMork return Err(SystemError::EISDIR); 488004e86ffSlogin } 489004e86ffSlogin 490004e86ffSlogin // 获取数据信息 491dfe53cf0SGnoCiYeH let mut private_data = match &*data { 492dfe53cf0SGnoCiYeH FilePrivateData::Procfs(p) => p.clone(), 493004e86ffSlogin _ => { 494004e86ffSlogin panic!("ProcFS: FilePrivateData mismatch!"); 495004e86ffSlogin } 496004e86ffSlogin }; 497004e86ffSlogin 498004e86ffSlogin // 根据文件类型读取相应数据 499004e86ffSlogin match inode.fdata.ftype { 500dfe53cf0SGnoCiYeH ProcFileType::ProcStatus => { 501dfe53cf0SGnoCiYeH return inode.proc_read(offset, len, buf, &mut private_data) 502dfe53cf0SGnoCiYeH } 503dfe53cf0SGnoCiYeH ProcFileType::ProcMeminfo => { 504dfe53cf0SGnoCiYeH return inode.proc_read(offset, len, buf, &mut private_data) 505dfe53cf0SGnoCiYeH } 5068d72b68dSJomo ProcFileType::ProcKmsg => (), 507004e86ffSlogin ProcFileType::Default => (), 508004e86ffSlogin }; 509004e86ffSlogin 510004e86ffSlogin // 默认读取 511004e86ffSlogin let start = inode.data.len().min(offset); 512004e86ffSlogin let end = inode.data.len().min(offset + len); 513004e86ffSlogin 514004e86ffSlogin // buffer空间不足 515004e86ffSlogin if buf.len() < (end - start) { 516676b8ef6SMork return Err(SystemError::ENOBUFS); 517004e86ffSlogin } 518004e86ffSlogin 519004e86ffSlogin // 拷贝数据 520004e86ffSlogin let src = &inode.data[start..end]; 521004e86ffSlogin buf[0..src.len()].copy_from_slice(src); 522004e86ffSlogin return Ok(src.len()); 523004e86ffSlogin } 524004e86ffSlogin 525004e86ffSlogin fn write_at( 526004e86ffSlogin &self, 527004e86ffSlogin _offset: usize, 528004e86ffSlogin _len: usize, 529004e86ffSlogin _buf: &[u8], 530dfe53cf0SGnoCiYeH _data: SpinLockGuard<FilePrivateData>, 531676b8ef6SMork ) -> Result<usize, SystemError> { 53279a452ceShoumkh return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP); 533004e86ffSlogin } 534004e86ffSlogin 535004e86ffSlogin fn fs(&self) -> Arc<dyn FileSystem> { 536004e86ffSlogin return self.0.lock().fs.upgrade().unwrap(); 537004e86ffSlogin } 538004e86ffSlogin 539004e86ffSlogin fn as_any_ref(&self) -> &dyn core::any::Any { 540004e86ffSlogin self 541004e86ffSlogin } 542004e86ffSlogin 543676b8ef6SMork fn metadata(&self) -> Result<Metadata, SystemError> { 544004e86ffSlogin let inode = self.0.lock(); 545004e86ffSlogin let metadata = inode.metadata.clone(); 546004e86ffSlogin 547004e86ffSlogin return Ok(metadata); 548004e86ffSlogin } 549004e86ffSlogin 550676b8ef6SMork fn set_metadata(&self, metadata: &Metadata) -> Result<(), SystemError> { 551004e86ffSlogin let mut inode = self.0.lock(); 552004e86ffSlogin inode.metadata.atime = metadata.atime; 553004e86ffSlogin inode.metadata.mtime = metadata.mtime; 554004e86ffSlogin inode.metadata.ctime = metadata.ctime; 555004e86ffSlogin inode.metadata.mode = metadata.mode; 556004e86ffSlogin inode.metadata.uid = metadata.uid; 557004e86ffSlogin inode.metadata.gid = metadata.gid; 558004e86ffSlogin 559004e86ffSlogin return Ok(()); 560004e86ffSlogin } 561004e86ffSlogin 562676b8ef6SMork fn resize(&self, len: usize) -> Result<(), SystemError> { 563004e86ffSlogin let mut inode = self.0.lock(); 564004e86ffSlogin if inode.metadata.file_type == FileType::File { 565004e86ffSlogin inode.data.resize(len, 0); 566004e86ffSlogin return Ok(()); 567004e86ffSlogin } else { 568676b8ef6SMork return Err(SystemError::EINVAL); 569004e86ffSlogin } 570004e86ffSlogin } 571004e86ffSlogin 572004e86ffSlogin fn create_with_data( 573004e86ffSlogin &self, 574004e86ffSlogin name: &str, 575004e86ffSlogin file_type: FileType, 5766b4e7a29SLoGin mode: ModeType, 577004e86ffSlogin data: usize, 578676b8ef6SMork ) -> Result<Arc<dyn IndexNode>, SystemError> { 579004e86ffSlogin // 获取当前inode 580004e86ffSlogin let mut inode = self.0.lock(); 581004e86ffSlogin // 如果当前inode不是文件夹,则返回 582004e86ffSlogin if inode.metadata.file_type != FileType::Dir { 583676b8ef6SMork return Err(SystemError::ENOTDIR); 584004e86ffSlogin } 585004e86ffSlogin // 如果有重名的,则返回 586004e86ffSlogin if inode.children.contains_key(name) { 587676b8ef6SMork return Err(SystemError::EEXIST); 588004e86ffSlogin } 589004e86ffSlogin 590004e86ffSlogin // 创建inode 591004e86ffSlogin let result: Arc<LockedProcFSInode> = 592004e86ffSlogin Arc::new(LockedProcFSInode(SpinLock::new(ProcFSInode { 593004e86ffSlogin parent: inode.self_ref.clone(), 594004e86ffSlogin self_ref: Weak::default(), 595004e86ffSlogin children: BTreeMap::new(), 596004e86ffSlogin data: Vec::new(), 597004e86ffSlogin metadata: Metadata { 598004e86ffSlogin dev_id: 0, 599004e86ffSlogin inode_id: generate_inode_id(), 600004e86ffSlogin size: 0, 601004e86ffSlogin blk_size: 0, 602004e86ffSlogin blocks: 0, 603004e86ffSlogin atime: TimeSpec::default(), 604004e86ffSlogin mtime: TimeSpec::default(), 605004e86ffSlogin ctime: TimeSpec::default(), 606b5b571e0SLoGin file_type, 607b5b571e0SLoGin mode, 608004e86ffSlogin nlinks: 1, 609004e86ffSlogin uid: 0, 610004e86ffSlogin gid: 0, 61102343d0bSLoGin raw_dev: DeviceNumber::from(data as u32), 612004e86ffSlogin }, 613004e86ffSlogin fs: inode.fs.clone(), 614004e86ffSlogin fdata: InodeInfo { 6151496ba7bSLoGin pid: Pid::new(0), 616004e86ffSlogin ftype: ProcFileType::Default, 617004e86ffSlogin }, 618004e86ffSlogin }))); 619004e86ffSlogin 620004e86ffSlogin // 初始化inode的自引用的weak指针 621004e86ffSlogin result.0.lock().self_ref = Arc::downgrade(&result); 622004e86ffSlogin 623004e86ffSlogin // 将子inode插入父inode的B树中 624004e86ffSlogin inode.children.insert(String::from(name), result.clone()); 625004e86ffSlogin 626004e86ffSlogin return Ok(result); 627004e86ffSlogin } 628004e86ffSlogin 629676b8ef6SMork fn link(&self, name: &str, other: &Arc<dyn IndexNode>) -> Result<(), SystemError> { 630004e86ffSlogin let other: &LockedProcFSInode = other 631004e86ffSlogin .downcast_ref::<LockedProcFSInode>() 632676b8ef6SMork .ok_or(SystemError::EPERM)?; 633004e86ffSlogin let mut inode: SpinLockGuard<ProcFSInode> = self.0.lock(); 634004e86ffSlogin let mut other_locked: SpinLockGuard<ProcFSInode> = other.0.lock(); 635004e86ffSlogin 636004e86ffSlogin // 如果当前inode不是文件夹,那么报错 637004e86ffSlogin if inode.metadata.file_type != FileType::Dir { 638676b8ef6SMork return Err(SystemError::ENOTDIR); 639004e86ffSlogin } 640004e86ffSlogin 641004e86ffSlogin // 如果另一个inode是文件夹,那么也报错 642004e86ffSlogin if other_locked.metadata.file_type == FileType::Dir { 643676b8ef6SMork return Err(SystemError::EISDIR); 644004e86ffSlogin } 645004e86ffSlogin 646004e86ffSlogin // 如果当前文件夹下已经有同名文件,也报错。 647004e86ffSlogin if inode.children.contains_key(name) { 648676b8ef6SMork return Err(SystemError::EEXIST); 649004e86ffSlogin } 650004e86ffSlogin 651004e86ffSlogin inode 652004e86ffSlogin .children 653004e86ffSlogin .insert(String::from(name), other_locked.self_ref.upgrade().unwrap()); 654004e86ffSlogin 655004e86ffSlogin // 增加硬链接计数 656004e86ffSlogin other_locked.metadata.nlinks += 1; 657004e86ffSlogin return Ok(()); 658004e86ffSlogin } 659004e86ffSlogin 660676b8ef6SMork fn unlink(&self, name: &str) -> Result<(), SystemError> { 661004e86ffSlogin let mut inode: SpinLockGuard<ProcFSInode> = self.0.lock(); 662004e86ffSlogin // 如果当前inode不是目录,那么也没有子目录/文件的概念了,因此要求当前inode的类型是目录 663004e86ffSlogin if inode.metadata.file_type != FileType::Dir { 664676b8ef6SMork return Err(SystemError::ENOTDIR); 665004e86ffSlogin } 6669e481b3bSTTaq 667004e86ffSlogin // 不允许删除当前文件夹,也不允许删除上一个目录 668004e86ffSlogin if name == "." || name == ".." { 669676b8ef6SMork return Err(SystemError::ENOTEMPTY); 670004e86ffSlogin } 671004e86ffSlogin 672004e86ffSlogin // 获得要删除的文件的inode 673676b8ef6SMork let to_delete = inode.children.get(name).ok_or(SystemError::ENOENT)?; 6749e481b3bSTTaq 675004e86ffSlogin // 减少硬链接计数 676004e86ffSlogin to_delete.0.lock().metadata.nlinks -= 1; 6779e481b3bSTTaq 678004e86ffSlogin // 在当前目录中删除这个子目录项 679004e86ffSlogin inode.children.remove(name); 6809e481b3bSTTaq 681004e86ffSlogin return Ok(()); 682004e86ffSlogin } 683004e86ffSlogin 6849e481b3bSTTaq fn move_to( 685004e86ffSlogin &self, 686004e86ffSlogin _old_name: &str, 687004e86ffSlogin _target: &Arc<dyn IndexNode>, 688004e86ffSlogin _new_name: &str, 689676b8ef6SMork ) -> Result<(), SystemError> { 69079a452ceShoumkh return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP); 691004e86ffSlogin } 692004e86ffSlogin 693676b8ef6SMork fn find(&self, name: &str) -> Result<Arc<dyn IndexNode>, SystemError> { 694004e86ffSlogin let inode = self.0.lock(); 695004e86ffSlogin 696004e86ffSlogin if inode.metadata.file_type != FileType::Dir { 697676b8ef6SMork return Err(SystemError::ENOTDIR); 698004e86ffSlogin } 699004e86ffSlogin 700004e86ffSlogin match name { 701004e86ffSlogin "" | "." => { 702676b8ef6SMork return Ok(inode.self_ref.upgrade().ok_or(SystemError::ENOENT)?); 703004e86ffSlogin } 704004e86ffSlogin 705004e86ffSlogin ".." => { 706676b8ef6SMork return Ok(inode.parent.upgrade().ok_or(SystemError::ENOENT)?); 707004e86ffSlogin } 708004e86ffSlogin name => { 709004e86ffSlogin // 在子目录项中查找 710676b8ef6SMork return Ok(inode.children.get(name).ok_or(SystemError::ENOENT)?.clone()); 711004e86ffSlogin } 712004e86ffSlogin } 713004e86ffSlogin } 714004e86ffSlogin 715676b8ef6SMork fn get_entry_name(&self, ino: InodeId) -> Result<String, SystemError> { 716004e86ffSlogin let inode: SpinLockGuard<ProcFSInode> = self.0.lock(); 717004e86ffSlogin if inode.metadata.file_type != FileType::Dir { 718676b8ef6SMork return Err(SystemError::ENOTDIR); 719004e86ffSlogin } 720004e86ffSlogin 7216b4e7a29SLoGin match ino.into() { 722004e86ffSlogin 0 => { 723004e86ffSlogin return Ok(String::from(".")); 724004e86ffSlogin } 725004e86ffSlogin 1 => { 726004e86ffSlogin return Ok(String::from("..")); 727004e86ffSlogin } 728004e86ffSlogin ino => { 729004e86ffSlogin // 暴力遍历所有的children,判断inode id是否相同 730004e86ffSlogin // TODO: 优化这里,这个地方性能很差! 731004e86ffSlogin let mut key: Vec<String> = inode 732004e86ffSlogin .children 733004e86ffSlogin .keys() 7346b4e7a29SLoGin .filter(|k| { 7356b4e7a29SLoGin inode 7366b4e7a29SLoGin .children 7376b4e7a29SLoGin .get(*k) 7386b4e7a29SLoGin .unwrap() 7396b4e7a29SLoGin .0 7406b4e7a29SLoGin .lock() 7416b4e7a29SLoGin .metadata 7426b4e7a29SLoGin .inode_id 7436b4e7a29SLoGin .into() 7446b4e7a29SLoGin == ino 7456b4e7a29SLoGin }) 746004e86ffSlogin .cloned() 747004e86ffSlogin .collect(); 748004e86ffSlogin 749004e86ffSlogin match key.len() { 750676b8ef6SMork 0=>{return Err(SystemError::ENOENT);} 751004e86ffSlogin 1=>{return Ok(key.remove(0));} 7526b4e7a29SLoGin _ => 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) 753004e86ffSlogin } 754004e86ffSlogin } 755004e86ffSlogin } 756004e86ffSlogin } 757004e86ffSlogin 758676b8ef6SMork fn list(&self) -> Result<Vec<String>, SystemError> { 759004e86ffSlogin let info = self.metadata()?; 760004e86ffSlogin if info.file_type != FileType::Dir { 761676b8ef6SMork return Err(SystemError::ENOTDIR); 762004e86ffSlogin } 763004e86ffSlogin 764004e86ffSlogin let mut keys: Vec<String> = Vec::new(); 765004e86ffSlogin keys.push(String::from(".")); 766004e86ffSlogin keys.push(String::from("..")); 767004e86ffSlogin keys.append(&mut self.0.lock().children.keys().cloned().collect()); 768004e86ffSlogin 769004e86ffSlogin return Ok(keys); 770004e86ffSlogin } 771004e86ffSlogin } 772004e86ffSlogin 773004e86ffSlogin /// @brief 向procfs注册进程 7741496ba7bSLoGin pub fn procfs_register_pid(pid: Pid) -> Result<(), SystemError> { 775004e86ffSlogin let procfs_inode = ROOT_INODE().find("proc")?; 776004e86ffSlogin 777004e86ffSlogin let procfs_inode = procfs_inode 778004e86ffSlogin .downcast_ref::<LockedProcFSInode>() 779004e86ffSlogin .expect("Failed to find procfs' root inode"); 780004e86ffSlogin let fs = procfs_inode.fs(); 781004e86ffSlogin let procfs: &ProcFS = fs.as_any_ref().downcast_ref::<ProcFS>().unwrap(); 782004e86ffSlogin 783004e86ffSlogin // 调用注册函数 784004e86ffSlogin procfs.register_pid(pid)?; 785004e86ffSlogin 786004e86ffSlogin return Ok(()); 787004e86ffSlogin } 788004e86ffSlogin 789004e86ffSlogin /// @brief 在ProcFS中,解除进程的注册 7901496ba7bSLoGin pub fn procfs_unregister_pid(pid: Pid) -> Result<(), SystemError> { 791004e86ffSlogin // 获取procfs实例 792004e86ffSlogin let procfs_inode: Arc<dyn IndexNode> = ROOT_INODE().find("proc")?; 793004e86ffSlogin 794004e86ffSlogin let procfs_inode: &LockedProcFSInode = procfs_inode 795004e86ffSlogin .downcast_ref::<LockedProcFSInode>() 796004e86ffSlogin .expect("Failed to find procfs' root inode"); 797004e86ffSlogin let fs: Arc<dyn FileSystem> = procfs_inode.fs(); 798004e86ffSlogin let procfs: &ProcFS = fs.as_any_ref().downcast_ref::<ProcFS>().unwrap(); 799004e86ffSlogin 800004e86ffSlogin // 调用解除注册函数 801004e86ffSlogin return procfs.unregister_pid(pid); 802004e86ffSlogin } 803b087521eSChiichen 804b087521eSChiichen pub fn procfs_init() -> Result<(), SystemError> { 805b087521eSChiichen static INIT: Once = Once::new(); 806b087521eSChiichen let mut result = None; 807b087521eSChiichen INIT.call_once(|| { 808b087521eSChiichen kinfo!("Initializing ProcFS..."); 80934e6d6c8Syuyi2439 // 创建 procfs 实例 810b087521eSChiichen let procfs: Arc<ProcFS> = ProcFS::new(); 811b087521eSChiichen 81234e6d6c8Syuyi2439 // procfs 挂载 813b087521eSChiichen let _t = ROOT_INODE() 814b087521eSChiichen .find("proc") 815b087521eSChiichen .expect("Cannot find /proc") 816b087521eSChiichen .mount(procfs) 817b087521eSChiichen .expect("Failed to mount proc"); 818b087521eSChiichen kinfo!("ProcFS mounted."); 819b087521eSChiichen result = Some(Ok(())); 820b087521eSChiichen }); 821b087521eSChiichen 822b087521eSChiichen return result.unwrap(); 823b087521eSChiichen } 824