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