xref: /DragonOS/kernel/src/filesystem/fat/fs.rs (revision f110d330d5493f383067b4e82ebbfb72f40457b2)
1 #![allow(dead_code)]
2 use core::intrinsics::unlikely;
3 use core::{any::Any, fmt::Debug};
4 
5 use alloc::{
6     collections::BTreeMap,
7     string::String,
8     sync::{Arc, Weak},
9     vec::Vec,
10 };
11 
12 use crate::filesystem::vfs::SpecialNodeData;
13 use crate::ipc::pipe::LockedPipeInode;
14 use crate::{
15     driver::base::block::{block_device::LBA_SIZE, disk_info::Partition, SeekFrom},
16     filesystem::vfs::{
17         core::generate_inode_id,
18         file::{FileMode, FilePrivateData},
19         syscall::ModeType,
20         FileSystem, FileType, IndexNode, InodeId, Metadata,
21     },
22     kerror,
23     libs::{
24         spinlock::{SpinLock, SpinLockGuard},
25         vec_cursor::VecCursor,
26     },
27     syscall::SystemError,
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     pub fn is_shut_bit_ok(&mut self) -> Result<bool, SystemError> {
788         match self.bpb.fat_type {
789             FATType::FAT32(_) => {
790                 // 对于FAT32, error bit位于第一个扇区的第8字节。
791                 let bit = self.get_fat_entry_raw(Cluster::new(1))? & 0x0800_0000;
792                 return Ok(bit > 0);
793             }
794             FATType::FAT16(_) => {
795                 let bit = self.get_fat_entry_raw(Cluster::new(1))? & 0x8000;
796                 return Ok(bit > 0);
797             }
798             _ => return Ok(true),
799         }
800     }
801 
802     /// @brief 判断FAT文件系统的hard error bit是否正常。
803     /// 如果此位为0,则文件系统驱动程序在上次安装卷时遇到磁盘 I/O 错误,这表明
804     /// 卷上的某些扇区可能已损坏。
805     /// 参考资料:https://thestarman.pcministry.com/DOS/DirtyShutdownFlag.html
806     ///
807     /// @return Ok(true) 正常
808     /// @return Ok(false) 不正常
809     /// @return Err(SystemError) 在判断时发生错误
810     pub fn is_hard_error_bit_ok(&mut self) -> Result<bool, SystemError> {
811         match self.bpb.fat_type {
812             FATType::FAT32(_) => {
813                 let bit = self.get_fat_entry_raw(Cluster::new(1))? & 0x0400_0000;
814                 return Ok(bit > 0);
815             }
816             FATType::FAT16(_) => {
817                 let bit = self.get_fat_entry_raw(Cluster::new(1))? & 0x4000;
818                 return Ok(bit > 0);
819             }
820             _ => return Ok(true),
821         }
822     }
823 
824     /// @brief 设置文件系统的shut bit为正常状态
825     /// 参考资料:https://thestarman.pcministry.com/DOS/DirtyShutdownFlag.html
826     ///
827     /// @return Ok(()) 设置成功
828     /// @return Err(SystemError) 在设置过程中,出现错误
829     pub fn set_shut_bit_ok(&mut self) -> Result<(), SystemError> {
830         match self.bpb.fat_type {
831             FATType::FAT32(_) => {
832                 let raw_entry = self.get_fat_entry_raw(Cluster::new(1))? | 0x0800_0000;
833                 self.set_entry(Cluster::new(1), FATEntry::Next(Cluster::new(raw_entry)))?;
834 
835                 return Ok(());
836             }
837 
838             FATType::FAT16(_) => {
839                 let raw_entry = self.get_fat_entry_raw(Cluster::new(1))? | 0x8000;
840                 self.set_entry(Cluster::new(1), FATEntry::Next(Cluster::new(raw_entry)))?;
841                 return Ok(());
842             }
843             _ => return Ok(()),
844         }
845     }
846 
847     /// @brief 设置文件系统的hard error bit为正常状态
848     /// 参考资料:https://thestarman.pcministry.com/DOS/DirtyShutdownFlag.html
849     ///
850     /// @return Ok(()) 设置成功
851     /// @return Err(SystemError) 在设置过程中,出现错误
852     pub fn set_hard_error_bit_ok(&mut self) -> Result<(), SystemError> {
853         match self.bpb.fat_type {
854             FATType::FAT32(_) => {
855                 let raw_entry = self.get_fat_entry_raw(Cluster::new(1))? | 0x0400_0000;
856                 self.set_entry(Cluster::new(1), FATEntry::Next(Cluster::new(raw_entry)))?;
857                 return Ok(());
858             }
859 
860             FATType::FAT16(_) => {
861                 let raw_entry = self.get_fat_entry_raw(Cluster::new(1))? | 0x4000;
862                 self.set_entry(Cluster::new(1), FATEntry::Next(Cluster::new(raw_entry)))?;
863                 return Ok(());
864             }
865             _ => return Ok(()),
866         }
867     }
868 
869     /// @brief 执行文件系统卸载前的一些准备工作:设置好对应的标志位,并把缓存中的数据刷入磁盘
870     pub fn umount(&mut self) -> Result<(), SystemError> {
871         self.fs_info.0.lock().flush(&self.partition)?;
872 
873         self.set_shut_bit_ok()?;
874 
875         self.set_hard_error_bit_ok()?;
876 
877         self.partition.disk().sync()?;
878 
879         return Ok(());
880     }
881 
882     /// @brief 获取文件系统的最大簇号
883     pub fn max_cluster_number(&self) -> Cluster {
884         match self.bpb.fat_type {
885             FATType::FAT32(s) => {
886                 // FAT32
887 
888                 // 数据扇区数量(总扇区数-保留扇区-FAT占用的扇区)
889                 let data_sec: u64 = self.bpb.total_sectors_32 as u64
890                     - (self.bpb.rsvd_sec_cnt as u64
891                         + self.bpb.num_fats as u64 * s.fat_size_32 as u64);
892 
893                 // 数据区的簇数量
894                 let total_clusters: u64 = data_sec / self.bpb.sector_per_cluster as u64;
895 
896                 // 返回最大的簇号
897                 return Cluster::new(total_clusters + RESERVED_CLUSTERS as u64 - 1);
898             }
899 
900             _ => {
901                 // FAT12 / FAT16
902                 let root_dir_sectors: u64 = (((self.bpb.root_entries_cnt as u64) * 32)
903                     + self.bpb.bytes_per_sector as u64
904                     - 1)
905                     / self.bpb.bytes_per_sector as u64;
906                 // 数据区扇区数
907                 let data_sec: u64 = self.bpb.total_sectors_16 as u64
908                     - (self.bpb.rsvd_sec_cnt as u64
909                         + (self.bpb.num_fats as u64 * self.bpb.fat_size_16 as u64)
910                         + root_dir_sectors);
911                 let total_clusters = data_sec / self.bpb.sector_per_cluster as u64;
912                 return Cluster::new(total_clusters + RESERVED_CLUSTERS as u64 - 1);
913             }
914         }
915     }
916 
917     /// @brief 在文件系统中寻找一个簇号在给定的范围(左闭右开区间)内的空闲簇
918     ///
919     /// @param start_cluster 起始簇号
920     /// @param end_cluster 终止簇号(不包含)
921     ///
922     /// @return Ok(Cluster) 寻找到的空闲簇
923     /// @return Err(SystemError) 错误码。如果磁盘无剩余空间,或者簇号达到给定的最大值,则返回-ENOSPC.
924     pub fn get_free_cluster(
925         &self,
926         start_cluster: Cluster,
927         end_cluster: Cluster,
928     ) -> Result<Cluster, SystemError> {
929         let max_cluster: Cluster = self.max_cluster_number();
930         let mut cluster: u64 = start_cluster.cluster_num;
931 
932         let fat_type: FATType = self.bpb.fat_type;
933         let fat_start_sector: u64 = self.fat_start_sector();
934         let bytes_per_sec: u64 = self.bpb.bytes_per_sector as u64;
935 
936         match fat_type {
937             FATType::FAT12(_) => {
938                 let part_bytes_offset: u64 =
939                     fat_type.get_fat_bytes_offset(start_cluster, fat_start_sector, bytes_per_sec);
940                 let in_block_offset = self.get_in_block_offset(part_bytes_offset);
941 
942                 let lba = self.get_lba_from_offset(self.bytes_to_sector(part_bytes_offset));
943 
944                 // 由于FAT12的FAT表不大于6K,因此直接读取6K
945                 let num_lba = (6 * 1024) / LBA_SIZE;
946                 let mut v: Vec<u8> = Vec::new();
947                 v.resize(num_lba * LBA_SIZE, 0);
948                 self.partition.disk().read_at(lba, num_lba, &mut v)?;
949 
950                 let mut cursor: VecCursor = VecCursor::new(v);
951                 cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?;
952 
953                 let mut packed_val: u16 = cursor.read_u16()?;
954                 loop {
955                     let val = if (cluster & 0x1) > 0 {
956                         packed_val >> 4
957                     } else {
958                         packed_val & 0x0fff
959                     };
960                     if val == 0 {
961                         return Ok(Cluster::new(cluster as u64));
962                     }
963 
964                     cluster += 1;
965 
966                     // 磁盘无剩余空间,或者簇号达到给定的最大值
967                     if cluster == end_cluster.cluster_num || cluster == max_cluster.cluster_num {
968                         return Err(SystemError::ENOSPC);
969                     }
970 
971                     packed_val = match cluster & 1 {
972                         0 => cursor.read_u16()?,
973                         _ => {
974                             let next_byte = cursor.read_u8()? as u16;
975                             (packed_val >> 8) | (next_byte << 8)
976                         }
977                     };
978                 }
979             }
980             FATType::FAT16(_) => {
981                 // todo: 优化这里,减少读取磁盘的次数。
982                 while cluster < end_cluster.cluster_num && cluster < max_cluster.cluster_num {
983                     let part_bytes_offset: u64 = fat_type.get_fat_bytes_offset(
984                         Cluster::new(cluster),
985                         fat_start_sector,
986                         bytes_per_sec,
987                     );
988                     let in_block_offset = self.get_in_block_offset(part_bytes_offset);
989 
990                     let lba = self.get_lba_from_offset(self.bytes_to_sector(part_bytes_offset));
991 
992                     let mut v: Vec<u8> = Vec::new();
993                     v.resize(self.lba_per_sector() * LBA_SIZE, 0);
994                     self.partition
995                         .disk()
996                         .read_at(lba, self.lba_per_sector(), &mut v)?;
997 
998                     let mut cursor: VecCursor = VecCursor::new(v);
999                     cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?;
1000 
1001                     let val = cursor.read_u16()?;
1002                     // 找到空闲簇
1003                     if val == 0 {
1004                         return Ok(Cluster::new(val as u64));
1005                     }
1006                     cluster += 1;
1007                 }
1008 
1009                 // 磁盘无剩余空间,或者簇号达到给定的最大值
1010                 return Err(SystemError::ENOSPC);
1011             }
1012             FATType::FAT32(_) => {
1013                 // todo: 优化这里,减少读取磁盘的次数。
1014                 while cluster < end_cluster.cluster_num && cluster < max_cluster.cluster_num {
1015                     let part_bytes_offset: u64 = fat_type.get_fat_bytes_offset(
1016                         Cluster::new(cluster),
1017                         fat_start_sector,
1018                         bytes_per_sec,
1019                     );
1020                     let in_block_offset = self.get_in_block_offset(part_bytes_offset);
1021 
1022                     let lba = self.get_lba_from_offset(self.bytes_to_sector(part_bytes_offset));
1023 
1024                     let mut v: Vec<u8> = Vec::new();
1025                     v.resize(self.lba_per_sector() * LBA_SIZE, 0);
1026                     self.partition
1027                         .disk()
1028                         .read_at(lba, self.lba_per_sector(), &mut v)?;
1029 
1030                     let mut cursor: VecCursor = VecCursor::new(v);
1031                     cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?;
1032 
1033                     let val = cursor.read_u32()? & 0x0fffffff;
1034 
1035                     if val == 0 {
1036                         return Ok(Cluster::new(cluster));
1037                     }
1038                     cluster += 1;
1039                 }
1040 
1041                 // 磁盘无剩余空间,或者簇号达到给定的最大值
1042                 return Err(SystemError::ENOSPC);
1043             }
1044         }
1045     }
1046 
1047     /// @brief 在FAT表中,设置指定的簇的信息。
1048     ///
1049     /// @param cluster 目标簇
1050     /// @param fat_entry 这个簇在FAT表中,存储的信息(下一个簇的簇号)
1051     pub fn set_entry(&self, cluster: Cluster, fat_entry: FATEntry) -> Result<(), SystemError> {
1052         // fat表项在分区上的字节偏移量
1053         let fat_part_bytes_offset: u64 = self.bpb.fat_type.get_fat_bytes_offset(
1054             cluster,
1055             self.fat_start_sector(),
1056             self.bpb.bytes_per_sector as u64,
1057         );
1058 
1059         match self.bpb.fat_type {
1060             FATType::FAT12(_) => {
1061                 // 计算要写入的值
1062                 let raw_val: u16 = match fat_entry {
1063                     FATEntry::Unused => 0,
1064                     FATEntry::Bad => 0xff7,
1065                     FATEntry::EndOfChain => 0xfff,
1066                     FATEntry::Next(c) => c.cluster_num as u16,
1067                 };
1068 
1069                 let in_block_offset = self.get_in_block_offset(fat_part_bytes_offset);
1070 
1071                 let lba = self.get_lba_from_offset(self.bytes_to_sector(fat_part_bytes_offset));
1072 
1073                 let mut v: Vec<u8> = Vec::new();
1074                 v.resize(LBA_SIZE, 0);
1075                 self.partition.disk().read_at(lba, 1, &mut v)?;
1076 
1077                 let mut cursor: VecCursor = VecCursor::new(v);
1078                 cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?;
1079 
1080                 let old_val: u16 = cursor.read_u16()?;
1081                 let new_val: u16 = if (cluster.cluster_num & 0x1) > 0 {
1082                     (old_val & 0x000f) | (raw_val << 4)
1083                 } else {
1084                     (old_val & 0xf000) | raw_val
1085                 };
1086 
1087                 // 写回数据到磁盘上
1088                 cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?;
1089                 cursor.write_u16(new_val)?;
1090                 self.partition.disk().write_at(lba, 1, cursor.as_slice())?;
1091                 return Ok(());
1092             }
1093             FATType::FAT16(_) => {
1094                 // 计算要写入的值
1095                 let raw_val: u16 = match fat_entry {
1096                     FATEntry::Unused => 0,
1097                     FATEntry::Bad => 0xfff7,
1098                     FATEntry::EndOfChain => 0xfdff,
1099                     FATEntry::Next(c) => c.cluster_num as u16,
1100                 };
1101 
1102                 let in_block_offset = self.get_in_block_offset(fat_part_bytes_offset);
1103 
1104                 let lba = self.get_lba_from_offset(self.bytes_to_sector(fat_part_bytes_offset));
1105 
1106                 let mut v: Vec<u8> = Vec::new();
1107                 v.resize(LBA_SIZE, 0);
1108                 self.partition.disk().read_at(lba, 1, &mut v)?;
1109 
1110                 let mut cursor: VecCursor = VecCursor::new(v);
1111                 cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?;
1112 
1113                 cursor.write_u16(raw_val)?;
1114                 self.partition.disk().write_at(lba, 1, cursor.as_slice())?;
1115 
1116                 return Ok(());
1117             }
1118             FATType::FAT32(_) => {
1119                 let fat_size: u64 = self.fat_size();
1120                 let bound: u64 = if self.mirroring_enabled() {
1121                     1
1122                 } else {
1123                     self.bpb.num_fats as u64
1124                 };
1125                 // kdebug!("set entry, bound={bound}, fat_size={fat_size}");
1126                 for i in 0..bound {
1127                     // 当前操作的FAT表在磁盘上的字节偏移量
1128                     let f_offset: u64 = fat_part_bytes_offset + i * fat_size;
1129                     let in_block_offset: u64 = self.get_in_block_offset(f_offset);
1130                     let lba = self.get_lba_from_offset(self.bytes_to_sector(f_offset));
1131 
1132                     // kdebug!("set entry, lba={lba}, in_block_offset={in_block_offset}");
1133                     let mut v: Vec<u8> = Vec::new();
1134                     v.resize(LBA_SIZE, 0);
1135                     self.partition.disk().read_at(lba, 1, &mut v)?;
1136 
1137                     let mut cursor: VecCursor = VecCursor::new(v);
1138                     cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?;
1139 
1140                     // FAT32的高4位保留
1141                     let old_bits = cursor.read_u32()? & 0xf0000000;
1142 
1143                     if fat_entry == FATEntry::Unused
1144                         && cluster.cluster_num >= 0x0ffffff7
1145                         && cluster.cluster_num <= 0x0fffffff
1146                     {
1147                         kerror!(
1148                             "FAT32: Reserved Cluster {:?} cannot be marked as free",
1149                             cluster
1150                         );
1151                         return Err(SystemError::EPERM);
1152                     }
1153 
1154                     // 计算要写入的值
1155                     let mut raw_val: u32 = match fat_entry {
1156                         FATEntry::Unused => 0,
1157                         FATEntry::Bad => 0x0FFFFFF7,
1158                         FATEntry::EndOfChain => 0x0FFFFFFF,
1159                         FATEntry::Next(c) => c.cluster_num as u32,
1160                     };
1161 
1162                     // 恢复保留位
1163                     raw_val |= old_bits;
1164 
1165                     // kdebug!("sent entry, raw_val={raw_val}");
1166 
1167                     cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?;
1168                     cursor.write_u32(raw_val)?;
1169 
1170                     self.partition.disk().write_at(lba, 1, cursor.as_slice())?;
1171                 }
1172 
1173                 return Ok(());
1174             }
1175         }
1176     }
1177 
1178     /// @brief 清空指定的簇
1179     ///
1180     /// @param cluster 要被清空的簇
1181     pub fn zero_cluster(&self, cluster: Cluster) -> Result<(), SystemError> {
1182         // 准备数据,用于写入
1183         let zeros: Vec<u8> = vec![0u8; self.bytes_per_cluster() as usize];
1184         let offset: usize = self.cluster_bytes_offset(cluster) as usize;
1185         self.partition
1186             .disk()
1187             .write_at_bytes(offset, zeros.len(), zeros.as_slice())?;
1188         return Ok(());
1189     }
1190 }
1191 
1192 impl Drop for FATFileSystem {
1193     fn drop(&mut self) {
1194         let r = self.umount();
1195         if r.is_err() {
1196             kerror!(
1197                 "Umount FAT filesystem failed: errno={:?}, FS detail:{self:?}",
1198                 r.unwrap_err()
1199             );
1200         }
1201     }
1202 }
1203 
1204 impl FATFsInfo {
1205     const LEAD_SIG: u32 = 0x41615252;
1206     const STRUC_SIG: u32 = 0x61417272;
1207     const TRAIL_SIG: u32 = 0xAA550000;
1208     const FS_INFO_SIZE: u64 = 512;
1209 
1210     /// @brief 从磁盘上读取FAT文件系统的FSInfo结构体
1211     ///
1212     /// @param partition 磁盘分区
1213     /// @param in_disk_fs_info_offset FSInfo扇区在磁盘内的字节偏移量(单位:字节)
1214     /// @param bytes_per_sec 每扇区字节数
1215     pub fn new(
1216         partition: Arc<Partition>,
1217         in_disk_fs_info_offset: u64,
1218         bytes_per_sec: usize,
1219     ) -> Result<Self, SystemError> {
1220         let mut v = Vec::<u8>::new();
1221         v.resize(bytes_per_sec, 0);
1222 
1223         // 计算fs_info扇区在磁盘上的字节偏移量,从磁盘读取数据
1224         partition
1225             .disk()
1226             .read_at(in_disk_fs_info_offset as usize / LBA_SIZE, 1, &mut v)?;
1227         let mut cursor = VecCursor::new(v);
1228 
1229         let mut fsinfo = FATFsInfo::default();
1230 
1231         fsinfo.lead_sig = cursor.read_u32()?;
1232         cursor.seek(SeekFrom::SeekCurrent(480))?;
1233         fsinfo.struc_sig = cursor.read_u32()?;
1234         fsinfo.free_count = cursor.read_u32()?;
1235         fsinfo.next_free = cursor.read_u32()?;
1236 
1237         cursor.seek(SeekFrom::SeekCurrent(12))?;
1238 
1239         fsinfo.trail_sig = cursor.read_u32()?;
1240         fsinfo.dirty = false;
1241         fsinfo.offset = Some(in_disk_fs_info_offset);
1242 
1243         if fsinfo.is_valid() {
1244             return Ok(fsinfo);
1245         } else {
1246             kerror!("Error occurred while parsing FATFsInfo.");
1247             return Err(SystemError::EINVAL);
1248         }
1249     }
1250 
1251     /// @brief 判断是否为正确的FsInfo结构体
1252     fn is_valid(&self) -> bool {
1253         self.lead_sig == Self::LEAD_SIG
1254             && self.struc_sig == Self::STRUC_SIG
1255             && self.trail_sig == Self::TRAIL_SIG
1256     }
1257 
1258     /// @brief 根据fsinfo的信息,计算当前总的空闲簇数量
1259     ///
1260     /// @param 当前文件系统的最大簇号
1261     pub fn count_free_cluster(&self, max_cluster: Cluster) -> Option<u64> {
1262         let count_clusters = max_cluster.cluster_num - RESERVED_CLUSTERS as u64 + 1;
1263         // 信息不合理,当前的FsInfo中存储的free count大于计算出来的值
1264         if self.free_count as u64 > count_clusters {
1265             return None;
1266         } else {
1267             match self.free_count {
1268                 // free count字段不可用
1269                 0xffffffff => return None,
1270                 // 返回FsInfo中存储的数据
1271                 n => return Some(n as u64),
1272             }
1273         }
1274     }
1275 
1276     /// @brief 更新FsInfo中的“空闲簇统计信息“为new_count
1277     ///
1278     /// 请注意,除非手动调用`flush()`,否则本函数不会将数据刷入磁盘
1279     pub fn update_free_count_abs(&mut self, new_count: u32) {
1280         self.free_count = new_count;
1281     }
1282 
1283     /// @brief 更新FsInfo中的“空闲簇统计信息“,把它加上delta.
1284     ///
1285     /// 请注意,除非手动调用`flush()`,否则本函数不会将数据刷入磁盘
1286     pub fn update_free_count_delta(&mut self, delta: i32) {
1287         self.free_count = (self.free_count as i32 + delta) as u32;
1288     }
1289 
1290     /// @brief 更新FsInfo中的“第一个空闲簇统计信息“为next_free.
1291     ///
1292     /// 请注意,除非手动调用`flush()`,否则本函数不会将数据刷入磁盘
1293     pub fn update_next_free(&mut self, next_free: u32) {
1294         // 这个值是参考量,不一定要准确,仅供加速查找
1295         self.next_free = next_free;
1296     }
1297 
1298     /// @brief 获取fs info 记载的第一个空闲簇。(不一定准确,仅供参考)
1299     pub fn next_free(&self) -> Option<u64> {
1300         match self.next_free {
1301             0xffffffff => return None,
1302             0 | 1 => return None,
1303             n => return Some(n as u64),
1304         };
1305     }
1306 
1307     /// @brief 把fs info刷入磁盘
1308     ///
1309     /// @param partition fs info所在的分区
1310     pub fn flush(&self, partition: &Arc<Partition>) -> Result<(), SystemError> {
1311         if let Some(off) = self.offset {
1312             let in_block_offset = off % LBA_SIZE as u64;
1313 
1314             let lba = off as usize / LBA_SIZE;
1315 
1316             let mut v: Vec<u8> = Vec::new();
1317             v.resize(LBA_SIZE, 0);
1318             partition.disk().read_at(lba, 1, &mut v)?;
1319 
1320             let mut cursor: VecCursor = VecCursor::new(v);
1321             cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?;
1322 
1323             cursor.write_u32(self.lead_sig)?;
1324             cursor.seek(SeekFrom::SeekCurrent(480))?;
1325             cursor.write_u32(self.struc_sig)?;
1326             cursor.write_u32(self.free_count)?;
1327             cursor.write_u32(self.next_free)?;
1328             cursor.seek(SeekFrom::SeekCurrent(12))?;
1329             cursor.write_u32(self.trail_sig)?;
1330 
1331             partition.disk().write_at(lba, 1, cursor.as_slice())?;
1332         }
1333         return Ok(());
1334     }
1335 
1336     /// @brief 读取磁盘上的Fs Info扇区,将里面的内容更新到结构体中
1337     ///
1338     /// @param partition fs info所在的分区
1339     pub fn update(&mut self, partition: Arc<Partition>) -> Result<(), SystemError> {
1340         if let Some(off) = self.offset {
1341             let in_block_offset = off % LBA_SIZE as u64;
1342 
1343             let lba = off as usize / LBA_SIZE;
1344 
1345             let mut v: Vec<u8> = Vec::new();
1346             v.resize(LBA_SIZE, 0);
1347             partition.disk().read_at(lba, 1, &mut v)?;
1348             let mut cursor: VecCursor = VecCursor::new(v);
1349             cursor.seek(SeekFrom::SeekSet(in_block_offset as i64))?;
1350             self.lead_sig = cursor.read_u32()?;
1351 
1352             cursor.seek(SeekFrom::SeekCurrent(480))?;
1353             self.struc_sig = cursor.read_u32()?;
1354             self.free_count = cursor.read_u32()?;
1355             self.next_free = cursor.read_u32()?;
1356             cursor.seek(SeekFrom::SeekCurrent(12))?;
1357             self.trail_sig = cursor.read_u32()?;
1358         }
1359         return Ok(());
1360     }
1361 }
1362 
1363 impl IndexNode for LockedFATInode {
1364     fn read_at(
1365         &self,
1366         offset: usize,
1367         len: usize,
1368         buf: &mut [u8],
1369         _data: &mut FilePrivateData,
1370     ) -> Result<usize, SystemError> {
1371         let mut guard: SpinLockGuard<FATInode> = self.0.lock();
1372         match &guard.inode_type {
1373             FATDirEntry::File(f) | FATDirEntry::VolId(f) => {
1374                 let r = f.read(
1375                     &guard.fs.upgrade().unwrap(),
1376                     &mut buf[0..len],
1377                     offset as u64,
1378                 );
1379                 guard.update_metadata();
1380                 return r;
1381             }
1382             FATDirEntry::Dir(_) => {
1383                 return Err(SystemError::EISDIR);
1384             }
1385             FATDirEntry::UnInit => {
1386                 kerror!("FATFS: param: Inode_type uninitialized.");
1387                 return Err(SystemError::EROFS);
1388             }
1389         }
1390     }
1391 
1392     fn write_at(
1393         &self,
1394         offset: usize,
1395         len: usize,
1396         buf: &[u8],
1397         _data: &mut FilePrivateData,
1398     ) -> Result<usize, SystemError> {
1399         let mut guard: SpinLockGuard<FATInode> = self.0.lock();
1400         let fs: &Arc<FATFileSystem> = &guard.fs.upgrade().unwrap();
1401 
1402         match &mut guard.inode_type {
1403             FATDirEntry::File(f) | FATDirEntry::VolId(f) => {
1404                 let r = f.write(fs, &buf[0..len], offset as u64);
1405                 guard.update_metadata();
1406                 return r;
1407             }
1408             FATDirEntry::Dir(_) => {
1409                 return Err(SystemError::EISDIR);
1410             }
1411             FATDirEntry::UnInit => {
1412                 kerror!("FATFS: param: Inode_type uninitialized.");
1413                 return Err(SystemError::EROFS);
1414             }
1415         }
1416     }
1417 
1418     fn create(
1419         &self,
1420         name: &str,
1421         file_type: FileType,
1422         _mode: ModeType,
1423     ) -> Result<Arc<dyn IndexNode>, SystemError> {
1424         // 由于FAT32不支持文件权限的功能,因此忽略mode参数
1425         let mut guard: SpinLockGuard<FATInode> = self.0.lock();
1426         let fs: &Arc<FATFileSystem> = &guard.fs.upgrade().unwrap();
1427 
1428         match &mut guard.inode_type {
1429             FATDirEntry::File(_) | FATDirEntry::VolId(_) => {
1430                 return Err(SystemError::ENOTDIR);
1431             }
1432             FATDirEntry::Dir(d) => match file_type {
1433                 FileType::File => {
1434                     d.create_file(name, fs)?;
1435                     return Ok(guard.find(name)?);
1436                 }
1437                 FileType::Dir => {
1438                     d.create_dir(name, fs)?;
1439                     return Ok(guard.find(name)?);
1440                 }
1441 
1442                 FileType::SymLink => return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP),
1443                 _ => return Err(SystemError::EINVAL),
1444             },
1445             FATDirEntry::UnInit => {
1446                 kerror!("FATFS: param: Inode_type uninitialized.");
1447                 return Err(SystemError::EROFS);
1448             }
1449         }
1450     }
1451 
1452     fn fs(&self) -> Arc<dyn FileSystem> {
1453         return self.0.lock().fs.upgrade().unwrap();
1454     }
1455 
1456     fn as_any_ref(&self) -> &dyn core::any::Any {
1457         return self;
1458     }
1459 
1460     fn metadata(&self) -> Result<Metadata, SystemError> {
1461         return Ok(self.0.lock().metadata.clone());
1462     }
1463     fn resize(&self, len: usize) -> Result<(), SystemError> {
1464         let mut guard: SpinLockGuard<FATInode> = self.0.lock();
1465         let fs: &Arc<FATFileSystem> = &guard.fs.upgrade().unwrap();
1466         let old_size = guard.metadata.size as usize;
1467 
1468         match &mut guard.inode_type {
1469             FATDirEntry::File(file) | FATDirEntry::VolId(file) => {
1470                 // 如果新的长度和旧的长度相同,那么就直接返回
1471                 if len == old_size {
1472                     return Ok(());
1473                 } else if len > old_size {
1474                     // 如果新的长度比旧的长度大,那么就在文件末尾添加空白
1475                     let mut buf: Vec<u8> = Vec::new();
1476                     let mut remain_size = len - old_size;
1477                     let buf_size = remain_size;
1478                     // let buf_size = core::cmp::min(remain_size, 512 * 1024);
1479                     buf.resize(buf_size, 0);
1480 
1481                     let mut offset = old_size;
1482                     while remain_size > 0 {
1483                         let write_size = core::cmp::min(remain_size, buf_size);
1484                         file.write(fs, &buf[0..write_size], offset as u64)?;
1485                         remain_size -= write_size;
1486                         offset += write_size;
1487                     }
1488                 } else {
1489                     file.truncate(fs, len as u64)?;
1490                 }
1491                 guard.update_metadata();
1492                 return Ok(());
1493             }
1494             FATDirEntry::Dir(_) => return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP),
1495             FATDirEntry::UnInit => {
1496                 kerror!("FATFS: param: Inode_type uninitialized.");
1497                 return Err(SystemError::EROFS);
1498             }
1499         }
1500     }
1501 
1502     fn truncate(&self, len: usize) -> Result<(), SystemError> {
1503         let guard: SpinLockGuard<FATInode> = self.0.lock();
1504         let old_size = guard.metadata.size as usize;
1505         if len < old_size {
1506             drop(guard);
1507             self.resize(len)
1508         } else {
1509             Ok(())
1510         }
1511     }
1512 
1513     fn list(&self) -> Result<Vec<String>, SystemError> {
1514         let mut guard: SpinLockGuard<FATInode> = self.0.lock();
1515         let fatent: &FATDirEntry = &guard.inode_type;
1516         match fatent {
1517             FATDirEntry::File(_) | FATDirEntry::VolId(_) => {
1518                 return Err(SystemError::ENOTDIR);
1519             }
1520             FATDirEntry::Dir(dir) => {
1521                 // 获取当前目录下的所有目录项
1522                 let mut ret: Vec<String> = Vec::new();
1523                 let dir_iter: FATDirIter = dir.to_iter(guard.fs.upgrade().unwrap());
1524                 for ent in dir_iter {
1525                     ret.push(ent.name());
1526 
1527                     // ====== 生成inode缓存,存入B树
1528                     let name: String = ent.name();
1529                     // kdebug!("name={name}");
1530 
1531                     if guard.children.contains_key(&name.to_uppercase()) == false
1532                         && name != "."
1533                         && name != ".."
1534                     {
1535                         // 创建新的inode
1536                         let entry_inode: Arc<LockedFATInode> = LockedFATInode::new(
1537                             guard.fs.upgrade().unwrap(),
1538                             guard.self_ref.clone(),
1539                             ent,
1540                         );
1541                         // 加入缓存区, 由于FAT文件系统的大小写不敏感问题,因此存入缓存区的key应当是全大写的
1542                         guard
1543                             .children
1544                             .insert(name.to_uppercase(), entry_inode.clone());
1545                     }
1546                 }
1547                 return Ok(ret);
1548             }
1549             FATDirEntry::UnInit => {
1550                 kerror!("FATFS: param: Inode_type uninitialized.");
1551                 return Err(SystemError::EROFS);
1552             }
1553         }
1554     }
1555 
1556     fn find(&self, name: &str) -> Result<Arc<dyn IndexNode>, SystemError> {
1557         let mut guard: SpinLockGuard<FATInode> = self.0.lock();
1558         let target = guard.find(name)?;
1559         return Ok(target);
1560     }
1561 
1562     fn open(&self, _data: &mut FilePrivateData, _mode: &FileMode) -> Result<(), SystemError> {
1563         return Ok(());
1564     }
1565 
1566     fn close(&self, _data: &mut FilePrivateData) -> Result<(), SystemError> {
1567         return Ok(());
1568     }
1569 
1570     fn unlink(&self, name: &str) -> Result<(), SystemError> {
1571         let mut guard: SpinLockGuard<FATInode> = self.0.lock();
1572         let target: Arc<LockedFATInode> = guard.find(name)?;
1573         // 对目标inode上锁,以防更改
1574         let target_guard: SpinLockGuard<FATInode> = target.0.lock();
1575         // 先从缓存删除
1576         let nod = guard.children.remove(&name.to_uppercase());
1577 
1578         // 若删除缓存中为管道的文件,则不需要再到磁盘删除
1579         if let Some(_) = nod {
1580             let file_type = target_guard.metadata.file_type;
1581             if file_type == FileType::Pipe {
1582                 return Ok(());
1583             }
1584         }
1585 
1586         let dir = match &guard.inode_type {
1587             FATDirEntry::File(_) | FATDirEntry::VolId(_) => {
1588                 return Err(SystemError::ENOTDIR);
1589             }
1590             FATDirEntry::Dir(d) => d,
1591             FATDirEntry::UnInit => {
1592                 kerror!("FATFS: param: Inode_type uninitialized.");
1593                 return Err(SystemError::EROFS);
1594             }
1595         };
1596         // 检查文件是否存在
1597         dir.check_existence(name, Some(false), guard.fs.upgrade().unwrap())?;
1598 
1599         // 再从磁盘删除
1600         let r = dir.remove(guard.fs.upgrade().unwrap().clone(), name, true);
1601         drop(target_guard);
1602         return r;
1603     }
1604 
1605     fn rmdir(&self, name: &str) -> Result<(), SystemError> {
1606         let mut guard: SpinLockGuard<FATInode> = self.0.lock();
1607         let target: Arc<LockedFATInode> = guard.find(name)?;
1608         // 对目标inode上锁,以防更改
1609         let target_guard: SpinLockGuard<FATInode> = target.0.lock();
1610         // 先从缓存删除
1611         guard.children.remove(&name.to_uppercase());
1612 
1613         let dir = match &guard.inode_type {
1614             FATDirEntry::File(_) | FATDirEntry::VolId(_) => {
1615                 return Err(SystemError::ENOTDIR);
1616             }
1617             FATDirEntry::Dir(d) => d,
1618             FATDirEntry::UnInit => {
1619                 kerror!("FATFS: param: Inode_type uninitialized.");
1620                 return Err(SystemError::EROFS);
1621             }
1622         };
1623         // 检查文件夹是否存在
1624         dir.check_existence(name, Some(true), guard.fs.upgrade().unwrap())?;
1625 
1626         // 再从磁盘删除
1627         let r: Result<(), SystemError> =
1628             dir.remove(guard.fs.upgrade().unwrap().clone(), name, true);
1629         if r.is_ok() {
1630             return r;
1631         } else {
1632             let r = r.unwrap_err();
1633             if r == SystemError::ENOTEMPTY {
1634                 // 如果要删除的是目录,且不为空,则删除动作未发生,重新加入缓存
1635                 guard.children.insert(name.to_uppercase(), target.clone());
1636                 drop(target_guard);
1637             }
1638             return Err(r);
1639         }
1640     }
1641 
1642     fn get_entry_name(&self, ino: InodeId) -> Result<String, SystemError> {
1643         let guard: SpinLockGuard<FATInode> = self.0.lock();
1644         if guard.metadata.file_type != FileType::Dir {
1645             return Err(SystemError::ENOTDIR);
1646         }
1647         match ino.into() {
1648             0 => {
1649                 return Ok(String::from("."));
1650             }
1651             1 => {
1652                 return Ok(String::from(".."));
1653             }
1654             ino => {
1655                 // 暴力遍历所有的children,判断inode id是否相同
1656                 // TODO: 优化这里,这个地方性能很差!
1657                 let mut key: Vec<String> = guard
1658                     .children
1659                     .keys()
1660                     .filter(|k| {
1661                         guard
1662                             .children
1663                             .get(*k)
1664                             .unwrap()
1665                             .metadata()
1666                             .unwrap()
1667                             .inode_id
1668                             .into()
1669                             == ino
1670                     })
1671                     .cloned()
1672                     .collect();
1673 
1674                 match key.len() {
1675                     0=>{return Err(SystemError::ENOENT);}
1676                     1=>{return Ok(key.remove(0));}
1677                     _ => 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)
1678                 }
1679             }
1680         }
1681     }
1682 
1683     fn mknod(
1684         &self,
1685         filename: &str,
1686         mode: ModeType,
1687         _dev_t: crate::driver::base::device::DeviceNumber,
1688     ) -> Result<Arc<dyn IndexNode>, SystemError> {
1689         let mut inode = self.0.lock();
1690         if inode.metadata.file_type != FileType::Dir {
1691             return Err(SystemError::ENOTDIR);
1692         }
1693 
1694         // 判断需要创建的类型
1695         if unlikely(mode.contains(ModeType::S_IFREG)) {
1696             // 普通文件
1697             return Ok(self.create(filename, FileType::File, mode)?);
1698         }
1699 
1700         let nod = LockedFATInode::new(
1701             inode.fs.upgrade().unwrap(),
1702             inode.self_ref.clone(),
1703             FATDirEntry::File(FATFile::default()),
1704         );
1705 
1706         if mode.contains(ModeType::S_IFIFO) {
1707             nod.0.lock().metadata.file_type = FileType::Pipe;
1708             // 创建pipe文件
1709             let pipe_inode = LockedPipeInode::new();
1710             // 设置special_node
1711             nod.0.lock().special_node = Some(SpecialNodeData::Pipe(pipe_inode));
1712         } else if mode.contains(ModeType::S_IFBLK) {
1713             nod.0.lock().metadata.file_type = FileType::BlockDevice;
1714             unimplemented!()
1715         } else if mode.contains(ModeType::S_IFCHR) {
1716             nod.0.lock().metadata.file_type = FileType::CharDevice;
1717             unimplemented!()
1718         } else {
1719             return Err(SystemError::EINVAL);
1720         }
1721 
1722         inode
1723             .children
1724             .insert(String::from(filename).to_uppercase(), nod.clone());
1725         Ok(nod)
1726     }
1727 
1728     fn special_node(&self) -> Option<SpecialNodeData> {
1729         self.0.lock().special_node.clone()
1730     }
1731 }
1732 
1733 impl Default for FATFsInfo {
1734     fn default() -> Self {
1735         return FATFsInfo {
1736             lead_sig: FATFsInfo::LEAD_SIG,
1737             struc_sig: FATFsInfo::STRUC_SIG,
1738             free_count: 0xFFFFFFFF,
1739             next_free: RESERVED_CLUSTERS,
1740             trail_sig: FATFsInfo::TRAIL_SIG,
1741             dirty: false,
1742             offset: None,
1743         };
1744     }
1745 }
1746 
1747 impl Cluster {
1748     pub fn new(cluster: u64) -> Self {
1749         return Cluster {
1750             cluster_num: cluster,
1751             parent_cluster: 0,
1752         };
1753     }
1754 }
1755 
1756 /// @brief 用于迭代FAT表的内容的簇迭代器对象
1757 #[derive(Debug)]
1758 struct ClusterIter<'a> {
1759     /// 迭代器的next要返回的簇
1760     current_cluster: Option<Cluster>,
1761     /// 属于的文件系统
1762     fs: &'a FATFileSystem,
1763 }
1764 
1765 impl<'a> Iterator for ClusterIter<'a> {
1766     type Item = Cluster;
1767 
1768     fn next(&mut self) -> Option<Self::Item> {
1769         // 当前要返回的簇
1770         let ret: Option<Cluster> = self.current_cluster;
1771 
1772         // 获得下一个要返回簇
1773         let new: Option<Cluster> = match self.current_cluster {
1774             Some(c) => {
1775                 let entry: Option<FATEntry> = self.fs.get_fat_entry(c).ok();
1776                 match entry {
1777                     Some(FATEntry::Next(c)) => Some(c),
1778                     _ => None,
1779                 }
1780             }
1781             _ => None,
1782         };
1783 
1784         self.current_cluster = new;
1785         return ret;
1786     }
1787 }
1788