1 use core::any::Any; 2 use core::intrinsics::unlikely; 3 4 use crate::filesystem::vfs::{FileSystemMakerData, FSMAKER}; 5 use crate::libs::rwlock::RwLock; 6 use crate::{ 7 driver::base::device::device_number::DeviceNumber, 8 filesystem::vfs::{core::generate_inode_id, FileType}, 9 ipc::pipe::LockedPipeInode, 10 libs::casting::DowncastArc, 11 libs::spinlock::{SpinLock, SpinLockGuard}, 12 time::PosixTimeSpec, 13 }; 14 15 use alloc::string::ToString; 16 use alloc::{ 17 collections::BTreeMap, 18 string::String, 19 sync::{Arc, Weak}, 20 vec::Vec, 21 }; 22 use system_error::SystemError; 23 24 use super::vfs::{ 25 file::FilePrivateData, syscall::ModeType, utils::DName, FileSystem, FileSystemMaker, FsInfo, 26 IndexNode, InodeId, Metadata, SpecialNodeData, 27 }; 28 29 use linkme::distributed_slice; 30 31 use super::vfs::{Magic, SuperBlock}; 32 33 /// RamFS的inode名称的最大长度 34 const RAMFS_MAX_NAMELEN: usize = 64; 35 const RAMFS_BLOCK_SIZE: u64 = 512; 36 /// @brief 内存文件系统的Inode结构体 37 #[derive(Debug)] 38 pub struct LockedRamFSInode(pub SpinLock<RamFSInode>); 39 40 /// @brief 内存文件系统结构体 41 #[derive(Debug)] 42 pub struct RamFS { 43 /// RamFS的root inode 44 root_inode: Arc<LockedRamFSInode>, 45 super_block: RwLock<SuperBlock>, 46 } 47 48 /// @brief 内存文件系统的Inode结构体(不包含锁) 49 #[derive(Debug)] 50 pub struct RamFSInode { 51 // parent变量目前只在find函数中使用到 52 // 所以只有当inode是文件夹的时候,parent才会生效 53 // 对于文件来说,parent就没什么作用了 54 // 关于parent的说明: 目录不允许有硬链接 55 /// 指向父Inode的弱引用 56 parent: Weak<LockedRamFSInode>, 57 /// 指向自身的弱引用 58 self_ref: Weak<LockedRamFSInode>, 59 /// 子Inode的B树 60 children: BTreeMap<DName, Arc<LockedRamFSInode>>, 61 /// 当前inode的数据部分 62 data: Vec<u8>, 63 /// 当前inode的元数据 64 metadata: Metadata, 65 /// 指向inode所在的文件系统对象的指针 66 fs: Weak<RamFS>, 67 /// 指向特殊节点 68 special_node: Option<SpecialNodeData>, 69 70 name: DName, 71 } 72 73 impl RamFSInode { 74 pub fn new() -> Self { 75 Self { 76 parent: Weak::default(), 77 self_ref: Weak::default(), 78 children: BTreeMap::new(), 79 data: Vec::new(), 80 metadata: Metadata { 81 dev_id: 0, 82 inode_id: generate_inode_id(), 83 size: 0, 84 blk_size: 0, 85 blocks: 0, 86 atime: PosixTimeSpec::default(), 87 mtime: PosixTimeSpec::default(), 88 ctime: PosixTimeSpec::default(), 89 file_type: FileType::Dir, 90 mode: ModeType::from_bits_truncate(0o777), 91 nlinks: 1, 92 uid: 0, 93 gid: 0, 94 raw_dev: DeviceNumber::default(), 95 }, 96 fs: Weak::default(), 97 special_node: None, 98 name: Default::default(), 99 } 100 } 101 } 102 impl FileSystem for RamFS { 103 fn root_inode(&self) -> Arc<dyn super::vfs::IndexNode> { 104 return self.root_inode.clone(); 105 } 106 107 fn info(&self) -> FsInfo { 108 return FsInfo { 109 blk_dev_id: 0, 110 max_name_len: RAMFS_MAX_NAMELEN, 111 }; 112 } 113 114 /// @brief 本函数用于实现动态转换。 115 /// 具体的文件系统在实现本函数时,最简单的方式就是:直接返回self 116 fn as_any_ref(&self) -> &dyn Any { 117 self 118 } 119 120 fn name(&self) -> &str { 121 "ramfs" 122 } 123 124 fn super_block(&self) -> SuperBlock { 125 self.super_block.read().clone() 126 } 127 } 128 129 impl RamFS { 130 pub fn new() -> Arc<Self> { 131 let super_block = SuperBlock::new( 132 Magic::RAMFS_MAGIC, 133 RAMFS_BLOCK_SIZE, 134 RAMFS_MAX_NAMELEN as u64, 135 ); 136 // 初始化root inode 137 let root: Arc<LockedRamFSInode> = 138 Arc::new(LockedRamFSInode(SpinLock::new(RamFSInode::new()))); 139 140 let result: Arc<RamFS> = Arc::new(RamFS { 141 root_inode: root, 142 super_block: RwLock::new(super_block), 143 }); 144 145 // 对root inode加锁,并继续完成初始化工作 146 let mut root_guard: SpinLockGuard<RamFSInode> = result.root_inode.0.lock(); 147 root_guard.parent = Arc::downgrade(&result.root_inode); 148 root_guard.self_ref = Arc::downgrade(&result.root_inode); 149 root_guard.fs = Arc::downgrade(&result); 150 // 释放锁 151 drop(root_guard); 152 153 return result; 154 } 155 156 pub fn make_ramfs( 157 _data: Option<&dyn FileSystemMakerData>, 158 ) -> Result<Arc<dyn FileSystem + 'static>, SystemError> { 159 let fs = RamFS::new(); 160 return Ok(fs); 161 } 162 } 163 #[distributed_slice(FSMAKER)] 164 static RAMFSMAKER: FileSystemMaker = FileSystemMaker::new( 165 "ramfs", 166 &(RamFS::make_ramfs 167 as fn( 168 Option<&dyn FileSystemMakerData>, 169 ) -> Result<Arc<dyn FileSystem + 'static>, SystemError>), 170 ); 171 172 impl IndexNode for LockedRamFSInode { 173 fn truncate(&self, len: usize) -> Result<(), SystemError> { 174 let mut inode = self.0.lock(); 175 176 //如果是文件夹,则报错 177 if inode.metadata.file_type == FileType::Dir { 178 return Err(SystemError::EINVAL); 179 } 180 181 //当前文件长度大于_len才进行截断,否则不操作 182 if inode.data.len() > len { 183 inode.data.resize(len, 0); 184 } 185 return Ok(()); 186 } 187 188 fn close(&self, _data: SpinLockGuard<FilePrivateData>) -> Result<(), SystemError> { 189 return Ok(()); 190 } 191 192 fn open( 193 &self, 194 _data: SpinLockGuard<FilePrivateData>, 195 _mode: &super::vfs::file::FileMode, 196 ) -> Result<(), SystemError> { 197 return Ok(()); 198 } 199 200 fn read_at( 201 &self, 202 offset: usize, 203 len: usize, 204 buf: &mut [u8], 205 _data: SpinLockGuard<FilePrivateData>, 206 ) -> Result<usize, SystemError> { 207 if buf.len() < len { 208 return Err(SystemError::EINVAL); 209 } 210 // 加锁 211 let inode: SpinLockGuard<RamFSInode> = self.0.lock(); 212 213 // 检查当前inode是否为一个文件夹,如果是的话,就返回错误 214 if inode.metadata.file_type == FileType::Dir { 215 return Err(SystemError::EISDIR); 216 } 217 218 let start = inode.data.len().min(offset); 219 let end = inode.data.len().min(offset + len); 220 221 // buffer空间不足 222 if buf.len() < (end - start) { 223 return Err(SystemError::ENOBUFS); 224 } 225 226 // 拷贝数据 227 let src = &inode.data[start..end]; 228 buf[0..src.len()].copy_from_slice(src); 229 return Ok(src.len()); 230 } 231 232 fn write_at( 233 &self, 234 offset: usize, 235 len: usize, 236 buf: &[u8], 237 _data: SpinLockGuard<FilePrivateData>, 238 ) -> Result<usize, SystemError> { 239 if buf.len() < len { 240 return Err(SystemError::EINVAL); 241 } 242 243 // 加锁 244 let mut inode: SpinLockGuard<RamFSInode> = self.0.lock(); 245 246 // 检查当前inode是否为一个文件夹,如果是的话,就返回错误 247 if inode.metadata.file_type == FileType::Dir { 248 return Err(SystemError::EISDIR); 249 } 250 251 let data: &mut Vec<u8> = &mut inode.data; 252 253 // 如果文件大小比原来的大,那就resize这个数组 254 if offset + len > data.len() { 255 data.resize(offset + len, 0); 256 } 257 258 let target = &mut data[offset..offset + len]; 259 target.copy_from_slice(&buf[0..len]); 260 return Ok(len); 261 } 262 263 fn fs(&self) -> Arc<dyn FileSystem> { 264 return self.0.lock().fs.upgrade().unwrap(); 265 } 266 267 fn as_any_ref(&self) -> &dyn core::any::Any { 268 self 269 } 270 271 fn metadata(&self) -> Result<Metadata, SystemError> { 272 let inode = self.0.lock(); 273 let mut metadata = inode.metadata.clone(); 274 metadata.size = inode.data.len() as i64; 275 276 return Ok(metadata); 277 } 278 279 fn set_metadata(&self, metadata: &Metadata) -> Result<(), SystemError> { 280 let mut inode = self.0.lock(); 281 inode.metadata.atime = metadata.atime; 282 inode.metadata.mtime = metadata.mtime; 283 inode.metadata.ctime = metadata.ctime; 284 inode.metadata.mode = metadata.mode; 285 inode.metadata.uid = metadata.uid; 286 inode.metadata.gid = metadata.gid; 287 288 return Ok(()); 289 } 290 291 fn resize(&self, len: usize) -> Result<(), SystemError> { 292 let mut inode = self.0.lock(); 293 if inode.metadata.file_type == FileType::File { 294 inode.data.resize(len, 0); 295 return Ok(()); 296 } else { 297 return Err(SystemError::EINVAL); 298 } 299 } 300 301 fn create_with_data( 302 &self, 303 name: &str, 304 file_type: FileType, 305 mode: ModeType, 306 data: usize, 307 ) -> Result<Arc<dyn IndexNode>, SystemError> { 308 let name = DName::from(name); 309 // 获取当前inode 310 let mut inode = self.0.lock(); 311 // 如果当前inode不是文件夹,则返回 312 if inode.metadata.file_type != FileType::Dir { 313 return Err(SystemError::ENOTDIR); 314 } 315 // 如果有重名的,则返回 316 if inode.children.contains_key(&name) { 317 return Err(SystemError::EEXIST); 318 } 319 320 // 创建inode 321 let result: Arc<LockedRamFSInode> = Arc::new(LockedRamFSInode(SpinLock::new(RamFSInode { 322 parent: inode.self_ref.clone(), 323 self_ref: Weak::default(), 324 children: BTreeMap::new(), 325 data: Vec::new(), 326 metadata: Metadata { 327 dev_id: 0, 328 inode_id: generate_inode_id(), 329 size: 0, 330 blk_size: 0, 331 blocks: 0, 332 atime: PosixTimeSpec::default(), 333 mtime: PosixTimeSpec::default(), 334 ctime: PosixTimeSpec::default(), 335 file_type, 336 mode, 337 nlinks: 1, 338 uid: 0, 339 gid: 0, 340 raw_dev: DeviceNumber::from(data as u32), 341 }, 342 fs: inode.fs.clone(), 343 special_node: None, 344 name: name.clone(), 345 }))); 346 347 // 初始化inode的自引用的weak指针 348 result.0.lock().self_ref = Arc::downgrade(&result); 349 350 // 将子inode插入父inode的B树中 351 inode.children.insert(name, result.clone()); 352 353 return Ok(result); 354 } 355 356 fn link(&self, name: &str, other: &Arc<dyn IndexNode>) -> Result<(), SystemError> { 357 let other: &LockedRamFSInode = other 358 .downcast_ref::<LockedRamFSInode>() 359 .ok_or(SystemError::EPERM)?; 360 let name = DName::from(name); 361 let mut inode: SpinLockGuard<RamFSInode> = self.0.lock(); 362 let mut other_locked: SpinLockGuard<RamFSInode> = other.0.lock(); 363 364 // 如果当前inode不是文件夹,那么报错 365 if inode.metadata.file_type != FileType::Dir { 366 return Err(SystemError::ENOTDIR); 367 } 368 369 // 如果另一个inode是文件夹,那么也报错 370 if other_locked.metadata.file_type == FileType::Dir { 371 return Err(SystemError::EISDIR); 372 } 373 374 // 如果当前文件夹下已经有同名文件,也报错。 375 if inode.children.contains_key(&name) { 376 return Err(SystemError::EEXIST); 377 } 378 379 inode 380 .children 381 .insert(name, other_locked.self_ref.upgrade().unwrap()); 382 383 // 增加硬链接计数 384 other_locked.metadata.nlinks += 1; 385 return Ok(()); 386 } 387 388 fn unlink(&self, name: &str) -> Result<(), SystemError> { 389 let mut inode: SpinLockGuard<RamFSInode> = self.0.lock(); 390 // 如果当前inode不是目录,那么也没有子目录/文件的概念了,因此要求当前inode的类型是目录 391 if inode.metadata.file_type != FileType::Dir { 392 return Err(SystemError::ENOTDIR); 393 } 394 // 不允许删除当前文件夹,也不允许删除上一个目录 395 if name == "." || name == ".." { 396 return Err(SystemError::ENOTEMPTY); 397 } 398 399 let name = DName::from(name); 400 // 获得要删除的文件的inode 401 let to_delete = inode.children.get(&name).ok_or(SystemError::ENOENT)?; 402 if to_delete.0.lock().metadata.file_type == FileType::Dir { 403 return Err(SystemError::EPERM); 404 } 405 // 减少硬链接计数 406 to_delete.0.lock().metadata.nlinks -= 1; 407 // 在当前目录中删除这个子目录项 408 inode.children.remove(&name); 409 return Ok(()); 410 } 411 412 fn rmdir(&self, name: &str) -> Result<(), SystemError> { 413 let name = DName::from(name); 414 let mut inode: SpinLockGuard<RamFSInode> = self.0.lock(); 415 // 如果当前inode不是目录,那么也没有子目录/文件的概念了,因此要求当前inode的类型是目录 416 if inode.metadata.file_type != FileType::Dir { 417 return Err(SystemError::ENOTDIR); 418 } 419 // 获得要删除的文件夹的inode 420 let to_delete = inode.children.get(&name).ok_or(SystemError::ENOENT)?; 421 if to_delete.0.lock().metadata.file_type != FileType::Dir { 422 return Err(SystemError::ENOTDIR); 423 } 424 425 to_delete.0.lock().metadata.nlinks -= 1; 426 // 在当前目录中删除这个子目录项 427 inode.children.remove(&name); 428 return Ok(()); 429 } 430 431 fn move_to( 432 &self, 433 old_name: &str, 434 target: &Arc<dyn IndexNode>, 435 new_name: &str, 436 ) -> Result<(), SystemError> { 437 let inode_to_move = self 438 .find(old_name)? 439 .downcast_arc::<LockedRamFSInode>() 440 .ok_or(SystemError::EINVAL)?; 441 442 let new_name = DName::from(new_name); 443 444 inode_to_move.0.lock().name = new_name.clone(); 445 446 let target_id = target.metadata()?.inode_id; 447 448 let mut self_inode = self.0.lock(); 449 // 判断是否在同一目录下, 是则进行重命名 450 if target_id == self_inode.metadata.inode_id { 451 self_inode.children.remove(&DName::from(old_name)); 452 self_inode.children.insert(new_name, inode_to_move); 453 return Ok(()); 454 } 455 drop(self_inode); 456 457 // 修改其对父节点的引用 458 inode_to_move.0.lock().parent = Arc::downgrade( 459 &target 460 .clone() 461 .downcast_arc::<LockedRamFSInode>() 462 .ok_or(SystemError::EINVAL)?, 463 ); 464 465 // 在新的目录下创建一个硬链接 466 target.link(new_name.as_ref(), &(inode_to_move as Arc<dyn IndexNode>))?; 467 468 // 取消现有的目录下的这个硬链接 469 if let Err(e) = self.unlink(old_name) { 470 // 当操作失败时回退操作 471 target.unlink(new_name.as_ref())?; 472 return Err(e); 473 } 474 475 return Ok(()); 476 } 477 478 fn find(&self, name: &str) -> Result<Arc<dyn IndexNode>, SystemError> { 479 let inode = self.0.lock(); 480 481 if inode.metadata.file_type != FileType::Dir { 482 return Err(SystemError::ENOTDIR); 483 } 484 485 match name { 486 "" | "." => { 487 return Ok(inode.self_ref.upgrade().ok_or(SystemError::ENOENT)?); 488 } 489 490 ".." => { 491 return Ok(inode.parent.upgrade().ok_or(SystemError::ENOENT)?); 492 } 493 name => { 494 // 在子目录项中查找 495 let name = DName::from(name); 496 return Ok(inode 497 .children 498 .get(&name) 499 .ok_or(SystemError::ENOENT)? 500 .clone()); 501 } 502 } 503 } 504 505 fn get_entry_name(&self, ino: InodeId) -> Result<String, SystemError> { 506 let inode: SpinLockGuard<RamFSInode> = self.0.lock(); 507 if inode.metadata.file_type != FileType::Dir { 508 return Err(SystemError::ENOTDIR); 509 } 510 511 match ino.into() { 512 0 => { 513 return Ok(String::from(".")); 514 } 515 1 => { 516 return Ok(String::from("..")); 517 } 518 ino => { 519 // 暴力遍历所有的children,判断inode id是否相同 520 // TODO: 优化这里,这个地方性能很差! 521 let mut key: Vec<String> = inode 522 .children 523 .iter() 524 .filter_map(|(k, v)| { 525 if v.0.lock().metadata.inode_id.into() == ino { 526 Some(k.to_string()) 527 } else { 528 None 529 } 530 }) 531 .collect(); 532 533 match key.len() { 534 0=>{return Err(SystemError::ENOENT);} 535 1=>{return Ok(key.remove(0));} 536 _ => panic!("Ramfs 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) 537 } 538 } 539 } 540 } 541 542 fn list(&self) -> Result<Vec<String>, SystemError> { 543 let info = self.metadata()?; 544 if info.file_type != FileType::Dir { 545 return Err(SystemError::ENOTDIR); 546 } 547 548 let mut keys: Vec<String> = Vec::new(); 549 keys.push(String::from(".")); 550 keys.push(String::from("..")); 551 keys.append( 552 &mut self 553 .0 554 .lock() 555 .children 556 .keys() 557 .map(|k| k.to_string()) 558 .collect(), 559 ); 560 561 return Ok(keys); 562 } 563 564 fn mknod( 565 &self, 566 filename: &str, 567 mode: ModeType, 568 _dev_t: DeviceNumber, 569 ) -> Result<Arc<dyn IndexNode>, SystemError> { 570 let mut inode = self.0.lock(); 571 if inode.metadata.file_type != FileType::Dir { 572 return Err(SystemError::ENOTDIR); 573 } 574 575 // 判断需要创建的类型 576 if unlikely(mode.contains(ModeType::S_IFREG)) { 577 // 普通文件 578 return self.create(filename, FileType::File, mode); 579 } 580 581 let filename = DName::from(filename); 582 583 let nod = Arc::new(LockedRamFSInode(SpinLock::new(RamFSInode { 584 parent: inode.self_ref.clone(), 585 self_ref: Weak::default(), 586 children: BTreeMap::new(), 587 data: Vec::new(), 588 metadata: Metadata { 589 dev_id: 0, 590 inode_id: generate_inode_id(), 591 size: 0, 592 blk_size: 0, 593 blocks: 0, 594 atime: PosixTimeSpec::default(), 595 mtime: PosixTimeSpec::default(), 596 ctime: PosixTimeSpec::default(), 597 file_type: FileType::Pipe, 598 mode, 599 nlinks: 1, 600 uid: 0, 601 gid: 0, 602 raw_dev: DeviceNumber::default(), 603 }, 604 fs: inode.fs.clone(), 605 special_node: None, 606 name: filename.clone(), 607 }))); 608 609 nod.0.lock().self_ref = Arc::downgrade(&nod); 610 611 if mode.contains(ModeType::S_IFIFO) { 612 nod.0.lock().metadata.file_type = FileType::Pipe; 613 // 创建pipe文件 614 let pipe_inode = LockedPipeInode::new(); 615 // 设置special_node 616 nod.0.lock().special_node = Some(SpecialNodeData::Pipe(pipe_inode)); 617 } else if mode.contains(ModeType::S_IFBLK) { 618 nod.0.lock().metadata.file_type = FileType::BlockDevice; 619 unimplemented!() 620 } else if mode.contains(ModeType::S_IFCHR) { 621 nod.0.lock().metadata.file_type = FileType::CharDevice; 622 unimplemented!() 623 } 624 625 inode.children.insert(filename, nod.clone()); 626 Ok(nod) 627 } 628 629 fn special_node(&self) -> Option<super::vfs::SpecialNodeData> { 630 return self.0.lock().special_node.clone(); 631 } 632 633 fn dname(&self) -> Result<DName, SystemError> { 634 Ok(self.0.lock().name.clone()) 635 } 636 637 fn parent(&self) -> Result<Arc<dyn IndexNode>, SystemError> { 638 self.0 639 .lock() 640 .parent 641 .upgrade() 642 .map(|item| item as Arc<dyn IndexNode>) 643 .ok_or(SystemError::EINVAL) 644 } 645 } 646