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