xref: /DragonOS/kernel/src/filesystem/vfs/mod.rs (revision 9365e8017b39582eca620ba93c64f1b3c87c73d4)
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 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};
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::EOPNOTSUPP_OR_ENOTSUP);
133     }
134 
135     /// @brief 关闭文件
136     ///
137     /// @return 成功:Ok()
138     ///         失败:Err(错误码)
139     fn close(&self, _data: SpinLockGuard<FilePrivateData>) -> Result<(), SystemError> {
140         // 若文件系统没有实现此方法,则返回“不支持”
141         return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
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::EOPNOTSUPP_OR_ENOTSUP);
184     }
185 
186     /// @brief 获取inode的元数据
187     ///
188     /// @return 成功:Ok(inode的元数据)
189     ///         失败:Err(错误码)
190     fn metadata(&self) -> Result<Metadata, SystemError> {
191         // 若文件系统没有实现此方法,则返回“不支持”
192         return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
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::EOPNOTSUPP_OR_ENOTSUP);
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::EOPNOTSUPP_OR_ENOTSUP);
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(-EOPNOTSUPP_OR_ENOTSUP)的返回值
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::EOPNOTSUPP_OR_ENOTSUP);
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::EOPNOTSUPP_OR_ENOTSUP);
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::EOPNOTSUPP_OR_ENOTSUP);
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::EOPNOTSUPP_OR_ENOTSUP);
285     }
286 
287     /// @brief 将指定名称的子目录项的文件内容,移动到target这个目录下。如果_old_name所指向的inode与_target的相同,那么则直接执行重命名的操作。
288     ///
289     /// @param old_name 旧的名字
290     ///
291     /// @param target 移动到指定的inode
292     ///
293     /// @param new_name 新的文件名
294     ///
295     /// @return 成功: Ok()
296     ///         失败: Err(错误码)
297     fn move_to(
298         &self,
299         _old_name: &str,
300         _target: &Arc<dyn IndexNode>,
301         _new_name: &str,
302     ) -> Result<(), SystemError> {
303         // 若文件系统没有实现此方法,则返回“不支持”
304         return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
305     }
306 
307     /// # 修改文件名
308     ///
309     ///
310     /// ## 参数
311     ///
312     /// - _old_name: 源文件路径
313     /// - _new_name: 目标文件路径
314     ///
315     /// ## 返回值
316     /// - Ok(返回值类型): 返回值的说明
317     /// - Err(错误值类型): 错误的说明
318     ///
319     fn rename(&self, _old_name: &str, _new_name: &str) -> Result<(), SystemError> {
320         // 若文件系统没有实现此方法,则返回“不支持”
321         return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
322     }
323 
324     /// @brief 寻找一个名为Name的inode
325     ///
326     /// @param name 要寻找的inode的名称
327     ///
328     /// @return 成功:Ok()
329     ///         失败:Err(错误码)
330     fn find(&self, _name: &str) -> Result<Arc<dyn IndexNode>, SystemError> {
331         // 若文件系统没有实现此方法,则返回“不支持”
332         return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
333     }
334 
335     /// @brief 根据inode号,获取子目录项的名字
336     ///
337     /// @param ino inode号
338     ///
339     /// @return 成功:Ok()
340     ///         失败:Err(错误码)
341     fn get_entry_name(&self, _ino: InodeId) -> Result<String, SystemError> {
342         // 若文件系统没有实现此方法,则返回“不支持”
343         return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
344     }
345 
346     /// @brief 根据inode号,获取子目录项的名字和元数据
347     ///
348     /// @param ino inode号
349     ///
350     /// @return 成功:Ok(String, Metadata)
351     ///         失败:Err(错误码)
352     fn get_entry_name_and_metadata(&self, ino: InodeId) -> Result<(String, Metadata), SystemError> {
353         // 如果有条件,请在文件系统中使用高效的方式实现本接口,而不是依赖这个低效率的默认实现。
354         let name = self.get_entry_name(ino)?;
355         let entry = self.find(&name)?;
356         return Ok((name, entry.metadata()?));
357     }
358 
359     /// @brief io control接口
360     ///
361     /// @param cmd 命令
362     /// @param data 数据
363     ///
364     /// @return 成功:Ok()
365     ///         失败:Err(错误码)
366     fn ioctl(
367         &self,
368         _cmd: u32,
369         _data: usize,
370         _private_data: &FilePrivateData,
371     ) -> Result<usize, SystemError> {
372         // 若文件系统没有实现此方法,则返回“不支持”
373         return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
374     }
375 
376     /// @brief 获取inode所在的文件系统的指针
377     fn fs(&self) -> Arc<dyn FileSystem>;
378 
379     /// @brief 本函数用于实现动态转换。
380     /// 具体的文件系统在实现本函数时,最简单的方式就是:直接返回self
381     fn as_any_ref(&self) -> &dyn Any;
382 
383     /// @brief 列出当前inode下的所有目录项的名字
384     fn list(&self) -> Result<Vec<String>, SystemError>;
385 
386     /// @brief 在当前Inode下,挂载一个新的文件系统
387     /// 请注意!该函数只能被MountFS实现,其他文件系统不应实现这个函数
388     fn mount(&self, _fs: Arc<dyn FileSystem>) -> Result<Arc<MountFS>, SystemError> {
389         return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
390     }
391 
392     /// @brief 截断当前inode到指定的长度。如果当前文件长度小于len,则不操作。
393     ///
394     /// @param len 要被截断到的目标长度
395     fn truncate(&self, _len: usize) -> Result<(), SystemError> {
396         return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
397     }
398 
399     /// @brief 将当前inode的内容同步到具体设备上
400     fn sync(&self) -> Result<(), SystemError> {
401         return Ok(());
402     }
403 
404     /// ## 创建一个特殊文件节点
405     /// - _filename: 文件名
406     /// - _mode: 权限信息
407     fn mknod(
408         &self,
409         _filename: &str,
410         _mode: ModeType,
411         _dev_t: DeviceNumber,
412     ) -> Result<Arc<dyn IndexNode>, SystemError> {
413         return Err(SystemError::EOPNOTSUPP_OR_ENOTSUP);
414     }
415 
416     /// ## 返回特殊文件的inode
417     fn special_node(&self) -> Option<SpecialNodeData> {
418         None
419     }
420 }
421 
422 impl DowncastArc for dyn IndexNode {
423     fn as_any_arc(self: Arc<Self>) -> Arc<dyn Any> {
424         self
425     }
426 }
427 
428 impl dyn IndexNode {
429     /// @brief 将当前Inode转换为一个具体的结构体(类型由T指定)
430     /// 如果类型正确,则返回Some,否则返回None
431     pub fn downcast_ref<T: IndexNode>(&self) -> Option<&T> {
432         return self.as_any_ref().downcast_ref::<T>();
433     }
434 
435     /// @brief 查找文件(不考虑符号链接)
436     ///
437     /// @param path 文件路径
438     ///
439     /// @return Ok(Arc<dyn IndexNode>) 要寻找的目录项的inode
440     /// @return Err(SystemError) 错误码
441     pub fn lookup(&self, path: &str) -> Result<Arc<dyn IndexNode>, SystemError> {
442         return self.lookup_follow_symlink(path, 0);
443     }
444 
445     /// @brief 查找文件(考虑符号链接)
446     ///
447     /// @param path 文件路径
448     /// @param max_follow_times 最大经过的符号链接的大小
449     ///
450     /// @return Ok(Arc<dyn IndexNode>) 要寻找的目录项的inode
451     /// @return Err(SystemError) 错误码
452     pub fn lookup_follow_symlink(
453         &self,
454         path: &str,
455         max_follow_times: usize,
456     ) -> Result<Arc<dyn IndexNode>, SystemError> {
457         if self.metadata()?.file_type != FileType::Dir {
458             return Err(SystemError::ENOTDIR);
459         }
460 
461         // 处理绝对路径
462         // result: 上一个被找到的inode
463         // rest_path: 还没有查找的路径
464         let (mut result, mut rest_path) = if let Some(rest) = path.strip_prefix('/') {
465             (ROOT_INODE().clone(), String::from(rest))
466         } else {
467             // 是相对路径
468             (self.find(".")?, String::from(path))
469         };
470 
471         // 逐级查找文件
472         while !rest_path.is_empty() {
473             // 当前这一级不是文件夹
474             if result.metadata()?.file_type != FileType::Dir {
475                 return Err(SystemError::ENOTDIR);
476             }
477 
478             let name;
479 
480             // 寻找“/”
481             match rest_path.find('/') {
482                 Some(pos) => {
483                     // 找到了,设置下一个要查找的名字
484                     name = String::from(&rest_path[0..pos]);
485                     // 剩余的路径字符串
486                     rest_path = String::from(&rest_path[pos + 1..]);
487                 }
488                 None => {
489                     name = rest_path;
490                     rest_path = String::new();
491                 }
492             }
493 
494             // 遇到连续多个"/"的情况
495             if name.is_empty() {
496                 continue;
497             }
498 
499             let inode = result.find(&name)?;
500 
501             // 处理符号链接的问题
502             if inode.metadata()?.file_type == FileType::SymLink && max_follow_times > 0 {
503                 let mut content = [0u8; 256];
504                 // 读取符号链接
505                 let len = inode.read_at(
506                     0,
507                     256,
508                     &mut content,
509                     SpinLock::new(FilePrivateData::Unused).lock(),
510                 )?;
511 
512                 // 将读到的数据转换为utf8字符串(先转为str,再转为String)
513                 let link_path = String::from(
514                     ::core::str::from_utf8(&content[..len]).map_err(|_| SystemError::ENOTDIR)?,
515                 );
516 
517                 let new_path = link_path + "/" + &rest_path;
518                 // 继续查找符号链接
519                 return result.lookup_follow_symlink(&new_path, max_follow_times - 1);
520             } else {
521                 result = inode;
522             }
523         }
524 
525         return Ok(result);
526     }
527 }
528 
529 /// IndexNode的元数据
530 ///
531 /// 对应Posix2008中的sys/stat.h中的定义 https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_stat.h.html
532 #[derive(Debug, PartialEq, Eq, Clone)]
533 pub struct Metadata {
534     /// 当前inode所在的文件系统的设备号
535     pub dev_id: usize,
536 
537     /// inode号
538     pub inode_id: InodeId,
539 
540     /// Inode的大小
541     /// 文件:文件大小(单位:字节)
542     /// 目录:目录项中的文件、文件夹数量
543     pub size: i64,
544 
545     /// Inode所在的文件系统中,每个块的大小
546     pub blk_size: usize,
547 
548     /// Inode所占的块的数目
549     pub blocks: usize,
550 
551     /// inode最后一次被访问的时间
552     pub atime: PosixTimeSpec,
553 
554     /// inode最后一次修改的时间
555     pub mtime: PosixTimeSpec,
556 
557     /// inode的创建时间
558     pub ctime: PosixTimeSpec,
559 
560     /// 文件类型
561     pub file_type: FileType,
562 
563     /// 权限
564     pub mode: ModeType,
565 
566     /// 硬链接的数量
567     pub nlinks: usize,
568 
569     /// User ID
570     pub uid: usize,
571 
572     /// Group ID
573     pub gid: usize,
574 
575     /// 文件指向的设备的id(对于设备文件系统来说)
576     pub raw_dev: DeviceNumber,
577 }
578 
579 impl Default for Metadata {
580     fn default() -> Self {
581         return Self {
582             dev_id: 0,
583             inode_id: InodeId::new(0),
584             size: 0,
585             blk_size: 0,
586             blocks: 0,
587             atime: PosixTimeSpec::default(),
588             mtime: PosixTimeSpec::default(),
589             ctime: PosixTimeSpec::default(),
590             file_type: FileType::File,
591             mode: ModeType::empty(),
592             nlinks: 1,
593             uid: 0,
594             gid: 0,
595             raw_dev: DeviceNumber::default(),
596         };
597     }
598 }
599 
600 #[derive(Debug, Clone)]
601 pub struct SuperBlock {
602     // type of filesystem
603     pub magic: Magic,
604     // optimal transfer block size
605     pub bsize: u64,
606     // total data blocks in filesystem
607     pub blocks: u64,
608     // free block in system
609     pub bfree: u64,
610     // 可供非特权用户使用的空闲块
611     pub bavail: u64,
612     // total inodes in filesystem
613     pub files: u64,
614     // free inodes in filesystem
615     pub ffree: u64,
616     // filesysytem id
617     pub fsid: u64,
618     // Max length of filename
619     pub namelen: u64,
620     // fragment size
621     pub frsize: u64,
622     // mount flags of filesystem
623     pub flags: u64,
624 }
625 
626 impl SuperBlock {
627     pub fn new(magic: Magic, bsize: u64, namelen: u64) -> Self {
628         Self {
629             magic,
630             bsize,
631             blocks: 0,
632             bfree: 0,
633             bavail: 0,
634             files: 0,
635             ffree: 0,
636             fsid: 0,
637             namelen,
638             frsize: 0,
639             flags: 0,
640         }
641     }
642 }
643 bitflags! {
644     pub struct Magic: u64 {
645         const DEVFS_MAGIC = 0x1373;
646         const FAT_MAGIC =  0xf2f52011;
647         const KER_MAGIC = 0x3153464b;
648         const PROC_MAGIC = 0x9fa0;
649         const RAMFS_MAGIC = 0x858458f6;
650         const MOUNT_MAGIC = 61267;
651     }
652 }
653 
654 /// @brief 所有文件系统都应该实现的trait
655 pub trait FileSystem: Any + Sync + Send + Debug {
656     /// @brief 获取当前文件系统的root inode的指针
657     fn root_inode(&self) -> Arc<dyn IndexNode>;
658 
659     /// @brief 获取当前文件系统的信息
660     fn info(&self) -> FsInfo;
661 
662     /// @brief 本函数用于实现动态转换。
663     /// 具体的文件系统在实现本函数时,最简单的方式就是:直接返回self
664     fn as_any_ref(&self) -> &dyn Any;
665 
666     fn name(&self) -> &str;
667 
668     fn super_block(&self) -> SuperBlock;
669 }
670 
671 impl DowncastArc for dyn FileSystem {
672     fn as_any_arc(self: Arc<Self>) -> Arc<dyn Any> {
673         self
674     }
675 }
676 
677 #[derive(Debug)]
678 pub struct FsInfo {
679     /// 文件系统所在的块设备的id
680     pub blk_dev_id: usize,
681     /// 文件名的最大长度
682     pub max_name_len: usize,
683 }
684 
685 /// @brief
686 #[repr(C)]
687 #[derive(Debug)]
688 pub struct Dirent {
689     d_ino: u64,    // 文件序列号
690     d_off: i64,    // dir偏移量
691     d_reclen: u16, // 目录下的记录数
692     d_type: u8,    // entry的类型
693     d_name: u8,    // 文件entry的名字(是一个零长数组), 本字段仅用于占位
694 }
695 
696 impl Metadata {
697     pub fn new(file_type: FileType, mode: ModeType) -> Self {
698         Metadata {
699             dev_id: 0,
700             inode_id: generate_inode_id(),
701             size: 0,
702             blk_size: 0,
703             blocks: 0,
704             atime: PosixTimeSpec::default(),
705             mtime: PosixTimeSpec::default(),
706             ctime: PosixTimeSpec::default(),
707             file_type,
708             mode,
709             nlinks: 1,
710             uid: 0,
711             gid: 0,
712             raw_dev: DeviceNumber::default(),
713         }
714     }
715 }
716 pub struct FileSystemMaker {
717     function: &'static FileSystemNewFunction,
718     name: &'static str,
719 }
720 
721 impl FileSystemMaker {
722     pub const fn new(
723         name: &'static str,
724         function: &'static FileSystemNewFunction,
725     ) -> FileSystemMaker {
726         FileSystemMaker { function, name }
727     }
728 
729     pub fn call(&self) -> Result<Arc<dyn FileSystem>, SystemError> {
730         (self.function)()
731     }
732 }
733 
734 pub type FileSystemNewFunction = fn() -> Result<Arc<dyn FileSystem>, SystemError>;
735 
736 #[macro_export]
737 macro_rules! define_filesystem_maker_slice {
738     ($name:ident) => {
739         #[::linkme::distributed_slice]
740         pub static $name: [FileSystemMaker] = [..];
741     };
742     () => {
743         compile_error!("define_filesystem_maker_slice! requires at least one argument: slice_name");
744     };
745 }
746 
747 /// 调用指定数组中的所有初始化器
748 #[macro_export]
749 macro_rules! producefs {
750     ($initializer_slice:ident,$filesystem:ident) => {
751         match $initializer_slice.iter().find(|&m| m.name == $filesystem) {
752             Some(maker) => maker.call(),
753             None => {
754                 kerror!("mismatch filesystem type : {}", $filesystem);
755                 Err(SystemError::EINVAL)
756             }
757         }
758     };
759 }
760 
761 define_filesystem_maker_slice!(FSMAKER);
762