1 use alloc::string::ToString; 2 use core::cmp::Ordering; 3 use core::intrinsics::unlikely; 4 use core::{any::Any, fmt::Debug}; 5 use log::error; 6 use system_error::SystemError; 7 8 use alloc::{ 9 collections::BTreeMap, 10 string::String, 11 sync::{Arc, Weak}, 12 vec::Vec, 13 }; 14 15 use crate::driver::base::block::gendisk::GenDisk; 16 use crate::driver::base::device::device_number::DeviceNumber; 17 use crate::filesystem::vfs::utils::DName; 18 use crate::filesystem::vfs::{Magic, SpecialNodeData, SuperBlock}; 19 use crate::ipc::pipe::LockedPipeInode; 20 use crate::{ 21 driver::base::block::{block_device::LBA_SIZE, disk_info::Partition, SeekFrom}, 22 filesystem::vfs::{ 23 core::generate_inode_id, 24 file::{FileMode, FilePrivateData}, 25 syscall::ModeType, 26 FileSystem, FileType, IndexNode, InodeId, Metadata, 27 }, 28 libs::{ 29 spinlock::{SpinLock, SpinLockGuard}, 30 vec_cursor::VecCursor, 31 }, 32 time::PosixTimeSpec, 33 }; 34 35 use super::entry::FATFile; 36 use super::{ 37 bpb::{BiosParameterBlock, FATType}, 38 entry::{FATDir, FATDirEntry, FATDirIter, FATEntry}, 39 utils::RESERVED_CLUSTERS, 40 }; 41 42 const FAT_MAX_NAMELEN: u64 = 255; 43 44 /// FAT32文件系统的最大的文件大小 45 pub const MAX_FILE_SIZE: u64 = 0xffff_ffff; 46 47 /// @brief 表示当前簇和上一个簇的关系的结构体 48 /// 定义这样一个结构体的原因是,FAT文件系统的文件中,前后两个簇具有关联关系。 49 #[allow(dead_code)] 50 #[derive(Debug, Clone, Copy, Default)] 51 pub struct Cluster { 52 pub cluster_num: u64, 53 pub parent_cluster: u64, 54 } 55 56 impl PartialOrd for Cluster { 57 /// @brief 根据当前簇号比较大小 58 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> { 59 return self.cluster_num.partial_cmp(&other.cluster_num); 60 } 61 } 62 63 impl PartialEq for Cluster { 64 /// @brief 根据当前簇号比较是否相等 65 fn eq(&self, other: &Self) -> bool { 66 self.cluster_num == other.cluster_num 67 } 68 } 69 70 impl Eq for Cluster {} 71 72 #[derive(Debug)] 73 pub struct FATFileSystem { 74 /// 当前文件系统所在的分区 75 pub gendisk: Arc<GenDisk>, 76 /// 当前文件系统的BOPB 77 pub bpb: BiosParameterBlock, 78 /// 当前文件系统的第一个数据扇区(相对分区开始位置) 79 pub first_data_sector: u64, 80 /// 文件系统信息结构体 81 pub fs_info: Arc<LockedFATFsInfo>, 82 /// 文件系统的根inode 83 root_inode: Arc<LockedFATInode>, 84 } 85 86 /// FAT文件系统的Inode 87 #[derive(Debug)] 88 pub struct LockedFATInode(SpinLock<FATInode>); 89 90 #[derive(Debug)] 91 pub struct LockedFATFsInfo(SpinLock<FATFsInfo>); 92 93 impl LockedFATFsInfo { 94 #[inline] 95 pub fn new(fs_info: FATFsInfo) -> Self { 96 return Self(SpinLock::new(fs_info)); 97 } 98 } 99 100 #[derive(Debug)] 101 pub struct FATInode { 102 /// 指向父Inode的弱引用 103 parent: Weak<LockedFATInode>, 104 /// 指向自身的弱引用 105 self_ref: Weak<LockedFATInode>, 106 /// 子Inode的B树. 该数据结构用作缓存区。其中,它的key表示inode的名称。 107 /// 请注意,由于FAT的查询过程对大小写不敏感,因此我们选择让key全部是大写的,方便统一操作。 108 children: BTreeMap<DName, Arc<LockedFATInode>>, 109 /// 当前inode的元数据 110 metadata: Metadata, 111 /// 指向inode所在的文件系统对象的指针 112 fs: Weak<FATFileSystem>, 113 114 /// 根据不同的Inode类型,创建不同的私有字段 115 inode_type: FATDirEntry, 116 117 /// 若该节点是特殊文件节点,该字段则为真正的文件节点 118 special_node: Option<SpecialNodeData>, 119 120 /// 目录名 121 dname: DName, 122 } 123 124 impl FATInode { 125 /// @brief 更新当前inode的元数据 126 pub fn update_metadata(&mut self) { 127 // todo: 更新文件的访问时间等信息 128 match &self.inode_type { 129 FATDirEntry::File(f) | FATDirEntry::VolId(f) => { 130 self.metadata.size = f.size() as i64; 131 } 132 FATDirEntry::Dir(d) => { 133 self.metadata.size = d.size(&self.fs.upgrade().unwrap().clone()) as i64; 134 } 135 FATDirEntry::UnInit => { 136 error!("update_metadata: Uninitialized FATDirEntry: {:?}", self); 137 return; 138 } 139 }; 140 } 141 142 fn find(&mut self, name: &str) -> Result<Arc<LockedFATInode>, SystemError> { 143 match &self.inode_type { 144 FATDirEntry::Dir(d) => { 145 let dname = DName::from(name.to_uppercase()); 146 // 尝试在缓存区查找 147 if let Some(entry) = self.children.get(&dname) { 148 return Ok(entry.clone()); 149 } 150 // 在缓存区找不到 151 // 在磁盘查找 152 let fat_entry: FATDirEntry = 153 d.find_entry(name, None, None, self.fs.upgrade().unwrap())?; 154 // 创建新的inode 155 let entry_inode: Arc<LockedFATInode> = LockedFATInode::new( 156 dname.clone(), 157 self.fs.upgrade().unwrap(), 158 self.self_ref.clone(), 159 fat_entry, 160 ); 161 // 加入缓存区, 由于FAT文件系统的大小写不敏感问题,因此存入缓存区的key应当是全大写的 162 self.children.insert(dname, entry_inode.clone()); 163 return Ok(entry_inode); 164 } 165 FATDirEntry::UnInit => { 166 panic!( 167 "Uninitialized FAT Inode, fs = {:?}, inode={self:?}", 168 self.fs 169 ) 170 } 171 _ => { 172 return Err(SystemError::ENOTDIR); 173 } 174 } 175 } 176 } 177 178 impl LockedFATInode { 179 pub fn new( 180 dname: DName, 181 fs: Arc<FATFileSystem>, 182 parent: Weak<LockedFATInode>, 183 inode_type: FATDirEntry, 184 ) -> Arc<LockedFATInode> { 185 let file_type = if let FATDirEntry::Dir(_) = inode_type { 186 FileType::Dir 187 } else { 188 FileType::File 189 }; 190 191 let inode: Arc<LockedFATInode> = Arc::new(LockedFATInode(SpinLock::new(FATInode { 192 parent, 193 self_ref: Weak::default(), 194 children: BTreeMap::new(), 195 fs: Arc::downgrade(&fs), 196 inode_type, 197 metadata: Metadata { 198 dev_id: 0, 199 inode_id: generate_inode_id(), 200 size: 0, 201 blk_size: fs.bpb.bytes_per_sector as usize, 202 blocks: if let FATType::FAT32(_) = fs.bpb.fat_type { 203 fs.bpb.total_sectors_32 as usize 204 } else { 205 fs.bpb.total_sectors_16 as usize 206 }, 207 atime: PosixTimeSpec::default(), 208 mtime: PosixTimeSpec::default(), 209 ctime: PosixTimeSpec::default(), 210 file_type, 211 mode: ModeType::from_bits_truncate(0o777), 212 nlinks: 1, 213 uid: 0, 214 gid: 0, 215 raw_dev: DeviceNumber::default(), 216 }, 217 special_node: None, 218 dname, 219 }))); 220 221 inode.0.lock().self_ref = Arc::downgrade(&inode); 222 223 inode.0.lock().update_metadata(); 224 225 return inode; 226 } 227 } 228 229 /// FsInfo结构体(内存中的一份拷贝,当卸载卷或者sync的时候,把它写入磁盘) 230 #[derive(Debug)] 231 pub struct FATFsInfo { 232 /// Lead Signature - must equal 0x41615252 233 lead_sig: u32, 234 /// Value must equal 0x61417272 235 struc_sig: u32, 236 /// 空闲簇数目 237 free_count: u32, 238 /// 第一个空闲簇的位置(不一定准确,仅供加速查找) 239 next_free: u32, 240 /// 0xAA550000 241 trail_sig: u32, 242 /// Dirty flag to flush to disk 243 dirty: bool, 244 /// FsInfo Structure 在磁盘上的字节偏移量 245 /// Not present for FAT12 and FAT16 246 offset: Option<u64>, 247 } 248 249 impl FileSystem for FATFileSystem { 250 fn root_inode(&self) -> Arc<dyn crate::filesystem::vfs::IndexNode> { 251 return self.root_inode.clone(); 252 } 253 254 fn info(&self) -> crate::filesystem::vfs::FsInfo { 255 todo!() 256 } 257 258 /// @brief 本函数用于实现动态转换。 259 /// 具体的文件系统在实现本函数时,最简单的方式就是:直接返回self 260 fn as_any_ref(&self) -> &dyn Any { 261 self 262 } 263 264 fn name(&self) -> &str { 265 "fat" 266 } 267 268 fn super_block(&self) -> SuperBlock { 269 SuperBlock::new( 270 Magic::FAT_MAGIC, 271 self.bpb.bytes_per_sector.into(), 272 FAT_MAX_NAMELEN, 273 ) 274 } 275 } 276 277 impl FATFileSystem { 278 /// FAT12允许的最大簇号 279 pub const FAT12_MAX_CLUSTER: u32 = 0xFF5; 280 /// FAT16允许的最大簇号 281 pub const FAT16_MAX_CLUSTER: u32 = 0xFFF5; 282 /// FAT32允许的最大簇号 283 pub const FAT32_MAX_CLUSTER: u32 = 0x0FFFFFF7; 284 285 pub fn new(gendisk: Arc<GenDisk>) -> Result<Arc<FATFileSystem>, SystemError> { 286 let bpb = BiosParameterBlock::new(&gendisk)?; 287 // 从磁盘上读取FAT32文件系统的FsInfo结构体 288 let fs_info: FATFsInfo = match bpb.fat_type { 289 FATType::FAT32(bpb32) => { 290 let fs_info_in_gendisk_bytes_offset = 291 bpb32.fs_info as usize * bpb.bytes_per_sector as usize; 292 FATFsInfo::new( 293 &gendisk, 294 fs_info_in_gendisk_bytes_offset, 295 bpb.bytes_per_sector as usize, 296 )? 297 } 298 _ => FATFsInfo::default(), 299 }; 300 301 // 根目录项占用的扇区数(向上取整) 302 let root_dir_sectors: u64 = ((bpb.root_entries_cnt as u64 * 32) 303 + (bpb.bytes_per_sector as u64 - 1)) 304 / (bpb.bytes_per_sector as u64); 305 306 // FAT表大小(单位:扇区) 307 let fat_size = if bpb.fat_size_16 != 0 { 308 bpb.fat_size_16 as u64 309 } else { 310 match bpb.fat_type { 311 FATType::FAT32(x) => x.fat_size_32 as u64, 312 _ => { 313 error!("FAT12 and FAT16 volumes should have non-zero BPB_FATSz16"); 314 return Err(SystemError::EINVAL); 315 } 316 } 317 }; 318 319 let first_data_sector = 320 bpb.rsvd_sec_cnt as u64 + (bpb.num_fats as u64 * fat_size) + root_dir_sectors; 321 322 // 创建文件系统的根节点 323 let root_inode: Arc<LockedFATInode> = Arc::new(LockedFATInode(SpinLock::new(FATInode { 324 parent: Weak::default(), 325 self_ref: Weak::default(), 326 children: BTreeMap::new(), 327 fs: Weak::default(), 328 inode_type: FATDirEntry::UnInit, 329 metadata: Metadata { 330 dev_id: 0, 331 inode_id: generate_inode_id(), 332 size: 0, 333 blk_size: bpb.bytes_per_sector as usize, 334 blocks: if let FATType::FAT32(_) = bpb.fat_type { 335 bpb.total_sectors_32 as usize 336 } else { 337 bpb.total_sectors_16 as usize 338 }, 339 atime: PosixTimeSpec::default(), 340 mtime: PosixTimeSpec::default(), 341 ctime: PosixTimeSpec::default(), 342 file_type: FileType::Dir, 343 mode: ModeType::from_bits_truncate(0o777), 344 nlinks: 1, 345 uid: 0, 346 gid: 0, 347 raw_dev: DeviceNumber::default(), 348 }, 349 special_node: None, 350 dname: DName::default(), 351 }))); 352 353 let result: Arc<FATFileSystem> = Arc::new(FATFileSystem { 354 gendisk, 355 bpb, 356 first_data_sector, 357 fs_info: Arc::new(LockedFATFsInfo::new(fs_info)), 358 root_inode, 359 }); 360 361 // 对root inode加锁,并继续完成初始化工作 362 let mut root_guard: SpinLockGuard<FATInode> = result.root_inode.0.lock(); 363 root_guard.inode_type = FATDirEntry::Dir(result.root_dir()); 364 root_guard.parent = Arc::downgrade(&result.root_inode); 365 root_guard.self_ref = Arc::downgrade(&result.root_inode); 366 root_guard.fs = Arc::downgrade(&result); 367 // 释放锁 368 drop(root_guard); 369 370 return Ok(result); 371 } 372 373 /// @brief 计算每个簇有多少个字节 374 #[inline] 375 pub fn bytes_per_cluster(&self) -> u64 { 376 return (self.bpb.bytes_per_sector as u64) * (self.bpb.sector_per_cluster as u64); 377 } 378 379 /// @brief 读取当前簇在FAT表中存储的信息 380 /// 381 /// @param cluster 当前簇 382 /// 383 /// @return Ok(FATEntry) 当前簇在FAT表中,存储的信息。(详情见FATEntry的注释) 384 /// @return Err(SystemError) 错误码 385 pub fn get_fat_entry(&self, cluster: Cluster) -> Result<FATEntry, SystemError> { 386 let current_cluster = cluster.cluster_num; 387 if current_cluster < 2 { 388 // 0号簇和1号簇是保留簇,不允许用户使用 389 return Err(SystemError::EINVAL); 390 } 391 392 let fat_type: FATType = self.bpb.fat_type; 393 // 获取FAT表的起始扇区(相对分区起始扇区的偏移量) 394 let fat_start_sector = self.fat_start_sector(); 395 let bytes_per_sec = self.bpb.bytes_per_sector as u64; 396 397 // cluster对应的FAT表项在分区内的字节偏移量 398 let fat_bytes_offset = 399 fat_type.get_fat_bytes_offset(cluster, fat_start_sector, bytes_per_sec); 400 401 // FAT表项所在的分区内LBA地址 402 let fat_ent_lba = fat_bytes_offset / LBA_SIZE as u64; 403 404 // FAT表项在逻辑块内的字节偏移量 405 let blk_offset = self.get_in_block_offset(fat_bytes_offset); 406 407 let mut v: Vec<u8> = vec![0; self.bpb.bytes_per_sector as usize]; 408 self.gendisk.read_at(&mut v, fat_ent_lba as usize)?; 409 410 let mut cursor = VecCursor::new(v); 411 cursor.seek(SeekFrom::SeekSet(blk_offset as i64))?; 412 413 let res: FATEntry = match self.bpb.fat_type { 414 FATType::FAT12(_) => { 415 let mut entry = cursor.read_u16()?; 416 // 由于FAT12文件系统的FAT表,每个entry占用1.5字节,因此奇数的簇需要取高12位的值。 417 if (current_cluster & 1) > 0 { 418 entry >>= 4; 419 } else { 420 entry &= 0x0fff; 421 } 422 423 if entry == 0 { 424 FATEntry::Unused 425 } else if entry == 0x0ff7 { 426 FATEntry::Bad 427 } else if entry >= 0x0ff8 { 428 FATEntry::EndOfChain 429 } else { 430 FATEntry::Next(Cluster { 431 cluster_num: entry as u64, 432 parent_cluster: current_cluster, 433 }) 434 } 435 } 436 FATType::FAT16(_) => { 437 let entry = cursor.read_u16()?; 438 439 if entry == 0 { 440 FATEntry::Unused 441 } else if entry == 0xfff7 { 442 FATEntry::Bad 443 } else if entry >= 0xfff8 { 444 FATEntry::EndOfChain 445 } else { 446 FATEntry::Next(Cluster { 447 cluster_num: entry as u64, 448 parent_cluster: current_cluster, 449 }) 450 } 451 } 452 FATType::FAT32(_) => { 453 let entry = cursor.read_u32()? & 0x0fffffff; 454 455 match entry { 456 _n if (0x0ffffff7..=0x0fffffff).contains(¤t_cluster) => { 457 // 当前簇号不是一个能被获得的簇(可能是文件系统出错了) 458 error!("FAT32 get fat entry: current cluster number [{}] is not an allocatable cluster number.", current_cluster); 459 FATEntry::Bad 460 } 461 0 => FATEntry::Unused, 462 0x0ffffff7 => FATEntry::Bad, 463 0x0ffffff8..=0x0fffffff => FATEntry::EndOfChain, 464 _n => FATEntry::Next(Cluster { 465 cluster_num: entry as u64, 466 parent_cluster: current_cluster, 467 }), 468 } 469 } 470 }; 471 return Ok(res); 472 } 473 474 /// @brief 读取当前簇在FAT表中存储的信息(直接返回读取到的值,而不加处理) 475 /// 476 /// @param cluster 当前簇 477 /// 478 /// @return Ok(u64) 当前簇在FAT表中,存储的信息。 479 /// @return Err(SystemError) 错误码 480 pub fn get_fat_entry_raw(&self, cluster: Cluster) -> Result<u64, SystemError> { 481 let current_cluster = cluster.cluster_num; 482 483 let fat_type: FATType = self.bpb.fat_type; 484 // 获取FAT表的起始扇区(相对分区起始扇区的偏移量) 485 let fat_start_sector = self.fat_start_sector(); 486 let bytes_per_sec = self.bpb.bytes_per_sector as u64; 487 488 // cluster对应的FAT表项在分区内的字节偏移量 489 let fat_bytes_offset = 490 fat_type.get_fat_bytes_offset(cluster, fat_start_sector, bytes_per_sec); 491 492 // FAT表项所在的分区内LBA地址 493 let fat_ent_lba = self.gendisk_lba_from_offset(self.bytes_to_sector(fat_bytes_offset)); 494 495 // FAT表项在逻辑块内的字节偏移量 496 let blk_offset = self.get_in_block_offset(fat_bytes_offset); 497 498 let mut v: Vec<u8> = vec![0; self.bpb.bytes_per_sector as usize]; 499 self.gendisk.read_at(&mut v, fat_ent_lba)?; 500 501 let mut cursor = VecCursor::new(v); 502 cursor.seek(SeekFrom::SeekSet(blk_offset as i64))?; 503 504 let res = match self.bpb.fat_type { 505 FATType::FAT12(_) => { 506 let mut entry = cursor.read_u16()?; 507 entry = if (current_cluster & 0x0001) > 0 { 508 entry >> 4 509 } else { 510 entry & 0x0fff 511 }; 512 entry as u64 513 } 514 FATType::FAT16(_) => { 515 let entry = (cursor.read_u16()?) as u64; 516 entry 517 } 518 FATType::FAT32(_) => { 519 let entry = cursor.read_u32()? & 0x0fff_ffff; 520 entry as u64 521 } 522 }; 523 524 return Ok(res); 525 } 526 527 /// @brief 获取当前文件系统的root inode,在分区内的字节偏移量 528 pub fn root_dir_bytes_offset(&self) -> u64 { 529 match self.bpb.fat_type { 530 FATType::FAT32(s) => { 531 let first_sec_cluster: u64 = (s.root_cluster as u64 - 2) 532 * (self.bpb.sector_per_cluster as u64) 533 + self.first_data_sector; 534 return (self.gendisk_lba_from_offset(first_sec_cluster) * LBA_SIZE) as u64; 535 } 536 _ => { 537 let root_sec = (self.bpb.rsvd_sec_cnt as u64) 538 + (self.bpb.num_fats as u64) * (self.bpb.fat_size_16 as u64); 539 return (self.gendisk_lba_from_offset(root_sec) * LBA_SIZE) as u64; 540 } 541 } 542 } 543 544 /// @brief 获取当前文件系统的根目录项区域的结束位置,在分区内的字节偏移量。 545 /// 请注意,当前函数只对FAT12/FAT16生效。对于FAT32,返回None 546 pub fn root_dir_end_bytes_offset(&self) -> Option<u64> { 547 match self.bpb.fat_type { 548 FATType::FAT12(_) | FATType::FAT16(_) => { 549 return Some( 550 self.root_dir_bytes_offset() + (self.bpb.root_entries_cnt as u64) * 32, 551 ); 552 } 553 _ => { 554 return None; 555 } 556 } 557 } 558 559 /// 获取簇在分区内的字节偏移量 560 pub fn cluster_bytes_offset(&self, cluster: Cluster) -> u64 { 561 if cluster.cluster_num >= 2 { 562 // 指定簇的第一个扇区号 563 let first_sec_of_cluster = (cluster.cluster_num - 2) 564 * (self.bpb.sector_per_cluster as u64) 565 + self.first_data_sector; 566 return first_sec_of_cluster * (self.bpb.bytes_per_sector as u64); 567 } else { 568 return 0; 569 } 570 } 571 572 /// @brief 获取一个空闲簇 573 /// 574 /// @param prev_cluster 簇链的前一个簇。本函数将会把新获取的簇,连接到它的后面。 575 /// 576 /// @return Ok(Cluster) 新获取的空闲簇 577 /// @return Err(SystemError) 错误码 578 pub fn allocate_cluster(&self, prev_cluster: Option<Cluster>) -> Result<Cluster, SystemError> { 579 let end_cluster: Cluster = self.max_cluster_number(); 580 let start_cluster: Cluster = match self.bpb.fat_type { 581 FATType::FAT32(_) => { 582 let next_free: u64 = self.fs_info.0.lock().next_free().unwrap_or(0xffffffff); 583 if next_free < end_cluster.cluster_num { 584 Cluster::new(next_free) 585 } else { 586 Cluster::new(RESERVED_CLUSTERS as u64) 587 } 588 } 589 _ => Cluster::new(RESERVED_CLUSTERS as u64), 590 }; 591 592 // 寻找一个空的簇 593 let free_cluster: Cluster = match self.get_free_cluster(start_cluster, end_cluster) { 594 Ok(c) => c, 595 Err(_) if start_cluster.cluster_num > RESERVED_CLUSTERS as u64 => { 596 self.get_free_cluster(Cluster::new(RESERVED_CLUSTERS as u64), end_cluster)? 597 } 598 Err(e) => return Err(e), 599 }; 600 601 self.set_entry(free_cluster, FATEntry::EndOfChain)?; 602 // 减少空闲簇计数 603 self.fs_info.0.lock().update_free_count_delta(-1); 604 // 更新搜索空闲簇的参考量 605 self.fs_info 606 .0 607 .lock() 608 .update_next_free((free_cluster.cluster_num + 1) as u32); 609 610 // 如果这个空闲簇不是簇链的第一个簇,那么把当前簇跟前一个簇连上。 611 if let Some(prev_cluster) = prev_cluster { 612 // debug!("set entry, prev ={prev_cluster:?}, next = {free_cluster:?}"); 613 self.set_entry(prev_cluster, FATEntry::Next(free_cluster))?; 614 } 615 // 清空新获取的这个簇 616 self.zero_cluster(free_cluster)?; 617 return Ok(free_cluster); 618 } 619 620 /// @brief 释放簇链上的所有簇 621 /// 622 /// @param start_cluster 簇链的第一个簇 623 pub fn deallocate_cluster_chain(&self, start_cluster: Cluster) -> Result<(), SystemError> { 624 let clusters: Vec<Cluster> = self.clusters(start_cluster); 625 for c in clusters { 626 self.deallocate_cluster(c)?; 627 } 628 return Ok(()); 629 } 630 631 /// @brief 释放簇 632 /// 633 /// @param 要释放的簇 634 pub fn deallocate_cluster(&self, cluster: Cluster) -> Result<(), SystemError> { 635 let entry: FATEntry = self.get_fat_entry(cluster)?; 636 // 如果不是坏簇 637 if entry != FATEntry::Bad { 638 self.set_entry(cluster, FATEntry::Unused)?; 639 self.fs_info.0.lock().update_free_count_delta(1); 640 // 安全选项:清空被释放的簇 641 #[cfg(feature = "fatfs-secure")] 642 self.zero_cluster(cluster)?; 643 return Ok(()); 644 } else { 645 // 不能释放坏簇 646 error!("Bad clusters cannot be freed."); 647 return Err(SystemError::EFAULT); 648 } 649 } 650 651 /// @brief 获取文件系统的根目录项 652 pub fn root_dir(&self) -> FATDir { 653 match self.bpb.fat_type { 654 FATType::FAT32(s) => { 655 return FATDir { 656 first_cluster: Cluster::new(s.root_cluster as u64), 657 dir_name: String::from("/"), 658 root_offset: None, 659 short_dir_entry: None, 660 loc: None, 661 }; 662 } 663 _ => FATDir { 664 first_cluster: Cluster::new(0), 665 dir_name: String::from("/"), 666 root_offset: Some(self.root_dir_bytes_offset()), 667 short_dir_entry: None, 668 loc: None, 669 }, 670 } 671 } 672 673 /// @brief 获取FAT表的起始扇区(相对分区起始扇区的偏移量) 674 pub fn fat_start_sector(&self) -> u64 { 675 let active_fat = self.active_fat(); 676 let fat_size = self.fat_size(); 677 return self.bpb.rsvd_sec_cnt as u64 + active_fat * fat_size; 678 } 679 680 /// @brief 获取当前活动的FAT表 681 pub fn active_fat(&self) -> u64 { 682 if self.mirroring_enabled() { 683 return 0; 684 } else { 685 match self.bpb.fat_type { 686 FATType::FAT32(bpb32) => { 687 return (bpb32.ext_flags & 0x0f) as u64; 688 } 689 _ => { 690 return 0; 691 } 692 } 693 } 694 } 695 696 /// @brief 获取当前文件系统的每个FAT表的大小 697 pub fn fat_size(&self) -> u64 { 698 if self.bpb.fat_size_16 != 0 { 699 return self.bpb.fat_size_16 as u64; 700 } else { 701 match self.bpb.fat_type { 702 FATType::FAT32(bpb32) => { 703 return bpb32.fat_size_32 as u64; 704 } 705 706 _ => { 707 panic!("FAT12 and FAT16 volumes should have non-zero BPB_FATSz16"); 708 } 709 } 710 } 711 } 712 713 /// @brief 判断当前文件系统是否启用了FAT表镜像 714 pub fn mirroring_enabled(&self) -> bool { 715 match self.bpb.fat_type { 716 FATType::FAT32(bpb32) => { 717 return (bpb32.ext_flags & 0x80) == 0; 718 } 719 _ => { 720 return false; 721 } 722 } 723 } 724 725 /// 获取分区内的扇区偏移量 726 #[inline] 727 pub fn gendisk_lba_from_offset(&self, in_partition_sec_offset: u64) -> usize { 728 return (in_partition_sec_offset * (self.bpb.bytes_per_sector as u64 / LBA_SIZE as u64)) 729 as usize; 730 } 731 732 /// @brief 获取每个扇区占用多少个LBA 733 #[inline] 734 pub fn lba_per_sector(&self) -> usize { 735 return self.bpb.bytes_per_sector as usize / LBA_SIZE; 736 } 737 738 /// @brief 将分区内字节偏移量转换为扇区偏移量 739 #[inline] 740 pub fn bytes_to_sector(&self, in_partition_bytes_offset: u64) -> u64 { 741 return in_partition_bytes_offset / (self.bpb.bytes_per_sector as u64); 742 } 743 744 /// @brief 根据字节偏移量计算在逻辑块内的字节偏移量 745 #[inline] 746 pub fn get_in_block_offset(&self, bytes_offset: u64) -> u64 { 747 return bytes_offset % LBA_SIZE as u64; 748 } 749 750 /// @brief 获取在FAT表中,以start_cluster开头的FAT链的所有簇的信息 751 /// 752 /// @param start_cluster 整个FAT链的起始簇号 753 pub fn clusters(&self, start_cluster: Cluster) -> Vec<Cluster> { 754 return self.cluster_iter(start_cluster).collect(); 755 } 756 757 /// @brief 获取在FAT表中,以start_cluster开头的FAT链的长度(总计经过多少个簇) 758 /// 759 /// @param start_cluster 整个FAT链的起始簇号 760 pub fn num_clusters_chain(&self, start_cluster: Cluster) -> u64 { 761 return self 762 .cluster_iter(start_cluster) 763 .fold(0, |size, _cluster| size + 1); 764 } 765 /// @brief 获取一个簇迭代器对象 766 /// 767 /// @param start_cluster 整个FAT链的起始簇号 768 fn cluster_iter(&self, start_cluster: Cluster) -> ClusterIter { 769 return ClusterIter { 770 current_cluster: Some(start_cluster), 771 fs: self, 772 }; 773 } 774 775 /// @brief 获取从start_cluster开始的簇链中,第n个簇的信息。(请注意,下标从0开始) 776 #[inline] 777 pub fn get_cluster_by_relative(&self, start_cluster: Cluster, n: usize) -> Option<Cluster> { 778 return self.cluster_iter(start_cluster).nth(n); 779 } 780 781 /// @brief 获取整个簇链的最后一个簇 782 #[inline] 783 pub fn get_last_cluster(&self, start_cluster: Cluster) -> Option<Cluster> { 784 return self.cluster_iter(start_cluster).last(); 785 } 786 787 /// @brief 判断FAT文件系统的shut bit是否正常。 788 /// shut bit 表示文件系统是否正常卸载。如果这一位是1,则表示这个卷是“干净的” 789 /// 参考资料:https://thestarman.pcministry.com/DOS/DirtyShutdownFlag.html 790 /// 791 /// @return Ok(true) 正常 792 /// @return Ok(false) 不正常 793 /// @return Err(SystemError) 在判断时发生错误 794 #[allow(dead_code)] 795 pub fn is_shut_bit_ok(&mut self) -> Result<bool, SystemError> { 796 match self.bpb.fat_type { 797 FATType::FAT32(_) => { 798 // 对于FAT32, error bit位于第一个扇区的第8字节。 799 let bit = self.get_fat_entry_raw(Cluster::new(1))? & 0x0800_0000; 800 return Ok(bit > 0); 801 } 802 FATType::FAT16(_) => { 803 let bit = self.get_fat_entry_raw(Cluster::new(1))? & 0x8000; 804 return Ok(bit > 0); 805 } 806 _ => return Ok(true), 807 } 808 } 809 810 /// @brief 判断FAT文件系统的hard error bit是否正常。 811 /// 如果此位为0,则文件系统驱动程序在上次安装卷时遇到磁盘 I/O 错误,这表明 812 /// 卷上的某些扇区可能已损坏。 813 /// 参考资料:https://thestarman.pcministry.com/DOS/DirtyShutdownFlag.html 814 /// 815 /// @return Ok(true) 正常 816 /// @return Ok(false) 不正常 817 /// @return Err(SystemError) 在判断时发生错误 818 pub fn is_hard_error_bit_ok(&mut self) -> Result<bool, SystemError> { 819 match self.bpb.fat_type { 820 FATType::FAT32(_) => { 821 let bit = self.get_fat_entry_raw(Cluster::new(1))? & 0x0400_0000; 822 return Ok(bit > 0); 823 } 824 FATType::FAT16(_) => { 825 let bit = self.get_fat_entry_raw(Cluster::new(1))? & 0x4000; 826 return Ok(bit > 0); 827 } 828 _ => return Ok(true), 829 } 830 } 831 832 /// @brief 设置文件系统的shut bit为正常状态 833 /// 参考资料:https://thestarman.pcministry.com/DOS/DirtyShutdownFlag.html 834 /// 835 /// @return Ok(()) 设置成功 836 /// @return Err(SystemError) 在设置过程中,出现错误 837 pub fn set_shut_bit_ok(&mut self) -> Result<(), SystemError> { 838 match self.bpb.fat_type { 839 FATType::FAT32(_) => { 840 let raw_entry = self.get_fat_entry_raw(Cluster::new(1))? | 0x0800_0000; 841 self.set_entry(Cluster::new(1), FATEntry::Next(Cluster::new(raw_entry)))?; 842 843 return Ok(()); 844 } 845 846 FATType::FAT16(_) => { 847 let raw_entry = self.get_fat_entry_raw(Cluster::new(1))? | 0x8000; 848 self.set_entry(Cluster::new(1), FATEntry::Next(Cluster::new(raw_entry)))?; 849 return Ok(()); 850 } 851 _ => return Ok(()), 852 } 853 } 854 855 /// @brief 设置文件系统的hard error bit为正常状态 856 /// 参考资料:https://thestarman.pcministry.com/DOS/DirtyShutdownFlag.html 857 /// 858 /// @return Ok(()) 设置成功 859 /// @return Err(SystemError) 在设置过程中,出现错误 860 pub fn set_hard_error_bit_ok(&mut self) -> Result<(), SystemError> { 861 match self.bpb.fat_type { 862 FATType::FAT32(_) => { 863 let raw_entry = self.get_fat_entry_raw(Cluster::new(1))? | 0x0400_0000; 864 self.set_entry(Cluster::new(1), FATEntry::Next(Cluster::new(raw_entry)))?; 865 return Ok(()); 866 } 867 868 FATType::FAT16(_) => { 869 let raw_entry = self.get_fat_entry_raw(Cluster::new(1))? | 0x4000; 870 self.set_entry(Cluster::new(1), FATEntry::Next(Cluster::new(raw_entry)))?; 871 return Ok(()); 872 } 873 _ => return Ok(()), 874 } 875 } 876 877 /// @brief 执行文件系统卸载前的一些准备工作:设置好对应的标志位,并把缓存中的数据刷入磁盘 878 pub fn umount(&mut self) -> Result<(), SystemError> { 879 self.fs_info.0.lock().flush(&self.gendisk)?; 880 881 self.set_shut_bit_ok()?; 882 883 self.set_hard_error_bit_ok()?; 884 885 self.gendisk.sync()?; 886 887 return Ok(()); 888 } 889 890 /// @brief 获取文件系统的最大簇号 891 pub fn max_cluster_number(&self) -> Cluster { 892 match self.bpb.fat_type { 893 FATType::FAT32(s) => { 894 // FAT32 895 896 // 数据扇区数量(总扇区数-保留扇区-FAT占用的扇区) 897 let data_sec: u64 = self.bpb.total_sectors_32 as u64 898 - (self.bpb.rsvd_sec_cnt as u64 899 + self.bpb.num_fats as u64 * s.fat_size_32 as u64); 900 901 // 数据区的簇数量 902 let total_clusters: u64 = data_sec / self.bpb.sector_per_cluster as u64; 903 904 // 返回最大的簇号 905 return Cluster::new(total_clusters + RESERVED_CLUSTERS as u64 - 1); 906 } 907 908 _ => { 909 // FAT12 / FAT16 910 let root_dir_sectors: u64 = (((self.bpb.root_entries_cnt as u64) * 32) 911 + self.bpb.bytes_per_sector as u64 912 - 1) 913 / self.bpb.bytes_per_sector as u64; 914 // 数据区扇区数 915 let data_sec: u64 = self.bpb.total_sectors_16 as u64 916 - (self.bpb.rsvd_sec_cnt as u64 917 + (self.bpb.num_fats as u64 * self.bpb.fat_size_16 as u64) 918 + root_dir_sectors); 919 let total_clusters = data_sec / self.bpb.sector_per_cluster as u64; 920 return Cluster::new(total_clusters + RESERVED_CLUSTERS as u64 - 1); 921 } 922 } 923 } 924 925 /// @brief 在文件系统中寻找一个簇号在给定的范围(左闭右开区间)内的空闲簇 926 /// 927 /// @param start_cluster 起始簇号 928 /// @param end_cluster 终止簇号(不包含) 929 /// 930 /// @return Ok(Cluster) 寻找到的空闲簇 931 /// @return Err(SystemError) 错误码。如果磁盘无剩余空间,或者簇号达到给定的最大值,则返回-ENOSPC. 932 pub fn get_free_cluster( 933 &self, 934 start_cluster: Cluster, 935 end_cluster: Cluster, 936 ) -> Result<Cluster, SystemError> { 937 let max_cluster: Cluster = self.max_cluster_number(); 938 let mut cluster: u64 = start_cluster.cluster_num; 939 940 let fat_type: FATType = self.bpb.fat_type; 941 let fat_start_sector: u64 = self.fat_start_sector(); 942 let bytes_per_sec: u64 = self.bpb.bytes_per_sector as u64; 943 944 match fat_type { 945 FATType::FAT12(_) => { 946 let part_bytes_offset: u64 = 947 fat_type.get_fat_bytes_offset(start_cluster, fat_start_sector, bytes_per_sec); 948 let in_block_offset = self.get_in_block_offset(part_bytes_offset); 949 950 let lba = self.gendisk_lba_from_offset(self.bytes_to_sector(part_bytes_offset)); 951 952 // 由于FAT12的FAT表不大于6K,因此直接读取6K 953 let num_lba = (6 * 1024) / LBA_SIZE; 954 let mut v: Vec<u8> = vec![0; num_lba * LBA_SIZE]; 955 self.gendisk.read_at(&mut v, lba)?; 956 957 let mut cursor: VecCursor = VecCursor::new(v); 958 cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 959 960 let mut packed_val: u16 = cursor.read_u16()?; 961 loop { 962 let val = if (cluster & 0x1) > 0 { 963 packed_val >> 4 964 } else { 965 packed_val & 0x0fff 966 }; 967 if val == 0 { 968 return Ok(Cluster::new(cluster)); 969 } 970 971 cluster += 1; 972 973 // 磁盘无剩余空间,或者簇号达到给定的最大值 974 if cluster == end_cluster.cluster_num || cluster == max_cluster.cluster_num { 975 return Err(SystemError::ENOSPC); 976 } 977 978 packed_val = match cluster & 1 { 979 0 => cursor.read_u16()?, 980 _ => { 981 let next_byte = cursor.read_u8()? as u16; 982 (packed_val >> 8) | (next_byte << 8) 983 } 984 }; 985 } 986 } 987 FATType::FAT16(_) => { 988 // todo: 优化这里,减少读取磁盘的次数。 989 while cluster < end_cluster.cluster_num && cluster < max_cluster.cluster_num { 990 let part_bytes_offset: u64 = fat_type.get_fat_bytes_offset( 991 Cluster::new(cluster), 992 fat_start_sector, 993 bytes_per_sec, 994 ); 995 let in_block_offset = self.get_in_block_offset(part_bytes_offset); 996 997 let lba = self.gendisk_lba_from_offset(self.bytes_to_sector(part_bytes_offset)); 998 999 let mut v: Vec<u8> = vec![0; self.lba_per_sector() * LBA_SIZE]; 1000 self.gendisk.read_at(&mut v, lba)?; 1001 1002 let mut cursor: VecCursor = VecCursor::new(v); 1003 cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 1004 1005 let val = cursor.read_u16()?; 1006 // 找到空闲簇 1007 if val == 0 { 1008 return Ok(Cluster::new(val as u64)); 1009 } 1010 cluster += 1; 1011 } 1012 1013 // 磁盘无剩余空间,或者簇号达到给定的最大值 1014 return Err(SystemError::ENOSPC); 1015 } 1016 FATType::FAT32(_) => { 1017 // todo: 优化这里,减少读取磁盘的次数。 1018 while cluster < end_cluster.cluster_num && cluster < max_cluster.cluster_num { 1019 let part_bytes_offset: u64 = fat_type.get_fat_bytes_offset( 1020 Cluster::new(cluster), 1021 fat_start_sector, 1022 bytes_per_sec, 1023 ); 1024 let in_block_offset = self.get_in_block_offset(part_bytes_offset); 1025 1026 let lba = self.gendisk_lba_from_offset(self.bytes_to_sector(part_bytes_offset)); 1027 1028 let mut v: Vec<u8> = vec![0; self.lba_per_sector() * LBA_SIZE]; 1029 self.gendisk.read_at(&mut v, lba)?; 1030 1031 let mut cursor: VecCursor = VecCursor::new(v); 1032 cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 1033 1034 let val = cursor.read_u32()? & 0x0fffffff; 1035 1036 if val == 0 { 1037 return Ok(Cluster::new(cluster)); 1038 } 1039 cluster += 1; 1040 } 1041 1042 // 磁盘无剩余空间,或者簇号达到给定的最大值 1043 return Err(SystemError::ENOSPC); 1044 } 1045 } 1046 } 1047 1048 /// @brief 在FAT表中,设置指定的簇的信息。 1049 /// 1050 /// @param cluster 目标簇 1051 /// @param fat_entry 这个簇在FAT表中,存储的信息(下一个簇的簇号) 1052 pub fn set_entry(&self, cluster: Cluster, fat_entry: FATEntry) -> Result<(), SystemError> { 1053 // fat表项在分区上的字节偏移量 1054 let fat_part_bytes_offset: u64 = self.bpb.fat_type.get_fat_bytes_offset( 1055 cluster, 1056 self.fat_start_sector(), 1057 self.bpb.bytes_per_sector as u64, 1058 ); 1059 1060 match self.bpb.fat_type { 1061 FATType::FAT12(_) => { 1062 // 计算要写入的值 1063 let raw_val: u16 = match fat_entry { 1064 FATEntry::Unused => 0, 1065 FATEntry::Bad => 0xff7, 1066 FATEntry::EndOfChain => 0xfff, 1067 FATEntry::Next(c) => c.cluster_num as u16, 1068 }; 1069 1070 let in_block_offset = self.get_in_block_offset(fat_part_bytes_offset); 1071 1072 let lba = self.gendisk_lba_from_offset(self.bytes_to_sector(fat_part_bytes_offset)); 1073 1074 let mut v: Vec<u8> = vec![0; LBA_SIZE]; 1075 self.gendisk.read_at(&mut v, lba)?; 1076 1077 let mut cursor: VecCursor = VecCursor::new(v); 1078 cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 1079 1080 let old_val: u16 = cursor.read_u16()?; 1081 let new_val: u16 = if (cluster.cluster_num & 0x1) > 0 { 1082 (old_val & 0x000f) | (raw_val << 4) 1083 } else { 1084 (old_val & 0xf000) | raw_val 1085 }; 1086 1087 // 写回数据到磁盘上 1088 cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 1089 cursor.write_u16(new_val)?; 1090 self.gendisk.write_at(cursor.as_slice(), lba)?; 1091 return Ok(()); 1092 } 1093 FATType::FAT16(_) => { 1094 // 计算要写入的值 1095 let raw_val: u16 = match fat_entry { 1096 FATEntry::Unused => 0, 1097 FATEntry::Bad => 0xfff7, 1098 FATEntry::EndOfChain => 0xfdff, 1099 FATEntry::Next(c) => c.cluster_num as u16, 1100 }; 1101 1102 let in_block_offset = self.get_in_block_offset(fat_part_bytes_offset); 1103 1104 let lba = self.gendisk_lba_from_offset(self.bytes_to_sector(fat_part_bytes_offset)); 1105 1106 let mut v: Vec<u8> = vec![0; LBA_SIZE]; 1107 self.gendisk.read_at(&mut v, lba)?; 1108 1109 let mut cursor: VecCursor = VecCursor::new(v); 1110 cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 1111 1112 cursor.write_u16(raw_val)?; 1113 self.gendisk.write_at(cursor.as_slice(), lba)?; 1114 1115 return Ok(()); 1116 } 1117 FATType::FAT32(_) => { 1118 let fat_size: u64 = self.fat_size(); 1119 let bound: u64 = if self.mirroring_enabled() { 1120 1 1121 } else { 1122 self.bpb.num_fats as u64 1123 }; 1124 // debug!("set entry, bound={bound}, fat_size={fat_size}"); 1125 for i in 0..bound { 1126 // 当前操作的FAT表在磁盘上的字节偏移量 1127 let f_offset: u64 = fat_part_bytes_offset + i * fat_size; 1128 let in_block_offset: u64 = self.get_in_block_offset(f_offset); 1129 let lba = self.gendisk_lba_from_offset(self.bytes_to_sector(f_offset)); 1130 1131 // debug!("set entry, lba={lba}, in_block_offset={in_block_offset}"); 1132 let mut v: Vec<u8> = vec![0; LBA_SIZE]; 1133 self.gendisk.read_at(&mut v, lba)?; 1134 1135 let mut cursor: VecCursor = VecCursor::new(v); 1136 cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 1137 1138 // FAT32的高4位保留 1139 let old_bits = cursor.read_u32()? & 0xf0000000; 1140 1141 if fat_entry == FATEntry::Unused 1142 && cluster.cluster_num >= 0x0ffffff7 1143 && cluster.cluster_num <= 0x0fffffff 1144 { 1145 error!( 1146 "FAT32: Reserved Cluster {:?} cannot be marked as free", 1147 cluster 1148 ); 1149 return Err(SystemError::EPERM); 1150 } 1151 1152 // 计算要写入的值 1153 let mut raw_val: u32 = match fat_entry { 1154 FATEntry::Unused => 0, 1155 FATEntry::Bad => 0x0FFFFFF7, 1156 FATEntry::EndOfChain => 0x0FFFFFFF, 1157 FATEntry::Next(c) => c.cluster_num as u32, 1158 }; 1159 1160 // 恢复保留位 1161 raw_val |= old_bits; 1162 1163 // debug!("sent entry, raw_val={raw_val}"); 1164 1165 cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 1166 cursor.write_u32(raw_val)?; 1167 1168 self.gendisk.write_at(cursor.as_slice(), lba)?; 1169 } 1170 1171 return Ok(()); 1172 } 1173 } 1174 } 1175 1176 /// # 清空指定的簇 1177 /// 1178 /// # 参数 1179 /// - cluster 要被清空的簇 1180 pub fn zero_cluster(&self, cluster: Cluster) -> Result<(), SystemError> { 1181 // 准备数据,用于写入 1182 let zeros: Vec<u8> = vec![0u8; self.bytes_per_cluster() as usize]; 1183 let offset = self.cluster_bytes_offset(cluster) as usize; 1184 self.gendisk.write_at_bytes(&zeros, offset)?; 1185 return Ok(()); 1186 } 1187 } 1188 1189 impl Drop for FATFileSystem { 1190 fn drop(&mut self) { 1191 let r = self.umount(); 1192 if r.is_err() { 1193 error!( 1194 "Umount FAT filesystem failed: errno={:?}, FS detail:{self:?}", 1195 r.as_ref().unwrap_err() 1196 ); 1197 } 1198 } 1199 } 1200 1201 impl FATFsInfo { 1202 const LEAD_SIG: u32 = 0x41615252; 1203 const STRUC_SIG: u32 = 0x61417272; 1204 const TRAIL_SIG: u32 = 0xAA550000; 1205 #[allow(dead_code)] 1206 const FS_INFO_SIZE: u64 = 512; 1207 1208 /// @brief 从磁盘上读取FAT文件系统的FSInfo结构体 1209 /// 1210 /// @param partition 磁盘分区 1211 /// @param in_gendisk_fs_info_offset FSInfo扇区在gendisk内的字节偏移量(单位:字节) 1212 /// @param bytes_per_sec 每扇区字节数 1213 pub fn new( 1214 gendisk: &Arc<GenDisk>, 1215 in_gendisk_fs_info_offset: usize, 1216 bytes_per_sec: usize, 1217 ) -> Result<Self, SystemError> { 1218 let mut v = vec![0; bytes_per_sec]; 1219 1220 // 读取磁盘上的FsInfo扇区 1221 gendisk.read_at_bytes(&mut v, in_gendisk_fs_info_offset)?; 1222 1223 let mut cursor = VecCursor::new(v); 1224 1225 let mut fsinfo = FATFsInfo { 1226 lead_sig: cursor.read_u32()?, 1227 ..Default::default() 1228 }; 1229 cursor.seek(SeekFrom::SeekCurrent(480))?; 1230 fsinfo.struc_sig = cursor.read_u32()?; 1231 fsinfo.free_count = cursor.read_u32()?; 1232 fsinfo.next_free = cursor.read_u32()?; 1233 1234 cursor.seek(SeekFrom::SeekCurrent(12))?; 1235 1236 fsinfo.trail_sig = cursor.read_u32()?; 1237 fsinfo.dirty = false; 1238 fsinfo.offset = Some(gendisk.disk_bytes_offset(in_gendisk_fs_info_offset) as u64); 1239 1240 if fsinfo.is_valid() { 1241 return Ok(fsinfo); 1242 } else { 1243 error!("Error occurred while parsing FATFsInfo."); 1244 return Err(SystemError::EINVAL); 1245 } 1246 } 1247 1248 /// @brief 判断是否为正确的FsInfo结构体 1249 fn is_valid(&self) -> bool { 1250 self.lead_sig == Self::LEAD_SIG 1251 && self.struc_sig == Self::STRUC_SIG 1252 && self.trail_sig == Self::TRAIL_SIG 1253 } 1254 1255 /// @brief 根据fsinfo的信息,计算当前总的空闲簇数量 1256 /// 1257 /// @param 当前文件系统的最大簇号 1258 pub fn count_free_cluster(&self, max_cluster: Cluster) -> Option<u64> { 1259 let count_clusters = max_cluster.cluster_num - RESERVED_CLUSTERS as u64 + 1; 1260 // 信息不合理,当前的FsInfo中存储的free count大于计算出来的值 1261 if self.free_count as u64 > count_clusters { 1262 return None; 1263 } else { 1264 match self.free_count { 1265 // free count字段不可用 1266 0xffffffff => return None, 1267 // 返回FsInfo中存储的数据 1268 n => return Some(n as u64), 1269 } 1270 } 1271 } 1272 1273 /// @brief 更新FsInfo中的“空闲簇统计信息“为new_count 1274 /// 1275 /// 请注意,除非手动调用`flush()`,否则本函数不会将数据刷入磁盘 1276 pub fn update_free_count_abs(&mut self, new_count: u32) { 1277 self.free_count = new_count; 1278 } 1279 1280 /// @brief 更新FsInfo中的“空闲簇统计信息“,把它加上delta. 1281 /// 1282 /// 请注意,除非手动调用`flush()`,否则本函数不会将数据刷入磁盘 1283 pub fn update_free_count_delta(&mut self, delta: i32) { 1284 self.free_count = (self.free_count as i32 + delta) as u32; 1285 } 1286 1287 /// @brief 更新FsInfo中的“第一个空闲簇统计信息“为next_free. 1288 /// 1289 /// 请注意,除非手动调用`flush()`,否则本函数不会将数据刷入磁盘 1290 pub fn update_next_free(&mut self, next_free: u32) { 1291 // 这个值是参考量,不一定要准确,仅供加速查找 1292 self.next_free = next_free; 1293 } 1294 1295 /// @brief 获取fs info 记载的第一个空闲簇。(不一定准确,仅供参考) 1296 pub fn next_free(&self) -> Option<u64> { 1297 match self.next_free { 1298 0xffffffff => return None, 1299 0 | 1 => return None, 1300 n => return Some(n as u64), 1301 }; 1302 } 1303 1304 /// @brief 把fs info刷入磁盘 1305 /// 1306 /// @param partition fs info所在的分区 1307 pub fn flush(&self, gendisk: &Arc<GenDisk>) -> Result<(), SystemError> { 1308 if let Some(off) = self.offset { 1309 let in_block_offset = off % LBA_SIZE as u64; 1310 1311 let lba = off as usize / LBA_SIZE; 1312 1313 let mut v: Vec<u8> = vec![0; LBA_SIZE]; 1314 gendisk.read_at(&mut v, lba)?; 1315 1316 let mut cursor: VecCursor = VecCursor::new(v); 1317 cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 1318 1319 cursor.write_u32(self.lead_sig)?; 1320 cursor.seek(SeekFrom::SeekCurrent(480))?; 1321 cursor.write_u32(self.struc_sig)?; 1322 cursor.write_u32(self.free_count)?; 1323 cursor.write_u32(self.next_free)?; 1324 cursor.seek(SeekFrom::SeekCurrent(12))?; 1325 cursor.write_u32(self.trail_sig)?; 1326 1327 gendisk.write_at(cursor.as_slice(), lba)?; 1328 } 1329 return Ok(()); 1330 } 1331 1332 /// @brief 读取磁盘上的Fs Info扇区,将里面的内容更新到结构体中 1333 /// 1334 /// @param partition fs info所在的分区 1335 pub fn update(&mut self, partition: Arc<Partition>) -> Result<(), SystemError> { 1336 if let Some(off) = self.offset { 1337 let in_block_offset = off % LBA_SIZE as u64; 1338 1339 let lba = off as usize / LBA_SIZE; 1340 1341 let mut v: Vec<u8> = vec![0; LBA_SIZE]; 1342 partition.disk().read_at(lba, 1, &mut v)?; 1343 let mut cursor: VecCursor = VecCursor::new(v); 1344 cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 1345 self.lead_sig = cursor.read_u32()?; 1346 1347 cursor.seek(SeekFrom::SeekCurrent(480))?; 1348 self.struc_sig = cursor.read_u32()?; 1349 self.free_count = cursor.read_u32()?; 1350 self.next_free = cursor.read_u32()?; 1351 cursor.seek(SeekFrom::SeekCurrent(12))?; 1352 self.trail_sig = cursor.read_u32()?; 1353 } 1354 return Ok(()); 1355 } 1356 } 1357 1358 impl IndexNode for LockedFATInode { 1359 fn read_at( 1360 &self, 1361 offset: usize, 1362 len: usize, 1363 buf: &mut [u8], 1364 _data: SpinLockGuard<FilePrivateData>, 1365 ) -> Result<usize, SystemError> { 1366 let mut guard: SpinLockGuard<FATInode> = self.0.lock(); 1367 match &guard.inode_type { 1368 FATDirEntry::File(f) | FATDirEntry::VolId(f) => { 1369 let r = f.read( 1370 &guard.fs.upgrade().unwrap(), 1371 &mut buf[0..len], 1372 offset as u64, 1373 ); 1374 guard.update_metadata(); 1375 return r; 1376 } 1377 FATDirEntry::Dir(_) => { 1378 return Err(SystemError::EISDIR); 1379 } 1380 FATDirEntry::UnInit => { 1381 error!("FATFS: param: Inode_type uninitialized."); 1382 return Err(SystemError::EROFS); 1383 } 1384 } 1385 } 1386 1387 fn write_at( 1388 &self, 1389 offset: usize, 1390 len: usize, 1391 buf: &[u8], 1392 _data: SpinLockGuard<FilePrivateData>, 1393 ) -> Result<usize, SystemError> { 1394 let mut guard: SpinLockGuard<FATInode> = self.0.lock(); 1395 let fs: &Arc<FATFileSystem> = &guard.fs.upgrade().unwrap(); 1396 1397 match &mut guard.inode_type { 1398 FATDirEntry::File(f) | FATDirEntry::VolId(f) => { 1399 let r = f.write(fs, &buf[0..len], offset as u64); 1400 guard.update_metadata(); 1401 return r; 1402 } 1403 FATDirEntry::Dir(_) => { 1404 return Err(SystemError::EISDIR); 1405 } 1406 FATDirEntry::UnInit => { 1407 error!("FATFS: param: Inode_type uninitialized."); 1408 return Err(SystemError::EROFS); 1409 } 1410 } 1411 } 1412 1413 fn create( 1414 &self, 1415 name: &str, 1416 file_type: FileType, 1417 _mode: ModeType, 1418 ) -> Result<Arc<dyn IndexNode>, SystemError> { 1419 // 由于FAT32不支持文件权限的功能,因此忽略mode参数 1420 let mut guard: SpinLockGuard<FATInode> = self.0.lock(); 1421 let fs: &Arc<FATFileSystem> = &guard.fs.upgrade().unwrap(); 1422 1423 match &mut guard.inode_type { 1424 FATDirEntry::File(_) | FATDirEntry::VolId(_) => { 1425 return Err(SystemError::ENOTDIR); 1426 } 1427 FATDirEntry::Dir(d) => match file_type { 1428 FileType::File => { 1429 d.create_file(name, fs)?; 1430 return Ok(guard.find(name)?); 1431 } 1432 FileType::Dir => { 1433 d.create_dir(name, fs)?; 1434 return Ok(guard.find(name)?); 1435 } 1436 1437 FileType::SymLink => return Err(SystemError::ENOSYS), 1438 _ => return Err(SystemError::EINVAL), 1439 }, 1440 FATDirEntry::UnInit => { 1441 error!("FATFS: param: Inode_type uninitialized."); 1442 return Err(SystemError::EROFS); 1443 } 1444 } 1445 } 1446 1447 fn fs(&self) -> Arc<dyn FileSystem> { 1448 return self.0.lock().fs.upgrade().unwrap(); 1449 } 1450 1451 fn as_any_ref(&self) -> &dyn core::any::Any { 1452 return self; 1453 } 1454 1455 fn metadata(&self) -> Result<Metadata, SystemError> { 1456 return Ok(self.0.lock().metadata.clone()); 1457 } 1458 fn set_metadata(&self, metadata: &Metadata) -> Result<(), SystemError> { 1459 let inode = &mut self.0.lock(); 1460 inode.metadata.atime = metadata.atime; 1461 inode.metadata.mtime = metadata.mtime; 1462 inode.metadata.ctime = metadata.ctime; 1463 inode.metadata.mode = metadata.mode; 1464 inode.metadata.uid = metadata.uid; 1465 inode.metadata.gid = metadata.gid; 1466 Ok(()) 1467 } 1468 fn resize(&self, len: usize) -> Result<(), SystemError> { 1469 let mut guard: SpinLockGuard<FATInode> = self.0.lock(); 1470 let fs: &Arc<FATFileSystem> = &guard.fs.upgrade().unwrap(); 1471 let old_size = guard.metadata.size as usize; 1472 1473 match &mut guard.inode_type { 1474 FATDirEntry::File(file) | FATDirEntry::VolId(file) => { 1475 // 如果新的长度和旧的长度相同,那么就直接返回 1476 match len.cmp(&old_size) { 1477 Ordering::Equal => { 1478 return Ok(()); 1479 } 1480 Ordering::Greater => { 1481 // 如果新的长度比旧的长度大,那么就在文件末尾添加空白 1482 let mut buf: Vec<u8> = Vec::new(); 1483 let mut remain_size = len - old_size; 1484 let buf_size = remain_size; 1485 // let buf_size = core::cmp::min(remain_size, 512 * 1024); 1486 buf.resize(buf_size, 0); 1487 1488 let mut offset = old_size; 1489 while remain_size > 0 { 1490 let write_size = core::cmp::min(remain_size, buf_size); 1491 file.write(fs, &buf[0..write_size], offset as u64)?; 1492 remain_size -= write_size; 1493 offset += write_size; 1494 } 1495 } 1496 Ordering::Less => { 1497 file.truncate(fs, len as u64)?; 1498 } 1499 } 1500 guard.update_metadata(); 1501 return Ok(()); 1502 } 1503 FATDirEntry::Dir(_) => return Err(SystemError::ENOSYS), 1504 FATDirEntry::UnInit => { 1505 error!("FATFS: param: Inode_type uninitialized."); 1506 return Err(SystemError::EROFS); 1507 } 1508 } 1509 } 1510 1511 fn truncate(&self, len: usize) -> Result<(), SystemError> { 1512 let guard: SpinLockGuard<FATInode> = self.0.lock(); 1513 let old_size = guard.metadata.size as usize; 1514 if len < old_size { 1515 drop(guard); 1516 self.resize(len) 1517 } else { 1518 Ok(()) 1519 } 1520 } 1521 1522 fn list(&self) -> Result<Vec<String>, SystemError> { 1523 let mut guard: SpinLockGuard<FATInode> = self.0.lock(); 1524 let fatent: &FATDirEntry = &guard.inode_type; 1525 match fatent { 1526 FATDirEntry::File(_) | FATDirEntry::VolId(_) => { 1527 return Err(SystemError::ENOTDIR); 1528 } 1529 FATDirEntry::Dir(dir) => { 1530 // 获取当前目录下的所有目录项 1531 let mut ret: Vec<String> = Vec::new(); 1532 let dir_iter: FATDirIter = dir.to_iter(guard.fs.upgrade().unwrap()); 1533 for ent in dir_iter { 1534 ret.push(ent.name()); 1535 1536 // ====== 生成inode缓存,存入B树 1537 let name = DName::from(ent.name().to_uppercase()); 1538 // debug!("name={name}"); 1539 1540 if !guard.children.contains_key(&name) 1541 && name.as_ref() != "." 1542 && name.as_ref() != ".." 1543 { 1544 // 创建新的inode 1545 let entry_inode: Arc<LockedFATInode> = LockedFATInode::new( 1546 name.clone(), 1547 guard.fs.upgrade().unwrap(), 1548 guard.self_ref.clone(), 1549 ent, 1550 ); 1551 // 加入缓存区, 由于FAT文件系统的大小写不敏感问题,因此存入缓存区的key应当是全大写的 1552 guard.children.insert(name, entry_inode.clone()); 1553 } 1554 } 1555 return Ok(ret); 1556 } 1557 FATDirEntry::UnInit => { 1558 error!("FATFS: param: Inode_type uninitialized."); 1559 return Err(SystemError::EROFS); 1560 } 1561 } 1562 } 1563 1564 fn find(&self, name: &str) -> Result<Arc<dyn IndexNode>, SystemError> { 1565 let mut guard: SpinLockGuard<FATInode> = self.0.lock(); 1566 let target = guard.find(name)?; 1567 return Ok(target); 1568 } 1569 1570 fn open( 1571 &self, 1572 _data: SpinLockGuard<FilePrivateData>, 1573 _mode: &FileMode, 1574 ) -> Result<(), SystemError> { 1575 return Ok(()); 1576 } 1577 1578 fn close(&self, _data: SpinLockGuard<FilePrivateData>) -> Result<(), SystemError> { 1579 return Ok(()); 1580 } 1581 1582 fn unlink(&self, name: &str) -> Result<(), SystemError> { 1583 let mut guard: SpinLockGuard<FATInode> = self.0.lock(); 1584 let target: Arc<LockedFATInode> = guard.find(name)?; 1585 // 对目标inode上锁,以防更改 1586 let target_guard: SpinLockGuard<FATInode> = target.0.lock(); 1587 // 先从缓存删除 1588 let nod = guard.children.remove(&DName::from(name.to_uppercase())); 1589 1590 // 若删除缓存中为管道的文件,则不需要再到磁盘删除 1591 if nod.is_some() { 1592 let file_type = target_guard.metadata.file_type; 1593 if file_type == FileType::Pipe { 1594 return Ok(()); 1595 } 1596 } 1597 1598 let dir = match &guard.inode_type { 1599 FATDirEntry::File(_) | FATDirEntry::VolId(_) => { 1600 return Err(SystemError::ENOTDIR); 1601 } 1602 FATDirEntry::Dir(d) => d, 1603 FATDirEntry::UnInit => { 1604 error!("FATFS: param: Inode_type uninitialized."); 1605 return Err(SystemError::EROFS); 1606 } 1607 }; 1608 // 检查文件是否存在 1609 dir.check_existence(name, Some(false), guard.fs.upgrade().unwrap())?; 1610 1611 // 再从磁盘删除 1612 let r = dir.remove(guard.fs.upgrade().unwrap().clone(), name, true); 1613 drop(target_guard); 1614 return r; 1615 } 1616 1617 fn rmdir(&self, name: &str) -> Result<(), SystemError> { 1618 let mut guard: SpinLockGuard<FATInode> = self.0.lock(); 1619 let target: Arc<LockedFATInode> = guard.find(name)?; 1620 // 对目标inode上锁,以防更改 1621 let target_guard: SpinLockGuard<FATInode> = target.0.lock(); 1622 // 先从缓存删除 1623 guard.children.remove(&DName::from(name.to_uppercase())); 1624 1625 let dir = match &guard.inode_type { 1626 FATDirEntry::File(_) | FATDirEntry::VolId(_) => { 1627 return Err(SystemError::ENOTDIR); 1628 } 1629 FATDirEntry::Dir(d) => d, 1630 FATDirEntry::UnInit => { 1631 error!("FATFS: param: Inode_type uninitialized."); 1632 return Err(SystemError::EROFS); 1633 } 1634 }; 1635 // 检查文件夹是否存在 1636 dir.check_existence(name, Some(true), guard.fs.upgrade().unwrap())?; 1637 1638 // 再从磁盘删除 1639 let r: Result<(), SystemError> = 1640 dir.remove(guard.fs.upgrade().unwrap().clone(), name, true); 1641 match r { 1642 Ok(_) => return r, 1643 Err(r) => { 1644 if r == SystemError::ENOTEMPTY { 1645 // 如果要删除的是目录,且不为空,则删除动作未发生,重新加入缓存 1646 guard 1647 .children 1648 .insert(DName::from(name.to_uppercase()), target.clone()); 1649 drop(target_guard); 1650 } 1651 return Err(r); 1652 } 1653 } 1654 } 1655 1656 fn move_to( 1657 &self, 1658 old_name: &str, 1659 target: &Arc<dyn IndexNode>, 1660 new_name: &str, 1661 ) -> Result<(), SystemError> { 1662 let old_id = self.metadata().unwrap().inode_id; 1663 let new_id = target.metadata().unwrap().inode_id; 1664 // 若在同一父目录下 1665 if old_id == new_id { 1666 let mut guard = self.0.lock(); 1667 let old_inode: Arc<LockedFATInode> = guard.find(old_name)?; 1668 // 对目标inode上锁,以防更改 1669 let old_inode_guard: SpinLockGuard<FATInode> = old_inode.0.lock(); 1670 let fs = old_inode_guard.fs.upgrade().unwrap(); 1671 // 从缓存删除 1672 let _nod = guard.children.remove(&DName::from(old_name.to_uppercase())); 1673 let old_dir = match &guard.inode_type { 1674 FATDirEntry::File(_) | FATDirEntry::VolId(_) => { 1675 return Err(SystemError::ENOTDIR); 1676 } 1677 FATDirEntry::Dir(d) => d, 1678 FATDirEntry::UnInit => { 1679 error!("FATFS: param: Inode_type uninitialized."); 1680 return Err(SystemError::EROFS); 1681 } 1682 }; 1683 // 检查文件是否存在 1684 // old_dir.check_existence(old_name, Some(false), guard.fs.upgrade().unwrap())?; 1685 1686 old_dir.rename(fs, old_name, new_name)?; 1687 } else { 1688 let mut old_guard = self.0.lock(); 1689 let other: &LockedFATInode = target 1690 .downcast_ref::<LockedFATInode>() 1691 .ok_or(SystemError::EPERM)?; 1692 1693 let new_guard = other.0.lock(); 1694 let old_inode: Arc<LockedFATInode> = old_guard.find(old_name)?; 1695 // 对目标inode上锁,以防更改 1696 let old_inode_guard: SpinLockGuard<FATInode> = old_inode.0.lock(); 1697 let fs = old_inode_guard.fs.upgrade().unwrap(); 1698 // 从缓存删除 1699 let _nod = old_guard 1700 .children 1701 .remove(&DName::from(old_name.to_uppercase())); 1702 let old_dir = match &old_guard.inode_type { 1703 FATDirEntry::File(_) | FATDirEntry::VolId(_) => { 1704 return Err(SystemError::ENOTDIR); 1705 } 1706 FATDirEntry::Dir(d) => d, 1707 FATDirEntry::UnInit => { 1708 error!("FATFS: param: Inode_type uninitialized."); 1709 return Err(SystemError::EROFS); 1710 } 1711 }; 1712 let new_dir = match &new_guard.inode_type { 1713 FATDirEntry::File(_) | FATDirEntry::VolId(_) => { 1714 return Err(SystemError::ENOTDIR); 1715 } 1716 FATDirEntry::Dir(d) => d, 1717 FATDirEntry::UnInit => { 1718 error!("FATFA: param: Inode_type uninitialized."); 1719 return Err(SystemError::EROFS); 1720 } 1721 }; 1722 // 检查文件是否存在 1723 old_dir.check_existence(old_name, Some(false), old_guard.fs.upgrade().unwrap())?; 1724 old_dir.rename_across(fs, new_dir, old_name, new_name)?; 1725 } 1726 1727 return Ok(()); 1728 } 1729 1730 fn get_entry_name(&self, ino: InodeId) -> Result<String, SystemError> { 1731 let guard: SpinLockGuard<FATInode> = self.0.lock(); 1732 if guard.metadata.file_type != FileType::Dir { 1733 return Err(SystemError::ENOTDIR); 1734 } 1735 match ino.into() { 1736 0 => { 1737 return Ok(String::from(".")); 1738 } 1739 1 => { 1740 return Ok(String::from("..")); 1741 } 1742 ino => { 1743 // 暴力遍历所有的children,判断inode id是否相同 1744 // TODO: 优化这里,这个地方性能很差! 1745 let mut key: Vec<String> = guard 1746 .children 1747 .iter() 1748 .filter_map(|(k, v)| { 1749 if v.0.lock().metadata.inode_id.into() == ino { 1750 Some(k.to_string()) 1751 } else { 1752 None 1753 } 1754 }) 1755 .collect(); 1756 1757 match key.len() { 1758 0=>{return Err(SystemError::ENOENT);} 1759 1=>{return Ok(key.remove(0));} 1760 _ => panic!("FatFS get_entry_name: key.len()={key_len}>1, current inode_id={inode_id:?}, to find={to_find:?}", key_len=key.len(), inode_id = guard.metadata.inode_id, to_find=ino) 1761 } 1762 } 1763 } 1764 } 1765 1766 fn mknod( 1767 &self, 1768 filename: &str, 1769 mode: ModeType, 1770 _dev_t: DeviceNumber, 1771 ) -> Result<Arc<dyn IndexNode>, SystemError> { 1772 let mut inode = self.0.lock(); 1773 if inode.metadata.file_type != FileType::Dir { 1774 return Err(SystemError::ENOTDIR); 1775 } 1776 1777 // 判断需要创建的类型 1778 if unlikely(mode.contains(ModeType::S_IFREG)) { 1779 // 普通文件 1780 return self.create(filename, FileType::File, mode); 1781 } 1782 1783 let filename = DName::from(filename.to_uppercase()); 1784 let nod = LockedFATInode::new( 1785 filename.clone(), 1786 inode.fs.upgrade().unwrap(), 1787 inode.self_ref.clone(), 1788 FATDirEntry::File(FATFile::default()), 1789 ); 1790 1791 if mode.contains(ModeType::S_IFIFO) { 1792 nod.0.lock().metadata.file_type = FileType::Pipe; 1793 // 创建pipe文件 1794 let pipe_inode = LockedPipeInode::new(); 1795 // 设置special_node 1796 nod.0.lock().special_node = Some(SpecialNodeData::Pipe(pipe_inode)); 1797 } else if mode.contains(ModeType::S_IFBLK) { 1798 nod.0.lock().metadata.file_type = FileType::BlockDevice; 1799 unimplemented!() 1800 } else if mode.contains(ModeType::S_IFCHR) { 1801 nod.0.lock().metadata.file_type = FileType::CharDevice; 1802 unimplemented!() 1803 } else { 1804 return Err(SystemError::EINVAL); 1805 } 1806 1807 inode.children.insert(filename, nod.clone()); 1808 Ok(nod) 1809 } 1810 1811 fn special_node(&self) -> Option<SpecialNodeData> { 1812 self.0.lock().special_node.clone() 1813 } 1814 1815 fn dname(&self) -> Result<DName, SystemError> { 1816 Ok(self.0.lock().dname.clone()) 1817 } 1818 1819 fn parent(&self) -> Result<Arc<dyn IndexNode>, SystemError> { 1820 self.0 1821 .lock() 1822 .parent 1823 .upgrade() 1824 .map(|item| item as Arc<dyn IndexNode>) 1825 .ok_or(SystemError::EINVAL) 1826 } 1827 } 1828 1829 impl Default for FATFsInfo { 1830 fn default() -> Self { 1831 return FATFsInfo { 1832 lead_sig: FATFsInfo::LEAD_SIG, 1833 struc_sig: FATFsInfo::STRUC_SIG, 1834 free_count: 0xFFFFFFFF, 1835 next_free: RESERVED_CLUSTERS, 1836 trail_sig: FATFsInfo::TRAIL_SIG, 1837 dirty: false, 1838 offset: None, 1839 }; 1840 } 1841 } 1842 1843 impl Cluster { 1844 pub fn new(cluster: u64) -> Self { 1845 return Cluster { 1846 cluster_num: cluster, 1847 parent_cluster: 0, 1848 }; 1849 } 1850 } 1851 1852 /// @brief 用于迭代FAT表的内容的簇迭代器对象 1853 #[derive(Debug)] 1854 struct ClusterIter<'a> { 1855 /// 迭代器的next要返回的簇 1856 current_cluster: Option<Cluster>, 1857 /// 属于的文件系统 1858 fs: &'a FATFileSystem, 1859 } 1860 1861 impl<'a> Iterator for ClusterIter<'a> { 1862 type Item = Cluster; 1863 1864 fn next(&mut self) -> Option<Self::Item> { 1865 // 当前要返回的簇 1866 let ret: Option<Cluster> = self.current_cluster; 1867 1868 // 获得下一个要返回簇 1869 let new: Option<Cluster> = match self.current_cluster { 1870 Some(c) => { 1871 let entry: Option<FATEntry> = self.fs.get_fat_entry(c).ok(); 1872 match entry { 1873 Some(FATEntry::Next(c)) => Some(c), 1874 _ => None, 1875 } 1876 } 1877 _ => None, 1878 }; 1879 1880 self.current_cluster = new; 1881 return ret; 1882 } 1883 } 1884