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