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