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