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