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