xref: /DragonOS/kernel/src/filesystem/fat/fs.rs (revision 6d81180b3b7328466b976b69c5f7782aa66d8a89)
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     filesystem::vfs::{
13         core::generate_inode_id,
14         file::{FileMode, FilePrivateData},
15         FileSystem, FileType, IndexNode, InodeId, Metadata, PollStatus,
16     },
17     io::{device::LBA_SIZE, disk_info::Partition, SeekFrom},
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             .device()
1178             .write_at(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: u32,
1426     ) -> Result<Arc<dyn IndexNode>, SystemError> {
1427         // 由于FAT32不支持文件权限的功能,因此忽略mode参数
1428 
1429         let mut guard: SpinLockGuard<FATInode> = self.0.lock();
1430         let fs: &Arc<FATFileSystem> = &guard.fs.upgrade().unwrap();
1431 
1432         match &mut guard.inode_type {
1433             FATDirEntry::File(_) | FATDirEntry::VolId(_) => {
1434                 return Err(SystemError::ENOTDIR);
1435             }
1436             FATDirEntry::Dir(d) => match file_type {
1437                 FileType::File => {
1438                     d.create_file(name, fs)?;
1439                     return Ok(guard.find(name)?);
1440                 }
1441                 FileType::Dir => {
1442                     d.create_dir(name, fs)?;
1443                     return Ok(guard.find(name)?);
1444                 }
1445 
1446                 FileType::SymLink => return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP),
1447                 _ => return Err(SystemError::EINVAL),
1448             },
1449             FATDirEntry::UnInit => {
1450                 kerror!("FATFS: param: Inode_type uninitialized.");
1451                 return Err(SystemError::EROFS);
1452             }
1453         }
1454     }
1455 
1456     fn fs(&self) -> Arc<dyn FileSystem> {
1457         return self.0.lock().fs.upgrade().unwrap();
1458     }
1459 
1460     fn as_any_ref(&self) -> &dyn core::any::Any {
1461         return self;
1462     }
1463 
1464     fn metadata(&self) -> Result<Metadata, SystemError> {
1465         return Ok(self.0.lock().metadata.clone());
1466     }
1467     fn resize(&self, len: usize) -> Result<(), SystemError> {
1468         let mut guard: SpinLockGuard<FATInode> = self.0.lock();
1469         let fs: &Arc<FATFileSystem> = &guard.fs.upgrade().unwrap();
1470         let old_size = guard.metadata.size as usize;
1471 
1472         match &mut guard.inode_type {
1473             FATDirEntry::File(file) | FATDirEntry::VolId(file) => {
1474                 // 如果新的长度和旧的长度相同,那么就直接返回
1475                 if len == old_size {
1476                     return Ok(());
1477                 } else if len > old_size {
1478                     // 如果新的长度比旧的长度大,那么就在文件末尾添加空白
1479                     let mut buf: Vec<u8> = Vec::new();
1480                     let mut remain_size = len - old_size;
1481                     let buf_size = remain_size;
1482                     // let buf_size = core::cmp::min(remain_size, 512 * 1024);
1483                     buf.resize(buf_size, 0);
1484 
1485                     let mut offset = old_size;
1486                     while remain_size > 0 {
1487                         let write_size = core::cmp::min(remain_size, buf_size);
1488                         file.write(fs, &buf[0..write_size], offset as u64)?;
1489                         remain_size -= write_size;
1490                         offset += write_size;
1491                     }
1492                 } else {
1493                     file.truncate(fs, len as u64)?;
1494                 }
1495                 guard.update_metadata();
1496                 return Ok(());
1497             }
1498             FATDirEntry::Dir(_) => return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP),
1499             FATDirEntry::UnInit => {
1500                 kerror!("FATFS: param: Inode_type uninitialized.");
1501                 return Err(SystemError::EROFS);
1502             }
1503         }
1504     }
1505 
1506     fn list(&self) -> Result<Vec<String>, SystemError> {
1507         let mut guard: SpinLockGuard<FATInode> = self.0.lock();
1508         let fatent: &FATDirEntry = &guard.inode_type;
1509         match fatent {
1510             FATDirEntry::File(_) | FATDirEntry::VolId(_) => {
1511                 return Err(SystemError::ENOTDIR);
1512             }
1513             FATDirEntry::Dir(dir) => {
1514                 // 获取当前目录下的所有目录项
1515                 let mut ret: Vec<String> = Vec::new();
1516                 let dir_iter: FATDirIter = dir.to_iter(guard.fs.upgrade().unwrap());
1517                 for ent in dir_iter {
1518                     ret.push(ent.name());
1519 
1520                     // ====== 生成inode缓存,存入B树
1521                     let name: String = ent.name();
1522                     // kdebug!("name={name}");
1523 
1524                     if guard.children.contains_key(&name.to_uppercase()) == false
1525                         && name != "."
1526                         && name != ".."
1527                     {
1528                         // 创建新的inode
1529                         let entry_inode: Arc<LockedFATInode> = LockedFATInode::new(
1530                             guard.fs.upgrade().unwrap(),
1531                             guard.self_ref.clone(),
1532                             ent,
1533                         );
1534                         // 加入缓存区, 由于FAT文件系统的大小写不敏感问题,因此存入缓存区的key应当是全大写的
1535                         guard
1536                             .children
1537                             .insert(name.to_uppercase(), entry_inode.clone());
1538                     }
1539                 }
1540                 return Ok(ret);
1541             }
1542             FATDirEntry::UnInit => {
1543                 kerror!("FATFS: param: Inode_type uninitialized.");
1544                 return Err(SystemError::EROFS);
1545             }
1546         }
1547     }
1548 
1549     fn find(&self, name: &str) -> Result<Arc<dyn IndexNode>, SystemError> {
1550         let mut guard: SpinLockGuard<FATInode> = self.0.lock();
1551         let target = guard.find(name)?;
1552         return Ok(target);
1553     }
1554 
1555     fn open(&self, _data: &mut FilePrivateData, _mode: &FileMode) -> Result<(), SystemError> {
1556         return Ok(());
1557     }
1558 
1559     fn close(&self, _data: &mut FilePrivateData) -> Result<(), SystemError> {
1560         return Ok(());
1561     }
1562 
1563     fn unlink(&self, name: &str) -> Result<(), SystemError> {
1564         let mut guard: SpinLockGuard<FATInode> = self.0.lock();
1565         let target: Arc<LockedFATInode> = guard.find(name)?;
1566         // 对目标inode上锁,以防更改
1567         let target_guard: SpinLockGuard<FATInode> = target.0.lock();
1568         // 先从缓存删除
1569         guard.children.remove(&name.to_uppercase());
1570 
1571         let dir = match &guard.inode_type {
1572             FATDirEntry::File(_) | FATDirEntry::VolId(_) => {
1573                 return Err(SystemError::ENOTDIR);
1574             }
1575             FATDirEntry::Dir(d) => d,
1576             FATDirEntry::UnInit => {
1577                 kerror!("FATFS: param: Inode_type uninitialized.");
1578                 return Err(SystemError::EROFS);
1579             }
1580         };
1581         // 检查文件是否存在
1582         dir.check_existence(name, Some(false), guard.fs.upgrade().unwrap())?;
1583 
1584         // 再从磁盘删除
1585         let r = dir.remove(guard.fs.upgrade().unwrap().clone(), name, true);
1586         drop(target_guard);
1587         return r;
1588     }
1589 
1590     fn rmdir(&self, name: &str) -> Result<(), SystemError> {
1591         let mut guard: SpinLockGuard<FATInode> = self.0.lock();
1592         let target: Arc<LockedFATInode> = guard.find(name)?;
1593         // 对目标inode上锁,以防更改
1594         let target_guard: SpinLockGuard<FATInode> = target.0.lock();
1595         // 先从缓存删除
1596         guard.children.remove(&name.to_uppercase());
1597 
1598         let dir = match &guard.inode_type {
1599             FATDirEntry::File(_) | FATDirEntry::VolId(_) => {
1600                 return Err(SystemError::ENOTDIR);
1601             }
1602             FATDirEntry::Dir(d) => d,
1603             FATDirEntry::UnInit => {
1604                 kerror!("FATFS: param: Inode_type uninitialized.");
1605                 return Err(SystemError::EROFS);
1606             }
1607         };
1608         // 检查文件夹是否存在
1609         dir.check_existence(name, Some(true), guard.fs.upgrade().unwrap())?;
1610 
1611         // 再从磁盘删除
1612         let r: Result<(), SystemError> =
1613             dir.remove(guard.fs.upgrade().unwrap().clone(), name, true);
1614         if r.is_ok() {
1615             return r;
1616         } else {
1617             let r = r.unwrap_err();
1618             if r == SystemError::ENOTEMPTY {
1619                 // 如果要删除的是目录,且不为空,则删除动作未发生,重新加入缓存
1620                 guard.children.insert(name.to_uppercase(), target.clone());
1621                 drop(target_guard);
1622             }
1623             return Err(r);
1624         }
1625     }
1626 
1627     fn get_entry_name(&self, ino: InodeId) -> Result<String, SystemError> {
1628         let guard: SpinLockGuard<FATInode> = self.0.lock();
1629         if guard.metadata.file_type != FileType::Dir {
1630             return Err(SystemError::ENOTDIR);
1631         }
1632         match ino {
1633             0 => {
1634                 return Ok(String::from("."));
1635             }
1636             1 => {
1637                 return Ok(String::from(".."));
1638             }
1639             ino => {
1640                 // 暴力遍历所有的children,判断inode id是否相同
1641                 // TODO: 优化这里,这个地方性能很差!
1642                 let mut key: Vec<String> = guard
1643                     .children
1644                     .keys()
1645                     .filter(|k| guard.children.get(*k).unwrap().metadata().unwrap().inode_id == ino)
1646                     .cloned()
1647                     .collect();
1648 
1649                 match key.len() {
1650                     0=>{return Err(SystemError::ENOENT);}
1651                     1=>{return Ok(key.remove(0));}
1652                     _ => 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)
1653                 }
1654             }
1655         }
1656     }
1657 }
1658 
1659 impl Default for FATFsInfo {
1660     fn default() -> Self {
1661         return FATFsInfo {
1662             lead_sig: FATFsInfo::LEAD_SIG,
1663             struc_sig: FATFsInfo::STRUC_SIG,
1664             free_count: 0xFFFFFFFF,
1665             next_free: RESERVED_CLUSTERS,
1666             trail_sig: FATFsInfo::TRAIL_SIG,
1667             dirty: false,
1668             offset: None,
1669         };
1670     }
1671 }
1672 
1673 impl Cluster {
1674     pub fn new(cluster: u64) -> Self {
1675         return Cluster {
1676             cluster_num: cluster,
1677             parent_cluster: 0,
1678         };
1679     }
1680 }
1681 
1682 /// @brief 用于迭代FAT表的内容的簇迭代器对象
1683 #[derive(Debug)]
1684 struct ClusterIter<'a> {
1685     /// 迭代器的next要返回的簇
1686     current_cluster: Option<Cluster>,
1687     /// 属于的文件系统
1688     fs: &'a FATFileSystem,
1689 }
1690 
1691 impl<'a> Iterator for ClusterIter<'a> {
1692     type Item = Cluster;
1693 
1694     fn next(&mut self) -> Option<Self::Item> {
1695         // 当前要返回的簇
1696         let ret: Option<Cluster> = self.current_cluster;
1697 
1698         // 获得下一个要返回簇
1699         let new: Option<Cluster> = match self.current_cluster {
1700             Some(c) => {
1701                 let entry: Option<FATEntry> = self.fs.get_fat_entry(c).ok();
1702                 match entry {
1703                     Some(FATEntry::Next(c)) => Some(c),
1704                     _ => None,
1705                 }
1706             }
1707             _ => None,
1708         };
1709 
1710         self.current_cluster = new;
1711         return ret;
1712     }
1713 }
1714