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