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