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