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