11074eb34SSamuel Dai use alloc::string::ToString; 2b5b571e0SLoGin use core::cmp::Ordering; 32dbef785SGnoCiYeH use core::intrinsics::unlikely; 4004e86ffSlogin use core::{any::Any, fmt::Debug}; 52eab6dd7S曾俊 use log::error; 691e9d4abSLoGin use system_error::SystemError; 7004e86ffSlogin 8004e86ffSlogin use alloc::{ 9004e86ffSlogin collections::BTreeMap, 10004e86ffSlogin string::String, 11004e86ffSlogin sync::{Arc, Weak}, 12004e86ffSlogin vec::Vec, 13004e86ffSlogin }; 14004e86ffSlogin 15*9fa0e95eSLoGin use crate::driver::base::block::gendisk::GenDisk; 16c566df45SLoGin use crate::driver::base::device::device_number::DeviceNumber; 171074eb34SSamuel Dai use crate::filesystem::vfs::utils::DName; 18597ecc08STTaq use crate::filesystem::vfs::{Magic, SpecialNodeData, SuperBlock}; 192dbef785SGnoCiYeH use crate::ipc::pipe::LockedPipeInode; 20004e86ffSlogin use crate::{ 21b087521eSChiichen driver::base::block::{block_device::LBA_SIZE, disk_info::Partition, SeekFrom}, 22004e86ffSlogin filesystem::vfs::{ 2373c607aaSYJwu2023 core::generate_inode_id, 2473c607aaSYJwu2023 file::{FileMode, FilePrivateData}, 256b4e7a29SLoGin syscall::ModeType, 2640609970SGnoCiYeH FileSystem, FileType, IndexNode, InodeId, Metadata, 27004e86ffSlogin }, 28004e86ffSlogin libs::{ 29004e86ffSlogin spinlock::{SpinLock, SpinLockGuard}, 30004e86ffSlogin vec_cursor::VecCursor, 31004e86ffSlogin }, 326fc066acSJomo time::PosixTimeSpec, 33004e86ffSlogin }; 34004e86ffSlogin 352dbef785SGnoCiYeH use super::entry::FATFile; 36004e86ffSlogin use super::{ 37004e86ffSlogin bpb::{BiosParameterBlock, FATType}, 38004e86ffSlogin entry::{FATDir, FATDirEntry, FATDirIter, FATEntry}, 39004e86ffSlogin utils::RESERVED_CLUSTERS, 40004e86ffSlogin }; 41004e86ffSlogin 42597ecc08STTaq const FAT_MAX_NAMELEN: u64 = 255; 43597ecc08STTaq 44004e86ffSlogin /// FAT32文件系统的最大的文件大小 45004e86ffSlogin pub const MAX_FILE_SIZE: u64 = 0xffff_ffff; 46004e86ffSlogin 47004e86ffSlogin /// @brief 表示当前簇和上一个簇的关系的结构体 48004e86ffSlogin /// 定义这样一个结构体的原因是,FAT文件系统的文件中,前后两个簇具有关联关系。 49bd70d2d1SLoGin #[allow(dead_code)] 50004e86ffSlogin #[derive(Debug, Clone, Copy, Default)] 51004e86ffSlogin pub struct Cluster { 52004e86ffSlogin pub cluster_num: u64, 53004e86ffSlogin pub parent_cluster: u64, 54004e86ffSlogin } 55004e86ffSlogin 56004e86ffSlogin impl PartialOrd for Cluster { 57004e86ffSlogin /// @brief 根据当前簇号比较大小 58004e86ffSlogin fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> { 59004e86ffSlogin return self.cluster_num.partial_cmp(&other.cluster_num); 60004e86ffSlogin } 61004e86ffSlogin } 62004e86ffSlogin 63004e86ffSlogin impl PartialEq for Cluster { 64004e86ffSlogin /// @brief 根据当前簇号比较是否相等 65004e86ffSlogin fn eq(&self, other: &Self) -> bool { 66004e86ffSlogin self.cluster_num == other.cluster_num 67004e86ffSlogin } 68004e86ffSlogin } 69004e86ffSlogin 70004e86ffSlogin impl Eq for Cluster {} 71004e86ffSlogin 72004e86ffSlogin #[derive(Debug)] 73004e86ffSlogin pub struct FATFileSystem { 74004e86ffSlogin /// 当前文件系统所在的分区 75*9fa0e95eSLoGin pub gendisk: Arc<GenDisk>, 76004e86ffSlogin /// 当前文件系统的BOPB 77004e86ffSlogin pub bpb: BiosParameterBlock, 78004e86ffSlogin /// 当前文件系统的第一个数据扇区(相对分区开始位置) 79004e86ffSlogin pub first_data_sector: u64, 80004e86ffSlogin /// 文件系统信息结构体 81004e86ffSlogin pub fs_info: Arc<LockedFATFsInfo>, 82004e86ffSlogin /// 文件系统的根inode 83004e86ffSlogin root_inode: Arc<LockedFATInode>, 84004e86ffSlogin } 85004e86ffSlogin 86004e86ffSlogin /// FAT文件系统的Inode 87004e86ffSlogin #[derive(Debug)] 88004e86ffSlogin pub struct LockedFATInode(SpinLock<FATInode>); 89004e86ffSlogin 90004e86ffSlogin #[derive(Debug)] 91004e86ffSlogin pub struct LockedFATFsInfo(SpinLock<FATFsInfo>); 92004e86ffSlogin 93004e86ffSlogin impl LockedFATFsInfo { 94004e86ffSlogin #[inline] 95004e86ffSlogin pub fn new(fs_info: FATFsInfo) -> Self { 96004e86ffSlogin return Self(SpinLock::new(fs_info)); 97004e86ffSlogin } 98004e86ffSlogin } 99004e86ffSlogin 100004e86ffSlogin #[derive(Debug)] 101004e86ffSlogin pub struct FATInode { 102004e86ffSlogin /// 指向父Inode的弱引用 103004e86ffSlogin parent: Weak<LockedFATInode>, 104004e86ffSlogin /// 指向自身的弱引用 105004e86ffSlogin self_ref: Weak<LockedFATInode>, 106004e86ffSlogin /// 子Inode的B树. 该数据结构用作缓存区。其中,它的key表示inode的名称。 107004e86ffSlogin /// 请注意,由于FAT的查询过程对大小写不敏感,因此我们选择让key全部是大写的,方便统一操作。 1081074eb34SSamuel Dai children: BTreeMap<DName, Arc<LockedFATInode>>, 109004e86ffSlogin /// 当前inode的元数据 110004e86ffSlogin metadata: Metadata, 111004e86ffSlogin /// 指向inode所在的文件系统对象的指针 112004e86ffSlogin fs: Weak<FATFileSystem>, 113004e86ffSlogin 114004e86ffSlogin /// 根据不同的Inode类型,创建不同的私有字段 115004e86ffSlogin inode_type: FATDirEntry, 1162dbef785SGnoCiYeH 1172dbef785SGnoCiYeH /// 若该节点是特殊文件节点,该字段则为真正的文件节点 1182dbef785SGnoCiYeH special_node: Option<SpecialNodeData>, 1191074eb34SSamuel Dai 1201074eb34SSamuel Dai /// 目录名 1211074eb34SSamuel Dai dname: DName, 122004e86ffSlogin } 123004e86ffSlogin 124004e86ffSlogin impl FATInode { 125004e86ffSlogin /// @brief 更新当前inode的元数据 126004e86ffSlogin pub fn update_metadata(&mut self) { 127004e86ffSlogin // todo: 更新文件的访问时间等信息 128004e86ffSlogin match &self.inode_type { 129004e86ffSlogin FATDirEntry::File(f) | FATDirEntry::VolId(f) => { 130004e86ffSlogin self.metadata.size = f.size() as i64; 131004e86ffSlogin } 132004e86ffSlogin FATDirEntry::Dir(d) => { 133004e86ffSlogin self.metadata.size = d.size(&self.fs.upgrade().unwrap().clone()) as i64; 134004e86ffSlogin } 135004e86ffSlogin FATDirEntry::UnInit => { 1362eab6dd7S曾俊 error!("update_metadata: Uninitialized FATDirEntry: {:?}", self); 137004e86ffSlogin return; 138004e86ffSlogin } 139004e86ffSlogin }; 140004e86ffSlogin } 141004e86ffSlogin 142676b8ef6SMork fn find(&mut self, name: &str) -> Result<Arc<LockedFATInode>, SystemError> { 143004e86ffSlogin match &self.inode_type { 144004e86ffSlogin FATDirEntry::Dir(d) => { 1451074eb34SSamuel Dai let dname = DName::from(name.to_uppercase()); 146004e86ffSlogin // 尝试在缓存区查找 1471074eb34SSamuel Dai if let Some(entry) = self.children.get(&dname) { 148004e86ffSlogin return Ok(entry.clone()); 149004e86ffSlogin } 150004e86ffSlogin // 在缓存区找不到 151004e86ffSlogin // 在磁盘查找 152004e86ffSlogin let fat_entry: FATDirEntry = 153004e86ffSlogin d.find_entry(name, None, None, self.fs.upgrade().unwrap())?; 154004e86ffSlogin // 创建新的inode 155004e86ffSlogin let entry_inode: Arc<LockedFATInode> = LockedFATInode::new( 1561074eb34SSamuel Dai dname.clone(), 157004e86ffSlogin self.fs.upgrade().unwrap(), 158004e86ffSlogin self.self_ref.clone(), 159004e86ffSlogin fat_entry, 160004e86ffSlogin ); 161004e86ffSlogin // 加入缓存区, 由于FAT文件系统的大小写不敏感问题,因此存入缓存区的key应当是全大写的 1621074eb34SSamuel Dai self.children.insert(dname, entry_inode.clone()); 163004e86ffSlogin return Ok(entry_inode); 164004e86ffSlogin } 165004e86ffSlogin FATDirEntry::UnInit => { 166004e86ffSlogin panic!( 167004e86ffSlogin "Uninitialized FAT Inode, fs = {:?}, inode={self:?}", 168004e86ffSlogin self.fs 169004e86ffSlogin ) 170004e86ffSlogin } 171004e86ffSlogin _ => { 172676b8ef6SMork return Err(SystemError::ENOTDIR); 173004e86ffSlogin } 174004e86ffSlogin } 175004e86ffSlogin } 176004e86ffSlogin } 177004e86ffSlogin 178004e86ffSlogin impl LockedFATInode { 179004e86ffSlogin pub fn new( 1801074eb34SSamuel Dai dname: DName, 181004e86ffSlogin fs: Arc<FATFileSystem>, 182004e86ffSlogin parent: Weak<LockedFATInode>, 183004e86ffSlogin inode_type: FATDirEntry, 184004e86ffSlogin ) -> Arc<LockedFATInode> { 185004e86ffSlogin let file_type = if let FATDirEntry::Dir(_) = inode_type { 186004e86ffSlogin FileType::Dir 187004e86ffSlogin } else { 188004e86ffSlogin FileType::File 189004e86ffSlogin }; 190004e86ffSlogin 191004e86ffSlogin let inode: Arc<LockedFATInode> = Arc::new(LockedFATInode(SpinLock::new(FATInode { 192b5b571e0SLoGin parent, 193004e86ffSlogin self_ref: Weak::default(), 194004e86ffSlogin children: BTreeMap::new(), 195004e86ffSlogin fs: Arc::downgrade(&fs), 196b5b571e0SLoGin inode_type, 197004e86ffSlogin metadata: Metadata { 198004e86ffSlogin dev_id: 0, 199004e86ffSlogin inode_id: generate_inode_id(), 200004e86ffSlogin size: 0, 201004e86ffSlogin blk_size: fs.bpb.bytes_per_sector as usize, 202004e86ffSlogin blocks: if let FATType::FAT32(_) = fs.bpb.fat_type { 203004e86ffSlogin fs.bpb.total_sectors_32 as usize 204004e86ffSlogin } else { 205004e86ffSlogin fs.bpb.total_sectors_16 as usize 206004e86ffSlogin }, 2076fc066acSJomo atime: PosixTimeSpec::default(), 2086fc066acSJomo mtime: PosixTimeSpec::default(), 2096fc066acSJomo ctime: PosixTimeSpec::default(), 210b5b571e0SLoGin file_type, 2116b4e7a29SLoGin mode: ModeType::from_bits_truncate(0o777), 212004e86ffSlogin nlinks: 1, 213004e86ffSlogin uid: 0, 214004e86ffSlogin gid: 0, 21502343d0bSLoGin raw_dev: DeviceNumber::default(), 216004e86ffSlogin }, 2172dbef785SGnoCiYeH special_node: None, 2181074eb34SSamuel Dai dname, 219004e86ffSlogin }))); 220004e86ffSlogin 221004e86ffSlogin inode.0.lock().self_ref = Arc::downgrade(&inode); 222004e86ffSlogin 223004e86ffSlogin inode.0.lock().update_metadata(); 224004e86ffSlogin 225004e86ffSlogin return inode; 226004e86ffSlogin } 227004e86ffSlogin } 228004e86ffSlogin 229004e86ffSlogin /// FsInfo结构体(内存中的一份拷贝,当卸载卷或者sync的时候,把它写入磁盘) 230004e86ffSlogin #[derive(Debug)] 231004e86ffSlogin pub struct FATFsInfo { 232004e86ffSlogin /// Lead Signature - must equal 0x41615252 233004e86ffSlogin lead_sig: u32, 234004e86ffSlogin /// Value must equal 0x61417272 235004e86ffSlogin struc_sig: u32, 236004e86ffSlogin /// 空闲簇数目 237004e86ffSlogin free_count: u32, 238004e86ffSlogin /// 第一个空闲簇的位置(不一定准确,仅供加速查找) 239004e86ffSlogin next_free: u32, 240004e86ffSlogin /// 0xAA550000 241004e86ffSlogin trail_sig: u32, 242004e86ffSlogin /// Dirty flag to flush to disk 243004e86ffSlogin dirty: bool, 244004e86ffSlogin /// FsInfo Structure 在磁盘上的字节偏移量 245004e86ffSlogin /// Not present for FAT12 and FAT16 246004e86ffSlogin offset: Option<u64>, 247004e86ffSlogin } 248004e86ffSlogin 249004e86ffSlogin impl FileSystem for FATFileSystem { 250004e86ffSlogin fn root_inode(&self) -> Arc<dyn crate::filesystem::vfs::IndexNode> { 251004e86ffSlogin return self.root_inode.clone(); 252004e86ffSlogin } 253004e86ffSlogin 254004e86ffSlogin fn info(&self) -> crate::filesystem::vfs::FsInfo { 255004e86ffSlogin todo!() 256004e86ffSlogin } 257004e86ffSlogin 258004e86ffSlogin /// @brief 本函数用于实现动态转换。 259004e86ffSlogin /// 具体的文件系统在实现本函数时,最简单的方式就是:直接返回self 260004e86ffSlogin fn as_any_ref(&self) -> &dyn Any { 261004e86ffSlogin self 262004e86ffSlogin } 2631d37ca6dSDonkey Kane 2641d37ca6dSDonkey Kane fn name(&self) -> &str { 2651d37ca6dSDonkey Kane "fat" 2661d37ca6dSDonkey Kane } 267597ecc08STTaq 268597ecc08STTaq fn super_block(&self) -> SuperBlock { 269597ecc08STTaq SuperBlock::new( 270597ecc08STTaq Magic::FAT_MAGIC, 271597ecc08STTaq self.bpb.bytes_per_sector.into(), 272597ecc08STTaq FAT_MAX_NAMELEN, 273597ecc08STTaq ) 274597ecc08STTaq } 275004e86ffSlogin } 276004e86ffSlogin 277004e86ffSlogin impl FATFileSystem { 2782286eda6SWaferJay /// FAT12允许的最大簇号 2792286eda6SWaferJay pub const FAT12_MAX_CLUSTER: u32 = 0xFF5; 2802286eda6SWaferJay /// FAT16允许的最大簇号 2812286eda6SWaferJay pub const FAT16_MAX_CLUSTER: u32 = 0xFFF5; 2822286eda6SWaferJay /// FAT32允许的最大簇号 2832286eda6SWaferJay pub const FAT32_MAX_CLUSTER: u32 = 0x0FFFFFF7; 2842286eda6SWaferJay 285*9fa0e95eSLoGin pub fn new(gendisk: Arc<GenDisk>) -> Result<Arc<FATFileSystem>, SystemError> { 286*9fa0e95eSLoGin let bpb = BiosParameterBlock::new(&gendisk)?; 287004e86ffSlogin // 从磁盘上读取FAT32文件系统的FsInfo结构体 288004e86ffSlogin let fs_info: FATFsInfo = match bpb.fat_type { 289004e86ffSlogin FATType::FAT32(bpb32) => { 290*9fa0e95eSLoGin let fs_info_in_gendisk_bytes_offset = 291*9fa0e95eSLoGin bpb32.fs_info as usize * bpb.bytes_per_sector as usize; 292004e86ffSlogin FATFsInfo::new( 293*9fa0e95eSLoGin &gendisk, 294*9fa0e95eSLoGin fs_info_in_gendisk_bytes_offset, 295004e86ffSlogin bpb.bytes_per_sector as usize, 296004e86ffSlogin )? 297004e86ffSlogin } 298004e86ffSlogin _ => FATFsInfo::default(), 299004e86ffSlogin }; 300004e86ffSlogin 301004e86ffSlogin // 根目录项占用的扇区数(向上取整) 302004e86ffSlogin let root_dir_sectors: u64 = ((bpb.root_entries_cnt as u64 * 32) 303004e86ffSlogin + (bpb.bytes_per_sector as u64 - 1)) 304004e86ffSlogin / (bpb.bytes_per_sector as u64); 305004e86ffSlogin 306004e86ffSlogin // FAT表大小(单位:扇区) 307004e86ffSlogin let fat_size = if bpb.fat_size_16 != 0 { 308004e86ffSlogin bpb.fat_size_16 as u64 309004e86ffSlogin } else { 310004e86ffSlogin match bpb.fat_type { 311004e86ffSlogin FATType::FAT32(x) => x.fat_size_32 as u64, 312004e86ffSlogin _ => { 3132eab6dd7S曾俊 error!("FAT12 and FAT16 volumes should have non-zero BPB_FATSz16"); 314676b8ef6SMork return Err(SystemError::EINVAL); 315004e86ffSlogin } 316004e86ffSlogin } 317004e86ffSlogin }; 318004e86ffSlogin 319004e86ffSlogin let first_data_sector = 320004e86ffSlogin bpb.rsvd_sec_cnt as u64 + (bpb.num_fats as u64 * fat_size) + root_dir_sectors; 321004e86ffSlogin 322004e86ffSlogin // 创建文件系统的根节点 323004e86ffSlogin let root_inode: Arc<LockedFATInode> = Arc::new(LockedFATInode(SpinLock::new(FATInode { 324004e86ffSlogin parent: Weak::default(), 325004e86ffSlogin self_ref: Weak::default(), 326004e86ffSlogin children: BTreeMap::new(), 327004e86ffSlogin fs: Weak::default(), 328004e86ffSlogin inode_type: FATDirEntry::UnInit, 329004e86ffSlogin metadata: Metadata { 330004e86ffSlogin dev_id: 0, 331004e86ffSlogin inode_id: generate_inode_id(), 332004e86ffSlogin size: 0, 333004e86ffSlogin blk_size: bpb.bytes_per_sector as usize, 334004e86ffSlogin blocks: if let FATType::FAT32(_) = bpb.fat_type { 335004e86ffSlogin bpb.total_sectors_32 as usize 336004e86ffSlogin } else { 337004e86ffSlogin bpb.total_sectors_16 as usize 338004e86ffSlogin }, 3396fc066acSJomo atime: PosixTimeSpec::default(), 3406fc066acSJomo mtime: PosixTimeSpec::default(), 3416fc066acSJomo ctime: PosixTimeSpec::default(), 342004e86ffSlogin file_type: FileType::Dir, 3436b4e7a29SLoGin mode: ModeType::from_bits_truncate(0o777), 344004e86ffSlogin nlinks: 1, 345004e86ffSlogin uid: 0, 346004e86ffSlogin gid: 0, 34702343d0bSLoGin raw_dev: DeviceNumber::default(), 348004e86ffSlogin }, 3492dbef785SGnoCiYeH special_node: None, 3501074eb34SSamuel Dai dname: DName::default(), 351004e86ffSlogin }))); 352004e86ffSlogin 353004e86ffSlogin let result: Arc<FATFileSystem> = Arc::new(FATFileSystem { 354*9fa0e95eSLoGin gendisk, 355004e86ffSlogin bpb, 356004e86ffSlogin first_data_sector, 357004e86ffSlogin fs_info: Arc::new(LockedFATFsInfo::new(fs_info)), 358b5b571e0SLoGin root_inode, 359004e86ffSlogin }); 360004e86ffSlogin 361004e86ffSlogin // 对root inode加锁,并继续完成初始化工作 362004e86ffSlogin let mut root_guard: SpinLockGuard<FATInode> = result.root_inode.0.lock(); 363004e86ffSlogin root_guard.inode_type = FATDirEntry::Dir(result.root_dir()); 364004e86ffSlogin root_guard.parent = Arc::downgrade(&result.root_inode); 365004e86ffSlogin root_guard.self_ref = Arc::downgrade(&result.root_inode); 366004e86ffSlogin root_guard.fs = Arc::downgrade(&result); 367004e86ffSlogin // 释放锁 368004e86ffSlogin drop(root_guard); 369004e86ffSlogin 370004e86ffSlogin return Ok(result); 371004e86ffSlogin } 372004e86ffSlogin 373004e86ffSlogin /// @brief 计算每个簇有多少个字节 374004e86ffSlogin #[inline] 375004e86ffSlogin pub fn bytes_per_cluster(&self) -> u64 { 376004e86ffSlogin return (self.bpb.bytes_per_sector as u64) * (self.bpb.sector_per_cluster as u64); 377004e86ffSlogin } 378004e86ffSlogin 379004e86ffSlogin /// @brief 读取当前簇在FAT表中存储的信息 380004e86ffSlogin /// 381004e86ffSlogin /// @param cluster 当前簇 382004e86ffSlogin /// 383004e86ffSlogin /// @return Ok(FATEntry) 当前簇在FAT表中,存储的信息。(详情见FATEntry的注释) 384676b8ef6SMork /// @return Err(SystemError) 错误码 385676b8ef6SMork pub fn get_fat_entry(&self, cluster: Cluster) -> Result<FATEntry, SystemError> { 386004e86ffSlogin let current_cluster = cluster.cluster_num; 3876d81180bSLoGin if current_cluster < 2 { 3886d81180bSLoGin // 0号簇和1号簇是保留簇,不允许用户使用 3896d81180bSLoGin return Err(SystemError::EINVAL); 3906d81180bSLoGin } 391004e86ffSlogin 392004e86ffSlogin let fat_type: FATType = self.bpb.fat_type; 393004e86ffSlogin // 获取FAT表的起始扇区(相对分区起始扇区的偏移量) 394004e86ffSlogin let fat_start_sector = self.fat_start_sector(); 395004e86ffSlogin let bytes_per_sec = self.bpb.bytes_per_sector as u64; 396004e86ffSlogin 397004e86ffSlogin // cluster对应的FAT表项在分区内的字节偏移量 398004e86ffSlogin let fat_bytes_offset = 399004e86ffSlogin fat_type.get_fat_bytes_offset(cluster, fat_start_sector, bytes_per_sec); 400004e86ffSlogin 401*9fa0e95eSLoGin // FAT表项所在的分区内LBA地址 402*9fa0e95eSLoGin let fat_ent_lba = fat_bytes_offset / LBA_SIZE as u64; 403004e86ffSlogin 404004e86ffSlogin // FAT表项在逻辑块内的字节偏移量 405004e86ffSlogin let blk_offset = self.get_in_block_offset(fat_bytes_offset); 406004e86ffSlogin 407b5b571e0SLoGin let mut v: Vec<u8> = vec![0; self.bpb.bytes_per_sector as usize]; 408*9fa0e95eSLoGin self.gendisk.read_at(&mut v, fat_ent_lba as usize)?; 409004e86ffSlogin 410004e86ffSlogin let mut cursor = VecCursor::new(v); 411004e86ffSlogin cursor.seek(SeekFrom::SeekSet(blk_offset as i64))?; 412004e86ffSlogin 413004e86ffSlogin let res: FATEntry = match self.bpb.fat_type { 414004e86ffSlogin FATType::FAT12(_) => { 415004e86ffSlogin let mut entry = cursor.read_u16()?; 416004e86ffSlogin // 由于FAT12文件系统的FAT表,每个entry占用1.5字节,因此奇数的簇需要取高12位的值。 417004e86ffSlogin if (current_cluster & 1) > 0 { 418004e86ffSlogin entry >>= 4; 419004e86ffSlogin } else { 420004e86ffSlogin entry &= 0x0fff; 421004e86ffSlogin } 422004e86ffSlogin 423004e86ffSlogin if entry == 0 { 424004e86ffSlogin FATEntry::Unused 425004e86ffSlogin } else if entry == 0x0ff7 { 426004e86ffSlogin FATEntry::Bad 427004e86ffSlogin } else if entry >= 0x0ff8 { 428004e86ffSlogin FATEntry::EndOfChain 429004e86ffSlogin } else { 430004e86ffSlogin FATEntry::Next(Cluster { 431004e86ffSlogin cluster_num: entry as u64, 432004e86ffSlogin parent_cluster: current_cluster, 433004e86ffSlogin }) 434004e86ffSlogin } 435004e86ffSlogin } 436004e86ffSlogin FATType::FAT16(_) => { 437004e86ffSlogin let entry = cursor.read_u16()?; 438004e86ffSlogin 439004e86ffSlogin if entry == 0 { 440004e86ffSlogin FATEntry::Unused 441004e86ffSlogin } else if entry == 0xfff7 { 442004e86ffSlogin FATEntry::Bad 443004e86ffSlogin } else if entry >= 0xfff8 { 444004e86ffSlogin FATEntry::EndOfChain 445004e86ffSlogin } else { 446004e86ffSlogin FATEntry::Next(Cluster { 447004e86ffSlogin cluster_num: entry as u64, 448004e86ffSlogin parent_cluster: current_cluster, 449004e86ffSlogin }) 450004e86ffSlogin } 451004e86ffSlogin } 452004e86ffSlogin FATType::FAT32(_) => { 453004e86ffSlogin let entry = cursor.read_u32()? & 0x0fffffff; 454004e86ffSlogin 455004e86ffSlogin match entry { 456b5b571e0SLoGin _n if (0x0ffffff7..=0x0fffffff).contains(¤t_cluster) => { 457004e86ffSlogin // 当前簇号不是一个能被获得的簇(可能是文件系统出错了) 4582eab6dd7S曾俊 error!("FAT32 get fat entry: current cluster number [{}] is not an allocatable cluster number.", current_cluster); 459004e86ffSlogin FATEntry::Bad 460004e86ffSlogin } 461004e86ffSlogin 0 => FATEntry::Unused, 462004e86ffSlogin 0x0ffffff7 => FATEntry::Bad, 463004e86ffSlogin 0x0ffffff8..=0x0fffffff => FATEntry::EndOfChain, 464004e86ffSlogin _n => FATEntry::Next(Cluster { 465004e86ffSlogin cluster_num: entry as u64, 466004e86ffSlogin parent_cluster: current_cluster, 467004e86ffSlogin }), 468004e86ffSlogin } 469004e86ffSlogin } 470004e86ffSlogin }; 471004e86ffSlogin return Ok(res); 472004e86ffSlogin } 473004e86ffSlogin 474004e86ffSlogin /// @brief 读取当前簇在FAT表中存储的信息(直接返回读取到的值,而不加处理) 475004e86ffSlogin /// 476004e86ffSlogin /// @param cluster 当前簇 477004e86ffSlogin /// 478004e86ffSlogin /// @return Ok(u64) 当前簇在FAT表中,存储的信息。 479676b8ef6SMork /// @return Err(SystemError) 错误码 480676b8ef6SMork pub fn get_fat_entry_raw(&self, cluster: Cluster) -> Result<u64, SystemError> { 481004e86ffSlogin let current_cluster = cluster.cluster_num; 482004e86ffSlogin 483004e86ffSlogin let fat_type: FATType = self.bpb.fat_type; 484004e86ffSlogin // 获取FAT表的起始扇区(相对分区起始扇区的偏移量) 485004e86ffSlogin let fat_start_sector = self.fat_start_sector(); 486004e86ffSlogin let bytes_per_sec = self.bpb.bytes_per_sector as u64; 487004e86ffSlogin 488004e86ffSlogin // cluster对应的FAT表项在分区内的字节偏移量 489004e86ffSlogin let fat_bytes_offset = 490004e86ffSlogin fat_type.get_fat_bytes_offset(cluster, fat_start_sector, bytes_per_sec); 491004e86ffSlogin 492*9fa0e95eSLoGin // FAT表项所在的分区内LBA地址 493*9fa0e95eSLoGin let fat_ent_lba = self.gendisk_lba_from_offset(self.bytes_to_sector(fat_bytes_offset)); 494004e86ffSlogin 495004e86ffSlogin // FAT表项在逻辑块内的字节偏移量 496004e86ffSlogin let blk_offset = self.get_in_block_offset(fat_bytes_offset); 497004e86ffSlogin 498b5b571e0SLoGin let mut v: Vec<u8> = vec![0; self.bpb.bytes_per_sector as usize]; 499*9fa0e95eSLoGin self.gendisk.read_at(&mut v, fat_ent_lba)?; 500004e86ffSlogin 501004e86ffSlogin let mut cursor = VecCursor::new(v); 502004e86ffSlogin cursor.seek(SeekFrom::SeekSet(blk_offset as i64))?; 503004e86ffSlogin 504004e86ffSlogin let res = match self.bpb.fat_type { 505004e86ffSlogin FATType::FAT12(_) => { 506004e86ffSlogin let mut entry = cursor.read_u16()?; 507004e86ffSlogin entry = if (current_cluster & 0x0001) > 0 { 508004e86ffSlogin entry >> 4 509004e86ffSlogin } else { 510004e86ffSlogin entry & 0x0fff 511004e86ffSlogin }; 512004e86ffSlogin entry as u64 513004e86ffSlogin } 514004e86ffSlogin FATType::FAT16(_) => { 515004e86ffSlogin let entry = (cursor.read_u16()?) as u64; 516004e86ffSlogin entry 517004e86ffSlogin } 518004e86ffSlogin FATType::FAT32(_) => { 519004e86ffSlogin let entry = cursor.read_u32()? & 0x0fff_ffff; 520004e86ffSlogin entry as u64 521004e86ffSlogin } 522004e86ffSlogin }; 523004e86ffSlogin 524004e86ffSlogin return Ok(res); 525004e86ffSlogin } 526004e86ffSlogin 527*9fa0e95eSLoGin /// @brief 获取当前文件系统的root inode,在分区内的字节偏移量 528004e86ffSlogin pub fn root_dir_bytes_offset(&self) -> u64 { 529004e86ffSlogin match self.bpb.fat_type { 530004e86ffSlogin FATType::FAT32(s) => { 531004e86ffSlogin let first_sec_cluster: u64 = (s.root_cluster as u64 - 2) 532004e86ffSlogin * (self.bpb.sector_per_cluster as u64) 533004e86ffSlogin + self.first_data_sector; 534*9fa0e95eSLoGin return (self.gendisk_lba_from_offset(first_sec_cluster) * LBA_SIZE) as u64; 535004e86ffSlogin } 536004e86ffSlogin _ => { 537004e86ffSlogin let root_sec = (self.bpb.rsvd_sec_cnt as u64) 538004e86ffSlogin + (self.bpb.num_fats as u64) * (self.bpb.fat_size_16 as u64); 539*9fa0e95eSLoGin return (self.gendisk_lba_from_offset(root_sec) * LBA_SIZE) as u64; 540004e86ffSlogin } 541004e86ffSlogin } 542004e86ffSlogin } 543004e86ffSlogin 544*9fa0e95eSLoGin /// @brief 获取当前文件系统的根目录项区域的结束位置,在分区内的字节偏移量。 545004e86ffSlogin /// 请注意,当前函数只对FAT12/FAT16生效。对于FAT32,返回None 546004e86ffSlogin pub fn root_dir_end_bytes_offset(&self) -> Option<u64> { 547004e86ffSlogin match self.bpb.fat_type { 548004e86ffSlogin FATType::FAT12(_) | FATType::FAT16(_) => { 549004e86ffSlogin return Some( 550004e86ffSlogin self.root_dir_bytes_offset() + (self.bpb.root_entries_cnt as u64) * 32, 551004e86ffSlogin ); 552004e86ffSlogin } 553004e86ffSlogin _ => { 554004e86ffSlogin return None; 555004e86ffSlogin } 556004e86ffSlogin } 557004e86ffSlogin } 558004e86ffSlogin 559*9fa0e95eSLoGin /// 获取簇在分区内的字节偏移量 560004e86ffSlogin pub fn cluster_bytes_offset(&self, cluster: Cluster) -> u64 { 561004e86ffSlogin if cluster.cluster_num >= 2 { 562004e86ffSlogin // 指定簇的第一个扇区号 563004e86ffSlogin let first_sec_of_cluster = (cluster.cluster_num - 2) 564004e86ffSlogin * (self.bpb.sector_per_cluster as u64) 565004e86ffSlogin + self.first_data_sector; 566*9fa0e95eSLoGin return first_sec_of_cluster * (self.bpb.bytes_per_sector as u64); 567004e86ffSlogin } else { 568004e86ffSlogin return 0; 569004e86ffSlogin } 570004e86ffSlogin } 571004e86ffSlogin 572004e86ffSlogin /// @brief 获取一个空闲簇 573004e86ffSlogin /// 574004e86ffSlogin /// @param prev_cluster 簇链的前一个簇。本函数将会把新获取的簇,连接到它的后面。 575004e86ffSlogin /// 576004e86ffSlogin /// @return Ok(Cluster) 新获取的空闲簇 577676b8ef6SMork /// @return Err(SystemError) 错误码 578676b8ef6SMork pub fn allocate_cluster(&self, prev_cluster: Option<Cluster>) -> Result<Cluster, SystemError> { 579004e86ffSlogin let end_cluster: Cluster = self.max_cluster_number(); 580004e86ffSlogin let start_cluster: Cluster = match self.bpb.fat_type { 581004e86ffSlogin FATType::FAT32(_) => { 582b5b571e0SLoGin let next_free: u64 = self.fs_info.0.lock().next_free().unwrap_or(0xffffffff); 583004e86ffSlogin if next_free < end_cluster.cluster_num { 584004e86ffSlogin Cluster::new(next_free) 585004e86ffSlogin } else { 586004e86ffSlogin Cluster::new(RESERVED_CLUSTERS as u64) 587004e86ffSlogin } 588004e86ffSlogin } 589004e86ffSlogin _ => Cluster::new(RESERVED_CLUSTERS as u64), 590004e86ffSlogin }; 591004e86ffSlogin 592004e86ffSlogin // 寻找一个空的簇 593004e86ffSlogin let free_cluster: Cluster = match self.get_free_cluster(start_cluster, end_cluster) { 594004e86ffSlogin Ok(c) => c, 595004e86ffSlogin Err(_) if start_cluster.cluster_num > RESERVED_CLUSTERS as u64 => { 596004e86ffSlogin self.get_free_cluster(Cluster::new(RESERVED_CLUSTERS as u64), end_cluster)? 597004e86ffSlogin } 598004e86ffSlogin Err(e) => return Err(e), 599004e86ffSlogin }; 600004e86ffSlogin 601004e86ffSlogin self.set_entry(free_cluster, FATEntry::EndOfChain)?; 602004e86ffSlogin // 减少空闲簇计数 603004e86ffSlogin self.fs_info.0.lock().update_free_count_delta(-1); 604004e86ffSlogin // 更新搜索空闲簇的参考量 605004e86ffSlogin self.fs_info 606004e86ffSlogin .0 607004e86ffSlogin .lock() 608004e86ffSlogin .update_next_free((free_cluster.cluster_num + 1) as u32); 609004e86ffSlogin 610004e86ffSlogin // 如果这个空闲簇不是簇链的第一个簇,那么把当前簇跟前一个簇连上。 611004e86ffSlogin if let Some(prev_cluster) = prev_cluster { 6122eab6dd7S曾俊 // debug!("set entry, prev ={prev_cluster:?}, next = {free_cluster:?}"); 613004e86ffSlogin self.set_entry(prev_cluster, FATEntry::Next(free_cluster))?; 614004e86ffSlogin } 615004e86ffSlogin // 清空新获取的这个簇 616004e86ffSlogin self.zero_cluster(free_cluster)?; 617004e86ffSlogin return Ok(free_cluster); 618004e86ffSlogin } 619004e86ffSlogin 620004e86ffSlogin /// @brief 释放簇链上的所有簇 621004e86ffSlogin /// 622004e86ffSlogin /// @param start_cluster 簇链的第一个簇 623676b8ef6SMork pub fn deallocate_cluster_chain(&self, start_cluster: Cluster) -> Result<(), SystemError> { 624004e86ffSlogin let clusters: Vec<Cluster> = self.clusters(start_cluster); 625004e86ffSlogin for c in clusters { 626004e86ffSlogin self.deallocate_cluster(c)?; 627004e86ffSlogin } 628004e86ffSlogin return Ok(()); 629004e86ffSlogin } 630004e86ffSlogin 631004e86ffSlogin /// @brief 释放簇 632004e86ffSlogin /// 633004e86ffSlogin /// @param 要释放的簇 634676b8ef6SMork pub fn deallocate_cluster(&self, cluster: Cluster) -> Result<(), SystemError> { 635004e86ffSlogin let entry: FATEntry = self.get_fat_entry(cluster)?; 636004e86ffSlogin // 如果不是坏簇 637004e86ffSlogin if entry != FATEntry::Bad { 638004e86ffSlogin self.set_entry(cluster, FATEntry::Unused)?; 639004e86ffSlogin self.fs_info.0.lock().update_free_count_delta(1); 640004e86ffSlogin // 安全选项:清空被释放的簇 641bd70d2d1SLoGin #[cfg(feature = "fatfs-secure")] 642004e86ffSlogin self.zero_cluster(cluster)?; 643004e86ffSlogin return Ok(()); 644004e86ffSlogin } else { 645004e86ffSlogin // 不能释放坏簇 6462eab6dd7S曾俊 error!("Bad clusters cannot be freed."); 647676b8ef6SMork return Err(SystemError::EFAULT); 648004e86ffSlogin } 649004e86ffSlogin } 650004e86ffSlogin 651004e86ffSlogin /// @brief 获取文件系统的根目录项 652004e86ffSlogin pub fn root_dir(&self) -> FATDir { 653004e86ffSlogin match self.bpb.fat_type { 654004e86ffSlogin FATType::FAT32(s) => { 655004e86ffSlogin return FATDir { 656004e86ffSlogin first_cluster: Cluster::new(s.root_cluster as u64), 657004e86ffSlogin dir_name: String::from("/"), 658004e86ffSlogin root_offset: None, 659004e86ffSlogin short_dir_entry: None, 660004e86ffSlogin loc: None, 661004e86ffSlogin }; 662004e86ffSlogin } 663004e86ffSlogin _ => FATDir { 664004e86ffSlogin first_cluster: Cluster::new(0), 665004e86ffSlogin dir_name: String::from("/"), 666004e86ffSlogin root_offset: Some(self.root_dir_bytes_offset()), 667004e86ffSlogin short_dir_entry: None, 668004e86ffSlogin loc: None, 669004e86ffSlogin }, 670004e86ffSlogin } 671004e86ffSlogin } 672004e86ffSlogin 673004e86ffSlogin /// @brief 获取FAT表的起始扇区(相对分区起始扇区的偏移量) 674004e86ffSlogin pub fn fat_start_sector(&self) -> u64 { 675004e86ffSlogin let active_fat = self.active_fat(); 676004e86ffSlogin let fat_size = self.fat_size(); 677004e86ffSlogin return self.bpb.rsvd_sec_cnt as u64 + active_fat * fat_size; 678004e86ffSlogin } 679004e86ffSlogin 680004e86ffSlogin /// @brief 获取当前活动的FAT表 681004e86ffSlogin pub fn active_fat(&self) -> u64 { 682004e86ffSlogin if self.mirroring_enabled() { 683004e86ffSlogin return 0; 684004e86ffSlogin } else { 685004e86ffSlogin match self.bpb.fat_type { 686004e86ffSlogin FATType::FAT32(bpb32) => { 687004e86ffSlogin return (bpb32.ext_flags & 0x0f) as u64; 688004e86ffSlogin } 689004e86ffSlogin _ => { 690004e86ffSlogin return 0; 691004e86ffSlogin } 692004e86ffSlogin } 693004e86ffSlogin } 694004e86ffSlogin } 695004e86ffSlogin 696004e86ffSlogin /// @brief 获取当前文件系统的每个FAT表的大小 697004e86ffSlogin pub fn fat_size(&self) -> u64 { 698004e86ffSlogin if self.bpb.fat_size_16 != 0 { 699004e86ffSlogin return self.bpb.fat_size_16 as u64; 700004e86ffSlogin } else { 701004e86ffSlogin match self.bpb.fat_type { 702004e86ffSlogin FATType::FAT32(bpb32) => { 703004e86ffSlogin return bpb32.fat_size_32 as u64; 704004e86ffSlogin } 705004e86ffSlogin 706004e86ffSlogin _ => { 707004e86ffSlogin panic!("FAT12 and FAT16 volumes should have non-zero BPB_FATSz16"); 708004e86ffSlogin } 709004e86ffSlogin } 710004e86ffSlogin } 711004e86ffSlogin } 712004e86ffSlogin 713004e86ffSlogin /// @brief 判断当前文件系统是否启用了FAT表镜像 714004e86ffSlogin pub fn mirroring_enabled(&self) -> bool { 715004e86ffSlogin match self.bpb.fat_type { 716004e86ffSlogin FATType::FAT32(bpb32) => { 717004e86ffSlogin return (bpb32.ext_flags & 0x80) == 0; 718004e86ffSlogin } 719004e86ffSlogin _ => { 720004e86ffSlogin return false; 721004e86ffSlogin } 722004e86ffSlogin } 723004e86ffSlogin } 724004e86ffSlogin 725*9fa0e95eSLoGin /// 获取分区内的扇区偏移量 726004e86ffSlogin #[inline] 727*9fa0e95eSLoGin pub fn gendisk_lba_from_offset(&self, in_partition_sec_offset: u64) -> usize { 728*9fa0e95eSLoGin return (in_partition_sec_offset * (self.bpb.bytes_per_sector as u64 / LBA_SIZE as u64)) 729004e86ffSlogin as usize; 730004e86ffSlogin } 731004e86ffSlogin 732004e86ffSlogin /// @brief 获取每个扇区占用多少个LBA 733004e86ffSlogin #[inline] 734004e86ffSlogin pub fn lba_per_sector(&self) -> usize { 735004e86ffSlogin return self.bpb.bytes_per_sector as usize / LBA_SIZE; 736004e86ffSlogin } 737004e86ffSlogin 738004e86ffSlogin /// @brief 将分区内字节偏移量转换为扇区偏移量 739004e86ffSlogin #[inline] 740004e86ffSlogin pub fn bytes_to_sector(&self, in_partition_bytes_offset: u64) -> u64 { 741004e86ffSlogin return in_partition_bytes_offset / (self.bpb.bytes_per_sector as u64); 742004e86ffSlogin } 743004e86ffSlogin 744004e86ffSlogin /// @brief 根据字节偏移量计算在逻辑块内的字节偏移量 745004e86ffSlogin #[inline] 746004e86ffSlogin pub fn get_in_block_offset(&self, bytes_offset: u64) -> u64 { 747004e86ffSlogin return bytes_offset % LBA_SIZE as u64; 748004e86ffSlogin } 749004e86ffSlogin 750004e86ffSlogin /// @brief 获取在FAT表中,以start_cluster开头的FAT链的所有簇的信息 751004e86ffSlogin /// 752004e86ffSlogin /// @param start_cluster 整个FAT链的起始簇号 753004e86ffSlogin pub fn clusters(&self, start_cluster: Cluster) -> Vec<Cluster> { 754004e86ffSlogin return self.cluster_iter(start_cluster).collect(); 755004e86ffSlogin } 756004e86ffSlogin 757004e86ffSlogin /// @brief 获取在FAT表中,以start_cluster开头的FAT链的长度(总计经过多少个簇) 758004e86ffSlogin /// 759004e86ffSlogin /// @param start_cluster 整个FAT链的起始簇号 760004e86ffSlogin pub fn num_clusters_chain(&self, start_cluster: Cluster) -> u64 { 761004e86ffSlogin return self 762004e86ffSlogin .cluster_iter(start_cluster) 763004e86ffSlogin .fold(0, |size, _cluster| size + 1); 764004e86ffSlogin } 765004e86ffSlogin /// @brief 获取一个簇迭代器对象 766004e86ffSlogin /// 767004e86ffSlogin /// @param start_cluster 整个FAT链的起始簇号 768004e86ffSlogin fn cluster_iter(&self, start_cluster: Cluster) -> ClusterIter { 769004e86ffSlogin return ClusterIter { 770004e86ffSlogin current_cluster: Some(start_cluster), 771004e86ffSlogin fs: self, 772004e86ffSlogin }; 773004e86ffSlogin } 774004e86ffSlogin 775004e86ffSlogin /// @brief 获取从start_cluster开始的簇链中,第n个簇的信息。(请注意,下标从0开始) 776004e86ffSlogin #[inline] 777004e86ffSlogin pub fn get_cluster_by_relative(&self, start_cluster: Cluster, n: usize) -> Option<Cluster> { 778b5b571e0SLoGin return self.cluster_iter(start_cluster).nth(n); 779004e86ffSlogin } 780004e86ffSlogin 781004e86ffSlogin /// @brief 获取整个簇链的最后一个簇 782004e86ffSlogin #[inline] 783004e86ffSlogin pub fn get_last_cluster(&self, start_cluster: Cluster) -> Option<Cluster> { 784004e86ffSlogin return self.cluster_iter(start_cluster).last(); 785004e86ffSlogin } 786004e86ffSlogin 787004e86ffSlogin /// @brief 判断FAT文件系统的shut bit是否正常。 788004e86ffSlogin /// shut bit 表示文件系统是否正常卸载。如果这一位是1,则表示这个卷是“干净的” 789004e86ffSlogin /// 参考资料:https://thestarman.pcministry.com/DOS/DirtyShutdownFlag.html 790004e86ffSlogin /// 791004e86ffSlogin /// @return Ok(true) 正常 792004e86ffSlogin /// @return Ok(false) 不正常 793676b8ef6SMork /// @return Err(SystemError) 在判断时发生错误 79491e9d4abSLoGin #[allow(dead_code)] 795676b8ef6SMork pub fn is_shut_bit_ok(&mut self) -> Result<bool, SystemError> { 796004e86ffSlogin match self.bpb.fat_type { 797004e86ffSlogin FATType::FAT32(_) => { 798004e86ffSlogin // 对于FAT32, error bit位于第一个扇区的第8字节。 799004e86ffSlogin let bit = self.get_fat_entry_raw(Cluster::new(1))? & 0x0800_0000; 800004e86ffSlogin return Ok(bit > 0); 801004e86ffSlogin } 802004e86ffSlogin FATType::FAT16(_) => { 803004e86ffSlogin let bit = self.get_fat_entry_raw(Cluster::new(1))? & 0x8000; 804004e86ffSlogin return Ok(bit > 0); 805004e86ffSlogin } 806004e86ffSlogin _ => return Ok(true), 807004e86ffSlogin } 808004e86ffSlogin } 809004e86ffSlogin 810004e86ffSlogin /// @brief 判断FAT文件系统的hard error bit是否正常。 811004e86ffSlogin /// 如果此位为0,则文件系统驱动程序在上次安装卷时遇到磁盘 I/O 错误,这表明 812004e86ffSlogin /// 卷上的某些扇区可能已损坏。 813004e86ffSlogin /// 参考资料:https://thestarman.pcministry.com/DOS/DirtyShutdownFlag.html 814004e86ffSlogin /// 815004e86ffSlogin /// @return Ok(true) 正常 816004e86ffSlogin /// @return Ok(false) 不正常 817676b8ef6SMork /// @return Err(SystemError) 在判断时发生错误 818676b8ef6SMork pub fn is_hard_error_bit_ok(&mut self) -> Result<bool, SystemError> { 819004e86ffSlogin match self.bpb.fat_type { 820004e86ffSlogin FATType::FAT32(_) => { 821004e86ffSlogin let bit = self.get_fat_entry_raw(Cluster::new(1))? & 0x0400_0000; 822004e86ffSlogin return Ok(bit > 0); 823004e86ffSlogin } 824004e86ffSlogin FATType::FAT16(_) => { 825004e86ffSlogin let bit = self.get_fat_entry_raw(Cluster::new(1))? & 0x4000; 826004e86ffSlogin return Ok(bit > 0); 827004e86ffSlogin } 828004e86ffSlogin _ => return Ok(true), 829004e86ffSlogin } 830004e86ffSlogin } 831004e86ffSlogin 832004e86ffSlogin /// @brief 设置文件系统的shut bit为正常状态 833004e86ffSlogin /// 参考资料:https://thestarman.pcministry.com/DOS/DirtyShutdownFlag.html 834004e86ffSlogin /// 835004e86ffSlogin /// @return Ok(()) 设置成功 836676b8ef6SMork /// @return Err(SystemError) 在设置过程中,出现错误 837676b8ef6SMork pub fn set_shut_bit_ok(&mut self) -> Result<(), SystemError> { 838004e86ffSlogin match self.bpb.fat_type { 839004e86ffSlogin FATType::FAT32(_) => { 840004e86ffSlogin let raw_entry = self.get_fat_entry_raw(Cluster::new(1))? | 0x0800_0000; 841004e86ffSlogin self.set_entry(Cluster::new(1), FATEntry::Next(Cluster::new(raw_entry)))?; 842004e86ffSlogin 843004e86ffSlogin return Ok(()); 844004e86ffSlogin } 845004e86ffSlogin 846004e86ffSlogin FATType::FAT16(_) => { 847004e86ffSlogin let raw_entry = self.get_fat_entry_raw(Cluster::new(1))? | 0x8000; 848004e86ffSlogin self.set_entry(Cluster::new(1), FATEntry::Next(Cluster::new(raw_entry)))?; 849004e86ffSlogin return Ok(()); 850004e86ffSlogin } 851004e86ffSlogin _ => return Ok(()), 852004e86ffSlogin } 853004e86ffSlogin } 854004e86ffSlogin 855004e86ffSlogin /// @brief 设置文件系统的hard error bit为正常状态 856004e86ffSlogin /// 参考资料:https://thestarman.pcministry.com/DOS/DirtyShutdownFlag.html 857004e86ffSlogin /// 858004e86ffSlogin /// @return Ok(()) 设置成功 859676b8ef6SMork /// @return Err(SystemError) 在设置过程中,出现错误 860676b8ef6SMork pub fn set_hard_error_bit_ok(&mut self) -> Result<(), SystemError> { 861004e86ffSlogin match self.bpb.fat_type { 862004e86ffSlogin FATType::FAT32(_) => { 863004e86ffSlogin let raw_entry = self.get_fat_entry_raw(Cluster::new(1))? | 0x0400_0000; 864004e86ffSlogin self.set_entry(Cluster::new(1), FATEntry::Next(Cluster::new(raw_entry)))?; 865004e86ffSlogin return Ok(()); 866004e86ffSlogin } 867004e86ffSlogin 868004e86ffSlogin FATType::FAT16(_) => { 869004e86ffSlogin let raw_entry = self.get_fat_entry_raw(Cluster::new(1))? | 0x4000; 870004e86ffSlogin self.set_entry(Cluster::new(1), FATEntry::Next(Cluster::new(raw_entry)))?; 871004e86ffSlogin return Ok(()); 872004e86ffSlogin } 873004e86ffSlogin _ => return Ok(()), 874004e86ffSlogin } 875004e86ffSlogin } 876004e86ffSlogin 877004e86ffSlogin /// @brief 执行文件系统卸载前的一些准备工作:设置好对应的标志位,并把缓存中的数据刷入磁盘 878676b8ef6SMork pub fn umount(&mut self) -> Result<(), SystemError> { 879*9fa0e95eSLoGin self.fs_info.0.lock().flush(&self.gendisk)?; 880004e86ffSlogin 881004e86ffSlogin self.set_shut_bit_ok()?; 882004e86ffSlogin 883004e86ffSlogin self.set_hard_error_bit_ok()?; 884004e86ffSlogin 885*9fa0e95eSLoGin self.gendisk.sync()?; 886004e86ffSlogin 887004e86ffSlogin return Ok(()); 888004e86ffSlogin } 889004e86ffSlogin 890004e86ffSlogin /// @brief 获取文件系统的最大簇号 891004e86ffSlogin pub fn max_cluster_number(&self) -> Cluster { 892004e86ffSlogin match self.bpb.fat_type { 893004e86ffSlogin FATType::FAT32(s) => { 894004e86ffSlogin // FAT32 895004e86ffSlogin 896004e86ffSlogin // 数据扇区数量(总扇区数-保留扇区-FAT占用的扇区) 897004e86ffSlogin let data_sec: u64 = self.bpb.total_sectors_32 as u64 898004e86ffSlogin - (self.bpb.rsvd_sec_cnt as u64 899004e86ffSlogin + self.bpb.num_fats as u64 * s.fat_size_32 as u64); 900004e86ffSlogin 901004e86ffSlogin // 数据区的簇数量 902004e86ffSlogin let total_clusters: u64 = data_sec / self.bpb.sector_per_cluster as u64; 903004e86ffSlogin 904004e86ffSlogin // 返回最大的簇号 905004e86ffSlogin return Cluster::new(total_clusters + RESERVED_CLUSTERS as u64 - 1); 906004e86ffSlogin } 907004e86ffSlogin 908004e86ffSlogin _ => { 909004e86ffSlogin // FAT12 / FAT16 910004e86ffSlogin let root_dir_sectors: u64 = (((self.bpb.root_entries_cnt as u64) * 32) 911004e86ffSlogin + self.bpb.bytes_per_sector as u64 912004e86ffSlogin - 1) 913004e86ffSlogin / self.bpb.bytes_per_sector as u64; 914004e86ffSlogin // 数据区扇区数 915004e86ffSlogin let data_sec: u64 = self.bpb.total_sectors_16 as u64 916004e86ffSlogin - (self.bpb.rsvd_sec_cnt as u64 917004e86ffSlogin + (self.bpb.num_fats as u64 * self.bpb.fat_size_16 as u64) 918004e86ffSlogin + root_dir_sectors); 919004e86ffSlogin let total_clusters = data_sec / self.bpb.sector_per_cluster as u64; 920004e86ffSlogin return Cluster::new(total_clusters + RESERVED_CLUSTERS as u64 - 1); 921004e86ffSlogin } 922004e86ffSlogin } 923004e86ffSlogin } 924004e86ffSlogin 925004e86ffSlogin /// @brief 在文件系统中寻找一个簇号在给定的范围(左闭右开区间)内的空闲簇 926004e86ffSlogin /// 927004e86ffSlogin /// @param start_cluster 起始簇号 928004e86ffSlogin /// @param end_cluster 终止簇号(不包含) 929004e86ffSlogin /// 930004e86ffSlogin /// @return Ok(Cluster) 寻找到的空闲簇 931676b8ef6SMork /// @return Err(SystemError) 错误码。如果磁盘无剩余空间,或者簇号达到给定的最大值,则返回-ENOSPC. 932004e86ffSlogin pub fn get_free_cluster( 933004e86ffSlogin &self, 934004e86ffSlogin start_cluster: Cluster, 935004e86ffSlogin end_cluster: Cluster, 936676b8ef6SMork ) -> Result<Cluster, SystemError> { 937004e86ffSlogin let max_cluster: Cluster = self.max_cluster_number(); 938004e86ffSlogin let mut cluster: u64 = start_cluster.cluster_num; 939004e86ffSlogin 940004e86ffSlogin let fat_type: FATType = self.bpb.fat_type; 941004e86ffSlogin let fat_start_sector: u64 = self.fat_start_sector(); 942004e86ffSlogin let bytes_per_sec: u64 = self.bpb.bytes_per_sector as u64; 943004e86ffSlogin 944004e86ffSlogin match fat_type { 945004e86ffSlogin FATType::FAT12(_) => { 946004e86ffSlogin let part_bytes_offset: u64 = 947004e86ffSlogin fat_type.get_fat_bytes_offset(start_cluster, fat_start_sector, bytes_per_sec); 948004e86ffSlogin let in_block_offset = self.get_in_block_offset(part_bytes_offset); 949004e86ffSlogin 950*9fa0e95eSLoGin let lba = self.gendisk_lba_from_offset(self.bytes_to_sector(part_bytes_offset)); 951004e86ffSlogin 952004e86ffSlogin // 由于FAT12的FAT表不大于6K,因此直接读取6K 953004e86ffSlogin let num_lba = (6 * 1024) / LBA_SIZE; 954b5b571e0SLoGin let mut v: Vec<u8> = vec![0; num_lba * LBA_SIZE]; 955*9fa0e95eSLoGin self.gendisk.read_at(&mut v, lba)?; 956004e86ffSlogin 957004e86ffSlogin let mut cursor: VecCursor = VecCursor::new(v); 958004e86ffSlogin cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 959004e86ffSlogin 960004e86ffSlogin let mut packed_val: u16 = cursor.read_u16()?; 961004e86ffSlogin loop { 962004e86ffSlogin let val = if (cluster & 0x1) > 0 { 963004e86ffSlogin packed_val >> 4 964004e86ffSlogin } else { 965004e86ffSlogin packed_val & 0x0fff 966004e86ffSlogin }; 967004e86ffSlogin if val == 0 { 968b5b571e0SLoGin return Ok(Cluster::new(cluster)); 969004e86ffSlogin } 970004e86ffSlogin 971004e86ffSlogin cluster += 1; 972004e86ffSlogin 973004e86ffSlogin // 磁盘无剩余空间,或者簇号达到给定的最大值 974004e86ffSlogin if cluster == end_cluster.cluster_num || cluster == max_cluster.cluster_num { 975676b8ef6SMork return Err(SystemError::ENOSPC); 976004e86ffSlogin } 977004e86ffSlogin 978004e86ffSlogin packed_val = match cluster & 1 { 979004e86ffSlogin 0 => cursor.read_u16()?, 980004e86ffSlogin _ => { 981004e86ffSlogin let next_byte = cursor.read_u8()? as u16; 982004e86ffSlogin (packed_val >> 8) | (next_byte << 8) 983004e86ffSlogin } 984004e86ffSlogin }; 985004e86ffSlogin } 986004e86ffSlogin } 987004e86ffSlogin FATType::FAT16(_) => { 988004e86ffSlogin // todo: 优化这里,减少读取磁盘的次数。 989004e86ffSlogin while cluster < end_cluster.cluster_num && cluster < max_cluster.cluster_num { 990004e86ffSlogin let part_bytes_offset: u64 = fat_type.get_fat_bytes_offset( 991004e86ffSlogin Cluster::new(cluster), 992004e86ffSlogin fat_start_sector, 993004e86ffSlogin bytes_per_sec, 994004e86ffSlogin ); 995004e86ffSlogin let in_block_offset = self.get_in_block_offset(part_bytes_offset); 996004e86ffSlogin 997*9fa0e95eSLoGin let lba = self.gendisk_lba_from_offset(self.bytes_to_sector(part_bytes_offset)); 998004e86ffSlogin 999b5b571e0SLoGin let mut v: Vec<u8> = vec![0; self.lba_per_sector() * LBA_SIZE]; 1000*9fa0e95eSLoGin self.gendisk.read_at(&mut v, lba)?; 1001004e86ffSlogin 1002004e86ffSlogin let mut cursor: VecCursor = VecCursor::new(v); 1003004e86ffSlogin cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 1004004e86ffSlogin 1005004e86ffSlogin let val = cursor.read_u16()?; 1006004e86ffSlogin // 找到空闲簇 1007004e86ffSlogin if val == 0 { 1008004e86ffSlogin return Ok(Cluster::new(val as u64)); 1009004e86ffSlogin } 1010004e86ffSlogin cluster += 1; 1011004e86ffSlogin } 1012004e86ffSlogin 1013004e86ffSlogin // 磁盘无剩余空间,或者簇号达到给定的最大值 1014676b8ef6SMork return Err(SystemError::ENOSPC); 1015004e86ffSlogin } 1016004e86ffSlogin FATType::FAT32(_) => { 1017004e86ffSlogin // todo: 优化这里,减少读取磁盘的次数。 1018004e86ffSlogin while cluster < end_cluster.cluster_num && cluster < max_cluster.cluster_num { 1019004e86ffSlogin let part_bytes_offset: u64 = fat_type.get_fat_bytes_offset( 1020004e86ffSlogin Cluster::new(cluster), 1021004e86ffSlogin fat_start_sector, 1022004e86ffSlogin bytes_per_sec, 1023004e86ffSlogin ); 1024004e86ffSlogin let in_block_offset = self.get_in_block_offset(part_bytes_offset); 1025004e86ffSlogin 1026*9fa0e95eSLoGin let lba = self.gendisk_lba_from_offset(self.bytes_to_sector(part_bytes_offset)); 1027004e86ffSlogin 1028b5b571e0SLoGin let mut v: Vec<u8> = vec![0; self.lba_per_sector() * LBA_SIZE]; 1029*9fa0e95eSLoGin self.gendisk.read_at(&mut v, lba)?; 1030004e86ffSlogin 1031004e86ffSlogin let mut cursor: VecCursor = VecCursor::new(v); 1032004e86ffSlogin cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 1033004e86ffSlogin 1034004e86ffSlogin let val = cursor.read_u32()? & 0x0fffffff; 1035004e86ffSlogin 1036004e86ffSlogin if val == 0 { 1037004e86ffSlogin return Ok(Cluster::new(cluster)); 1038004e86ffSlogin } 1039004e86ffSlogin cluster += 1; 1040004e86ffSlogin } 1041004e86ffSlogin 1042004e86ffSlogin // 磁盘无剩余空间,或者簇号达到给定的最大值 1043676b8ef6SMork return Err(SystemError::ENOSPC); 1044004e86ffSlogin } 1045004e86ffSlogin } 1046004e86ffSlogin } 1047004e86ffSlogin 1048004e86ffSlogin /// @brief 在FAT表中,设置指定的簇的信息。 1049004e86ffSlogin /// 1050004e86ffSlogin /// @param cluster 目标簇 1051004e86ffSlogin /// @param fat_entry 这个簇在FAT表中,存储的信息(下一个簇的簇号) 1052676b8ef6SMork pub fn set_entry(&self, cluster: Cluster, fat_entry: FATEntry) -> Result<(), SystemError> { 1053004e86ffSlogin // fat表项在分区上的字节偏移量 1054004e86ffSlogin let fat_part_bytes_offset: u64 = self.bpb.fat_type.get_fat_bytes_offset( 1055004e86ffSlogin cluster, 1056004e86ffSlogin self.fat_start_sector(), 1057004e86ffSlogin self.bpb.bytes_per_sector as u64, 1058004e86ffSlogin ); 1059004e86ffSlogin 1060004e86ffSlogin match self.bpb.fat_type { 1061004e86ffSlogin FATType::FAT12(_) => { 1062004e86ffSlogin // 计算要写入的值 1063004e86ffSlogin let raw_val: u16 = match fat_entry { 1064004e86ffSlogin FATEntry::Unused => 0, 1065004e86ffSlogin FATEntry::Bad => 0xff7, 1066004e86ffSlogin FATEntry::EndOfChain => 0xfff, 1067004e86ffSlogin FATEntry::Next(c) => c.cluster_num as u16, 1068004e86ffSlogin }; 1069004e86ffSlogin 1070004e86ffSlogin let in_block_offset = self.get_in_block_offset(fat_part_bytes_offset); 1071004e86ffSlogin 1072*9fa0e95eSLoGin let lba = self.gendisk_lba_from_offset(self.bytes_to_sector(fat_part_bytes_offset)); 1073004e86ffSlogin 1074b5b571e0SLoGin let mut v: Vec<u8> = vec![0; LBA_SIZE]; 1075*9fa0e95eSLoGin self.gendisk.read_at(&mut v, lba)?; 1076004e86ffSlogin 1077004e86ffSlogin let mut cursor: VecCursor = VecCursor::new(v); 1078004e86ffSlogin cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 1079004e86ffSlogin 1080004e86ffSlogin let old_val: u16 = cursor.read_u16()?; 1081004e86ffSlogin let new_val: u16 = if (cluster.cluster_num & 0x1) > 0 { 1082004e86ffSlogin (old_val & 0x000f) | (raw_val << 4) 1083004e86ffSlogin } else { 1084004e86ffSlogin (old_val & 0xf000) | raw_val 1085004e86ffSlogin }; 1086004e86ffSlogin 1087004e86ffSlogin // 写回数据到磁盘上 1088004e86ffSlogin cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 1089004e86ffSlogin cursor.write_u16(new_val)?; 1090*9fa0e95eSLoGin self.gendisk.write_at(cursor.as_slice(), lba)?; 1091004e86ffSlogin return Ok(()); 1092004e86ffSlogin } 1093004e86ffSlogin FATType::FAT16(_) => { 1094004e86ffSlogin // 计算要写入的值 1095004e86ffSlogin let raw_val: u16 = match fat_entry { 1096004e86ffSlogin FATEntry::Unused => 0, 1097004e86ffSlogin FATEntry::Bad => 0xfff7, 1098004e86ffSlogin FATEntry::EndOfChain => 0xfdff, 1099004e86ffSlogin FATEntry::Next(c) => c.cluster_num as u16, 1100004e86ffSlogin }; 1101004e86ffSlogin 1102004e86ffSlogin let in_block_offset = self.get_in_block_offset(fat_part_bytes_offset); 1103004e86ffSlogin 1104*9fa0e95eSLoGin let lba = self.gendisk_lba_from_offset(self.bytes_to_sector(fat_part_bytes_offset)); 1105004e86ffSlogin 1106b5b571e0SLoGin let mut v: Vec<u8> = vec![0; LBA_SIZE]; 1107*9fa0e95eSLoGin self.gendisk.read_at(&mut v, lba)?; 1108004e86ffSlogin 1109004e86ffSlogin let mut cursor: VecCursor = VecCursor::new(v); 1110004e86ffSlogin cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 1111004e86ffSlogin 1112004e86ffSlogin cursor.write_u16(raw_val)?; 1113*9fa0e95eSLoGin self.gendisk.write_at(cursor.as_slice(), lba)?; 1114004e86ffSlogin 1115004e86ffSlogin return Ok(()); 1116004e86ffSlogin } 1117004e86ffSlogin FATType::FAT32(_) => { 1118004e86ffSlogin let fat_size: u64 = self.fat_size(); 1119004e86ffSlogin let bound: u64 = if self.mirroring_enabled() { 1120004e86ffSlogin 1 1121004e86ffSlogin } else { 1122004e86ffSlogin self.bpb.num_fats as u64 1123004e86ffSlogin }; 11242eab6dd7S曾俊 // debug!("set entry, bound={bound}, fat_size={fat_size}"); 1125004e86ffSlogin for i in 0..bound { 1126004e86ffSlogin // 当前操作的FAT表在磁盘上的字节偏移量 1127004e86ffSlogin let f_offset: u64 = fat_part_bytes_offset + i * fat_size; 1128004e86ffSlogin let in_block_offset: u64 = self.get_in_block_offset(f_offset); 1129*9fa0e95eSLoGin let lba = self.gendisk_lba_from_offset(self.bytes_to_sector(f_offset)); 1130004e86ffSlogin 11312eab6dd7S曾俊 // debug!("set entry, lba={lba}, in_block_offset={in_block_offset}"); 1132b5b571e0SLoGin let mut v: Vec<u8> = vec![0; LBA_SIZE]; 1133*9fa0e95eSLoGin self.gendisk.read_at(&mut v, lba)?; 1134004e86ffSlogin 1135004e86ffSlogin let mut cursor: VecCursor = VecCursor::new(v); 1136004e86ffSlogin cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 1137004e86ffSlogin 1138004e86ffSlogin // FAT32的高4位保留 1139004e86ffSlogin let old_bits = cursor.read_u32()? & 0xf0000000; 1140004e86ffSlogin 1141004e86ffSlogin if fat_entry == FATEntry::Unused 1142004e86ffSlogin && cluster.cluster_num >= 0x0ffffff7 1143004e86ffSlogin && cluster.cluster_num <= 0x0fffffff 1144004e86ffSlogin { 11452eab6dd7S曾俊 error!( 1146004e86ffSlogin "FAT32: Reserved Cluster {:?} cannot be marked as free", 1147004e86ffSlogin cluster 1148004e86ffSlogin ); 1149676b8ef6SMork return Err(SystemError::EPERM); 1150004e86ffSlogin } 1151004e86ffSlogin 1152004e86ffSlogin // 计算要写入的值 1153004e86ffSlogin let mut raw_val: u32 = match fat_entry { 1154004e86ffSlogin FATEntry::Unused => 0, 1155004e86ffSlogin FATEntry::Bad => 0x0FFFFFF7, 1156004e86ffSlogin FATEntry::EndOfChain => 0x0FFFFFFF, 1157004e86ffSlogin FATEntry::Next(c) => c.cluster_num as u32, 1158004e86ffSlogin }; 1159004e86ffSlogin 1160004e86ffSlogin // 恢复保留位 1161004e86ffSlogin raw_val |= old_bits; 1162004e86ffSlogin 11632eab6dd7S曾俊 // debug!("sent entry, raw_val={raw_val}"); 1164004e86ffSlogin 1165004e86ffSlogin cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 1166004e86ffSlogin cursor.write_u32(raw_val)?; 1167004e86ffSlogin 1168*9fa0e95eSLoGin self.gendisk.write_at(cursor.as_slice(), lba)?; 1169004e86ffSlogin } 1170004e86ffSlogin 1171004e86ffSlogin return Ok(()); 1172004e86ffSlogin } 1173004e86ffSlogin } 1174004e86ffSlogin } 1175004e86ffSlogin 1176*9fa0e95eSLoGin /// # 清空指定的簇 1177004e86ffSlogin /// 1178*9fa0e95eSLoGin /// # 参数 1179*9fa0e95eSLoGin /// - cluster 要被清空的簇 1180676b8ef6SMork pub fn zero_cluster(&self, cluster: Cluster) -> Result<(), SystemError> { 1181004e86ffSlogin // 准备数据,用于写入 1182004e86ffSlogin let zeros: Vec<u8> = vec![0u8; self.bytes_per_cluster() as usize]; 1183*9fa0e95eSLoGin let offset = self.cluster_bytes_offset(cluster) as usize; 1184*9fa0e95eSLoGin self.gendisk.write_at_bytes(&zeros, offset)?; 1185004e86ffSlogin return Ok(()); 1186004e86ffSlogin } 1187004e86ffSlogin } 1188004e86ffSlogin 1189004e86ffSlogin impl Drop for FATFileSystem { 1190004e86ffSlogin fn drop(&mut self) { 1191004e86ffSlogin let r = self.umount(); 1192004e86ffSlogin if r.is_err() { 11932eab6dd7S曾俊 error!( 1194676b8ef6SMork "Umount FAT filesystem failed: errno={:?}, FS detail:{self:?}", 11958d72b68dSJomo r.as_ref().unwrap_err() 1196004e86ffSlogin ); 1197004e86ffSlogin } 1198004e86ffSlogin } 1199004e86ffSlogin } 1200004e86ffSlogin 1201004e86ffSlogin impl FATFsInfo { 1202004e86ffSlogin const LEAD_SIG: u32 = 0x41615252; 1203004e86ffSlogin const STRUC_SIG: u32 = 0x61417272; 1204004e86ffSlogin const TRAIL_SIG: u32 = 0xAA550000; 120591e9d4abSLoGin #[allow(dead_code)] 1206004e86ffSlogin const FS_INFO_SIZE: u64 = 512; 1207004e86ffSlogin 1208004e86ffSlogin /// @brief 从磁盘上读取FAT文件系统的FSInfo结构体 1209004e86ffSlogin /// 1210004e86ffSlogin /// @param partition 磁盘分区 1211*9fa0e95eSLoGin /// @param in_gendisk_fs_info_offset FSInfo扇区在gendisk内的字节偏移量(单位:字节) 1212004e86ffSlogin /// @param bytes_per_sec 每扇区字节数 1213004e86ffSlogin pub fn new( 1214*9fa0e95eSLoGin gendisk: &Arc<GenDisk>, 1215*9fa0e95eSLoGin in_gendisk_fs_info_offset: usize, 1216004e86ffSlogin bytes_per_sec: usize, 1217676b8ef6SMork ) -> Result<Self, SystemError> { 1218b5b571e0SLoGin let mut v = vec![0; bytes_per_sec]; 1219004e86ffSlogin 1220*9fa0e95eSLoGin // 读取磁盘上的FsInfo扇区 1221*9fa0e95eSLoGin gendisk.read_at_bytes(&mut v, in_gendisk_fs_info_offset)?; 1222*9fa0e95eSLoGin 1223004e86ffSlogin let mut cursor = VecCursor::new(v); 1224004e86ffSlogin 1225b5b571e0SLoGin let mut fsinfo = FATFsInfo { 1226b5b571e0SLoGin lead_sig: cursor.read_u32()?, 1227b5b571e0SLoGin ..Default::default() 1228b5b571e0SLoGin }; 1229004e86ffSlogin cursor.seek(SeekFrom::SeekCurrent(480))?; 1230004e86ffSlogin fsinfo.struc_sig = cursor.read_u32()?; 1231004e86ffSlogin fsinfo.free_count = cursor.read_u32()?; 1232004e86ffSlogin fsinfo.next_free = cursor.read_u32()?; 1233004e86ffSlogin 1234004e86ffSlogin cursor.seek(SeekFrom::SeekCurrent(12))?; 1235004e86ffSlogin 1236004e86ffSlogin fsinfo.trail_sig = cursor.read_u32()?; 1237004e86ffSlogin fsinfo.dirty = false; 1238*9fa0e95eSLoGin fsinfo.offset = Some(gendisk.disk_bytes_offset(in_gendisk_fs_info_offset) as u64); 1239004e86ffSlogin 1240004e86ffSlogin if fsinfo.is_valid() { 1241004e86ffSlogin return Ok(fsinfo); 1242004e86ffSlogin } else { 12432eab6dd7S曾俊 error!("Error occurred while parsing FATFsInfo."); 1244676b8ef6SMork return Err(SystemError::EINVAL); 1245004e86ffSlogin } 1246004e86ffSlogin } 1247004e86ffSlogin 1248004e86ffSlogin /// @brief 判断是否为正确的FsInfo结构体 1249004e86ffSlogin fn is_valid(&self) -> bool { 1250004e86ffSlogin self.lead_sig == Self::LEAD_SIG 1251004e86ffSlogin && self.struc_sig == Self::STRUC_SIG 1252004e86ffSlogin && self.trail_sig == Self::TRAIL_SIG 1253004e86ffSlogin } 1254004e86ffSlogin 1255004e86ffSlogin /// @brief 根据fsinfo的信息,计算当前总的空闲簇数量 1256004e86ffSlogin /// 1257004e86ffSlogin /// @param 当前文件系统的最大簇号 1258004e86ffSlogin pub fn count_free_cluster(&self, max_cluster: Cluster) -> Option<u64> { 1259004e86ffSlogin let count_clusters = max_cluster.cluster_num - RESERVED_CLUSTERS as u64 + 1; 1260004e86ffSlogin // 信息不合理,当前的FsInfo中存储的free count大于计算出来的值 1261004e86ffSlogin if self.free_count as u64 > count_clusters { 1262004e86ffSlogin return None; 1263004e86ffSlogin } else { 1264004e86ffSlogin match self.free_count { 1265004e86ffSlogin // free count字段不可用 1266004e86ffSlogin 0xffffffff => return None, 1267004e86ffSlogin // 返回FsInfo中存储的数据 1268004e86ffSlogin n => return Some(n as u64), 1269004e86ffSlogin } 1270004e86ffSlogin } 1271004e86ffSlogin } 1272004e86ffSlogin 1273004e86ffSlogin /// @brief 更新FsInfo中的“空闲簇统计信息“为new_count 1274004e86ffSlogin /// 1275004e86ffSlogin /// 请注意,除非手动调用`flush()`,否则本函数不会将数据刷入磁盘 1276004e86ffSlogin pub fn update_free_count_abs(&mut self, new_count: u32) { 1277004e86ffSlogin self.free_count = new_count; 1278004e86ffSlogin } 1279004e86ffSlogin 1280004e86ffSlogin /// @brief 更新FsInfo中的“空闲簇统计信息“,把它加上delta. 1281004e86ffSlogin /// 1282004e86ffSlogin /// 请注意,除非手动调用`flush()`,否则本函数不会将数据刷入磁盘 1283004e86ffSlogin pub fn update_free_count_delta(&mut self, delta: i32) { 1284004e86ffSlogin self.free_count = (self.free_count as i32 + delta) as u32; 1285004e86ffSlogin } 1286004e86ffSlogin 1287004e86ffSlogin /// @brief 更新FsInfo中的“第一个空闲簇统计信息“为next_free. 1288004e86ffSlogin /// 1289004e86ffSlogin /// 请注意,除非手动调用`flush()`,否则本函数不会将数据刷入磁盘 1290004e86ffSlogin pub fn update_next_free(&mut self, next_free: u32) { 1291004e86ffSlogin // 这个值是参考量,不一定要准确,仅供加速查找 1292004e86ffSlogin self.next_free = next_free; 1293004e86ffSlogin } 1294004e86ffSlogin 1295004e86ffSlogin /// @brief 获取fs info 记载的第一个空闲簇。(不一定准确,仅供参考) 1296004e86ffSlogin pub fn next_free(&self) -> Option<u64> { 1297004e86ffSlogin match self.next_free { 1298004e86ffSlogin 0xffffffff => return None, 1299004e86ffSlogin 0 | 1 => return None, 1300004e86ffSlogin n => return Some(n as u64), 1301004e86ffSlogin }; 1302004e86ffSlogin } 1303004e86ffSlogin 1304004e86ffSlogin /// @brief 把fs info刷入磁盘 1305004e86ffSlogin /// 1306004e86ffSlogin /// @param partition fs info所在的分区 1307*9fa0e95eSLoGin pub fn flush(&self, gendisk: &Arc<GenDisk>) -> Result<(), SystemError> { 1308004e86ffSlogin if let Some(off) = self.offset { 1309004e86ffSlogin let in_block_offset = off % LBA_SIZE as u64; 1310004e86ffSlogin 1311004e86ffSlogin let lba = off as usize / LBA_SIZE; 1312004e86ffSlogin 1313b5b571e0SLoGin let mut v: Vec<u8> = vec![0; LBA_SIZE]; 1314*9fa0e95eSLoGin gendisk.read_at(&mut v, lba)?; 1315004e86ffSlogin 1316004e86ffSlogin let mut cursor: VecCursor = VecCursor::new(v); 1317004e86ffSlogin cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 1318004e86ffSlogin 1319004e86ffSlogin cursor.write_u32(self.lead_sig)?; 1320004e86ffSlogin cursor.seek(SeekFrom::SeekCurrent(480))?; 1321004e86ffSlogin cursor.write_u32(self.struc_sig)?; 1322004e86ffSlogin cursor.write_u32(self.free_count)?; 1323004e86ffSlogin cursor.write_u32(self.next_free)?; 1324004e86ffSlogin cursor.seek(SeekFrom::SeekCurrent(12))?; 1325004e86ffSlogin cursor.write_u32(self.trail_sig)?; 1326004e86ffSlogin 1327*9fa0e95eSLoGin gendisk.write_at(cursor.as_slice(), lba)?; 1328004e86ffSlogin } 1329004e86ffSlogin return Ok(()); 1330004e86ffSlogin } 1331004e86ffSlogin 1332004e86ffSlogin /// @brief 读取磁盘上的Fs Info扇区,将里面的内容更新到结构体中 1333004e86ffSlogin /// 1334004e86ffSlogin /// @param partition fs info所在的分区 1335676b8ef6SMork pub fn update(&mut self, partition: Arc<Partition>) -> Result<(), SystemError> { 1336004e86ffSlogin if let Some(off) = self.offset { 1337004e86ffSlogin let in_block_offset = off % LBA_SIZE as u64; 1338004e86ffSlogin 1339004e86ffSlogin let lba = off as usize / LBA_SIZE; 1340004e86ffSlogin 1341b5b571e0SLoGin let mut v: Vec<u8> = vec![0; LBA_SIZE]; 1342004e86ffSlogin partition.disk().read_at(lba, 1, &mut v)?; 1343004e86ffSlogin let mut cursor: VecCursor = VecCursor::new(v); 1344004e86ffSlogin cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?; 1345004e86ffSlogin self.lead_sig = cursor.read_u32()?; 1346004e86ffSlogin 1347004e86ffSlogin cursor.seek(SeekFrom::SeekCurrent(480))?; 1348004e86ffSlogin self.struc_sig = cursor.read_u32()?; 1349004e86ffSlogin self.free_count = cursor.read_u32()?; 1350004e86ffSlogin self.next_free = cursor.read_u32()?; 1351004e86ffSlogin cursor.seek(SeekFrom::SeekCurrent(12))?; 1352004e86ffSlogin self.trail_sig = cursor.read_u32()?; 1353004e86ffSlogin } 1354004e86ffSlogin return Ok(()); 1355004e86ffSlogin } 1356004e86ffSlogin } 1357004e86ffSlogin 1358004e86ffSlogin impl IndexNode for LockedFATInode { 1359004e86ffSlogin fn read_at( 1360004e86ffSlogin &self, 1361004e86ffSlogin offset: usize, 1362004e86ffSlogin len: usize, 1363004e86ffSlogin buf: &mut [u8], 1364dfe53cf0SGnoCiYeH _data: SpinLockGuard<FilePrivateData>, 1365676b8ef6SMork ) -> Result<usize, SystemError> { 1366004e86ffSlogin let mut guard: SpinLockGuard<FATInode> = self.0.lock(); 1367004e86ffSlogin match &guard.inode_type { 1368004e86ffSlogin FATDirEntry::File(f) | FATDirEntry::VolId(f) => { 1369004e86ffSlogin let r = f.read( 1370004e86ffSlogin &guard.fs.upgrade().unwrap(), 1371004e86ffSlogin &mut buf[0..len], 1372004e86ffSlogin offset as u64, 1373004e86ffSlogin ); 1374004e86ffSlogin guard.update_metadata(); 1375004e86ffSlogin return r; 1376004e86ffSlogin } 1377004e86ffSlogin FATDirEntry::Dir(_) => { 1378676b8ef6SMork return Err(SystemError::EISDIR); 1379004e86ffSlogin } 1380004e86ffSlogin FATDirEntry::UnInit => { 13812eab6dd7S曾俊 error!("FATFS: param: Inode_type uninitialized."); 1382676b8ef6SMork return Err(SystemError::EROFS); 1383004e86ffSlogin } 1384004e86ffSlogin } 1385004e86ffSlogin } 1386004e86ffSlogin 1387004e86ffSlogin fn write_at( 1388004e86ffSlogin &self, 1389004e86ffSlogin offset: usize, 1390004e86ffSlogin len: usize, 1391004e86ffSlogin buf: &[u8], 1392dfe53cf0SGnoCiYeH _data: SpinLockGuard<FilePrivateData>, 1393676b8ef6SMork ) -> Result<usize, SystemError> { 1394004e86ffSlogin let mut guard: SpinLockGuard<FATInode> = self.0.lock(); 1395004e86ffSlogin let fs: &Arc<FATFileSystem> = &guard.fs.upgrade().unwrap(); 1396004e86ffSlogin 1397004e86ffSlogin match &mut guard.inode_type { 1398004e86ffSlogin FATDirEntry::File(f) | FATDirEntry::VolId(f) => { 1399004e86ffSlogin let r = f.write(fs, &buf[0..len], offset as u64); 1400004e86ffSlogin guard.update_metadata(); 1401004e86ffSlogin return r; 1402004e86ffSlogin } 1403004e86ffSlogin FATDirEntry::Dir(_) => { 1404676b8ef6SMork return Err(SystemError::EISDIR); 1405004e86ffSlogin } 1406004e86ffSlogin FATDirEntry::UnInit => { 14072eab6dd7S曾俊 error!("FATFS: param: Inode_type uninitialized."); 1408676b8ef6SMork return Err(SystemError::EROFS); 1409004e86ffSlogin } 1410004e86ffSlogin } 1411004e86ffSlogin } 1412004e86ffSlogin 1413004e86ffSlogin fn create( 1414004e86ffSlogin &self, 1415004e86ffSlogin name: &str, 1416004e86ffSlogin file_type: FileType, 14176b4e7a29SLoGin _mode: ModeType, 1418676b8ef6SMork ) -> Result<Arc<dyn IndexNode>, SystemError> { 1419004e86ffSlogin // 由于FAT32不支持文件权限的功能,因此忽略mode参数 1420004e86ffSlogin let mut guard: SpinLockGuard<FATInode> = self.0.lock(); 1421004e86ffSlogin let fs: &Arc<FATFileSystem> = &guard.fs.upgrade().unwrap(); 1422004e86ffSlogin 1423004e86ffSlogin match &mut guard.inode_type { 1424004e86ffSlogin FATDirEntry::File(_) | FATDirEntry::VolId(_) => { 1425676b8ef6SMork return Err(SystemError::ENOTDIR); 1426004e86ffSlogin } 1427004e86ffSlogin FATDirEntry::Dir(d) => match file_type { 1428004e86ffSlogin FileType::File => { 1429004e86ffSlogin d.create_file(name, fs)?; 1430004e86ffSlogin return Ok(guard.find(name)?); 1431004e86ffSlogin } 1432004e86ffSlogin FileType::Dir => { 1433004e86ffSlogin d.create_dir(name, fs)?; 1434004e86ffSlogin return Ok(guard.find(name)?); 1435004e86ffSlogin } 1436004e86ffSlogin 14371074eb34SSamuel Dai FileType::SymLink => return Err(SystemError::ENOSYS), 1438676b8ef6SMork _ => return Err(SystemError::EINVAL), 1439004e86ffSlogin }, 1440004e86ffSlogin FATDirEntry::UnInit => { 14412eab6dd7S曾俊 error!("FATFS: param: Inode_type uninitialized."); 1442676b8ef6SMork return Err(SystemError::EROFS); 1443004e86ffSlogin } 1444004e86ffSlogin } 1445004e86ffSlogin } 1446004e86ffSlogin 1447004e86ffSlogin fn fs(&self) -> Arc<dyn FileSystem> { 1448004e86ffSlogin return self.0.lock().fs.upgrade().unwrap(); 1449004e86ffSlogin } 1450004e86ffSlogin 1451004e86ffSlogin fn as_any_ref(&self) -> &dyn core::any::Any { 1452004e86ffSlogin return self; 1453004e86ffSlogin } 1454004e86ffSlogin 1455676b8ef6SMork fn metadata(&self) -> Result<Metadata, SystemError> { 1456004e86ffSlogin return Ok(self.0.lock().metadata.clone()); 1457004e86ffSlogin } 14586f189d27Slinfeng fn set_metadata(&self, metadata: &Metadata) -> Result<(), SystemError> { 14596f189d27Slinfeng let inode = &mut self.0.lock(); 14606f189d27Slinfeng inode.metadata.atime = metadata.atime; 14616f189d27Slinfeng inode.metadata.mtime = metadata.mtime; 14626f189d27Slinfeng inode.metadata.ctime = metadata.ctime; 14636f189d27Slinfeng inode.metadata.mode = metadata.mode; 14646f189d27Slinfeng inode.metadata.uid = metadata.uid; 14656f189d27Slinfeng inode.metadata.gid = metadata.gid; 14666f189d27Slinfeng Ok(()) 14676f189d27Slinfeng } 14686d81180bSLoGin fn resize(&self, len: usize) -> Result<(), SystemError> { 14696d81180bSLoGin let mut guard: SpinLockGuard<FATInode> = self.0.lock(); 14706d81180bSLoGin let fs: &Arc<FATFileSystem> = &guard.fs.upgrade().unwrap(); 14716d81180bSLoGin let old_size = guard.metadata.size as usize; 14726d81180bSLoGin 14736d81180bSLoGin match &mut guard.inode_type { 14746d81180bSLoGin FATDirEntry::File(file) | FATDirEntry::VolId(file) => { 14756d81180bSLoGin // 如果新的长度和旧的长度相同,那么就直接返回 1476b5b571e0SLoGin match len.cmp(&old_size) { 1477b5b571e0SLoGin Ordering::Equal => { 14786d81180bSLoGin return Ok(()); 1479b5b571e0SLoGin } 1480b5b571e0SLoGin Ordering::Greater => { 14816d81180bSLoGin // 如果新的长度比旧的长度大,那么就在文件末尾添加空白 14826d81180bSLoGin let mut buf: Vec<u8> = Vec::new(); 14836d81180bSLoGin let mut remain_size = len - old_size; 14846d81180bSLoGin let buf_size = remain_size; 14856d81180bSLoGin // let buf_size = core::cmp::min(remain_size, 512 * 1024); 14866d81180bSLoGin buf.resize(buf_size, 0); 14876d81180bSLoGin 14886d81180bSLoGin let mut offset = old_size; 14896d81180bSLoGin while remain_size > 0 { 14906d81180bSLoGin let write_size = core::cmp::min(remain_size, buf_size); 14916d81180bSLoGin file.write(fs, &buf[0..write_size], offset as u64)?; 14926d81180bSLoGin remain_size -= write_size; 14936d81180bSLoGin offset += write_size; 14946d81180bSLoGin } 1495b5b571e0SLoGin } 1496b5b571e0SLoGin Ordering::Less => { 14976d81180bSLoGin file.truncate(fs, len as u64)?; 14986d81180bSLoGin } 1499b5b571e0SLoGin } 15006d81180bSLoGin guard.update_metadata(); 15016d81180bSLoGin return Ok(()); 15026d81180bSLoGin } 15031074eb34SSamuel Dai FATDirEntry::Dir(_) => return Err(SystemError::ENOSYS), 15046d81180bSLoGin FATDirEntry::UnInit => { 15052eab6dd7S曾俊 error!("FATFS: param: Inode_type uninitialized."); 15066d81180bSLoGin return Err(SystemError::EROFS); 15076d81180bSLoGin } 15086d81180bSLoGin } 15096d81180bSLoGin } 1510004e86ffSlogin 151104babc3fSMemoryShore fn truncate(&self, len: usize) -> Result<(), SystemError> { 151204babc3fSMemoryShore let guard: SpinLockGuard<FATInode> = self.0.lock(); 151304babc3fSMemoryShore let old_size = guard.metadata.size as usize; 151404babc3fSMemoryShore if len < old_size { 151504babc3fSMemoryShore drop(guard); 151604babc3fSMemoryShore self.resize(len) 151704babc3fSMemoryShore } else { 151804babc3fSMemoryShore Ok(()) 151904babc3fSMemoryShore } 152004babc3fSMemoryShore } 152104babc3fSMemoryShore 1522676b8ef6SMork fn list(&self) -> Result<Vec<String>, SystemError> { 1523004e86ffSlogin let mut guard: SpinLockGuard<FATInode> = self.0.lock(); 1524004e86ffSlogin let fatent: &FATDirEntry = &guard.inode_type; 1525004e86ffSlogin match fatent { 1526004e86ffSlogin FATDirEntry::File(_) | FATDirEntry::VolId(_) => { 1527676b8ef6SMork return Err(SystemError::ENOTDIR); 1528004e86ffSlogin } 1529004e86ffSlogin FATDirEntry::Dir(dir) => { 1530004e86ffSlogin // 获取当前目录下的所有目录项 1531004e86ffSlogin let mut ret: Vec<String> = Vec::new(); 1532004e86ffSlogin let dir_iter: FATDirIter = dir.to_iter(guard.fs.upgrade().unwrap()); 1533004e86ffSlogin for ent in dir_iter { 1534004e86ffSlogin ret.push(ent.name()); 1535004e86ffSlogin 1536004e86ffSlogin // ====== 生成inode缓存,存入B树 15371074eb34SSamuel Dai let name = DName::from(ent.name().to_uppercase()); 15382eab6dd7S曾俊 // debug!("name={name}"); 1539004e86ffSlogin 15401074eb34SSamuel Dai if !guard.children.contains_key(&name) 15411074eb34SSamuel Dai && name.as_ref() != "." 15421074eb34SSamuel Dai && name.as_ref() != ".." 1543004e86ffSlogin { 1544004e86ffSlogin // 创建新的inode 1545004e86ffSlogin let entry_inode: Arc<LockedFATInode> = LockedFATInode::new( 15461074eb34SSamuel Dai name.clone(), 1547004e86ffSlogin guard.fs.upgrade().unwrap(), 1548004e86ffSlogin guard.self_ref.clone(), 1549004e86ffSlogin ent, 1550004e86ffSlogin ); 1551004e86ffSlogin // 加入缓存区, 由于FAT文件系统的大小写不敏感问题,因此存入缓存区的key应当是全大写的 15521074eb34SSamuel Dai guard.children.insert(name, entry_inode.clone()); 1553004e86ffSlogin } 1554004e86ffSlogin } 1555004e86ffSlogin return Ok(ret); 1556004e86ffSlogin } 1557004e86ffSlogin FATDirEntry::UnInit => { 15582eab6dd7S曾俊 error!("FATFS: param: Inode_type uninitialized."); 1559676b8ef6SMork return Err(SystemError::EROFS); 1560004e86ffSlogin } 1561004e86ffSlogin } 1562004e86ffSlogin } 1563004e86ffSlogin 1564676b8ef6SMork fn find(&self, name: &str) -> Result<Arc<dyn IndexNode>, SystemError> { 1565004e86ffSlogin let mut guard: SpinLockGuard<FATInode> = self.0.lock(); 1566004e86ffSlogin let target = guard.find(name)?; 1567004e86ffSlogin return Ok(target); 1568004e86ffSlogin } 1569004e86ffSlogin 1570dfe53cf0SGnoCiYeH fn open( 1571dfe53cf0SGnoCiYeH &self, 1572dfe53cf0SGnoCiYeH _data: SpinLockGuard<FilePrivateData>, 1573dfe53cf0SGnoCiYeH _mode: &FileMode, 1574dfe53cf0SGnoCiYeH ) -> Result<(), SystemError> { 1575004e86ffSlogin return Ok(()); 1576004e86ffSlogin } 1577004e86ffSlogin 1578dfe53cf0SGnoCiYeH fn close(&self, _data: SpinLockGuard<FilePrivateData>) -> Result<(), SystemError> { 1579004e86ffSlogin return Ok(()); 1580004e86ffSlogin } 1581004e86ffSlogin 1582676b8ef6SMork fn unlink(&self, name: &str) -> Result<(), SystemError> { 1583004e86ffSlogin let mut guard: SpinLockGuard<FATInode> = self.0.lock(); 1584004e86ffSlogin let target: Arc<LockedFATInode> = guard.find(name)?; 1585004e86ffSlogin // 对目标inode上锁,以防更改 1586004e86ffSlogin let target_guard: SpinLockGuard<FATInode> = target.0.lock(); 1587004e86ffSlogin // 先从缓存删除 15881074eb34SSamuel Dai let nod = guard.children.remove(&DName::from(name.to_uppercase())); 15892dbef785SGnoCiYeH 15902dbef785SGnoCiYeH // 若删除缓存中为管道的文件,则不需要再到磁盘删除 1591b5b571e0SLoGin if nod.is_some() { 15922dbef785SGnoCiYeH let file_type = target_guard.metadata.file_type; 15932dbef785SGnoCiYeH if file_type == FileType::Pipe { 15942dbef785SGnoCiYeH return Ok(()); 15952dbef785SGnoCiYeH } 15962dbef785SGnoCiYeH } 1597004e86ffSlogin 1598004e86ffSlogin let dir = match &guard.inode_type { 1599004e86ffSlogin FATDirEntry::File(_) | FATDirEntry::VolId(_) => { 1600676b8ef6SMork return Err(SystemError::ENOTDIR); 1601004e86ffSlogin } 1602004e86ffSlogin FATDirEntry::Dir(d) => d, 1603004e86ffSlogin FATDirEntry::UnInit => { 16042eab6dd7S曾俊 error!("FATFS: param: Inode_type uninitialized."); 1605676b8ef6SMork return Err(SystemError::EROFS); 1606004e86ffSlogin } 1607004e86ffSlogin }; 1608004e86ffSlogin // 检查文件是否存在 1609004e86ffSlogin dir.check_existence(name, Some(false), guard.fs.upgrade().unwrap())?; 1610004e86ffSlogin 1611004e86ffSlogin // 再从磁盘删除 1612004e86ffSlogin let r = dir.remove(guard.fs.upgrade().unwrap().clone(), name, true); 1613004e86ffSlogin drop(target_guard); 1614004e86ffSlogin return r; 1615004e86ffSlogin } 1616004e86ffSlogin 1617676b8ef6SMork fn rmdir(&self, name: &str) -> Result<(), SystemError> { 1618004e86ffSlogin let mut guard: SpinLockGuard<FATInode> = self.0.lock(); 1619004e86ffSlogin let target: Arc<LockedFATInode> = guard.find(name)?; 1620004e86ffSlogin // 对目标inode上锁,以防更改 1621004e86ffSlogin let target_guard: SpinLockGuard<FATInode> = target.0.lock(); 1622004e86ffSlogin // 先从缓存删除 16231074eb34SSamuel Dai guard.children.remove(&DName::from(name.to_uppercase())); 1624004e86ffSlogin 1625004e86ffSlogin let dir = match &guard.inode_type { 1626004e86ffSlogin FATDirEntry::File(_) | FATDirEntry::VolId(_) => { 1627676b8ef6SMork return Err(SystemError::ENOTDIR); 1628004e86ffSlogin } 1629004e86ffSlogin FATDirEntry::Dir(d) => d, 1630004e86ffSlogin FATDirEntry::UnInit => { 16312eab6dd7S曾俊 error!("FATFS: param: Inode_type uninitialized."); 1632676b8ef6SMork return Err(SystemError::EROFS); 1633004e86ffSlogin } 1634004e86ffSlogin }; 1635004e86ffSlogin // 检查文件夹是否存在 1636004e86ffSlogin dir.check_existence(name, Some(true), guard.fs.upgrade().unwrap())?; 1637004e86ffSlogin 1638004e86ffSlogin // 再从磁盘删除 163978bf93f0SYJwu2023 let r: Result<(), SystemError> = 164078bf93f0SYJwu2023 dir.remove(guard.fs.upgrade().unwrap().clone(), name, true); 1641b5b571e0SLoGin match r { 1642b5b571e0SLoGin Ok(_) => return r, 1643b5b571e0SLoGin Err(r) => { 1644676b8ef6SMork if r == SystemError::ENOTEMPTY { 1645004e86ffSlogin // 如果要删除的是目录,且不为空,则删除动作未发生,重新加入缓存 16461074eb34SSamuel Dai guard 16471074eb34SSamuel Dai .children 16481074eb34SSamuel Dai .insert(DName::from(name.to_uppercase()), target.clone()); 1649004e86ffSlogin drop(target_guard); 1650004e86ffSlogin } 1651004e86ffSlogin return Err(r); 1652004e86ffSlogin } 1653004e86ffSlogin } 1654b5b571e0SLoGin } 1655004e86ffSlogin 16569e481b3bSTTaq fn move_to( 16579e481b3bSTTaq &self, 16589e481b3bSTTaq old_name: &str, 16599e481b3bSTTaq target: &Arc<dyn IndexNode>, 16609e481b3bSTTaq new_name: &str, 16619e481b3bSTTaq ) -> Result<(), SystemError> { 16629e481b3bSTTaq let old_id = self.metadata().unwrap().inode_id; 16639e481b3bSTTaq let new_id = target.metadata().unwrap().inode_id; 16649e481b3bSTTaq // 若在同一父目录下 16659e481b3bSTTaq if old_id == new_id { 16669e481b3bSTTaq let mut guard = self.0.lock(); 16679e481b3bSTTaq let old_inode: Arc<LockedFATInode> = guard.find(old_name)?; 16689e481b3bSTTaq // 对目标inode上锁,以防更改 16699e481b3bSTTaq let old_inode_guard: SpinLockGuard<FATInode> = old_inode.0.lock(); 16709e481b3bSTTaq let fs = old_inode_guard.fs.upgrade().unwrap(); 16719e481b3bSTTaq // 从缓存删除 16721074eb34SSamuel Dai let _nod = guard.children.remove(&DName::from(old_name.to_uppercase())); 16739e481b3bSTTaq let old_dir = match &guard.inode_type { 16749e481b3bSTTaq FATDirEntry::File(_) | FATDirEntry::VolId(_) => { 16759e481b3bSTTaq return Err(SystemError::ENOTDIR); 16769e481b3bSTTaq } 16779e481b3bSTTaq FATDirEntry::Dir(d) => d, 16789e481b3bSTTaq FATDirEntry::UnInit => { 16792eab6dd7S曾俊 error!("FATFS: param: Inode_type uninitialized."); 16809e481b3bSTTaq return Err(SystemError::EROFS); 16819e481b3bSTTaq } 16829e481b3bSTTaq }; 16839e481b3bSTTaq // 检查文件是否存在 16849e481b3bSTTaq // old_dir.check_existence(old_name, Some(false), guard.fs.upgrade().unwrap())?; 16859e481b3bSTTaq 16869e481b3bSTTaq old_dir.rename(fs, old_name, new_name)?; 16879e481b3bSTTaq } else { 16889e481b3bSTTaq let mut old_guard = self.0.lock(); 16899e481b3bSTTaq let other: &LockedFATInode = target 16909e481b3bSTTaq .downcast_ref::<LockedFATInode>() 16919e481b3bSTTaq .ok_or(SystemError::EPERM)?; 16929e481b3bSTTaq 16939e481b3bSTTaq let new_guard = other.0.lock(); 16949e481b3bSTTaq let old_inode: Arc<LockedFATInode> = old_guard.find(old_name)?; 16959e481b3bSTTaq // 对目标inode上锁,以防更改 16969e481b3bSTTaq let old_inode_guard: SpinLockGuard<FATInode> = old_inode.0.lock(); 16979e481b3bSTTaq let fs = old_inode_guard.fs.upgrade().unwrap(); 16989e481b3bSTTaq // 从缓存删除 16991074eb34SSamuel Dai let _nod = old_guard 17001074eb34SSamuel Dai .children 17011074eb34SSamuel Dai .remove(&DName::from(old_name.to_uppercase())); 17029e481b3bSTTaq let old_dir = match &old_guard.inode_type { 17039e481b3bSTTaq FATDirEntry::File(_) | FATDirEntry::VolId(_) => { 17049e481b3bSTTaq return Err(SystemError::ENOTDIR); 17059e481b3bSTTaq } 17069e481b3bSTTaq FATDirEntry::Dir(d) => d, 17079e481b3bSTTaq FATDirEntry::UnInit => { 17082eab6dd7S曾俊 error!("FATFS: param: Inode_type uninitialized."); 17099e481b3bSTTaq return Err(SystemError::EROFS); 17109e481b3bSTTaq } 17119e481b3bSTTaq }; 17129e481b3bSTTaq let new_dir = match &new_guard.inode_type { 17139e481b3bSTTaq FATDirEntry::File(_) | FATDirEntry::VolId(_) => { 17149e481b3bSTTaq return Err(SystemError::ENOTDIR); 17159e481b3bSTTaq } 17169e481b3bSTTaq FATDirEntry::Dir(d) => d, 17179e481b3bSTTaq FATDirEntry::UnInit => { 17182eab6dd7S曾俊 error!("FATFA: param: Inode_type uninitialized."); 17199e481b3bSTTaq return Err(SystemError::EROFS); 17209e481b3bSTTaq } 17219e481b3bSTTaq }; 17229e481b3bSTTaq // 检查文件是否存在 17239e481b3bSTTaq old_dir.check_existence(old_name, Some(false), old_guard.fs.upgrade().unwrap())?; 17249e481b3bSTTaq old_dir.rename_across(fs, new_dir, old_name, new_name)?; 17259e481b3bSTTaq } 17269e481b3bSTTaq 17279e481b3bSTTaq return Ok(()); 17289e481b3bSTTaq } 17299e481b3bSTTaq 1730676b8ef6SMork fn get_entry_name(&self, ino: InodeId) -> Result<String, SystemError> { 1731004e86ffSlogin let guard: SpinLockGuard<FATInode> = self.0.lock(); 1732004e86ffSlogin if guard.metadata.file_type != FileType::Dir { 1733676b8ef6SMork return Err(SystemError::ENOTDIR); 1734004e86ffSlogin } 17356b4e7a29SLoGin match ino.into() { 1736004e86ffSlogin 0 => { 1737004e86ffSlogin return Ok(String::from(".")); 1738004e86ffSlogin } 1739004e86ffSlogin 1 => { 1740004e86ffSlogin return Ok(String::from("..")); 1741004e86ffSlogin } 1742004e86ffSlogin ino => { 1743004e86ffSlogin // 暴力遍历所有的children,判断inode id是否相同 1744004e86ffSlogin // TODO: 优化这里,这个地方性能很差! 1745004e86ffSlogin let mut key: Vec<String> = guard 1746004e86ffSlogin .children 17471074eb34SSamuel Dai .iter() 17481074eb34SSamuel Dai .filter_map(|(k, v)| { 17491074eb34SSamuel Dai if v.0.lock().metadata.inode_id.into() == ino { 17501074eb34SSamuel Dai Some(k.to_string()) 17511074eb34SSamuel Dai } else { 17521074eb34SSamuel Dai None 17531074eb34SSamuel Dai } 17546b4e7a29SLoGin }) 1755004e86ffSlogin .collect(); 1756004e86ffSlogin 1757004e86ffSlogin match key.len() { 1758676b8ef6SMork 0=>{return Err(SystemError::ENOENT);} 1759004e86ffSlogin 1=>{return Ok(key.remove(0));} 17606b4e7a29SLoGin _ => 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) 1761004e86ffSlogin } 1762004e86ffSlogin } 1763004e86ffSlogin } 1764004e86ffSlogin } 17652dbef785SGnoCiYeH 17662dbef785SGnoCiYeH fn mknod( 17672dbef785SGnoCiYeH &self, 17682dbef785SGnoCiYeH filename: &str, 17692dbef785SGnoCiYeH mode: ModeType, 1770c566df45SLoGin _dev_t: DeviceNumber, 17712dbef785SGnoCiYeH ) -> Result<Arc<dyn IndexNode>, SystemError> { 17722dbef785SGnoCiYeH let mut inode = self.0.lock(); 17732dbef785SGnoCiYeH if inode.metadata.file_type != FileType::Dir { 17742dbef785SGnoCiYeH return Err(SystemError::ENOTDIR); 17752dbef785SGnoCiYeH } 17762dbef785SGnoCiYeH 17772dbef785SGnoCiYeH // 判断需要创建的类型 17782dbef785SGnoCiYeH if unlikely(mode.contains(ModeType::S_IFREG)) { 17792dbef785SGnoCiYeH // 普通文件 1780b5b571e0SLoGin return self.create(filename, FileType::File, mode); 17812dbef785SGnoCiYeH } 17822dbef785SGnoCiYeH 17831074eb34SSamuel Dai let filename = DName::from(filename.to_uppercase()); 17842dbef785SGnoCiYeH let nod = LockedFATInode::new( 17851074eb34SSamuel Dai filename.clone(), 17862dbef785SGnoCiYeH inode.fs.upgrade().unwrap(), 17872dbef785SGnoCiYeH inode.self_ref.clone(), 17882dbef785SGnoCiYeH FATDirEntry::File(FATFile::default()), 17892dbef785SGnoCiYeH ); 17902dbef785SGnoCiYeH 17912dbef785SGnoCiYeH if mode.contains(ModeType::S_IFIFO) { 17922dbef785SGnoCiYeH nod.0.lock().metadata.file_type = FileType::Pipe; 17932dbef785SGnoCiYeH // 创建pipe文件 17942dbef785SGnoCiYeH let pipe_inode = LockedPipeInode::new(); 17952dbef785SGnoCiYeH // 设置special_node 17962dbef785SGnoCiYeH nod.0.lock().special_node = Some(SpecialNodeData::Pipe(pipe_inode)); 17972dbef785SGnoCiYeH } else if mode.contains(ModeType::S_IFBLK) { 17982dbef785SGnoCiYeH nod.0.lock().metadata.file_type = FileType::BlockDevice; 17992dbef785SGnoCiYeH unimplemented!() 18002dbef785SGnoCiYeH } else if mode.contains(ModeType::S_IFCHR) { 18012dbef785SGnoCiYeH nod.0.lock().metadata.file_type = FileType::CharDevice; 18022dbef785SGnoCiYeH unimplemented!() 18031effcfe5SGnoCiYeH } else { 18041effcfe5SGnoCiYeH return Err(SystemError::EINVAL); 18052dbef785SGnoCiYeH } 18062dbef785SGnoCiYeH 18071074eb34SSamuel Dai inode.children.insert(filename, nod.clone()); 18082dbef785SGnoCiYeH Ok(nod) 18092dbef785SGnoCiYeH } 18102dbef785SGnoCiYeH 18112dbef785SGnoCiYeH fn special_node(&self) -> Option<SpecialNodeData> { 18122dbef785SGnoCiYeH self.0.lock().special_node.clone() 18132dbef785SGnoCiYeH } 18141074eb34SSamuel Dai 18151074eb34SSamuel Dai fn dname(&self) -> Result<DName, SystemError> { 18161074eb34SSamuel Dai Ok(self.0.lock().dname.clone()) 18171074eb34SSamuel Dai } 18181074eb34SSamuel Dai 18191074eb34SSamuel Dai fn parent(&self) -> Result<Arc<dyn IndexNode>, SystemError> { 18201074eb34SSamuel Dai self.0 18211074eb34SSamuel Dai .lock() 18221074eb34SSamuel Dai .parent 18231074eb34SSamuel Dai .upgrade() 18241074eb34SSamuel Dai .map(|item| item as Arc<dyn IndexNode>) 18251074eb34SSamuel Dai .ok_or(SystemError::EINVAL) 18261074eb34SSamuel Dai } 1827004e86ffSlogin } 1828004e86ffSlogin 1829004e86ffSlogin impl Default for FATFsInfo { 1830004e86ffSlogin fn default() -> Self { 1831004e86ffSlogin return FATFsInfo { 1832004e86ffSlogin lead_sig: FATFsInfo::LEAD_SIG, 1833004e86ffSlogin struc_sig: FATFsInfo::STRUC_SIG, 1834004e86ffSlogin free_count: 0xFFFFFFFF, 1835004e86ffSlogin next_free: RESERVED_CLUSTERS, 1836004e86ffSlogin trail_sig: FATFsInfo::TRAIL_SIG, 1837004e86ffSlogin dirty: false, 1838004e86ffSlogin offset: None, 1839004e86ffSlogin }; 1840004e86ffSlogin } 1841004e86ffSlogin } 1842004e86ffSlogin 1843004e86ffSlogin impl Cluster { 1844004e86ffSlogin pub fn new(cluster: u64) -> Self { 1845004e86ffSlogin return Cluster { 1846004e86ffSlogin cluster_num: cluster, 1847004e86ffSlogin parent_cluster: 0, 1848004e86ffSlogin }; 1849004e86ffSlogin } 1850004e86ffSlogin } 1851004e86ffSlogin 1852004e86ffSlogin /// @brief 用于迭代FAT表的内容的簇迭代器对象 1853004e86ffSlogin #[derive(Debug)] 1854004e86ffSlogin struct ClusterIter<'a> { 1855004e86ffSlogin /// 迭代器的next要返回的簇 1856004e86ffSlogin current_cluster: Option<Cluster>, 1857004e86ffSlogin /// 属于的文件系统 1858004e86ffSlogin fs: &'a FATFileSystem, 1859004e86ffSlogin } 1860004e86ffSlogin 1861004e86ffSlogin impl<'a> Iterator for ClusterIter<'a> { 1862004e86ffSlogin type Item = Cluster; 1863004e86ffSlogin 1864004e86ffSlogin fn next(&mut self) -> Option<Self::Item> { 1865004e86ffSlogin // 当前要返回的簇 1866004e86ffSlogin let ret: Option<Cluster> = self.current_cluster; 1867004e86ffSlogin 1868004e86ffSlogin // 获得下一个要返回簇 1869004e86ffSlogin let new: Option<Cluster> = match self.current_cluster { 1870004e86ffSlogin Some(c) => { 1871004e86ffSlogin let entry: Option<FATEntry> = self.fs.get_fat_entry(c).ok(); 1872004e86ffSlogin match entry { 1873004e86ffSlogin Some(FATEntry::Next(c)) => Some(c), 1874004e86ffSlogin _ => None, 1875004e86ffSlogin } 1876004e86ffSlogin } 1877004e86ffSlogin _ => None, 1878004e86ffSlogin }; 1879004e86ffSlogin 1880004e86ffSlogin self.current_cluster = new; 1881004e86ffSlogin return ret; 1882004e86ffSlogin } 1883004e86ffSlogin } 1884