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.priority(); 172 let vrtime = sched_info_guard.virtual_runtime(); 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( 187 &mut format!("\npriority:\t{}", priority.data()) 188 .as_bytes() 189 .to_owned(), 190 ); 191 pdata.append( 192 &mut format!("\npreempt:\t{}", pcb.preempt_count()) 193 .as_bytes() 194 .to_owned(), 195 ); 196 pdata.append(&mut format!("\nvrtime:\t{}", vrtime).as_bytes().to_owned()); 197 198 if let Some(user_vm) = pcb.basic().user_vm() { 199 let address_space_guard = user_vm.read(); 200 // todo: 当前进程运行过程中占用内存的峰值 201 let hiwater_vm: u64 = 0; 202 // 进程代码段的大小 203 let text = (address_space_guard.end_code - address_space_guard.start_code) / 1024; 204 // 进程数据段的大小 205 let data = (address_space_guard.end_data - address_space_guard.start_data) / 1024; 206 drop(address_space_guard); 207 pdata.append( 208 &mut format!("\nVmPeak:\t{} kB", hiwater_vm) 209 .as_bytes() 210 .to_owned(), 211 ); 212 pdata.append(&mut format!("\nVmData:\t{} kB", data).as_bytes().to_owned()); 213 pdata.append(&mut format!("\nVmExe:\t{} kB", text).as_bytes().to_owned()); 214 } 215 216 pdata.append( 217 &mut format!("\nflags: {:?}\n", pcb.flags().clone()) 218 .as_bytes() 219 .to_owned(), 220 ); 221 222 // 去除多余的\0 223 self.trim_string(pdata); 224 225 return Ok((pdata.len() * size_of::<u8>()) as i64); 226 } 227 228 /// 打开 meminfo 文件 229 fn open_meminfo(&self, pdata: &mut ProcfsFilePrivateData) -> Result<i64, SystemError> { 230 // 获取内存信息 231 let usage = unsafe { LockedFrameAllocator.usage() }; 232 233 // 传入数据 234 let data: &mut Vec<u8> = &mut pdata.data; 235 236 data.append( 237 &mut format!("MemTotal:\t{} kB\n", usage.total().bytes() >> 10) 238 .as_bytes() 239 .to_owned(), 240 ); 241 242 data.append( 243 &mut format!("MemFree:\t{} kB\n", usage.free().bytes() >> 10) 244 .as_bytes() 245 .to_owned(), 246 ); 247 248 // 去除多余的\0 249 self.trim_string(data); 250 251 return Ok((data.len() * size_of::<u8>()) as i64); 252 } 253 254 /// proc文件系统读取函数 255 fn proc_read( 256 &self, 257 offset: usize, 258 len: usize, 259 buf: &mut [u8], 260 pdata: &mut ProcfsFilePrivateData, 261 ) -> Result<usize, SystemError> { 262 let start = pdata.data.len().min(offset); 263 let end = pdata.data.len().min(offset + len); 264 265 // buffer空间不足 266 if buf.len() < (end - start) { 267 return Err(SystemError::ENOBUFS); 268 } 269 270 // 拷贝数据 271 let src = &pdata.data[start..end]; 272 buf[0..src.len()].copy_from_slice(src); 273 return Ok(src.len()); 274 } 275 } 276 277 impl FileSystem for ProcFS { 278 fn root_inode(&self) -> Arc<dyn super::vfs::IndexNode> { 279 return self.root_inode.clone(); 280 } 281 282 fn info(&self) -> FsInfo { 283 return FsInfo { 284 blk_dev_id: 0, 285 max_name_len: PROCFS_MAX_NAMELEN, 286 }; 287 } 288 289 fn as_any_ref(&self) -> &dyn core::any::Any { 290 self 291 } 292 fn name(&self) -> &str { 293 "procfs" 294 } 295 296 fn super_block(&self) -> SuperBlock { 297 self.super_block.read().clone() 298 } 299 } 300 301 impl ProcFS { 302 pub fn new() -> Arc<Self> { 303 let super_block = SuperBlock::new( 304 Magic::PROC_MAGIC, 305 PROCFS_BLOCK_SIZE, 306 PROCFS_MAX_NAMELEN as u64, 307 ); 308 // 初始化root inode 309 let root: Arc<LockedProcFSInode> = 310 Arc::new(LockedProcFSInode(SpinLock::new(ProcFSInode { 311 parent: Weak::default(), 312 self_ref: Weak::default(), 313 children: BTreeMap::new(), 314 data: Vec::new(), 315 metadata: Metadata { 316 dev_id: 0, 317 inode_id: generate_inode_id(), 318 size: 0, 319 blk_size: 0, 320 blocks: 0, 321 atime: TimeSpec::default(), 322 mtime: TimeSpec::default(), 323 ctime: TimeSpec::default(), 324 file_type: FileType::Dir, 325 mode: ModeType::from_bits_truncate(0o555), 326 nlinks: 1, 327 uid: 0, 328 gid: 0, 329 raw_dev: DeviceNumber::default(), 330 }, 331 fs: Weak::default(), 332 fdata: InodeInfo { 333 pid: Pid::new(0), 334 ftype: ProcFileType::Default, 335 }, 336 }))); 337 338 let result: Arc<ProcFS> = Arc::new(ProcFS { 339 root_inode: root, 340 super_block: RwLock::new(super_block), 341 }); 342 343 // 对root inode加锁,并继续完成初始化工作 344 let mut root_guard: SpinLockGuard<ProcFSInode> = result.root_inode.0.lock(); 345 root_guard.parent = Arc::downgrade(&result.root_inode); 346 root_guard.self_ref = Arc::downgrade(&result.root_inode); 347 root_guard.fs = Arc::downgrade(&result); 348 // 释放锁 349 drop(root_guard); 350 351 // 创建meminfo文件 352 let inode = result.root_inode(); 353 let binding = inode.create( 354 "meminfo", 355 FileType::File, 356 ModeType::from_bits_truncate(0o444), 357 ); 358 if let Ok(meminfo) = binding { 359 let meminfo_file = meminfo 360 .as_any_ref() 361 .downcast_ref::<LockedProcFSInode>() 362 .unwrap(); 363 meminfo_file.0.lock().fdata.pid = Pid::new(0); 364 meminfo_file.0.lock().fdata.ftype = ProcFileType::ProcMeminfo; 365 } else { 366 panic!("create meminfo error"); 367 } 368 369 // 创建kmsg文件 370 let binding = inode.create("kmsg", FileType::File, ModeType::from_bits_truncate(0o444)); 371 if let Ok(kmsg) = binding { 372 let kmsg_file = kmsg 373 .as_any_ref() 374 .downcast_ref::<LockedProcFSInode>() 375 .unwrap(); 376 kmsg_file.0.lock().fdata.pid = Pid::new(1); 377 kmsg_file.0.lock().fdata.ftype = ProcFileType::ProcKmsg; 378 } else { 379 panic!("create ksmg error"); 380 } 381 382 return result; 383 } 384 385 /// @brief 进程注册函数 386 /// @usage 在进程中调用并创建进程对应文件 387 pub fn register_pid(&self, pid: Pid) -> Result<(), SystemError> { 388 // 获取当前inode 389 let inode: Arc<dyn IndexNode> = self.root_inode(); 390 // 创建对应进程文件夹 391 let pid_dir: Arc<dyn IndexNode> = inode.create( 392 &pid.to_string(), 393 FileType::Dir, 394 ModeType::from_bits_truncate(0o555), 395 )?; 396 // 创建相关文件 397 // status文件 398 let binding: Arc<dyn IndexNode> = pid_dir.create( 399 "status", 400 FileType::File, 401 ModeType::from_bits_truncate(0o444), 402 )?; 403 let status_file: &LockedProcFSInode = binding 404 .as_any_ref() 405 .downcast_ref::<LockedProcFSInode>() 406 .unwrap(); 407 status_file.0.lock().fdata.pid = pid; 408 status_file.0.lock().fdata.ftype = ProcFileType::ProcStatus; 409 410 //todo: 创建其他文件 411 412 return Ok(()); 413 } 414 415 /// @brief 解除进程注册 416 /// 417 pub fn unregister_pid(&self, pid: Pid) -> Result<(), SystemError> { 418 // 获取当前inode 419 let proc: Arc<dyn IndexNode> = self.root_inode(); 420 // 获取进程文件夹 421 let pid_dir: Arc<dyn IndexNode> = proc.find(&pid.to_string())?; 422 // 删除进程文件夹下文件 423 pid_dir.unlink("status")?; 424 425 // 查看进程文件是否还存在 426 // let pf= pid_dir.find("status").expect("Cannot find status"); 427 428 // 删除进程文件夹 429 proc.unlink(&pid.to_string())?; 430 431 return Ok(()); 432 } 433 } 434 435 impl IndexNode for LockedProcFSInode { 436 fn open(&self, data: &mut FilePrivateData, _mode: &FileMode) -> 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, data: &mut 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: &mut 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 private_data = match data { 492 FilePrivateData::Procfs(p) => p, 493 _ => { 494 panic!("ProcFS: FilePrivateData mismatch!"); 495 } 496 }; 497 498 // 根据文件类型读取相应数据 499 match inode.fdata.ftype { 500 ProcFileType::ProcStatus => return inode.proc_read(offset, len, buf, private_data), 501 ProcFileType::ProcMeminfo => return inode.proc_read(offset, len, buf, private_data), 502 ProcFileType::ProcKmsg => (), 503 ProcFileType::Default => (), 504 }; 505 506 // 默认读取 507 let start = inode.data.len().min(offset); 508 let end = inode.data.len().min(offset + len); 509 510 // buffer空间不足 511 if buf.len() < (end - start) { 512 return Err(SystemError::ENOBUFS); 513 } 514 515 // 拷贝数据 516 let src = &inode.data[start..end]; 517 buf[0..src.len()].copy_from_slice(src); 518 return Ok(src.len()); 519 } 520 521 fn write_at( 522 &self, 523 _offset: usize, 524 _len: usize, 525 _buf: &[u8], 526 _data: &mut FilePrivateData, 527 ) -> Result<usize, SystemError> { 528 return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP); 529 } 530 531 fn fs(&self) -> Arc<dyn FileSystem> { 532 return self.0.lock().fs.upgrade().unwrap(); 533 } 534 535 fn as_any_ref(&self) -> &dyn core::any::Any { 536 self 537 } 538 539 fn metadata(&self) -> Result<Metadata, SystemError> { 540 let inode = self.0.lock(); 541 let metadata = inode.metadata.clone(); 542 543 return Ok(metadata); 544 } 545 546 fn set_metadata(&self, metadata: &Metadata) -> Result<(), SystemError> { 547 let mut inode = self.0.lock(); 548 inode.metadata.atime = metadata.atime; 549 inode.metadata.mtime = metadata.mtime; 550 inode.metadata.ctime = metadata.ctime; 551 inode.metadata.mode = metadata.mode; 552 inode.metadata.uid = metadata.uid; 553 inode.metadata.gid = metadata.gid; 554 555 return Ok(()); 556 } 557 558 fn resize(&self, len: usize) -> Result<(), SystemError> { 559 let mut inode = self.0.lock(); 560 if inode.metadata.file_type == FileType::File { 561 inode.data.resize(len, 0); 562 return Ok(()); 563 } else { 564 return Err(SystemError::EINVAL); 565 } 566 } 567 568 fn create_with_data( 569 &self, 570 name: &str, 571 file_type: FileType, 572 mode: ModeType, 573 data: usize, 574 ) -> Result<Arc<dyn IndexNode>, SystemError> { 575 // 获取当前inode 576 let mut inode = self.0.lock(); 577 // 如果当前inode不是文件夹,则返回 578 if inode.metadata.file_type != FileType::Dir { 579 return Err(SystemError::ENOTDIR); 580 } 581 // 如果有重名的,则返回 582 if inode.children.contains_key(name) { 583 return Err(SystemError::EEXIST); 584 } 585 586 // 创建inode 587 let result: Arc<LockedProcFSInode> = 588 Arc::new(LockedProcFSInode(SpinLock::new(ProcFSInode { 589 parent: inode.self_ref.clone(), 590 self_ref: Weak::default(), 591 children: BTreeMap::new(), 592 data: Vec::new(), 593 metadata: Metadata { 594 dev_id: 0, 595 inode_id: generate_inode_id(), 596 size: 0, 597 blk_size: 0, 598 blocks: 0, 599 atime: TimeSpec::default(), 600 mtime: TimeSpec::default(), 601 ctime: TimeSpec::default(), 602 file_type, 603 mode, 604 nlinks: 1, 605 uid: 0, 606 gid: 0, 607 raw_dev: DeviceNumber::from(data as u32), 608 }, 609 fs: inode.fs.clone(), 610 fdata: InodeInfo { 611 pid: Pid::new(0), 612 ftype: ProcFileType::Default, 613 }, 614 }))); 615 616 // 初始化inode的自引用的weak指针 617 result.0.lock().self_ref = Arc::downgrade(&result); 618 619 // 将子inode插入父inode的B树中 620 inode.children.insert(String::from(name), result.clone()); 621 622 return Ok(result); 623 } 624 625 fn link(&self, name: &str, other: &Arc<dyn IndexNode>) -> Result<(), SystemError> { 626 let other: &LockedProcFSInode = other 627 .downcast_ref::<LockedProcFSInode>() 628 .ok_or(SystemError::EPERM)?; 629 let mut inode: SpinLockGuard<ProcFSInode> = self.0.lock(); 630 let mut other_locked: SpinLockGuard<ProcFSInode> = other.0.lock(); 631 632 // 如果当前inode不是文件夹,那么报错 633 if inode.metadata.file_type != FileType::Dir { 634 return Err(SystemError::ENOTDIR); 635 } 636 637 // 如果另一个inode是文件夹,那么也报错 638 if other_locked.metadata.file_type == FileType::Dir { 639 return Err(SystemError::EISDIR); 640 } 641 642 // 如果当前文件夹下已经有同名文件,也报错。 643 if inode.children.contains_key(name) { 644 return Err(SystemError::EEXIST); 645 } 646 647 inode 648 .children 649 .insert(String::from(name), other_locked.self_ref.upgrade().unwrap()); 650 651 // 增加硬链接计数 652 other_locked.metadata.nlinks += 1; 653 return Ok(()); 654 } 655 656 fn unlink(&self, name: &str) -> Result<(), SystemError> { 657 let mut inode: SpinLockGuard<ProcFSInode> = self.0.lock(); 658 // 如果当前inode不是目录,那么也没有子目录/文件的概念了,因此要求当前inode的类型是目录 659 if inode.metadata.file_type != FileType::Dir { 660 return Err(SystemError::ENOTDIR); 661 } 662 663 // 不允许删除当前文件夹,也不允许删除上一个目录 664 if name == "." || name == ".." { 665 return Err(SystemError::ENOTEMPTY); 666 } 667 668 // 获得要删除的文件的inode 669 let to_delete = inode.children.get(name).ok_or(SystemError::ENOENT)?; 670 671 // 减少硬链接计数 672 to_delete.0.lock().metadata.nlinks -= 1; 673 674 // 在当前目录中删除这个子目录项 675 inode.children.remove(name); 676 677 return Ok(()); 678 } 679 680 fn move_to( 681 &self, 682 _old_name: &str, 683 _target: &Arc<dyn IndexNode>, 684 _new_name: &str, 685 ) -> Result<(), SystemError> { 686 return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP); 687 } 688 689 fn find(&self, name: &str) -> Result<Arc<dyn IndexNode>, SystemError> { 690 let inode = self.0.lock(); 691 692 if inode.metadata.file_type != FileType::Dir { 693 return Err(SystemError::ENOTDIR); 694 } 695 696 match name { 697 "" | "." => { 698 return Ok(inode.self_ref.upgrade().ok_or(SystemError::ENOENT)?); 699 } 700 701 ".." => { 702 return Ok(inode.parent.upgrade().ok_or(SystemError::ENOENT)?); 703 } 704 name => { 705 // 在子目录项中查找 706 return Ok(inode.children.get(name).ok_or(SystemError::ENOENT)?.clone()); 707 } 708 } 709 } 710 711 fn get_entry_name(&self, ino: InodeId) -> Result<String, SystemError> { 712 let inode: SpinLockGuard<ProcFSInode> = self.0.lock(); 713 if inode.metadata.file_type != FileType::Dir { 714 return Err(SystemError::ENOTDIR); 715 } 716 717 match ino.into() { 718 0 => { 719 return Ok(String::from(".")); 720 } 721 1 => { 722 return Ok(String::from("..")); 723 } 724 ino => { 725 // 暴力遍历所有的children,判断inode id是否相同 726 // TODO: 优化这里,这个地方性能很差! 727 let mut key: Vec<String> = inode 728 .children 729 .keys() 730 .filter(|k| { 731 inode 732 .children 733 .get(*k) 734 .unwrap() 735 .0 736 .lock() 737 .metadata 738 .inode_id 739 .into() 740 == ino 741 }) 742 .cloned() 743 .collect(); 744 745 match key.len() { 746 0=>{return Err(SystemError::ENOENT);} 747 1=>{return Ok(key.remove(0));} 748 _ => 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) 749 } 750 } 751 } 752 } 753 754 fn list(&self) -> Result<Vec<String>, SystemError> { 755 let info = self.metadata()?; 756 if info.file_type != FileType::Dir { 757 return Err(SystemError::ENOTDIR); 758 } 759 760 let mut keys: Vec<String> = Vec::new(); 761 keys.push(String::from(".")); 762 keys.push(String::from("..")); 763 keys.append(&mut self.0.lock().children.keys().cloned().collect()); 764 765 return Ok(keys); 766 } 767 } 768 769 /// @brief 向procfs注册进程 770 pub fn procfs_register_pid(pid: Pid) -> Result<(), SystemError> { 771 let procfs_inode = ROOT_INODE().find("proc")?; 772 773 let procfs_inode = procfs_inode 774 .downcast_ref::<LockedProcFSInode>() 775 .expect("Failed to find procfs' root inode"); 776 let fs = procfs_inode.fs(); 777 let procfs: &ProcFS = fs.as_any_ref().downcast_ref::<ProcFS>().unwrap(); 778 779 // 调用注册函数 780 procfs.register_pid(pid)?; 781 782 return Ok(()); 783 } 784 785 /// @brief 在ProcFS中,解除进程的注册 786 pub fn procfs_unregister_pid(pid: Pid) -> Result<(), SystemError> { 787 // 获取procfs实例 788 let procfs_inode: Arc<dyn IndexNode> = ROOT_INODE().find("proc")?; 789 790 let procfs_inode: &LockedProcFSInode = procfs_inode 791 .downcast_ref::<LockedProcFSInode>() 792 .expect("Failed to find procfs' root inode"); 793 let fs: Arc<dyn FileSystem> = procfs_inode.fs(); 794 let procfs: &ProcFS = fs.as_any_ref().downcast_ref::<ProcFS>().unwrap(); 795 796 // 调用解除注册函数 797 return procfs.unregister_pid(pid); 798 } 799 800 pub fn procfs_init() -> Result<(), SystemError> { 801 static INIT: Once = Once::new(); 802 let mut result = None; 803 INIT.call_once(|| { 804 kinfo!("Initializing ProcFS..."); 805 // 创建 procfs 实例 806 let procfs: Arc<ProcFS> = ProcFS::new(); 807 808 // procfs 挂载 809 let _t = ROOT_INODE() 810 .find("proc") 811 .expect("Cannot find /proc") 812 .mount(procfs) 813 .expect("Failed to mount proc"); 814 kinfo!("ProcFS mounted."); 815 result = Some(Ok(())); 816 }); 817 818 return result.unwrap(); 819 } 820