xref: /DragonOS/kernel/src/filesystem/vfs/core.rs (revision 9fa0e95eeed8630a8a69c874090af2f10e8eee02)
16b4e7a29SLoGin use core::{hint::spin_loop, sync::atomic::Ordering};
2004e86ffSlogin 
3942cf26bSLoGin use alloc::sync::Arc;
42eab6dd7S曾俊 use log::{error, info};
591e9d4abSLoGin use system_error::SystemError;
6004e86ffSlogin 
7004e86ffSlogin use crate::{
8*9fa0e95eSLoGin     driver::base::block::manager::block_dev_manager,
9004e86ffSlogin     filesystem::{
10b087521eSChiichen         devfs::devfs_init,
11004e86ffSlogin         fat::fs::FATFileSystem,
12b087521eSChiichen         procfs::procfs_init,
13004e86ffSlogin         ramfs::RamFS,
14b087521eSChiichen         sysfs::sysfs_init,
156b4e7a29SLoGin         vfs::{mount::MountFS, syscall::ModeType, AtomicInodeId, FileSystem, FileType},
16004e86ffSlogin     },
17bf4a4899SLoGin     process::ProcessManager,
18004e86ffSlogin };
19004e86ffSlogin 
20bf4a4899SLoGin use super::{
211074eb34SSamuel Dai     fcntl::AtFlags,
22bf4a4899SLoGin     file::FileMode,
231074eb34SSamuel Dai     mount::{init_mountlist, MOUNT_LIST},
241074eb34SSamuel Dai     syscall::UmountFlag,
25bf4a4899SLoGin     utils::{rsplit_path, user_path_at},
2682df0a13Shmt     IndexNode, InodeId, VFS_MAX_FOLLOW_SYMLINK_TIMES,
27bf4a4899SLoGin };
28004e86ffSlogin 
29*9fa0e95eSLoGin /// 当没有指定根文件系统时,尝试的根文件系统列表
30*9fa0e95eSLoGin const ROOTFS_TRY_LIST: [&str; 4] = ["/dev/sda1", "/dev/sda", "/dev/vda1", "/dev/vda"];
31*9fa0e95eSLoGin 
32004e86ffSlogin /// @brief 原子地生成新的Inode号。
33004e86ffSlogin /// 请注意,所有的inode号都需要通过该函数来生成.全局的inode号,除了以下两个特殊的以外,都是唯一的
34004e86ffSlogin /// 特殊的两个inode号:
35004e86ffSlogin /// [0]: 对应'.'目录项
36004e86ffSlogin /// [1]: 对应'..'目录项
generate_inode_id() -> InodeId37004e86ffSlogin pub fn generate_inode_id() -> InodeId {
386b4e7a29SLoGin     static INO: AtomicInodeId = AtomicInodeId::new(InodeId::new(1));
396b4e7a29SLoGin     return INO.fetch_add(InodeId::new(1), Ordering::SeqCst);
40004e86ffSlogin }
41004e86ffSlogin 
427ae679ddSLoGin static mut __ROOT_INODE: Option<Arc<dyn IndexNode>> = None;
43004e86ffSlogin 
44004e86ffSlogin /// @brief 获取全局的根节点
45004e86ffSlogin #[inline(always)]
46004e86ffSlogin #[allow(non_snake_case)]
ROOT_INODE() -> Arc<dyn IndexNode>47004e86ffSlogin pub fn ROOT_INODE() -> Arc<dyn IndexNode> {
48004e86ffSlogin     unsafe {
49004e86ffSlogin         return __ROOT_INODE.as_ref().unwrap().clone();
50004e86ffSlogin     }
51004e86ffSlogin }
52004e86ffSlogin 
535b59005fSLoGin /// 初始化虚拟文件系统
545b59005fSLoGin #[inline(never)]
vfs_init() -> Result<(), SystemError>555b59005fSLoGin pub fn vfs_init() -> Result<(), SystemError> {
56004e86ffSlogin     // 使用Ramfs作为默认的根文件系统
57004e86ffSlogin     let ramfs = RamFS::new();
58004e86ffSlogin     let mount_fs = MountFS::new(ramfs, None);
597ae679ddSLoGin     let root_inode = mount_fs.root_inode();
601074eb34SSamuel Dai     init_mountlist();
61004e86ffSlogin     unsafe {
627ae679ddSLoGin         __ROOT_INODE = Some(root_inode.clone());
63004e86ffSlogin     }
64004e86ffSlogin 
65b087521eSChiichen     procfs_init().expect("Failed to initialize procfs");
66004e86ffSlogin 
67b087521eSChiichen     devfs_init().expect("Failed to initialize devfs");
68004e86ffSlogin 
69b087521eSChiichen     sysfs_init().expect("Failed to initialize sysfs");
70dd9f1fc1STingHuang 
717ae679ddSLoGin     let root_entries = ROOT_INODE().list().expect("VFS init failed");
72b5b571e0SLoGin     if !root_entries.is_empty() {
732eab6dd7S曾俊         info!("Successfully initialized VFS!");
74004e86ffSlogin     }
755b59005fSLoGin     return Ok(());
76004e86ffSlogin }
77004e86ffSlogin 
78004e86ffSlogin /// @brief 迁移伪文件系统的inode
79004e86ffSlogin /// 请注意,为了避免删掉了伪文件系统内的信息,因此没有在原root inode那里调用unlink.
migrate_virtual_filesystem(new_fs: Arc<dyn FileSystem>) -> Result<(), SystemError>80676b8ef6SMork fn migrate_virtual_filesystem(new_fs: Arc<dyn FileSystem>) -> Result<(), SystemError> {
812eab6dd7S曾俊     info!("VFS: Migrating filesystems...");
82004e86ffSlogin 
83004e86ffSlogin     let new_fs = MountFS::new(new_fs, None);
84004e86ffSlogin     // 获取新的根文件系统的根节点的引用
857ae679ddSLoGin     let new_root_inode = new_fs.root_inode();
86004e86ffSlogin 
871074eb34SSamuel Dai     // ==== 在这里获取要被迁移的文件系统的inode并迁移 ===
881074eb34SSamuel Dai     // 因为是换根所以路径没有变化
891074eb34SSamuel Dai     // 不需要重新注册挂载目录
901074eb34SSamuel Dai     new_root_inode
911074eb34SSamuel Dai         .mkdir("proc", ModeType::from_bits_truncate(0o755))
921074eb34SSamuel Dai         .expect("Unable to create /proc")
931074eb34SSamuel Dai         .mount_from(ROOT_INODE().find("proc").expect("proc not mounted!"))
941074eb34SSamuel Dai         .expect("Failed to migrate filesystem of proc");
951074eb34SSamuel Dai     new_root_inode
961074eb34SSamuel Dai         .mkdir("dev", ModeType::from_bits_truncate(0o755))
971074eb34SSamuel Dai         .expect("Unable to create /dev")
981074eb34SSamuel Dai         .mount_from(ROOT_INODE().find("dev").expect("dev not mounted!"))
991074eb34SSamuel Dai         .expect("Failed to migrate filesystem of dev");
1001074eb34SSamuel Dai     new_root_inode
1011074eb34SSamuel Dai         .mkdir("sys", ModeType::from_bits_truncate(0o755))
1021074eb34SSamuel Dai         .expect("Unable to create /sys")
1031074eb34SSamuel Dai         .mount_from(ROOT_INODE().find("sys").expect("sys not mounted!"))
1041074eb34SSamuel Dai         .expect("Failed to migrate filesystem of sys");
105c719ddc6SSaga1718 
106004e86ffSlogin     unsafe {
107004e86ffSlogin         // drop旧的Root inode
1087ae679ddSLoGin         let old_root_inode = __ROOT_INODE.take().unwrap();
109004e86ffSlogin         // 设置全局的新的ROOT Inode
1101074eb34SSamuel Dai         __ROOT_INODE = Some(new_root_inode.clone());
1111074eb34SSamuel Dai         drop(old_root_inode);
112004e86ffSlogin     }
113004e86ffSlogin 
1142eab6dd7S曾俊     info!("VFS: Migrate filesystems done!");
115004e86ffSlogin 
116004e86ffSlogin     return Ok(());
117004e86ffSlogin }
118004e86ffSlogin 
mount_root_fs() -> Result<(), SystemError>119731bc2b3SLoGin pub fn mount_root_fs() -> Result<(), SystemError> {
120*9fa0e95eSLoGin     info!("Try to mount root fs...");
121*9fa0e95eSLoGin     block_dev_manager().print_gendisks();
122004e86ffSlogin 
123*9fa0e95eSLoGin     let gendisk = ROOTFS_TRY_LIST
124*9fa0e95eSLoGin         .iter()
125*9fa0e95eSLoGin         .find_map(|&path| {
126*9fa0e95eSLoGin             if let Some(gd) = block_dev_manager().lookup_gendisk_by_path(path) {
127*9fa0e95eSLoGin                 info!("Use {} as rootfs", path);
128*9fa0e95eSLoGin                 return Some(gd);
129*9fa0e95eSLoGin             }
130*9fa0e95eSLoGin             return None;
131*9fa0e95eSLoGin         })
132*9fa0e95eSLoGin         .ok_or(SystemError::ENODEV)?;
133*9fa0e95eSLoGin 
134*9fa0e95eSLoGin     let fatfs: Result<Arc<FATFileSystem>, SystemError> = FATFileSystem::new(gendisk);
135004e86ffSlogin     if fatfs.is_err() {
1362eab6dd7S曾俊         error!(
137004e86ffSlogin             "Failed to initialize fatfs, code={:?}",
138004e86ffSlogin             fatfs.as_ref().err()
139004e86ffSlogin         );
140004e86ffSlogin         loop {
141004e86ffSlogin             spin_loop();
142004e86ffSlogin         }
143004e86ffSlogin     }
144004e86ffSlogin     let fatfs: Arc<FATFileSystem> = fatfs.unwrap();
145004e86ffSlogin     let r = migrate_virtual_filesystem(fatfs);
146004e86ffSlogin     if r.is_err() {
1472eab6dd7S曾俊         error!("Failed to migrate virtual filesystem to FAT32!");
148004e86ffSlogin         loop {
149004e86ffSlogin             spin_loop();
150004e86ffSlogin         }
151004e86ffSlogin     }
1522eab6dd7S曾俊     info!("Successfully migrate rootfs to FAT32!");
153004e86ffSlogin 
1541496ba7bSLoGin     return Ok(());
155004e86ffSlogin }
156004e86ffSlogin 
157004e86ffSlogin /// @brief 创建文件/文件夹
do_mkdir_at( dirfd: i32, path: &str, mode: FileMode, ) -> Result<Arc<dyn IndexNode>, SystemError>1581074eb34SSamuel Dai pub fn do_mkdir_at(
1591074eb34SSamuel Dai     dirfd: i32,
1601074eb34SSamuel Dai     path: &str,
1611074eb34SSamuel Dai     mode: FileMode,
1621074eb34SSamuel Dai ) -> Result<Arc<dyn IndexNode>, SystemError> {
1632eab6dd7S曾俊     // debug!("Call do mkdir at");
1641074eb34SSamuel Dai     let (mut current_inode, path) =
1651074eb34SSamuel Dai         user_path_at(&ProcessManager::current_pcb(), dirfd, path.trim())?;
1661074eb34SSamuel Dai     let (name, parent) = rsplit_path(&path);
1671074eb34SSamuel Dai     if let Some(parent) = parent {
1681074eb34SSamuel Dai         current_inode = current_inode.lookup(parent)?;
169004e86ffSlogin     }
1702eab6dd7S曾俊     // debug!("mkdir at {:?}", current_inode.metadata()?.inode_id);
1711074eb34SSamuel Dai     return current_inode.mkdir(name, ModeType::from_bits_truncate(mode.bits()));
172004e86ffSlogin }
173004e86ffSlogin 
174821bb9a2SXshine /// @brief 删除文件夹
do_remove_dir(dirfd: i32, path: &str) -> Result<u64, SystemError>175bf4a4899SLoGin pub fn do_remove_dir(dirfd: i32, path: &str) -> Result<u64, SystemError> {
17682df0a13Shmt     let path = path.trim();
177004e86ffSlogin 
178bf4a4899SLoGin     let pcb = ProcessManager::current_pcb();
1790fb515b0SLoGin     let (inode_begin, remain_path) = user_path_at(&pcb, dirfd, path)?;
180bf4a4899SLoGin     let (filename, parent_path) = rsplit_path(&remain_path);
1815eeefb8cSChenzx 
1825eeefb8cSChenzx     // 最后一项文件项为.时返回EINVAL
1835eeefb8cSChenzx     if filename == "." {
1845eeefb8cSChenzx         return Err(SystemError::EINVAL);
1855eeefb8cSChenzx     }
1865eeefb8cSChenzx 
187004e86ffSlogin     // 查找父目录
188bf4a4899SLoGin     let parent_inode: Arc<dyn IndexNode> = inode_begin
189bf4a4899SLoGin         .lookup_follow_symlink(parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
190004e86ffSlogin 
191004e86ffSlogin     if parent_inode.metadata()?.file_type != FileType::Dir {
192676b8ef6SMork         return Err(SystemError::ENOTDIR);
193004e86ffSlogin     }
194004e86ffSlogin 
1955eeefb8cSChenzx     // 在目标点为symlink时也返回ENOTDIR
1965eeefb8cSChenzx     let target_inode = parent_inode.find(filename)?;
197004e86ffSlogin     if target_inode.metadata()?.file_type != FileType::Dir {
198676b8ef6SMork         return Err(SystemError::ENOTDIR);
199004e86ffSlogin     }
200004e86ffSlogin 
201004e86ffSlogin     // 删除文件夹
202004e86ffSlogin     parent_inode.rmdir(filename)?;
203004e86ffSlogin 
204004e86ffSlogin     return Ok(0);
205004e86ffSlogin }
206004e86ffSlogin 
207004e86ffSlogin /// @brief 删除文件
do_unlink_at(dirfd: i32, path: &str) -> Result<u64, SystemError>208bf4a4899SLoGin pub fn do_unlink_at(dirfd: i32, path: &str) -> Result<u64, SystemError> {
20982df0a13Shmt     let path = path.trim();
21082df0a13Shmt 
211bf4a4899SLoGin     let pcb = ProcessManager::current_pcb();
2120fb515b0SLoGin     let (inode_begin, remain_path) = user_path_at(&pcb, dirfd, path)?;
213bf4a4899SLoGin     let inode: Result<Arc<dyn IndexNode>, SystemError> =
214bf4a4899SLoGin         inode_begin.lookup_follow_symlink(&remain_path, VFS_MAX_FOLLOW_SYMLINK_TIMES);
215004e86ffSlogin 
216004e86ffSlogin     if inode.is_err() {
217004e86ffSlogin         let errno = inode.clone().unwrap_err();
218004e86ffSlogin         // 文件不存在,且需要创建
219676b8ef6SMork         if errno == SystemError::ENOENT {
220676b8ef6SMork             return Err(SystemError::ENOENT);
221004e86ffSlogin         }
222004e86ffSlogin     }
223004e86ffSlogin     // 禁止在目录上unlink
224004e86ffSlogin     if inode.unwrap().metadata()?.file_type == FileType::Dir {
225676b8ef6SMork         return Err(SystemError::EPERM);
226004e86ffSlogin     }
227004e86ffSlogin 
228f4acaec4SMemoryShore     let (filename, parent_path) = rsplit_path(&remain_path);
229004e86ffSlogin     // 查找父目录
230bf4a4899SLoGin     let parent_inode: Arc<dyn IndexNode> = inode_begin
231bf4a4899SLoGin         .lookup_follow_symlink(parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
232004e86ffSlogin 
233004e86ffSlogin     if parent_inode.metadata()?.file_type != FileType::Dir {
234676b8ef6SMork         return Err(SystemError::ENOTDIR);
235004e86ffSlogin     }
236004e86ffSlogin 
237004e86ffSlogin     // 删除文件
238004e86ffSlogin     parent_inode.unlink(filename)?;
239004e86ffSlogin 
240004e86ffSlogin     return Ok(0);
241004e86ffSlogin }
2421d37ca6dSDonkey Kane 
2431074eb34SSamuel Dai /// # do_mount - 挂载文件系统
2441074eb34SSamuel Dai ///
2451074eb34SSamuel Dai /// 将给定的文件系统挂载到指定的挂载点。
2461074eb34SSamuel Dai ///
2471074eb34SSamuel Dai /// 此函数会检查是否已经挂载了相同的文件系统,如果已经挂载,则返回错误。
2481074eb34SSamuel Dai /// 它还会处理符号链接,并确保挂载点是有效的。
2491074eb34SSamuel Dai ///
2501074eb34SSamuel Dai /// ## 参数
2511074eb34SSamuel Dai ///
2521074eb34SSamuel Dai /// - `fs`: Arc<dyn FileSystem>,要挂载的文件系统。
2531074eb34SSamuel Dai /// - `mount_point`: &str,挂载点路径。
2541074eb34SSamuel Dai ///
2551074eb34SSamuel Dai /// ## 返回值
2561074eb34SSamuel Dai ///
2571074eb34SSamuel Dai /// - `Ok(Arc<MountFS>)`: 挂载成功后返回挂载的文件系统。
2581074eb34SSamuel Dai /// - `Err(SystemError)`: 挂载失败时返回错误。
do_mount(fs: Arc<dyn FileSystem>, mount_point: &str) -> Result<Arc<MountFS>, SystemError>2591074eb34SSamuel Dai pub fn do_mount(fs: Arc<dyn FileSystem>, mount_point: &str) -> Result<Arc<MountFS>, SystemError> {
2601074eb34SSamuel Dai     let (current_node, rest_path) = user_path_at(
2611074eb34SSamuel Dai         &ProcessManager::current_pcb(),
2621074eb34SSamuel Dai         AtFlags::AT_FDCWD.bits(),
2631074eb34SSamuel Dai         mount_point,
2641074eb34SSamuel Dai     )?;
2651074eb34SSamuel Dai     let inode = current_node.lookup_follow_symlink(&rest_path, VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
2661074eb34SSamuel Dai     if let Some((_, rest, _fs)) = MOUNT_LIST().get_mount_point(mount_point) {
2671074eb34SSamuel Dai         if rest.is_empty() {
2681074eb34SSamuel Dai             return Err(SystemError::EBUSY);
2691074eb34SSamuel Dai         }
2701074eb34SSamuel Dai     }
2711074eb34SSamuel Dai     // 移至IndexNode.mount()来记录
2721074eb34SSamuel Dai     return inode.mount(fs);
2731074eb34SSamuel Dai }
2741074eb34SSamuel Dai 
2751074eb34SSamuel Dai /// # do_mount_mkdir - 在指定挂载点创建目录并挂载文件系统
2761074eb34SSamuel Dai ///
2771074eb34SSamuel Dai /// 在指定的挂载点创建一个目录,并将其挂载到文件系统中。如果挂载点已经存在,并且不是空的,
2781074eb34SSamuel Dai /// 则会返回错误。成功时,会返回一个新的挂载文件系统的引用。
2791074eb34SSamuel Dai ///
2801074eb34SSamuel Dai /// ## 参数
2811074eb34SSamuel Dai ///
2821074eb34SSamuel Dai /// - `fs`: FileSystem - 文件系统的引用,用于创建和挂载目录。
2831074eb34SSamuel Dai /// - `mount_point`: &str - 挂载点路径,用于创建和挂载目录。
2841074eb34SSamuel Dai ///
2851074eb34SSamuel Dai /// ## 返回值
2861074eb34SSamuel Dai ///
2871074eb34SSamuel Dai /// - `Ok(Arc<MountFS>)`: 成功挂载文件系统后,返回挂载文件系统的共享引用。
2881074eb34SSamuel Dai /// - `Err(SystemError)`: 挂载失败时,返回系统错误。
do_mount_mkdir( fs: Arc<dyn FileSystem>, mount_point: &str, ) -> Result<Arc<MountFS>, SystemError>2891074eb34SSamuel Dai pub fn do_mount_mkdir(
2901074eb34SSamuel Dai     fs: Arc<dyn FileSystem>,
2911074eb34SSamuel Dai     mount_point: &str,
2921074eb34SSamuel Dai ) -> Result<Arc<MountFS>, SystemError> {
2931074eb34SSamuel Dai     let inode = do_mkdir_at(
2941074eb34SSamuel Dai         AtFlags::AT_FDCWD.bits(),
2951074eb34SSamuel Dai         mount_point,
2961074eb34SSamuel Dai         FileMode::from_bits_truncate(0o755),
2971074eb34SSamuel Dai     )?;
2981074eb34SSamuel Dai     if let Some((_, rest, _fs)) = MOUNT_LIST().get_mount_point(mount_point) {
2991074eb34SSamuel Dai         if rest.is_empty() {
3001074eb34SSamuel Dai             return Err(SystemError::EBUSY);
3011074eb34SSamuel Dai         }
3021074eb34SSamuel Dai     }
3031074eb34SSamuel Dai     return inode.mount(fs);
3041074eb34SSamuel Dai }
3051074eb34SSamuel Dai 
3061074eb34SSamuel Dai /// # do_umount2 - 执行卸载文件系统的函数
3071074eb34SSamuel Dai ///
3081074eb34SSamuel Dai /// 这个函数用于卸载指定的文件系统。
3091074eb34SSamuel Dai ///
3101074eb34SSamuel Dai /// ## 参数
3111074eb34SSamuel Dai ///
3121074eb34SSamuel Dai /// - dirfd: i32 - 目录文件描述符,用于指定要卸载的文件系统的根目录。
3131074eb34SSamuel Dai /// - target: &str - 要卸载的文件系统的目标路径。
3141074eb34SSamuel Dai /// - _flag: UmountFlag - 卸载标志,目前未使用。
3151074eb34SSamuel Dai ///
3161074eb34SSamuel Dai /// ## 返回值
3171074eb34SSamuel Dai ///
3181074eb34SSamuel Dai /// - Ok(Arc<MountFS>): 成功时返回文件系统的 Arc 引用。
3191074eb34SSamuel Dai /// - Err(SystemError): 出错时返回系统错误。
3201074eb34SSamuel Dai ///
3211074eb34SSamuel Dai /// ## 错误处理
3221074eb34SSamuel Dai ///
3231074eb34SSamuel Dai /// 如果指定的路径没有对应的文件系统,或者在尝试卸载时发生错误,将返回错误。
do_umount2( dirfd: i32, target: &str, _flag: UmountFlag, ) -> Result<Arc<MountFS>, SystemError>3241074eb34SSamuel Dai pub fn do_umount2(
3251074eb34SSamuel Dai     dirfd: i32,
3261074eb34SSamuel Dai     target: &str,
3271074eb34SSamuel Dai     _flag: UmountFlag,
3281074eb34SSamuel Dai ) -> Result<Arc<MountFS>, SystemError> {
3291074eb34SSamuel Dai     let (work, rest) = user_path_at(&ProcessManager::current_pcb(), dirfd, target)?;
3301074eb34SSamuel Dai     let path = work.absolute_path()? + &rest;
3311074eb34SSamuel Dai     let do_umount = || -> Result<Arc<MountFS>, SystemError> {
3321074eb34SSamuel Dai         if let Some(fs) = MOUNT_LIST().remove(path) {
3331074eb34SSamuel Dai             // Todo: 占用检测
3341074eb34SSamuel Dai             fs.umount()?;
3351074eb34SSamuel Dai             return Ok(fs);
3361074eb34SSamuel Dai         }
3371074eb34SSamuel Dai         return Err(SystemError::EINVAL);
3381074eb34SSamuel Dai     };
3391074eb34SSamuel Dai     return do_umount();
3401d37ca6dSDonkey Kane }
341