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