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