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