1*004e86ffSlogin use core::intrinsics::size_of; 206b09f34Skong 3*004e86ffSlogin use alloc::{ 4*004e86ffSlogin borrow::ToOwned, 5*004e86ffSlogin collections::BTreeMap, 6*004e86ffSlogin format, 7*004e86ffSlogin string::{String, ToString}, 8*004e86ffSlogin sync::{Arc, Weak}, 9*004e86ffSlogin vec::Vec, 10*004e86ffSlogin }; 11*004e86ffSlogin 12*004e86ffSlogin use crate::{ 13*004e86ffSlogin filesystem::vfs::{ 14*004e86ffSlogin core::{generate_inode_id, ROOT_INODE}, 15*004e86ffSlogin FileType, 16*004e86ffSlogin }, 17*004e86ffSlogin include::bindings::bindings::{ 18*004e86ffSlogin pid_t, process_find_pcb_by_pid, EEXIST, EINVAL, EISDIR, ENOBUFS, ENOENT, ENOTDIR, 19*004e86ffSlogin ENOTEMPTY, ENOTSUP, EPERM, ESRCH, 20*004e86ffSlogin }, 21*004e86ffSlogin kerror, 22*004e86ffSlogin libs::spinlock::{SpinLock, SpinLockGuard}, 23*004e86ffSlogin time::TimeSpec, 24*004e86ffSlogin }; 25*004e86ffSlogin 26*004e86ffSlogin use super::vfs::{ 27*004e86ffSlogin file::FilePrivateData, FileSystem, FsInfo, IndexNode, InodeId, Metadata, PollStatus, 28*004e86ffSlogin }; 29*004e86ffSlogin 30*004e86ffSlogin /// @brief 进程文件类型 31*004e86ffSlogin /// @usage 用于定义进程文件夹下的各类文件类型 32*004e86ffSlogin #[derive(Debug)] 33*004e86ffSlogin #[repr(u8)] 34*004e86ffSlogin pub enum ProcFileType { 35*004e86ffSlogin ///展示进程状态信息 36*004e86ffSlogin ProcStatus = 0, 37*004e86ffSlogin //todo: 其他文件类型 38*004e86ffSlogin ///默认文件类型 39*004e86ffSlogin Default, 40*004e86ffSlogin } 41*004e86ffSlogin 42*004e86ffSlogin impl From<u8> for ProcFileType { 43*004e86ffSlogin fn from(value: u8) -> Self { 44*004e86ffSlogin match value { 45*004e86ffSlogin 0 => ProcFileType::ProcStatus, 46*004e86ffSlogin _ => ProcFileType::Default, 47*004e86ffSlogin } 48*004e86ffSlogin } 49*004e86ffSlogin } 50*004e86ffSlogin /// @brief 节点私有信息结构体 51*004e86ffSlogin /// @usage 用于传入各类文件所需的信息 52*004e86ffSlogin #[derive(Debug)] 53*004e86ffSlogin pub struct InodeInfo { 54*004e86ffSlogin ///进程的pid 55*004e86ffSlogin pid: i64, 56*004e86ffSlogin ///文件类型 57*004e86ffSlogin ftype: ProcFileType, 58*004e86ffSlogin //其他需要传入的信息在此定义 59*004e86ffSlogin } 60*004e86ffSlogin 61*004e86ffSlogin /// @brief procfs的inode名称的最大长度 62*004e86ffSlogin const PROCFS_MAX_NAMELEN: usize = 64; 63*004e86ffSlogin 64*004e86ffSlogin /// @brief procfs文件系统的Inode结构体 65*004e86ffSlogin #[derive(Debug)] 66*004e86ffSlogin pub struct LockedProcFSInode(SpinLock<ProcFSInode>); 67*004e86ffSlogin 68*004e86ffSlogin /// @brief procfs文件系统结构体 69*004e86ffSlogin #[derive(Debug)] 70*004e86ffSlogin pub struct ProcFS { 71*004e86ffSlogin /// procfs的root inode 72*004e86ffSlogin root_inode: Arc<LockedProcFSInode>, 73*004e86ffSlogin } 74*004e86ffSlogin 75*004e86ffSlogin #[derive(Debug, Clone)] 76*004e86ffSlogin pub struct ProcfsFilePrivateData { 77*004e86ffSlogin data: Vec<u8>, 78*004e86ffSlogin } 79*004e86ffSlogin 80*004e86ffSlogin impl ProcfsFilePrivateData { 81*004e86ffSlogin pub fn new() -> Self { 82*004e86ffSlogin return ProcfsFilePrivateData { data: Vec::new() }; 83*004e86ffSlogin } 84*004e86ffSlogin } 85*004e86ffSlogin 86*004e86ffSlogin /// @brief procfs文件系统的Inode结构体(不包含锁) 87*004e86ffSlogin #[derive(Debug)] 88*004e86ffSlogin pub struct ProcFSInode { 89*004e86ffSlogin /// 指向父Inode的弱引用 90*004e86ffSlogin parent: Weak<LockedProcFSInode>, 91*004e86ffSlogin /// 指向自身的弱引用 92*004e86ffSlogin self_ref: Weak<LockedProcFSInode>, 93*004e86ffSlogin /// 子Inode的B树 94*004e86ffSlogin children: BTreeMap<String, Arc<LockedProcFSInode>>, 95*004e86ffSlogin /// 当前inode的数据部分 96*004e86ffSlogin data: Vec<u8>, 97*004e86ffSlogin /// 当前inode的元数据 98*004e86ffSlogin metadata: Metadata, 99*004e86ffSlogin /// 指向inode所在的文件系统对象的指针 100*004e86ffSlogin fs: Weak<ProcFS>, 101*004e86ffSlogin /// 储存私有信息 102*004e86ffSlogin fdata: InodeInfo, 103*004e86ffSlogin } 104*004e86ffSlogin 105*004e86ffSlogin /// 对ProcFSInode实现获取各类文件信息的函数 106*004e86ffSlogin impl ProcFSInode { 107*004e86ffSlogin /// @brief 去除Vec中所有的\0,并在结尾添加\0 108*004e86ffSlogin #[inline] 109*004e86ffSlogin fn trim_string(&self, data: &mut Vec<u8>) { 110*004e86ffSlogin data.drain_filter(|x: &mut u8| *x == 0); 111*004e86ffSlogin data.push(0); 112*004e86ffSlogin } 113*004e86ffSlogin // todo:其他数据获取函数实现 114*004e86ffSlogin 115*004e86ffSlogin /// @brief 打开status文件 116*004e86ffSlogin /// 117*004e86ffSlogin fn open_status(&self, pdata: &mut ProcfsFilePrivateData) -> Result<i64, i32> { 118*004e86ffSlogin // 获取该pid对应的pcb结构体 119*004e86ffSlogin let pid: &i64 = &self.fdata.pid; 120*004e86ffSlogin let pcb = unsafe { process_find_pcb_by_pid(*pid).as_mut() }; 121*004e86ffSlogin let pcb = if pcb.is_none() { 122*004e86ffSlogin kerror!( 123*004e86ffSlogin "ProcFS: Cannot find pcb for pid {} when opening its 'status' file.", 124*004e86ffSlogin pid 125*004e86ffSlogin ); 126*004e86ffSlogin return Err(-(ESRCH as i32)); 127*004e86ffSlogin } else { 128*004e86ffSlogin pcb.unwrap() 129*004e86ffSlogin }; 130*004e86ffSlogin // 传入数据 131*004e86ffSlogin let pdata: &mut Vec<u8> = &mut pdata.data; 132*004e86ffSlogin // !!!!!由于目前有bug,不能获取到pcb的name,因此暂时用'Unknown'代替 133*004e86ffSlogin let tmp_name: Vec<u8> = "Unknown".as_bytes().to_vec(); 134*004e86ffSlogin // kdebug!("pcb.name={:?}", pcb.name); 135*004e86ffSlogin // let mut tmp_name: Vec<u8> = Vec::with_capacity(pcb.name.len()); 136*004e86ffSlogin // for val in pcb.name.iter() { 137*004e86ffSlogin // tmp_name.push(*val as u8); 138*004e86ffSlogin // } 139*004e86ffSlogin 140*004e86ffSlogin pdata.append( 141*004e86ffSlogin &mut format!( 142*004e86ffSlogin "Name:\t{}", 143*004e86ffSlogin String::from_utf8(tmp_name).unwrap_or("NULL".to_string()) 144*004e86ffSlogin ) 145*004e86ffSlogin .as_bytes() 146*004e86ffSlogin .to_owned(), 147*004e86ffSlogin ); 148*004e86ffSlogin pdata.append(&mut format!("\nstate:\t{}", pcb.state).as_bytes().to_owned()); 149*004e86ffSlogin pdata.append(&mut format!("\npid:\t{}", pcb.pid).as_bytes().to_owned()); 150*004e86ffSlogin pdata.append( 151*004e86ffSlogin &mut format!("\nPpid:\t{}", unsafe { *pcb.parent_pcb }.pid) 152*004e86ffSlogin .as_bytes() 153*004e86ffSlogin .to_owned(), 154*004e86ffSlogin ); 155*004e86ffSlogin pdata.append(&mut format!("\ncpu_id:\t{}", pcb.cpu_id).as_bytes().to_owned()); 156*004e86ffSlogin pdata.append( 157*004e86ffSlogin &mut format!("\npriority:\t{}", pcb.priority) 158*004e86ffSlogin .as_bytes() 159*004e86ffSlogin .to_owned(), 160*004e86ffSlogin ); 161*004e86ffSlogin pdata.append( 162*004e86ffSlogin &mut format!("\npreempt:\t{}", pcb.preempt_count) 163*004e86ffSlogin .as_bytes() 164*004e86ffSlogin .to_owned(), 165*004e86ffSlogin ); 166*004e86ffSlogin pdata.append( 167*004e86ffSlogin &mut format!("\nvrtime:\t{}", pcb.virtual_runtime) 168*004e86ffSlogin .as_bytes() 169*004e86ffSlogin .to_owned(), 170*004e86ffSlogin ); 171*004e86ffSlogin 172*004e86ffSlogin // 当前进程运行过程中占用内存的峰值 173*004e86ffSlogin let hiwater_vm: u64 = 174*004e86ffSlogin unsafe { *(*pcb.mm).vmas }.vm_end - unsafe { *(*pcb.mm).vmas }.vm_start; 175*004e86ffSlogin // 进程数据段的大小 176*004e86ffSlogin let text: u64 = unsafe { *pcb.mm }.code_addr_end - unsafe { *pcb.mm }.code_addr_start; 177*004e86ffSlogin // 进程代码的大小 178*004e86ffSlogin let data: u64 = unsafe { *pcb.mm }.data_addr_end - unsafe { *pcb.mm }.data_addr_start; 179*004e86ffSlogin 180*004e86ffSlogin pdata.append( 181*004e86ffSlogin &mut format!("\nVmPeak:\t{} kB", hiwater_vm) 182*004e86ffSlogin .as_bytes() 183*004e86ffSlogin .to_owned(), 184*004e86ffSlogin ); 185*004e86ffSlogin pdata.append(&mut format!("\nVmData:\t{} kB", data).as_bytes().to_owned()); 186*004e86ffSlogin pdata.append(&mut format!("\nVmExe:\t{} kB\n", text).as_bytes().to_owned()); 187*004e86ffSlogin 188*004e86ffSlogin // 去除多余的\0 189*004e86ffSlogin self.trim_string(pdata); 190*004e86ffSlogin 191*004e86ffSlogin return Ok((pdata.len() * size_of::<u8>()) as i64); 192*004e86ffSlogin } 193*004e86ffSlogin 194*004e86ffSlogin /// status文件读取函数 195*004e86ffSlogin fn read_status( 196*004e86ffSlogin &self, 197*004e86ffSlogin offset: usize, 198*004e86ffSlogin len: usize, 199*004e86ffSlogin buf: &mut [u8], 200*004e86ffSlogin _pdata: &mut ProcfsFilePrivateData, 201*004e86ffSlogin ) -> Result<usize, i32> { 202*004e86ffSlogin let start = _pdata.data.len().min(offset); 203*004e86ffSlogin let end = _pdata.data.len().min(offset + len); 204*004e86ffSlogin 205*004e86ffSlogin // buffer空间不足 206*004e86ffSlogin if buf.len() < (end - start) { 207*004e86ffSlogin return Err(-(ENOBUFS as i32)); 208*004e86ffSlogin } 209*004e86ffSlogin 210*004e86ffSlogin // 拷贝数据 211*004e86ffSlogin let src = &_pdata.data[start..end]; 212*004e86ffSlogin buf[0..src.len()].copy_from_slice(src); 213*004e86ffSlogin return Ok(src.len()); 214*004e86ffSlogin } 215*004e86ffSlogin } 216*004e86ffSlogin 217*004e86ffSlogin impl FileSystem for ProcFS { 218*004e86ffSlogin fn root_inode(&self) -> Arc<dyn super::vfs::IndexNode> { 219*004e86ffSlogin return self.root_inode.clone(); 220*004e86ffSlogin } 221*004e86ffSlogin 222*004e86ffSlogin fn info(&self) -> FsInfo { 223*004e86ffSlogin return FsInfo { 224*004e86ffSlogin blk_dev_id: 0, 225*004e86ffSlogin max_name_len: PROCFS_MAX_NAMELEN, 226*004e86ffSlogin }; 227*004e86ffSlogin } 228*004e86ffSlogin 229*004e86ffSlogin fn as_any_ref(&self) -> &dyn core::any::Any { 230*004e86ffSlogin self 231*004e86ffSlogin } 232*004e86ffSlogin } 233*004e86ffSlogin 234*004e86ffSlogin impl ProcFS { 235*004e86ffSlogin pub fn new() -> Arc<Self> { 236*004e86ffSlogin // 初始化root inode 237*004e86ffSlogin let root: Arc<LockedProcFSInode> = 238*004e86ffSlogin Arc::new(LockedProcFSInode(SpinLock::new(ProcFSInode { 239*004e86ffSlogin parent: Weak::default(), 240*004e86ffSlogin self_ref: Weak::default(), 241*004e86ffSlogin children: BTreeMap::new(), 242*004e86ffSlogin data: Vec::new(), 243*004e86ffSlogin metadata: Metadata { 244*004e86ffSlogin dev_id: 0, 245*004e86ffSlogin inode_id: generate_inode_id(), 246*004e86ffSlogin size: 0, 247*004e86ffSlogin blk_size: 0, 248*004e86ffSlogin blocks: 0, 249*004e86ffSlogin atime: TimeSpec::default(), 250*004e86ffSlogin mtime: TimeSpec::default(), 251*004e86ffSlogin ctime: TimeSpec::default(), 252*004e86ffSlogin file_type: FileType::Dir, 253*004e86ffSlogin mode: 0o777, 254*004e86ffSlogin nlinks: 1, 255*004e86ffSlogin uid: 0, 256*004e86ffSlogin gid: 0, 257*004e86ffSlogin raw_dev: 0, 258*004e86ffSlogin }, 259*004e86ffSlogin fs: Weak::default(), 260*004e86ffSlogin fdata: InodeInfo { 261*004e86ffSlogin pid: 0, 262*004e86ffSlogin ftype: ProcFileType::Default, 263*004e86ffSlogin }, 264*004e86ffSlogin }))); 265*004e86ffSlogin 266*004e86ffSlogin let result: Arc<ProcFS> = Arc::new(ProcFS { root_inode: root }); 267*004e86ffSlogin 268*004e86ffSlogin // 对root inode加锁,并继续完成初始化工作 269*004e86ffSlogin let mut root_guard: SpinLockGuard<ProcFSInode> = result.root_inode.0.lock(); 270*004e86ffSlogin root_guard.parent = Arc::downgrade(&result.root_inode); 271*004e86ffSlogin root_guard.self_ref = Arc::downgrade(&result.root_inode); 272*004e86ffSlogin root_guard.fs = Arc::downgrade(&result); 273*004e86ffSlogin // 释放锁 274*004e86ffSlogin drop(root_guard); 275*004e86ffSlogin 276*004e86ffSlogin return result; 277*004e86ffSlogin } 278*004e86ffSlogin 279*004e86ffSlogin /// @brief 进程注册函数 280*004e86ffSlogin /// @usage 在进程中调用并创建进程对应文件 281*004e86ffSlogin pub fn register_pid(&self, pid: i64) -> Result<(), i32> { 282*004e86ffSlogin // 获取当前inode 283*004e86ffSlogin let proc: Arc<dyn IndexNode> = self.root_inode(); 284*004e86ffSlogin // 创建对应进程文件夹 285*004e86ffSlogin let _pf: Arc<dyn IndexNode> = proc.create(&pid.to_string(), FileType::Dir, 0o777)?; 286*004e86ffSlogin // 创建相关文件 287*004e86ffSlogin // status文件 288*004e86ffSlogin let binding: Arc<dyn IndexNode> = _pf.create("status", FileType::File, 0o777)?; 289*004e86ffSlogin let _sf: &LockedProcFSInode = binding 290*004e86ffSlogin .as_any_ref() 291*004e86ffSlogin .downcast_ref::<LockedProcFSInode>() 292*004e86ffSlogin .unwrap(); 293*004e86ffSlogin _sf.0.lock().fdata.pid = pid; 294*004e86ffSlogin _sf.0.lock().fdata.ftype = ProcFileType::ProcStatus; 295*004e86ffSlogin 296*004e86ffSlogin //todo: 创建其他文件 297*004e86ffSlogin 298*004e86ffSlogin return Ok(()); 299*004e86ffSlogin } 300*004e86ffSlogin 301*004e86ffSlogin /// @brief 解除进程注册 302*004e86ffSlogin /// 303*004e86ffSlogin pub fn unregister_pid(&self, pid: i64) -> Result<(), i32> { 304*004e86ffSlogin // 获取当前inode 305*004e86ffSlogin let proc: Arc<dyn IndexNode> = self.root_inode(); 306*004e86ffSlogin // 获取进程文件夹 307*004e86ffSlogin let pid_dir: Arc<dyn IndexNode> = proc.find(&format!("{}", pid))?; 308*004e86ffSlogin // 删除进程文件夹下文件 309*004e86ffSlogin pid_dir.unlink("status")?; 310*004e86ffSlogin 311*004e86ffSlogin // 查看进程文件是否还存在 312*004e86ffSlogin // let pf= pid_dir.find("status").expect("Cannot find status"); 313*004e86ffSlogin 314*004e86ffSlogin // 删除进程文件夹 315*004e86ffSlogin proc.unlink(&format!("{}", pid))?; 316*004e86ffSlogin 317*004e86ffSlogin return Ok(()); 318*004e86ffSlogin } 319*004e86ffSlogin } 320*004e86ffSlogin 321*004e86ffSlogin impl IndexNode for LockedProcFSInode { 322*004e86ffSlogin fn open(&self, data: &mut FilePrivateData) -> Result<(), i32> { 323*004e86ffSlogin // 加锁 324*004e86ffSlogin let mut inode: SpinLockGuard<ProcFSInode> = self.0.lock(); 325*004e86ffSlogin 326*004e86ffSlogin // 如果inode类型为文件夹,则直接返回成功 327*004e86ffSlogin if let FileType::Dir = inode.metadata.file_type { 328*004e86ffSlogin return Ok(()); 329*004e86ffSlogin } 330*004e86ffSlogin let mut private_data = ProcfsFilePrivateData::new(); 331*004e86ffSlogin // 根据文件类型获取相应数据 332*004e86ffSlogin let file_size = match inode.fdata.ftype { 333*004e86ffSlogin ProcFileType::ProcStatus => inode.open_status(&mut private_data)?, 334*004e86ffSlogin _ => { 335*004e86ffSlogin todo!() 336*004e86ffSlogin } 337*004e86ffSlogin }; 338*004e86ffSlogin *data = FilePrivateData::Procfs(private_data); 339*004e86ffSlogin // 更新metadata里面的文件大小数值 340*004e86ffSlogin inode.metadata.size = file_size; 341*004e86ffSlogin 342*004e86ffSlogin return Ok(()); 343*004e86ffSlogin } 344*004e86ffSlogin 345*004e86ffSlogin fn close(&self, data: &mut FilePrivateData) -> Result<(), i32> { 346*004e86ffSlogin let guard: SpinLockGuard<ProcFSInode> = self.0.lock(); 347*004e86ffSlogin // 如果inode类型为文件夹,则直接返回成功 348*004e86ffSlogin if let FileType::Dir = guard.metadata.file_type { 349*004e86ffSlogin return Ok(()); 350*004e86ffSlogin } 351*004e86ffSlogin // 获取数据信息 352*004e86ffSlogin let private_data = match data { 353*004e86ffSlogin FilePrivateData::Procfs(p) => p, 354*004e86ffSlogin _ => { 355*004e86ffSlogin panic!("ProcFS: FilePrivateData mismatch!"); 356*004e86ffSlogin } 357*004e86ffSlogin }; 358*004e86ffSlogin // 释放资源 359*004e86ffSlogin drop(private_data); 360*004e86ffSlogin return Ok(()); 361*004e86ffSlogin } 362*004e86ffSlogin 363*004e86ffSlogin fn read_at( 364*004e86ffSlogin &self, 365*004e86ffSlogin offset: usize, 366*004e86ffSlogin len: usize, 367*004e86ffSlogin buf: &mut [u8], 368*004e86ffSlogin data: &mut FilePrivateData, 369*004e86ffSlogin ) -> Result<usize, i32> { 370*004e86ffSlogin if buf.len() < len { 371*004e86ffSlogin return Err(-(EINVAL as i32)); 372*004e86ffSlogin } 373*004e86ffSlogin // 加锁 374*004e86ffSlogin let inode: SpinLockGuard<ProcFSInode> = self.0.lock(); 375*004e86ffSlogin 376*004e86ffSlogin // 检查当前inode是否为一个文件夹,如果是的话,就返回错误 377*004e86ffSlogin if inode.metadata.file_type == FileType::Dir { 378*004e86ffSlogin return Err(-(EISDIR as i32)); 379*004e86ffSlogin } 380*004e86ffSlogin 381*004e86ffSlogin // 获取数据信息 382*004e86ffSlogin let private_data = match data { 383*004e86ffSlogin FilePrivateData::Procfs(p) => p, 384*004e86ffSlogin _ => { 385*004e86ffSlogin panic!("ProcFS: FilePrivateData mismatch!"); 386*004e86ffSlogin } 387*004e86ffSlogin }; 388*004e86ffSlogin 389*004e86ffSlogin // 根据文件类型读取相应数据 390*004e86ffSlogin match inode.fdata.ftype { 391*004e86ffSlogin ProcFileType::ProcStatus => return inode.read_status(offset, len, buf, private_data), 392*004e86ffSlogin ProcFileType::Default => (), 393*004e86ffSlogin }; 394*004e86ffSlogin 395*004e86ffSlogin // 默认读取 396*004e86ffSlogin let start = inode.data.len().min(offset); 397*004e86ffSlogin let end = inode.data.len().min(offset + len); 398*004e86ffSlogin 399*004e86ffSlogin // buffer空间不足 400*004e86ffSlogin if buf.len() < (end - start) { 401*004e86ffSlogin return Err(-(ENOBUFS as i32)); 402*004e86ffSlogin } 403*004e86ffSlogin 404*004e86ffSlogin // 拷贝数据 405*004e86ffSlogin let src = &inode.data[start..end]; 406*004e86ffSlogin buf[0..src.len()].copy_from_slice(src); 407*004e86ffSlogin return Ok(src.len()); 408*004e86ffSlogin } 409*004e86ffSlogin 410*004e86ffSlogin fn write_at( 411*004e86ffSlogin &self, 412*004e86ffSlogin _offset: usize, 413*004e86ffSlogin _len: usize, 414*004e86ffSlogin _buf: &[u8], 415*004e86ffSlogin _data: &mut FilePrivateData, 416*004e86ffSlogin ) -> Result<usize, i32> { 417*004e86ffSlogin return Err(-(ENOTSUP as i32)); 418*004e86ffSlogin } 419*004e86ffSlogin 420*004e86ffSlogin fn poll(&self) -> Result<PollStatus, i32> { 421*004e86ffSlogin // 加锁 422*004e86ffSlogin let inode: SpinLockGuard<ProcFSInode> = self.0.lock(); 423*004e86ffSlogin 424*004e86ffSlogin // 检查当前inode是否为一个文件夹,如果是的话,就返回错误 425*004e86ffSlogin if inode.metadata.file_type == FileType::Dir { 426*004e86ffSlogin return Err(-(EISDIR as i32)); 427*004e86ffSlogin } 428*004e86ffSlogin 429*004e86ffSlogin return Ok(PollStatus { 430*004e86ffSlogin flags: PollStatus::READ_MASK, 431*004e86ffSlogin }); 432*004e86ffSlogin } 433*004e86ffSlogin 434*004e86ffSlogin fn fs(&self) -> Arc<dyn FileSystem> { 435*004e86ffSlogin return self.0.lock().fs.upgrade().unwrap(); 436*004e86ffSlogin } 437*004e86ffSlogin 438*004e86ffSlogin fn as_any_ref(&self) -> &dyn core::any::Any { 439*004e86ffSlogin self 440*004e86ffSlogin } 441*004e86ffSlogin 442*004e86ffSlogin fn metadata(&self) -> Result<Metadata, i32> { 443*004e86ffSlogin let inode = self.0.lock(); 444*004e86ffSlogin let metadata = inode.metadata.clone(); 445*004e86ffSlogin 446*004e86ffSlogin return Ok(metadata); 447*004e86ffSlogin } 448*004e86ffSlogin 449*004e86ffSlogin fn set_metadata(&self, metadata: &Metadata) -> Result<(), i32> { 450*004e86ffSlogin let mut inode = self.0.lock(); 451*004e86ffSlogin inode.metadata.atime = metadata.atime; 452*004e86ffSlogin inode.metadata.mtime = metadata.mtime; 453*004e86ffSlogin inode.metadata.ctime = metadata.ctime; 454*004e86ffSlogin inode.metadata.mode = metadata.mode; 455*004e86ffSlogin inode.metadata.uid = metadata.uid; 456*004e86ffSlogin inode.metadata.gid = metadata.gid; 457*004e86ffSlogin 458*004e86ffSlogin return Ok(()); 459*004e86ffSlogin } 460*004e86ffSlogin 461*004e86ffSlogin fn resize(&self, len: usize) -> Result<(), i32> { 462*004e86ffSlogin let mut inode = self.0.lock(); 463*004e86ffSlogin if inode.metadata.file_type == FileType::File { 464*004e86ffSlogin inode.data.resize(len, 0); 465*004e86ffSlogin return Ok(()); 466*004e86ffSlogin } else { 467*004e86ffSlogin return Err(-(EINVAL as i32)); 468*004e86ffSlogin } 469*004e86ffSlogin } 470*004e86ffSlogin 471*004e86ffSlogin fn create_with_data( 472*004e86ffSlogin &self, 473*004e86ffSlogin name: &str, 474*004e86ffSlogin file_type: FileType, 475*004e86ffSlogin mode: u32, 476*004e86ffSlogin data: usize, 477*004e86ffSlogin ) -> Result<Arc<dyn IndexNode>, i32> { 478*004e86ffSlogin // 获取当前inode 479*004e86ffSlogin let mut inode = self.0.lock(); 480*004e86ffSlogin // 如果当前inode不是文件夹,则返回 481*004e86ffSlogin if inode.metadata.file_type != FileType::Dir { 482*004e86ffSlogin return Err(-(ENOTDIR as i32)); 483*004e86ffSlogin } 484*004e86ffSlogin // 如果有重名的,则返回 485*004e86ffSlogin if inode.children.contains_key(name) { 486*004e86ffSlogin return Err(-(EEXIST as i32)); 487*004e86ffSlogin } 488*004e86ffSlogin 489*004e86ffSlogin // 创建inode 490*004e86ffSlogin let result: Arc<LockedProcFSInode> = 491*004e86ffSlogin Arc::new(LockedProcFSInode(SpinLock::new(ProcFSInode { 492*004e86ffSlogin parent: inode.self_ref.clone(), 493*004e86ffSlogin self_ref: Weak::default(), 494*004e86ffSlogin children: BTreeMap::new(), 495*004e86ffSlogin data: Vec::new(), 496*004e86ffSlogin metadata: Metadata { 497*004e86ffSlogin dev_id: 0, 498*004e86ffSlogin inode_id: generate_inode_id(), 499*004e86ffSlogin size: 0, 500*004e86ffSlogin blk_size: 0, 501*004e86ffSlogin blocks: 0, 502*004e86ffSlogin atime: TimeSpec::default(), 503*004e86ffSlogin mtime: TimeSpec::default(), 504*004e86ffSlogin ctime: TimeSpec::default(), 505*004e86ffSlogin file_type: file_type, 506*004e86ffSlogin mode: mode, 507*004e86ffSlogin nlinks: 1, 508*004e86ffSlogin uid: 0, 509*004e86ffSlogin gid: 0, 510*004e86ffSlogin raw_dev: data, 511*004e86ffSlogin }, 512*004e86ffSlogin fs: inode.fs.clone(), 513*004e86ffSlogin fdata: InodeInfo { 514*004e86ffSlogin pid: 0, 515*004e86ffSlogin ftype: ProcFileType::Default, 516*004e86ffSlogin }, 517*004e86ffSlogin }))); 518*004e86ffSlogin 519*004e86ffSlogin // 初始化inode的自引用的weak指针 520*004e86ffSlogin result.0.lock().self_ref = Arc::downgrade(&result); 521*004e86ffSlogin 522*004e86ffSlogin // 将子inode插入父inode的B树中 523*004e86ffSlogin inode.children.insert(String::from(name), result.clone()); 524*004e86ffSlogin 525*004e86ffSlogin return Ok(result); 526*004e86ffSlogin } 527*004e86ffSlogin 528*004e86ffSlogin fn link(&self, name: &str, other: &Arc<dyn IndexNode>) -> Result<(), i32> { 529*004e86ffSlogin let other: &LockedProcFSInode = other 530*004e86ffSlogin .downcast_ref::<LockedProcFSInode>() 531*004e86ffSlogin .ok_or(-(EPERM as i32))?; 532*004e86ffSlogin let mut inode: SpinLockGuard<ProcFSInode> = self.0.lock(); 533*004e86ffSlogin let mut other_locked: SpinLockGuard<ProcFSInode> = other.0.lock(); 534*004e86ffSlogin 535*004e86ffSlogin // 如果当前inode不是文件夹,那么报错 536*004e86ffSlogin if inode.metadata.file_type != FileType::Dir { 537*004e86ffSlogin return Err(-(ENOTDIR as i32)); 538*004e86ffSlogin } 539*004e86ffSlogin 540*004e86ffSlogin // 如果另一个inode是文件夹,那么也报错 541*004e86ffSlogin if other_locked.metadata.file_type == FileType::Dir { 542*004e86ffSlogin return Err(-(EISDIR as i32)); 543*004e86ffSlogin } 544*004e86ffSlogin 545*004e86ffSlogin // 如果当前文件夹下已经有同名文件,也报错。 546*004e86ffSlogin if inode.children.contains_key(name) { 547*004e86ffSlogin return Err(-(EEXIST as i32)); 548*004e86ffSlogin } 549*004e86ffSlogin 550*004e86ffSlogin inode 551*004e86ffSlogin .children 552*004e86ffSlogin .insert(String::from(name), other_locked.self_ref.upgrade().unwrap()); 553*004e86ffSlogin 554*004e86ffSlogin // 增加硬链接计数 555*004e86ffSlogin other_locked.metadata.nlinks += 1; 556*004e86ffSlogin return Ok(()); 557*004e86ffSlogin } 558*004e86ffSlogin 559*004e86ffSlogin fn unlink(&self, name: &str) -> Result<(), i32> { 560*004e86ffSlogin let mut inode: SpinLockGuard<ProcFSInode> = self.0.lock(); 561*004e86ffSlogin // 如果当前inode不是目录,那么也没有子目录/文件的概念了,因此要求当前inode的类型是目录 562*004e86ffSlogin if inode.metadata.file_type != FileType::Dir { 563*004e86ffSlogin return Err(-(ENOTDIR as i32)); 564*004e86ffSlogin } 565*004e86ffSlogin // 不允许删除当前文件夹,也不允许删除上一个目录 566*004e86ffSlogin if name == "." || name == ".." { 567*004e86ffSlogin return Err(-(ENOTEMPTY as i32)); 568*004e86ffSlogin } 569*004e86ffSlogin 570*004e86ffSlogin // 获得要删除的文件的inode 571*004e86ffSlogin let to_delete = inode.children.get(name).ok_or(-(ENOENT as i32))?; 572*004e86ffSlogin // 减少硬链接计数 573*004e86ffSlogin to_delete.0.lock().metadata.nlinks -= 1; 574*004e86ffSlogin // 在当前目录中删除这个子目录项 575*004e86ffSlogin inode.children.remove(name); 576*004e86ffSlogin return Ok(()); 577*004e86ffSlogin } 578*004e86ffSlogin 579*004e86ffSlogin fn move_( 580*004e86ffSlogin &self, 581*004e86ffSlogin _old_name: &str, 582*004e86ffSlogin _target: &Arc<dyn IndexNode>, 583*004e86ffSlogin _new_name: &str, 584*004e86ffSlogin ) -> Result<(), i32> { 585*004e86ffSlogin return Err(-(ENOTSUP as i32)); 586*004e86ffSlogin } 587*004e86ffSlogin 588*004e86ffSlogin fn find(&self, name: &str) -> Result<Arc<dyn IndexNode>, i32> { 589*004e86ffSlogin let inode = self.0.lock(); 590*004e86ffSlogin 591*004e86ffSlogin if inode.metadata.file_type != FileType::Dir { 592*004e86ffSlogin return Err(-(ENOTDIR as i32)); 593*004e86ffSlogin } 594*004e86ffSlogin 595*004e86ffSlogin match name { 596*004e86ffSlogin "" | "." => { 597*004e86ffSlogin return Ok(inode.self_ref.upgrade().ok_or(-(ENOENT as i32))?); 598*004e86ffSlogin } 599*004e86ffSlogin 600*004e86ffSlogin ".." => { 601*004e86ffSlogin return Ok(inode.parent.upgrade().ok_or(-(ENOENT as i32))?); 602*004e86ffSlogin } 603*004e86ffSlogin name => { 604*004e86ffSlogin // 在子目录项中查找 605*004e86ffSlogin return Ok(inode.children.get(name).ok_or(-(ENOENT as i32))?.clone()); 606*004e86ffSlogin } 607*004e86ffSlogin } 608*004e86ffSlogin } 609*004e86ffSlogin 610*004e86ffSlogin fn get_entry_name(&self, ino: InodeId) -> Result<String, i32> { 611*004e86ffSlogin let inode: SpinLockGuard<ProcFSInode> = self.0.lock(); 612*004e86ffSlogin if inode.metadata.file_type != FileType::Dir { 613*004e86ffSlogin return Err(-(ENOTDIR as i32)); 614*004e86ffSlogin } 615*004e86ffSlogin 616*004e86ffSlogin match ino { 617*004e86ffSlogin 0 => { 618*004e86ffSlogin return Ok(String::from(".")); 619*004e86ffSlogin } 620*004e86ffSlogin 1 => { 621*004e86ffSlogin return Ok(String::from("..")); 622*004e86ffSlogin } 623*004e86ffSlogin ino => { 624*004e86ffSlogin // 暴力遍历所有的children,判断inode id是否相同 625*004e86ffSlogin // TODO: 优化这里,这个地方性能很差! 626*004e86ffSlogin let mut key: Vec<String> = inode 627*004e86ffSlogin .children 628*004e86ffSlogin .keys() 629*004e86ffSlogin .filter(|k| inode.children.get(*k).unwrap().0.lock().metadata.inode_id == ino) 630*004e86ffSlogin .cloned() 631*004e86ffSlogin .collect(); 632*004e86ffSlogin 633*004e86ffSlogin match key.len() { 634*004e86ffSlogin 0=>{return Err(-(ENOENT as i32));} 635*004e86ffSlogin 1=>{return Ok(key.remove(0));} 636*004e86ffSlogin _ => 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) 637*004e86ffSlogin } 638*004e86ffSlogin } 639*004e86ffSlogin } 640*004e86ffSlogin } 641*004e86ffSlogin 642*004e86ffSlogin fn list(&self) -> Result<Vec<String>, i32> { 643*004e86ffSlogin let info = self.metadata()?; 644*004e86ffSlogin if info.file_type != FileType::Dir { 645*004e86ffSlogin return Err(-(ENOTDIR as i32)); 646*004e86ffSlogin } 647*004e86ffSlogin 648*004e86ffSlogin let mut keys: Vec<String> = Vec::new(); 649*004e86ffSlogin keys.push(String::from(".")); 650*004e86ffSlogin keys.push(String::from("..")); 651*004e86ffSlogin keys.append(&mut self.0.lock().children.keys().cloned().collect()); 652*004e86ffSlogin 653*004e86ffSlogin return Ok(keys); 654*004e86ffSlogin } 655*004e86ffSlogin } 656*004e86ffSlogin 657*004e86ffSlogin #[no_mangle] 658*004e86ffSlogin pub extern "C" fn rs_procfs_register_pid(pid: pid_t) -> u64 { 659*004e86ffSlogin let r = procfs_register_pid(pid); 660*004e86ffSlogin if r.is_ok() { 661*004e86ffSlogin return 0; 662*004e86ffSlogin } else { 663*004e86ffSlogin return r.unwrap_err() as u64; 664*004e86ffSlogin } 665*004e86ffSlogin } 666*004e86ffSlogin 667*004e86ffSlogin /// @brief 向procfs注册进程 668*004e86ffSlogin pub fn procfs_register_pid(pid: pid_t) -> Result<(), i32> { 669*004e86ffSlogin let procfs_inode = ROOT_INODE().find("proc")?; 670*004e86ffSlogin 671*004e86ffSlogin let procfs_inode = procfs_inode 672*004e86ffSlogin .downcast_ref::<LockedProcFSInode>() 673*004e86ffSlogin .expect("Failed to find procfs' root inode"); 674*004e86ffSlogin let fs = procfs_inode.fs(); 675*004e86ffSlogin let procfs: &ProcFS = fs.as_any_ref().downcast_ref::<ProcFS>().unwrap(); 676*004e86ffSlogin 677*004e86ffSlogin // 调用注册函数 678*004e86ffSlogin procfs.register_pid(pid)?; 679*004e86ffSlogin 680*004e86ffSlogin return Ok(()); 681*004e86ffSlogin } 682*004e86ffSlogin 683*004e86ffSlogin #[no_mangle] 684*004e86ffSlogin pub extern "C" fn rs_procfs_unregister_pid(pid: pid_t) -> u64 { 685*004e86ffSlogin let r = procfs_unregister_pid(pid); 686*004e86ffSlogin if r.is_ok() { 687*004e86ffSlogin return 0; 688*004e86ffSlogin } else { 689*004e86ffSlogin return r.unwrap_err() as u64; 690*004e86ffSlogin } 691*004e86ffSlogin } 692*004e86ffSlogin 693*004e86ffSlogin /// @brief 在ProcFS中,解除进程的注册 694*004e86ffSlogin pub fn procfs_unregister_pid(pid: pid_t) -> Result<(), i32> { 695*004e86ffSlogin // 获取procfs实例 696*004e86ffSlogin let procfs_inode: Arc<dyn IndexNode> = ROOT_INODE().find("proc")?; 697*004e86ffSlogin 698*004e86ffSlogin let procfs_inode: &LockedProcFSInode = procfs_inode 699*004e86ffSlogin .downcast_ref::<LockedProcFSInode>() 700*004e86ffSlogin .expect("Failed to find procfs' root inode"); 701*004e86ffSlogin let fs: Arc<dyn FileSystem> = procfs_inode.fs(); 702*004e86ffSlogin let procfs: &ProcFS = fs.as_any_ref().downcast_ref::<ProcFS>().unwrap(); 703*004e86ffSlogin 704*004e86ffSlogin // 调用解除注册函数 705*004e86ffSlogin return procfs.unregister_pid(pid); 706*004e86ffSlogin } 707