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