xref: /DragonOS/kernel/src/filesystem/vfs/mod.rs (revision 731bc2b32d7b37298883d7a15b6dca659b436ee4)
1 pub mod core;
2 pub mod fcntl;
3 pub mod file;
4 pub mod mount;
5 pub mod open;
6 pub mod syscall;
7 pub mod utils;
8 
9 use ::core::{any::Any, fmt::Debug, sync::atomic::AtomicUsize};
10 use alloc::{string::String, sync::Arc, vec::Vec};
11 use intertrait::CastFromSync;
12 use system_error::SystemError;
13 
14 use crate::{
15     driver::base::{
16         block::block_device::BlockDevice, char::CharDevice, device::device_number::DeviceNumber,
17     },
18     ipc::pipe::LockedPipeInode,
19     libs::{
20         casting::DowncastArc,
21         spinlock::{SpinLock, SpinLockGuard},
22     },
23     time::PosixTimeSpec,
24 };
25 
26 use self::{core::generate_inode_id, file::FileMode, syscall::ModeType, utils::DName};
27 pub use self::{core::ROOT_INODE, file::FilePrivateData, mount::MountFS};
28 
29 /// vfs容许的最大的路径名称长度
30 pub const MAX_PATHLEN: usize = 1024;
31 
32 // 定义inode号
33 int_like!(InodeId, AtomicInodeId, usize, AtomicUsize);
34 
35 /// 文件的类型
36 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
37 pub enum FileType {
38     /// 文件
39     File,
40     /// 文件夹
41     Dir,
42     /// 块设备
43     BlockDevice,
44     /// 字符设备
45     CharDevice,
46     /// 帧缓冲设备
47     FramebufferDevice,
48     /// kvm设备
49     KvmDevice,
50     /// 管道文件
51     Pipe,
52     /// 符号链接
53     SymLink,
54     /// 套接字
55     Socket,
56 }
57 
58 #[allow(dead_code)]
59 #[derive(Debug, Clone)]
60 pub enum SpecialNodeData {
61     /// 管道文件
62     Pipe(Arc<LockedPipeInode>),
63     /// 字符设备
64     CharDevice(Arc<dyn CharDevice>),
65     /// 块设备
66     BlockDevice(Arc<dyn BlockDevice>),
67 }
68 
69 /* these are defined by POSIX and also present in glibc's dirent.h */
70 /// 完整含义请见 http://www.gnu.org/software/libc/manual/html_node/Directory-Entries.html
71 #[allow(dead_code)]
72 pub const DT_UNKNOWN: u16 = 0;
73 /// 命名管道,或者FIFO
74 pub const DT_FIFO: u16 = 1;
75 // 字符设备
76 pub const DT_CHR: u16 = 2;
77 // 目录
78 pub const DT_DIR: u16 = 4;
79 // 块设备
80 pub const DT_BLK: u16 = 6;
81 // 常规文件
82 pub const DT_REG: u16 = 8;
83 // 符号链接
84 pub const DT_LNK: u16 = 10;
85 // 是一个socket
86 pub const DT_SOCK: u16 = 12;
87 // 这个是抄Linux的,还不知道含义
88 #[allow(dead_code)]
89 pub const DT_WHT: u16 = 14;
90 #[allow(dead_code)]
91 pub const DT_MAX: u16 = 16;
92 
93 /// vfs容许的最大的符号链接跳转次数
94 pub const VFS_MAX_FOLLOW_SYMLINK_TIMES: usize = 8;
95 
96 impl FileType {
97     pub fn get_file_type_num(&self) -> u16 {
98         return match self {
99             FileType::File => DT_REG,
100             FileType::Dir => DT_DIR,
101             FileType::BlockDevice => DT_BLK,
102             FileType::CharDevice => DT_CHR,
103             FileType::KvmDevice => DT_CHR,
104             FileType::Pipe => DT_FIFO,
105             FileType::SymLink => DT_LNK,
106             FileType::Socket => DT_SOCK,
107             FileType::FramebufferDevice => DT_CHR,
108         };
109     }
110 }
111 
112 bitflags! {
113     /// @brief inode的状态(由poll方法返回)
114     pub struct PollStatus: u8 {
115         const WRITE = 1u8 << 0;
116         const READ = 1u8 << 1;
117         const ERROR = 1u8 << 2;
118     }
119 }
120 
121 pub trait IndexNode: Any + Sync + Send + Debug + CastFromSync {
122     /// @brief 打开文件
123     ///
124     /// @return 成功:Ok()
125     ///         失败:Err(错误码)
126     fn open(
127         &self,
128         _data: SpinLockGuard<FilePrivateData>,
129         _mode: &FileMode,
130     ) -> Result<(), SystemError> {
131         // 若文件系统没有实现此方法,则返回“不支持”
132         return Err(SystemError::ENOSYS);
133     }
134 
135     /// @brief 关闭文件
136     ///
137     /// @return 成功:Ok()
138     ///         失败:Err(错误码)
139     fn close(&self, _data: SpinLockGuard<FilePrivateData>) -> Result<(), SystemError> {
140         // 若文件系统没有实现此方法,则返回“不支持”
141         return Err(SystemError::ENOSYS);
142     }
143 
144     /// @brief 在inode的指定偏移量开始,读取指定大小的数据
145     ///
146     /// @param offset 起始位置在Inode中的偏移量
147     /// @param len 要读取的字节数
148     /// @param buf 缓冲区. 请注意,必须满足@buf.len()>=@len
149     /// @param _data 各文件系统系统所需私有信息
150     ///
151     /// @return 成功:Ok(读取的字节数)
152     ///         失败:Err(Posix错误码)
153     fn read_at(
154         &self,
155         offset: usize,
156         len: usize,
157         buf: &mut [u8],
158         _data: SpinLockGuard<FilePrivateData>,
159     ) -> Result<usize, SystemError>;
160 
161     /// @brief 在inode的指定偏移量开始,写入指定大小的数据(从buf的第0byte开始写入)
162     ///
163     /// @param offset 起始位置在Inode中的偏移量
164     /// @param len 要写入的字节数
165     /// @param buf 缓冲区. 请注意,必须满足@buf.len()>=@len
166     /// @param _data 各文件系统系统所需私有信息
167     ///
168     /// @return 成功:Ok(写入的字节数)
169     ///         失败:Err(Posix错误码)
170     fn write_at(
171         &self,
172         offset: usize,
173         len: usize,
174         buf: &[u8],
175         _data: SpinLockGuard<FilePrivateData>,
176     ) -> Result<usize, SystemError>;
177 
178     /// @brief 获取当前inode的状态。
179     ///
180     /// @return PollStatus结构体
181     fn poll(&self, _private_data: &FilePrivateData) -> Result<usize, SystemError> {
182         // 若文件系统没有实现此方法,则返回“不支持”
183         return Err(SystemError::ENOSYS);
184     }
185 
186     /// @brief 获取inode的元数据
187     ///
188     /// @return 成功:Ok(inode的元数据)
189     ///         失败:Err(错误码)
190     fn metadata(&self) -> Result<Metadata, SystemError> {
191         // 若文件系统没有实现此方法,则返回“不支持”
192         return Err(SystemError::ENOSYS);
193     }
194 
195     /// @brief 设置inode的元数据
196     ///
197     /// @return 成功:Ok()
198     ///         失败:Err(错误码)
199     fn set_metadata(&self, _metadata: &Metadata) -> Result<(), SystemError> {
200         // 若文件系统没有实现此方法,则返回“不支持”
201         return Err(SystemError::ENOSYS);
202     }
203 
204     /// @brief 重新设置文件的大小
205     ///
206     /// 如果文件大小增加,则文件内容不变,但是文件的空洞部分会被填充为0
207     /// 如果文件大小减小,则文件内容会被截断
208     ///
209     /// @return 成功:Ok()
210     ///         失败:Err(错误码)
211     fn resize(&self, _len: usize) -> Result<(), SystemError> {
212         // 若文件系统没有实现此方法,则返回“不支持”
213         return Err(SystemError::ENOSYS);
214     }
215 
216     /// @brief 在当前目录下创建一个新的inode
217     ///
218     /// @param name 目录项的名字
219     /// @param file_type 文件类型
220     /// @param mode 权限
221     ///
222     /// @return 创建成功:返回Ok(新的inode的Arc指针)
223     /// @return 创建失败:返回Err(错误码)
224     fn create(
225         &self,
226         name: &str,
227         file_type: FileType,
228         mode: ModeType,
229     ) -> Result<Arc<dyn IndexNode>, SystemError> {
230         // 若文件系统没有实现此方法,则默认调用其create_with_data方法。如果仍未实现,则会得到一个Err(-ENOSYS)的返回值
231         return self.create_with_data(name, file_type, mode, 0);
232     }
233 
234     /// @brief 在当前目录下创建一个新的inode,并传入一个简单的data字段,方便进行初始化。
235     ///
236     /// @param name 目录项的名字
237     /// @param file_type 文件类型
238     /// @param mode 权限
239     /// @param data 用于初始化该inode的数据。(为0则表示忽略此字段)对于不同的文件系统来说,代表的含义可能不同。
240     ///
241     /// @return 创建成功:返回Ok(新的inode的Arc指针)
242     /// @return 创建失败:返回Err(错误码)
243     fn create_with_data(
244         &self,
245         _name: &str,
246         _file_type: FileType,
247         _mode: ModeType,
248         _data: usize,
249     ) -> Result<Arc<dyn IndexNode>, SystemError> {
250         // 若文件系统没有实现此方法,则返回“不支持”
251         return Err(SystemError::ENOSYS);
252     }
253 
254     /// @brief 在当前目录下,创建一个名为Name的硬链接,指向另一个IndexNode
255     ///
256     /// @param name 硬链接的名称
257     /// @param other 要被指向的IndexNode的Arc指针
258     ///
259     /// @return 成功:Ok()
260     ///         失败:Err(错误码)
261     fn link(&self, _name: &str, _other: &Arc<dyn IndexNode>) -> Result<(), SystemError> {
262         // 若文件系统没有实现此方法,则返回“不支持”
263         return Err(SystemError::ENOSYS);
264     }
265 
266     /// @brief 在当前目录下,删除一个名为Name的硬链接
267     ///
268     /// @param name 硬链接的名称
269     ///
270     /// @return 成功:Ok()
271     ///         失败:Err(错误码)
272     fn unlink(&self, _name: &str) -> Result<(), SystemError> {
273         // 若文件系统没有实现此方法,则返回“不支持”
274         return Err(SystemError::ENOSYS);
275     }
276 
277     /// @brief 删除文件夹
278     ///
279     /// @param name 文件夹名称
280     ///
281     /// @return 成功 Ok(())
282     /// @return 失败 Err(错误码)
283     fn rmdir(&self, _name: &str) -> Result<(), SystemError> {
284         return Err(SystemError::ENOSYS);
285     }
286 
287     /// 将指定的`old_name`子目录项移动到target目录下, 并予以`new_name`。
288     ///
289     /// # Behavior
290     /// 如果old_name所指向的inode与target的相同,那么则直接**执行重命名的操作**。
291     fn move_to(
292         &self,
293         _old_name: &str,
294         _target: &Arc<dyn IndexNode>,
295         _new_name: &str,
296     ) -> Result<(), SystemError> {
297         // 若文件系统没有实现此方法,则返回“不支持”
298         return Err(SystemError::ENOSYS);
299     }
300 
301     /// @brief 寻找一个名为Name的inode
302     ///
303     /// @param name 要寻找的inode的名称
304     ///
305     /// @return 成功:Ok()
306     ///         失败:Err(错误码)
307     fn find(&self, _name: &str) -> Result<Arc<dyn IndexNode>, SystemError> {
308         // 若文件系统没有实现此方法,则返回“不支持”
309         return Err(SystemError::ENOSYS);
310     }
311 
312     /// @brief 根据inode号,获取子目录项的名字
313     ///
314     /// @param ino inode号
315     ///
316     /// @return 成功:Ok()
317     ///         失败:Err(错误码)
318     fn get_entry_name(&self, _ino: InodeId) -> Result<String, SystemError> {
319         // 若文件系统没有实现此方法,则返回“不支持”
320         return Err(SystemError::ENOSYS);
321     }
322 
323     /// @brief 根据inode号,获取子目录项的名字和元数据
324     ///
325     /// @param ino inode号
326     ///
327     /// @return 成功:Ok(String, Metadata)
328     ///         失败:Err(错误码)
329     fn get_entry_name_and_metadata(&self, ino: InodeId) -> Result<(String, Metadata), SystemError> {
330         // 如果有条件,请在文件系统中使用高效的方式实现本接口,而不是依赖这个低效率的默认实现。
331         let name = self.get_entry_name(ino)?;
332         let entry = self.find(&name)?;
333         return Ok((name, entry.metadata()?));
334     }
335 
336     /// @brief io control接口
337     ///
338     /// @param cmd 命令
339     /// @param data 数据
340     ///
341     /// @return 成功:Ok()
342     ///         失败:Err(错误码)
343     fn ioctl(
344         &self,
345         _cmd: u32,
346         _data: usize,
347         _private_data: &FilePrivateData,
348     ) -> Result<usize, SystemError> {
349         // 若文件系统没有实现此方法,则返回“不支持”
350         return Err(SystemError::ENOSYS);
351     }
352 
353     /// @brief 获取inode所在的文件系统的指针
354     fn fs(&self) -> Arc<dyn FileSystem>;
355 
356     /// @brief 本函数用于实现动态转换。
357     /// 具体的文件系统在实现本函数时,最简单的方式就是:直接返回self
358     fn as_any_ref(&self) -> &dyn Any;
359 
360     /// @brief 列出当前inode下的所有目录项的名字
361     fn list(&self) -> Result<Vec<String>, SystemError>;
362 
363     /// # mount - 挂载文件系统
364     ///
365     /// 将给定的文件系统挂载到当前的文件系统节点上。
366     ///
367     /// 该函数是`MountFS`结构体的实例方法,用于将一个新的文件系统挂载到调用它的`MountFS`实例上。
368     ///
369     /// ## 参数
370     ///
371     /// - `fs`: `Arc<dyn FileSystem>` - 要挂载的文件系统的共享引用。
372     ///
373     /// ## 返回值
374     ///
375     /// - `Ok(Arc<MountFS>)`: 新的挂载文件系统的共享引用。
376     /// - `Err(SystemError)`: 挂载过程中出现的错误。
377     ///
378     /// ## 错误处理
379     ///
380     /// - 如果文件系统不是目录类型,则返回`SystemError::ENOTDIR`错误。
381     /// - 如果当前路径已经是挂载点,则返回`SystemError::EBUSY`错误。
382     ///
383     /// ## 副作用
384     ///
385     /// - 该函数会在`MountFS`实例上创建一个新的挂载点。
386     /// - 该函数会在全局的挂载列表中记录新的挂载关系。
387     fn mount(&self, _fs: Arc<dyn FileSystem>) -> Result<Arc<MountFS>, SystemError> {
388         return Err(SystemError::ENOSYS);
389     }
390 
391     /// # mount_from - 从给定的目录挂载已有挂载信息的文件系统
392     ///
393     /// 这个函数将一个已有挂载信息的文件系统从给定的目录挂载到当前目录。
394     ///
395     /// ## 参数
396     ///
397     /// - `from`: Arc<dyn IndexNode> - 要挂载的目录的引用。
398     ///
399     /// ## 返回值
400     ///
401     /// - Ok(Arc<MountFS>): 挂载的新文件系统的引用。
402     /// - Err(SystemError): 如果发生错误,返回系统错误。
403     ///
404     /// ## 错误处理
405     ///
406     /// - 如果给定的目录不是目录类型,返回`SystemError::ENOTDIR`。
407     /// - 如果当前目录已经是挂载点的根目录,返回`SystemError::EBUSY`。
408     ///
409     /// ## 副作用
410     ///
411     /// - 系统初始化用,其他情况不应调用此函数
412     fn mount_from(&self, _des: Arc<dyn IndexNode>) -> Result<Arc<MountFS>, SystemError> {
413         return Err(SystemError::ENOSYS);
414     }
415 
416     /// # umount - 卸载当前Inode下的文件系统
417     ///
418     /// 该函数是特定于`MountFS`实现的,其他文件系统不应实现此函数。
419     ///
420     /// ## 参数
421     ///
422     /// 无
423     ///
424     /// ## 返回值
425     ///
426     /// - Ok(Arc<MountFS>): 卸载的文件系统的引用。
427     /// - Err(SystemError): 如果发生错误,返回系统错误。
428     ///
429     /// ## 行为
430     ///
431     /// - 查找路径
432     /// - 定位到父文件系统的挂载点
433     /// - 将挂载点与子文件系统的根进行叠加
434     /// - 判断是否为子文件系统的根
435     /// - 调用父文件系统挂载点的`_umount`方法进行卸载
436     fn umount(&self) -> Result<Arc<MountFS>, SystemError> {
437         return Err(SystemError::ENOSYS);
438     }
439 
440     /// # absolute_path 获取目录项绝对路径
441     ///
442     /// ## 参数
443     ///
444     /// 无
445     ///
446     /// ## 返回值
447     ///
448     /// - Ok(String): 路径
449     /// - Err(SystemError): 文件系统不支持dname parent api
450     ///
451     /// ## Behavior
452     ///
453     /// 该函数只能被MountFS实现,其他文件系统不应实现这个函数
454     ///
455     /// # Performance
456     ///
457     /// 这是一个O(n)的路径查询,并且在未实现DName缓存的文件系统中,性能极差;
458     /// 即使实现了DName也尽量不要用。
459     fn absolute_path(&self) -> Result<String, SystemError> {
460         return Err(SystemError::ENOSYS);
461     }
462 
463     /// @brief 截断当前inode到指定的长度。如果当前文件长度小于len,则不操作。
464     ///
465     /// @param len 要被截断到的目标长度
466     fn truncate(&self, _len: usize) -> Result<(), SystemError> {
467         return Err(SystemError::ENOSYS);
468     }
469 
470     /// @brief 将当前inode的内容同步到具体设备上
471     fn sync(&self) -> Result<(), SystemError> {
472         return Ok(());
473     }
474 
475     /// ## 创建一个特殊文件节点
476     /// - _filename: 文件名
477     /// - _mode: 权限信息
478     fn mknod(
479         &self,
480         _filename: &str,
481         _mode: ModeType,
482         _dev_t: DeviceNumber,
483     ) -> Result<Arc<dyn IndexNode>, SystemError> {
484         return Err(SystemError::ENOSYS);
485     }
486 
487     /// # mkdir - 新建名称为`name`的目录项
488     ///
489     /// 当目录下已有名称为`name`的文件夹时,返回该目录项的引用;否则新建`name`文件夹,并返回该引用。
490     ///
491     /// 该函数会检查`name`目录是否已存在,如果存在但类型不为文件夹,则会返回`EEXIST`错误。
492     ///
493     /// # 参数
494     ///
495     /// - `name`: &str - 要新建的目录项的名称。
496     /// - `mode`: ModeType - 设置目录项的权限模式。
497     ///
498     /// # 返回值
499     ///
500     /// - `Ok(Arc<dyn IndexNode>)`: 成功时返回`name`目录项的共享引用。
501     /// - `Err(SystemError)`: 出错时返回错误信息。
502     fn mkdir(&self, name: &str, mode: ModeType) -> Result<Arc<dyn IndexNode>, SystemError> {
503         match self.find(name) {
504             Ok(inode) => {
505                 if inode.metadata()?.file_type == FileType::Dir {
506                     Ok(inode)
507                 } else {
508                     Err(SystemError::EEXIST)
509                 }
510             }
511             Err(SystemError::ENOENT) => self.create(name, FileType::Dir, mode),
512             Err(err) => Err(err),
513         }
514     }
515 
516     /// ## 返回特殊文件的inode
517     fn special_node(&self) -> Option<SpecialNodeData> {
518         None
519     }
520 
521     /// # dname - 返回目录名
522     ///
523     /// 此函数用于返回一个目录名。
524     ///
525     /// ## 参数
526     ///
527     /// 无
528     ///
529     /// ## 返回值
530     /// - Ok(DName): 成功时返回一个目录名。
531     /// - Err(SystemError): 如果系统不支持此操作,则返回一个系统错误。
532     fn dname(&self) -> Result<DName, SystemError> {
533         return Err(SystemError::ENOSYS);
534     }
535 
536     /// # parent - 返回父目录的引用
537     ///
538     /// 当该目录是当前文件系统的根目录时,返回自身的引用。
539     ///
540     /// ## 参数
541     ///
542     /// 无
543     ///
544     /// ## 返回值
545     ///
546     /// - Ok(Arc<dyn IndexNode>): A reference to the parent directory
547     /// - Err(SystemError): If there is an error in finding the parent directory
548     fn parent(&self) -> Result<Arc<dyn IndexNode>, SystemError> {
549         return self.find("..");
550     }
551 }
552 
553 impl DowncastArc for dyn IndexNode {
554     fn as_any_arc(self: Arc<Self>) -> Arc<dyn Any> {
555         self
556     }
557 }
558 
559 impl dyn IndexNode {
560     /// @brief 将当前Inode转换为一个具体的结构体(类型由T指定)
561     /// 如果类型正确,则返回Some,否则返回None
562     pub fn downcast_ref<T: IndexNode>(&self) -> Option<&T> {
563         return self.as_any_ref().downcast_ref::<T>();
564     }
565 
566     /// @brief 查找文件(不考虑符号链接)
567     ///
568     /// @param path 文件路径
569     ///
570     /// @return Ok(Arc<dyn IndexNode>) 要寻找的目录项的inode
571     /// @return Err(SystemError) 错误码
572     pub fn lookup(&self, path: &str) -> Result<Arc<dyn IndexNode>, SystemError> {
573         return self.lookup_follow_symlink(path, 0);
574     }
575 
576     /// @brief 查找文件(考虑符号链接)
577     ///
578     /// @param path 文件路径
579     /// @param max_follow_times 最大经过的符号链接的大小
580     ///
581     /// @return Ok(Arc<dyn IndexNode>) 要寻找的目录项的inode
582     /// @return Err(SystemError) 错误码
583     pub fn lookup_follow_symlink(
584         &self,
585         path: &str,
586         max_follow_times: usize,
587     ) -> Result<Arc<dyn IndexNode>, SystemError> {
588         if self.metadata()?.file_type != FileType::Dir {
589             return Err(SystemError::ENOTDIR);
590         }
591 
592         // 处理绝对路径
593         // result: 上一个被找到的inode
594         // rest_path: 还没有查找的路径
595         let (mut result, mut rest_path) = if let Some(rest) = path.strip_prefix('/') {
596             (ROOT_INODE().clone(), String::from(rest))
597         } else {
598             // 是相对路径
599             (self.find(".")?, String::from(path))
600         };
601 
602         // 逐级查找文件
603         while !rest_path.is_empty() {
604             // 当前这一级不是文件夹
605             if result.metadata()?.file_type != FileType::Dir {
606                 return Err(SystemError::ENOTDIR);
607             }
608 
609             let name;
610 
611             // 寻找“/”
612             match rest_path.find('/') {
613                 Some(pos) => {
614                     // 找到了,设置下一个要查找的名字
615                     name = String::from(&rest_path[0..pos]);
616                     // 剩余的路径字符串
617                     rest_path = String::from(&rest_path[pos + 1..]);
618                 }
619                 None => {
620                     name = rest_path;
621                     rest_path = String::new();
622                 }
623             }
624 
625             // 遇到连续多个"/"的情况
626             if name.is_empty() {
627                 continue;
628             }
629 
630             let inode = result.find(&name)?;
631 
632             // 处理符号链接的问题
633             if inode.metadata()?.file_type == FileType::SymLink && max_follow_times > 0 {
634                 let mut content = [0u8; 256];
635                 // 读取符号链接
636                 let len = inode.read_at(
637                     0,
638                     256,
639                     &mut content,
640                     SpinLock::new(FilePrivateData::Unused).lock(),
641                 )?;
642 
643                 // 将读到的数据转换为utf8字符串(先转为str,再转为String)
644                 let link_path = String::from(
645                     ::core::str::from_utf8(&content[..len]).map_err(|_| SystemError::ENOTDIR)?,
646                 );
647 
648                 let new_path = link_path + "/" + &rest_path;
649                 // 继续查找符号链接
650                 return result.lookup_follow_symlink(&new_path, max_follow_times - 1);
651             } else {
652                 result = inode;
653             }
654         }
655 
656         return Ok(result);
657     }
658 }
659 
660 /// IndexNode的元数据
661 ///
662 /// 对应Posix2008中的sys/stat.h中的定义 https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_stat.h.html
663 #[derive(Debug, PartialEq, Eq, Clone)]
664 pub struct Metadata {
665     /// 当前inode所在的文件系统的设备号
666     pub dev_id: usize,
667 
668     /// inode号
669     pub inode_id: InodeId,
670 
671     /// Inode的大小
672     /// 文件:文件大小(单位:字节)
673     /// 目录:目录项中的文件、文件夹数量
674     pub size: i64,
675 
676     /// Inode所在的文件系统中,每个块的大小
677     pub blk_size: usize,
678 
679     /// Inode所占的块的数目
680     pub blocks: usize,
681 
682     /// inode最后一次被访问的时间
683     pub atime: PosixTimeSpec,
684 
685     /// inode最后一次修改的时间
686     pub mtime: PosixTimeSpec,
687 
688     /// inode的创建时间
689     pub ctime: PosixTimeSpec,
690 
691     /// 文件类型
692     pub file_type: FileType,
693 
694     /// 权限
695     pub mode: ModeType,
696 
697     /// 硬链接的数量
698     pub nlinks: usize,
699 
700     /// User ID
701     pub uid: usize,
702 
703     /// Group ID
704     pub gid: usize,
705 
706     /// 文件指向的设备的id(对于设备文件系统来说)
707     pub raw_dev: DeviceNumber,
708 }
709 
710 impl Default for Metadata {
711     fn default() -> Self {
712         return Self {
713             dev_id: 0,
714             inode_id: InodeId::new(0),
715             size: 0,
716             blk_size: 0,
717             blocks: 0,
718             atime: PosixTimeSpec::default(),
719             mtime: PosixTimeSpec::default(),
720             ctime: PosixTimeSpec::default(),
721             file_type: FileType::File,
722             mode: ModeType::empty(),
723             nlinks: 1,
724             uid: 0,
725             gid: 0,
726             raw_dev: DeviceNumber::default(),
727         };
728     }
729 }
730 
731 #[derive(Debug, Clone)]
732 pub struct SuperBlock {
733     // type of filesystem
734     pub magic: Magic,
735     // optimal transfer block size
736     pub bsize: u64,
737     // total data blocks in filesystem
738     pub blocks: u64,
739     // free block in system
740     pub bfree: u64,
741     // 可供非特权用户使用的空闲块
742     pub bavail: u64,
743     // total inodes in filesystem
744     pub files: u64,
745     // free inodes in filesystem
746     pub ffree: u64,
747     // filesysytem id
748     pub fsid: u64,
749     // Max length of filename
750     pub namelen: u64,
751     // fragment size
752     pub frsize: u64,
753     // mount flags of filesystem
754     pub flags: u64,
755 }
756 
757 impl SuperBlock {
758     pub fn new(magic: Magic, bsize: u64, namelen: u64) -> Self {
759         Self {
760             magic,
761             bsize,
762             blocks: 0,
763             bfree: 0,
764             bavail: 0,
765             files: 0,
766             ffree: 0,
767             fsid: 0,
768             namelen,
769             frsize: 0,
770             flags: 0,
771         }
772     }
773 }
774 bitflags! {
775     pub struct Magic: u64 {
776         const DEVFS_MAGIC = 0x1373;
777         const FAT_MAGIC =  0xf2f52011;
778         const KER_MAGIC = 0x3153464b;
779         const PROC_MAGIC = 0x9fa0;
780         const RAMFS_MAGIC = 0x858458f6;
781         const MOUNT_MAGIC = 61267;
782     }
783 }
784 
785 /// @brief 所有文件系统都应该实现的trait
786 pub trait FileSystem: Any + Sync + Send + Debug {
787     /// @brief 获取当前文件系统的root inode的指针
788     fn root_inode(&self) -> Arc<dyn IndexNode>;
789 
790     /// @brief 获取当前文件系统的信息
791     fn info(&self) -> FsInfo;
792 
793     /// @brief 本函数用于实现动态转换。
794     /// 具体的文件系统在实现本函数时,最简单的方式就是:直接返回self
795     fn as_any_ref(&self) -> &dyn Any;
796 
797     fn name(&self) -> &str;
798 
799     fn super_block(&self) -> SuperBlock;
800 }
801 
802 impl DowncastArc for dyn FileSystem {
803     fn as_any_arc(self: Arc<Self>) -> Arc<dyn Any> {
804         self
805     }
806 }
807 
808 #[derive(Debug)]
809 pub struct FsInfo {
810     /// 文件系统所在的块设备的id
811     pub blk_dev_id: usize,
812     /// 文件名的最大长度
813     pub max_name_len: usize,
814 }
815 
816 /// @brief
817 #[repr(C)]
818 #[derive(Debug)]
819 pub struct Dirent {
820     d_ino: u64,    // 文件序列号
821     d_off: i64,    // dir偏移量
822     d_reclen: u16, // 目录下的记录数
823     d_type: u8,    // entry的类型
824     d_name: u8,    // 文件entry的名字(是一个零长数组), 本字段仅用于占位
825 }
826 
827 impl Metadata {
828     pub fn new(file_type: FileType, mode: ModeType) -> Self {
829         Metadata {
830             dev_id: 0,
831             inode_id: generate_inode_id(),
832             size: 0,
833             blk_size: 0,
834             blocks: 0,
835             atime: PosixTimeSpec::default(),
836             mtime: PosixTimeSpec::default(),
837             ctime: PosixTimeSpec::default(),
838             file_type,
839             mode,
840             nlinks: 1,
841             uid: 0,
842             gid: 0,
843             raw_dev: DeviceNumber::default(),
844         }
845     }
846 }
847 pub struct FileSystemMaker {
848     function: &'static FileSystemNewFunction,
849     name: &'static str,
850 }
851 
852 impl FileSystemMaker {
853     pub const fn new(
854         name: &'static str,
855         function: &'static FileSystemNewFunction,
856     ) -> FileSystemMaker {
857         FileSystemMaker { function, name }
858     }
859 
860     pub fn call(&self) -> Result<Arc<dyn FileSystem>, SystemError> {
861         (self.function)()
862     }
863 }
864 
865 pub type FileSystemNewFunction = fn() -> Result<Arc<dyn FileSystem>, SystemError>;
866 
867 #[macro_export]
868 macro_rules! define_filesystem_maker_slice {
869     ($name:ident) => {
870         #[::linkme::distributed_slice]
871         pub static $name: [FileSystemMaker] = [..];
872     };
873     () => {
874         compile_error!("define_filesystem_maker_slice! requires at least one argument: slice_name");
875     };
876 }
877 
878 /// 调用指定数组中的所有初始化器
879 #[macro_export]
880 macro_rules! producefs {
881     ($initializer_slice:ident,$filesystem:ident) => {
882         match $initializer_slice.iter().find(|&m| m.name == $filesystem) {
883             Some(maker) => maker.call(),
884             None => {
885                 kerror!("mismatch filesystem type : {}", $filesystem);
886                 Err(SystemError::EINVAL)
887             }
888         }
889     };
890 }
891 
892 define_filesystem_maker_slice!(FSMAKER);
893