xref: /DragonOS/kernel/src/filesystem/vfs/mod.rs (revision 38458c72672b8f53ebe43c4300e3bcd504cb5abc)
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     fn kernel_ioctl(
354         &self,
355         _arg: Arc<dyn crate::net::event_poll::KernelIoctlData>,
356         _data: &FilePrivateData,
357     ) -> Result<usize, SystemError> {
358         return Err(SystemError::ENOSYS);
359     }
360 
361     /// @brief 获取inode所在的文件系统的指针
362     fn fs(&self) -> Arc<dyn FileSystem>;
363 
364     /// @brief 本函数用于实现动态转换。
365     /// 具体的文件系统在实现本函数时,最简单的方式就是:直接返回self
366     fn as_any_ref(&self) -> &dyn Any;
367 
368     /// @brief 列出当前inode下的所有目录项的名字
369     fn list(&self) -> Result<Vec<String>, SystemError>;
370 
371     /// # mount - 挂载文件系统
372     ///
373     /// 将给定的文件系统挂载到当前的文件系统节点上。
374     ///
375     /// 该函数是`MountFS`结构体的实例方法,用于将一个新的文件系统挂载到调用它的`MountFS`实例上。
376     ///
377     /// ## 参数
378     ///
379     /// - `fs`: `Arc<dyn FileSystem>` - 要挂载的文件系统的共享引用。
380     ///
381     /// ## 返回值
382     ///
383     /// - `Ok(Arc<MountFS>)`: 新的挂载文件系统的共享引用。
384     /// - `Err(SystemError)`: 挂载过程中出现的错误。
385     ///
386     /// ## 错误处理
387     ///
388     /// - 如果文件系统不是目录类型,则返回`SystemError::ENOTDIR`错误。
389     /// - 如果当前路径已经是挂载点,则返回`SystemError::EBUSY`错误。
390     ///
391     /// ## 副作用
392     ///
393     /// - 该函数会在`MountFS`实例上创建一个新的挂载点。
394     /// - 该函数会在全局的挂载列表中记录新的挂载关系。
395     fn mount(&self, _fs: Arc<dyn FileSystem>) -> Result<Arc<MountFS>, SystemError> {
396         return Err(SystemError::ENOSYS);
397     }
398 
399     /// # mount_from - 从给定的目录挂载已有挂载信息的文件系统
400     ///
401     /// 这个函数将一个已有挂载信息的文件系统从给定的目录挂载到当前目录。
402     ///
403     /// ## 参数
404     ///
405     /// - `from`: Arc<dyn IndexNode> - 要挂载的目录的引用。
406     ///
407     /// ## 返回值
408     ///
409     /// - Ok(Arc<MountFS>): 挂载的新文件系统的引用。
410     /// - Err(SystemError): 如果发生错误,返回系统错误。
411     ///
412     /// ## 错误处理
413     ///
414     /// - 如果给定的目录不是目录类型,返回`SystemError::ENOTDIR`。
415     /// - 如果当前目录已经是挂载点的根目录,返回`SystemError::EBUSY`。
416     ///
417     /// ## 副作用
418     ///
419     /// - 系统初始化用,其他情况不应调用此函数
420     fn mount_from(&self, _des: Arc<dyn IndexNode>) -> Result<Arc<MountFS>, SystemError> {
421         return Err(SystemError::ENOSYS);
422     }
423 
424     /// # umount - 卸载当前Inode下的文件系统
425     ///
426     /// 该函数是特定于`MountFS`实现的,其他文件系统不应实现此函数。
427     ///
428     /// ## 参数
429     ///
430     /// 无
431     ///
432     /// ## 返回值
433     ///
434     /// - Ok(Arc<MountFS>): 卸载的文件系统的引用。
435     /// - Err(SystemError): 如果发生错误,返回系统错误。
436     ///
437     /// ## 行为
438     ///
439     /// - 查找路径
440     /// - 定位到父文件系统的挂载点
441     /// - 将挂载点与子文件系统的根进行叠加
442     /// - 判断是否为子文件系统的根
443     /// - 调用父文件系统挂载点的`_umount`方法进行卸载
444     fn umount(&self) -> Result<Arc<MountFS>, SystemError> {
445         return Err(SystemError::ENOSYS);
446     }
447 
448     /// # absolute_path 获取目录项绝对路径
449     ///
450     /// ## 参数
451     ///
452     /// 无
453     ///
454     /// ## 返回值
455     ///
456     /// - Ok(String): 路径
457     /// - Err(SystemError): 文件系统不支持dname parent api
458     ///
459     /// ## Behavior
460     ///
461     /// 该函数只能被MountFS实现,其他文件系统不应实现这个函数
462     ///
463     /// # Performance
464     ///
465     /// 这是一个O(n)的路径查询,并且在未实现DName缓存的文件系统中,性能极差;
466     /// 即使实现了DName也尽量不要用。
467     fn absolute_path(&self) -> Result<String, SystemError> {
468         return Err(SystemError::ENOSYS);
469     }
470 
471     /// @brief 截断当前inode到指定的长度。如果当前文件长度小于len,则不操作。
472     ///
473     /// @param len 要被截断到的目标长度
474     fn truncate(&self, _len: usize) -> Result<(), SystemError> {
475         return Err(SystemError::ENOSYS);
476     }
477 
478     /// @brief 将当前inode的内容同步到具体设备上
479     fn sync(&self) -> Result<(), SystemError> {
480         return Ok(());
481     }
482 
483     /// ## 创建一个特殊文件节点
484     /// - _filename: 文件名
485     /// - _mode: 权限信息
486     fn mknod(
487         &self,
488         _filename: &str,
489         _mode: ModeType,
490         _dev_t: DeviceNumber,
491     ) -> Result<Arc<dyn IndexNode>, SystemError> {
492         return Err(SystemError::ENOSYS);
493     }
494 
495     /// # mkdir - 新建名称为`name`的目录项
496     ///
497     /// 当目录下已有名称为`name`的文件夹时,返回该目录项的引用;否则新建`name`文件夹,并返回该引用。
498     ///
499     /// 该函数会检查`name`目录是否已存在,如果存在但类型不为文件夹,则会返回`EEXIST`错误。
500     ///
501     /// # 参数
502     ///
503     /// - `name`: &str - 要新建的目录项的名称。
504     /// - `mode`: ModeType - 设置目录项的权限模式。
505     ///
506     /// # 返回值
507     ///
508     /// - `Ok(Arc<dyn IndexNode>)`: 成功时返回`name`目录项的共享引用。
509     /// - `Err(SystemError)`: 出错时返回错误信息。
510     fn mkdir(&self, name: &str, mode: ModeType) -> Result<Arc<dyn IndexNode>, SystemError> {
511         match self.find(name) {
512             Ok(inode) => {
513                 if inode.metadata()?.file_type == FileType::Dir {
514                     Ok(inode)
515                 } else {
516                     Err(SystemError::EEXIST)
517                 }
518             }
519             Err(SystemError::ENOENT) => self.create(name, FileType::Dir, mode),
520             Err(err) => Err(err),
521         }
522     }
523 
524     /// ## 返回特殊文件的inode
525     fn special_node(&self) -> Option<SpecialNodeData> {
526         None
527     }
528 
529     /// # dname - 返回目录名
530     ///
531     /// 此函数用于返回一个目录名。
532     ///
533     /// ## 参数
534     ///
535     /// 无
536     ///
537     /// ## 返回值
538     /// - Ok(DName): 成功时返回一个目录名。
539     /// - Err(SystemError): 如果系统不支持此操作,则返回一个系统错误。
540     fn dname(&self) -> Result<DName, SystemError> {
541         return Err(SystemError::ENOSYS);
542     }
543 
544     /// # parent - 返回父目录的引用
545     ///
546     /// 当该目录是当前文件系统的根目录时,返回自身的引用。
547     ///
548     /// ## 参数
549     ///
550     /// 无
551     ///
552     /// ## 返回值
553     ///
554     /// - Ok(Arc<dyn IndexNode>): A reference to the parent directory
555     /// - Err(SystemError): If there is an error in finding the parent directory
556     fn parent(&self) -> Result<Arc<dyn IndexNode>, SystemError> {
557         return self.find("..");
558     }
559 }
560 
561 impl DowncastArc for dyn IndexNode {
562     fn as_any_arc(self: Arc<Self>) -> Arc<dyn Any> {
563         self
564     }
565 }
566 
567 impl dyn IndexNode {
568     /// @brief 将当前Inode转换为一个具体的结构体(类型由T指定)
569     /// 如果类型正确,则返回Some,否则返回None
570     pub fn downcast_ref<T: IndexNode>(&self) -> Option<&T> {
571         return self.as_any_ref().downcast_ref::<T>();
572     }
573 
574     /// @brief 查找文件(不考虑符号链接)
575     ///
576     /// @param path 文件路径
577     ///
578     /// @return Ok(Arc<dyn IndexNode>) 要寻找的目录项的inode
579     /// @return Err(SystemError) 错误码
580     pub fn lookup(&self, path: &str) -> Result<Arc<dyn IndexNode>, SystemError> {
581         return self.lookup_follow_symlink(path, 0);
582     }
583 
584     /// @brief 查找文件(考虑符号链接)
585     ///
586     /// @param path 文件路径
587     /// @param max_follow_times 最大经过的符号链接的大小
588     ///
589     /// @return Ok(Arc<dyn IndexNode>) 要寻找的目录项的inode
590     /// @return Err(SystemError) 错误码
591     pub fn lookup_follow_symlink(
592         &self,
593         path: &str,
594         max_follow_times: usize,
595     ) -> Result<Arc<dyn IndexNode>, SystemError> {
596         if self.metadata()?.file_type != FileType::Dir {
597             return Err(SystemError::ENOTDIR);
598         }
599 
600         // 处理绝对路径
601         // result: 上一个被找到的inode
602         // rest_path: 还没有查找的路径
603         let (mut result, mut rest_path) = if let Some(rest) = path.strip_prefix('/') {
604             (ROOT_INODE().clone(), String::from(rest))
605         } else {
606             // 是相对路径
607             (self.find(".")?, String::from(path))
608         };
609 
610         // 逐级查找文件
611         while !rest_path.is_empty() {
612             // 当前这一级不是文件夹
613             if result.metadata()?.file_type != FileType::Dir {
614                 return Err(SystemError::ENOTDIR);
615             }
616 
617             let name;
618 
619             // 寻找“/”
620             match rest_path.find('/') {
621                 Some(pos) => {
622                     // 找到了,设置下一个要查找的名字
623                     name = String::from(&rest_path[0..pos]);
624                     // 剩余的路径字符串
625                     rest_path = String::from(&rest_path[pos + 1..]);
626                 }
627                 None => {
628                     name = rest_path;
629                     rest_path = String::new();
630                 }
631             }
632 
633             // 遇到连续多个"/"的情况
634             if name.is_empty() {
635                 continue;
636             }
637 
638             let inode = result.find(&name)?;
639 
640             // 处理符号链接的问题
641             if inode.metadata()?.file_type == FileType::SymLink && max_follow_times > 0 {
642                 let mut content = [0u8; 256];
643                 // 读取符号链接
644                 let len = inode.read_at(
645                     0,
646                     256,
647                     &mut content,
648                     SpinLock::new(FilePrivateData::Unused).lock(),
649                 )?;
650 
651                 // 将读到的数据转换为utf8字符串(先转为str,再转为String)
652                 let link_path = String::from(
653                     ::core::str::from_utf8(&content[..len]).map_err(|_| SystemError::ENOTDIR)?,
654                 );
655 
656                 let new_path = link_path + "/" + &rest_path;
657                 // 继续查找符号链接
658                 return result.lookup_follow_symlink(&new_path, max_follow_times - 1);
659             } else {
660                 result = inode;
661             }
662         }
663 
664         return Ok(result);
665     }
666 }
667 
668 /// IndexNode的元数据
669 ///
670 /// 对应Posix2008中的sys/stat.h中的定义 https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_stat.h.html
671 #[derive(Debug, PartialEq, Eq, Clone)]
672 pub struct Metadata {
673     /// 当前inode所在的文件系统的设备号
674     pub dev_id: usize,
675 
676     /// inode号
677     pub inode_id: InodeId,
678 
679     /// Inode的大小
680     /// 文件:文件大小(单位:字节)
681     /// 目录:目录项中的文件、文件夹数量
682     pub size: i64,
683 
684     /// Inode所在的文件系统中,每个块的大小
685     pub blk_size: usize,
686 
687     /// Inode所占的块的数目
688     pub blocks: usize,
689 
690     /// inode最后一次被访问的时间
691     pub atime: PosixTimeSpec,
692 
693     /// inode最后一次修改的时间
694     pub mtime: PosixTimeSpec,
695 
696     /// inode的创建时间
697     pub ctime: PosixTimeSpec,
698 
699     /// 文件类型
700     pub file_type: FileType,
701 
702     /// 权限
703     pub mode: ModeType,
704 
705     /// 硬链接的数量
706     pub nlinks: usize,
707 
708     /// User ID
709     pub uid: usize,
710 
711     /// Group ID
712     pub gid: usize,
713 
714     /// 文件指向的设备的id(对于设备文件系统来说)
715     pub raw_dev: DeviceNumber,
716 }
717 
718 impl Default for Metadata {
719     fn default() -> Self {
720         return Self {
721             dev_id: 0,
722             inode_id: InodeId::new(0),
723             size: 0,
724             blk_size: 0,
725             blocks: 0,
726             atime: PosixTimeSpec::default(),
727             mtime: PosixTimeSpec::default(),
728             ctime: PosixTimeSpec::default(),
729             file_type: FileType::File,
730             mode: ModeType::empty(),
731             nlinks: 1,
732             uid: 0,
733             gid: 0,
734             raw_dev: DeviceNumber::default(),
735         };
736     }
737 }
738 
739 #[derive(Debug, Clone)]
740 pub struct SuperBlock {
741     // type of filesystem
742     pub magic: Magic,
743     // optimal transfer block size
744     pub bsize: u64,
745     // total data blocks in filesystem
746     pub blocks: u64,
747     // free block in system
748     pub bfree: u64,
749     // 可供非特权用户使用的空闲块
750     pub bavail: u64,
751     // total inodes in filesystem
752     pub files: u64,
753     // free inodes in filesystem
754     pub ffree: u64,
755     // filesysytem id
756     pub fsid: u64,
757     // Max length of filename
758     pub namelen: u64,
759     // fragment size
760     pub frsize: u64,
761     // mount flags of filesystem
762     pub flags: u64,
763 }
764 
765 impl SuperBlock {
766     pub fn new(magic: Magic, bsize: u64, namelen: u64) -> Self {
767         Self {
768             magic,
769             bsize,
770             blocks: 0,
771             bfree: 0,
772             bavail: 0,
773             files: 0,
774             ffree: 0,
775             fsid: 0,
776             namelen,
777             frsize: 0,
778             flags: 0,
779         }
780     }
781 }
782 bitflags! {
783     pub struct Magic: u64 {
784         const DEVFS_MAGIC = 0x1373;
785         const FAT_MAGIC =  0xf2f52011;
786         const KER_MAGIC = 0x3153464b;
787         const PROC_MAGIC = 0x9fa0;
788         const RAMFS_MAGIC = 0x858458f6;
789         const MOUNT_MAGIC = 61267;
790     }
791 }
792 
793 /// @brief 所有文件系统都应该实现的trait
794 pub trait FileSystem: Any + Sync + Send + Debug {
795     /// @brief 获取当前文件系统的root inode的指针
796     fn root_inode(&self) -> Arc<dyn IndexNode>;
797 
798     /// @brief 获取当前文件系统的信息
799     fn info(&self) -> FsInfo;
800 
801     /// @brief 本函数用于实现动态转换。
802     /// 具体的文件系统在实现本函数时,最简单的方式就是:直接返回self
803     fn as_any_ref(&self) -> &dyn Any;
804 
805     fn name(&self) -> &str;
806 
807     fn super_block(&self) -> SuperBlock;
808 }
809 
810 impl DowncastArc for dyn FileSystem {
811     fn as_any_arc(self: Arc<Self>) -> Arc<dyn Any> {
812         self
813     }
814 }
815 
816 #[derive(Debug)]
817 pub struct FsInfo {
818     /// 文件系统所在的块设备的id
819     pub blk_dev_id: usize,
820     /// 文件名的最大长度
821     pub max_name_len: usize,
822 }
823 
824 /// @brief
825 #[repr(C)]
826 #[derive(Debug)]
827 pub struct Dirent {
828     d_ino: u64,    // 文件序列号
829     d_off: i64,    // dir偏移量
830     d_reclen: u16, // 目录下的记录数
831     d_type: u8,    // entry的类型
832     d_name: u8,    // 文件entry的名字(是一个零长数组), 本字段仅用于占位
833 }
834 
835 impl Metadata {
836     pub fn new(file_type: FileType, mode: ModeType) -> Self {
837         Metadata {
838             dev_id: 0,
839             inode_id: generate_inode_id(),
840             size: 0,
841             blk_size: 0,
842             blocks: 0,
843             atime: PosixTimeSpec::default(),
844             mtime: PosixTimeSpec::default(),
845             ctime: PosixTimeSpec::default(),
846             file_type,
847             mode,
848             nlinks: 1,
849             uid: 0,
850             gid: 0,
851             raw_dev: DeviceNumber::default(),
852         }
853     }
854 }
855 pub struct FileSystemMaker {
856     function: &'static FileSystemNewFunction,
857     name: &'static str,
858 }
859 
860 impl FileSystemMaker {
861     pub const fn new(
862         name: &'static str,
863         function: &'static FileSystemNewFunction,
864     ) -> FileSystemMaker {
865         FileSystemMaker { function, name }
866     }
867 
868     pub fn call(&self) -> Result<Arc<dyn FileSystem>, SystemError> {
869         (self.function)()
870     }
871 }
872 
873 pub type FileSystemNewFunction = fn() -> Result<Arc<dyn FileSystem>, SystemError>;
874 
875 #[macro_export]
876 macro_rules! define_filesystem_maker_slice {
877     ($name:ident) => {
878         #[::linkme::distributed_slice]
879         pub static $name: [FileSystemMaker] = [..];
880     };
881     () => {
882         compile_error!("define_filesystem_maker_slice! requires at least one argument: slice_name");
883     };
884 }
885 
886 /// 调用指定数组中的所有初始化器
887 #[macro_export]
888 macro_rules! producefs {
889     ($initializer_slice:ident,$filesystem:ident) => {
890         match $initializer_slice.iter().find(|&m| m.name == $filesystem) {
891             Some(maker) => maker.call(),
892             None => {
893                 log::error!("mismatch filesystem type : {}", $filesystem);
894                 Err(SystemError::EINVAL)
895             }
896         }
897     };
898 }
899 
900 define_filesystem_maker_slice!(FSMAKER);
901