xref: /DragonOS/kernel/src/filesystem/vfs/core.rs (revision db7c782a9aaacb320027167bda4f23751b8f36e1)
1 use core::{hint::spin_loop, sync::atomic::Ordering};
2 
3 use alloc::sync::Arc;
4 use log::{error, info};
5 use system_error::SystemError;
6 
7 use crate::{
8     driver::base::block::manager::block_dev_manager,
9     filesystem::{
10         devfs::devfs_init,
11         fat::fs::FATFileSystem,
12         procfs::procfs_init,
13         ramfs::RamFS,
14         sysfs::sysfs_init,
15         vfs::{mount::MountFS, syscall::ModeType, AtomicInodeId, FileSystem, FileType},
16     },
17     process::ProcessManager,
18 };
19 
20 use super::{
21     fcntl::AtFlags,
22     file::FileMode,
23     mount::{init_mountlist, MOUNT_LIST},
24     syscall::UmountFlag,
25     utils::{rsplit_path, user_path_at},
26     IndexNode, InodeId, VFS_MAX_FOLLOW_SYMLINK_TIMES,
27 };
28 
29 /// 当没有指定根文件系统时,尝试的根文件系统列表
30 const ROOTFS_TRY_LIST: [&str; 4] = ["/dev/sda1", "/dev/sda", "/dev/vda1", "/dev/vda"];
31 
32 /// @brief 原子地生成新的Inode号。
33 /// 请注意,所有的inode号都需要通过该函数来生成.全局的inode号,除了以下两个特殊的以外,都是唯一的
34 /// 特殊的两个inode号:
35 /// [0]: 对应'.'目录项
36 /// [1]: 对应'..'目录项
37 pub fn generate_inode_id() -> InodeId {
38     static INO: AtomicInodeId = AtomicInodeId::new(InodeId::new(1));
39     return INO.fetch_add(InodeId::new(1), Ordering::SeqCst);
40 }
41 
42 static mut __ROOT_INODE: Option<Arc<dyn IndexNode>> = None;
43 
44 /// @brief 获取全局的根节点
45 #[inline(always)]
46 #[allow(non_snake_case)]
47 pub fn ROOT_INODE() -> Arc<dyn IndexNode> {
48     unsafe {
49         return __ROOT_INODE.as_ref().unwrap().clone();
50     }
51 }
52 
53 /// 初始化虚拟文件系统
54 #[inline(never)]
55 pub fn vfs_init() -> Result<(), SystemError> {
56     // 使用Ramfs作为默认的根文件系统
57     let ramfs = RamFS::new();
58     let mount_fs = MountFS::new(ramfs, None);
59     let root_inode = mount_fs.root_inode();
60     init_mountlist();
61     unsafe {
62         __ROOT_INODE = Some(root_inode.clone());
63     }
64 
65     procfs_init().expect("Failed to initialize procfs");
66 
67     devfs_init().expect("Failed to initialize devfs");
68 
69     sysfs_init().expect("Failed to initialize sysfs");
70 
71     let root_entries = ROOT_INODE().list().expect("VFS init failed");
72     if !root_entries.is_empty() {
73         info!("Successfully initialized VFS!");
74     }
75     return Ok(());
76 }
77 
78 /// @brief 迁移伪文件系统的inode
79 /// 请注意,为了避免删掉了伪文件系统内的信息,因此没有在原root inode那里调用unlink.
80 fn migrate_virtual_filesystem(new_fs: Arc<dyn FileSystem>) -> Result<(), SystemError> {
81     info!("VFS: Migrating filesystems...");
82 
83     let new_fs = MountFS::new(new_fs, None);
84     // 获取新的根文件系统的根节点的引用
85     let new_root_inode = new_fs.root_inode();
86 
87     // ==== 在这里获取要被迁移的文件系统的inode并迁移 ===
88     // 因为是换根所以路径没有变化
89     // 不需要重新注册挂载目录
90     new_root_inode
91         .mkdir("proc", ModeType::from_bits_truncate(0o755))
92         .expect("Unable to create /proc")
93         .mount_from(ROOT_INODE().find("proc").expect("proc not mounted!"))
94         .expect("Failed to migrate filesystem of proc");
95     new_root_inode
96         .mkdir("dev", ModeType::from_bits_truncate(0o755))
97         .expect("Unable to create /dev")
98         .mount_from(ROOT_INODE().find("dev").expect("dev not mounted!"))
99         .expect("Failed to migrate filesystem of dev");
100     new_root_inode
101         .mkdir("sys", ModeType::from_bits_truncate(0o755))
102         .expect("Unable to create /sys")
103         .mount_from(ROOT_INODE().find("sys").expect("sys not mounted!"))
104         .expect("Failed to migrate filesystem of sys");
105 
106     unsafe {
107         // drop旧的Root inode
108         let old_root_inode = __ROOT_INODE.take().unwrap();
109         // 设置全局的新的ROOT Inode
110         __ROOT_INODE = Some(new_root_inode.clone());
111         drop(old_root_inode);
112     }
113 
114     info!("VFS: Migrate filesystems done!");
115 
116     return Ok(());
117 }
118 
119 pub fn mount_root_fs() -> Result<(), SystemError> {
120     info!("Try to mount root fs...");
121     block_dev_manager().print_gendisks();
122 
123     let gendisk = ROOTFS_TRY_LIST
124         .iter()
125         .find_map(|&path| {
126             if let Some(gd) = block_dev_manager().lookup_gendisk_by_path(path) {
127                 info!("Use {} as rootfs", path);
128                 return Some(gd);
129             }
130             return None;
131         })
132         .ok_or(SystemError::ENODEV)?;
133 
134     let fatfs: Result<Arc<FATFileSystem>, SystemError> = FATFileSystem::new(gendisk);
135     if fatfs.is_err() {
136         error!(
137             "Failed to initialize fatfs, code={:?}",
138             fatfs.as_ref().err()
139         );
140         loop {
141             spin_loop();
142         }
143     }
144     let fatfs: Arc<FATFileSystem> = fatfs.unwrap();
145     let r = migrate_virtual_filesystem(fatfs);
146     if r.is_err() {
147         error!("Failed to migrate virtual filesystem to FAT32!");
148         loop {
149             spin_loop();
150         }
151     }
152     info!("Successfully migrate rootfs to FAT32!");
153 
154     return Ok(());
155 }
156 
157 /// @brief 创建文件/文件夹
158 pub fn do_mkdir_at(
159     dirfd: i32,
160     path: &str,
161     mode: FileMode,
162 ) -> Result<Arc<dyn IndexNode>, SystemError> {
163     // debug!("Call do mkdir at");
164     let (mut current_inode, path) =
165         user_path_at(&ProcessManager::current_pcb(), dirfd, path.trim())?;
166     let (name, parent) = rsplit_path(&path);
167     if let Some(parent) = parent {
168         current_inode = current_inode.lookup(parent)?;
169     }
170     // debug!("mkdir at {:?}", current_inode.metadata()?.inode_id);
171     return current_inode.mkdir(name, ModeType::from_bits_truncate(mode.bits()));
172 }
173 
174 /// @brief 删除文件夹
175 pub fn do_remove_dir(dirfd: i32, path: &str) -> Result<u64, SystemError> {
176     let path = path.trim();
177 
178     let pcb = ProcessManager::current_pcb();
179     let (inode_begin, remain_path) = user_path_at(&pcb, dirfd, path)?;
180     let (filename, parent_path) = rsplit_path(&remain_path);
181 
182     // 最后一项文件项为.时返回EINVAL
183     if filename == "." {
184         return Err(SystemError::EINVAL);
185     }
186 
187     // 查找父目录
188     let parent_inode: Arc<dyn IndexNode> = inode_begin
189         .lookup_follow_symlink(parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
190 
191     if parent_inode.metadata()?.file_type != FileType::Dir {
192         return Err(SystemError::ENOTDIR);
193     }
194 
195     // 在目标点为symlink时也返回ENOTDIR
196     let target_inode = parent_inode.find(filename)?;
197     if target_inode.metadata()?.file_type != FileType::Dir {
198         return Err(SystemError::ENOTDIR);
199     }
200 
201     // 删除文件夹
202     parent_inode.rmdir(filename)?;
203 
204     return Ok(0);
205 }
206 
207 /// @brief 删除文件
208 pub fn do_unlink_at(dirfd: i32, path: &str) -> Result<u64, SystemError> {
209     let path = path.trim();
210 
211     let pcb = ProcessManager::current_pcb();
212     let (inode_begin, remain_path) = user_path_at(&pcb, dirfd, path)?;
213     let inode: Result<Arc<dyn IndexNode>, SystemError> =
214         inode_begin.lookup_follow_symlink(&remain_path, VFS_MAX_FOLLOW_SYMLINK_TIMES);
215 
216     if inode.is_err() {
217         let errno = inode.clone().unwrap_err();
218         // 文件不存在,且需要创建
219         if errno == SystemError::ENOENT {
220             return Err(SystemError::ENOENT);
221         }
222     }
223     // 禁止在目录上unlink
224     if inode.unwrap().metadata()?.file_type == FileType::Dir {
225         return Err(SystemError::EPERM);
226     }
227 
228     let (filename, parent_path) = rsplit_path(&remain_path);
229     // 查找父目录
230     let parent_inode: Arc<dyn IndexNode> = inode_begin
231         .lookup_follow_symlink(parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
232 
233     if parent_inode.metadata()?.file_type != FileType::Dir {
234         return Err(SystemError::ENOTDIR);
235     }
236 
237     // 删除文件
238     parent_inode.unlink(filename)?;
239 
240     return Ok(0);
241 }
242 
243 /// # do_mount - 挂载文件系统
244 ///
245 /// 将给定的文件系统挂载到指定的挂载点。
246 ///
247 /// 此函数会检查是否已经挂载了相同的文件系统,如果已经挂载,则返回错误。
248 /// 它还会处理符号链接,并确保挂载点是有效的。
249 ///
250 /// ## 参数
251 ///
252 /// - `fs`: Arc<dyn FileSystem>,要挂载的文件系统。
253 /// - `mount_point`: &str,挂载点路径。
254 ///
255 /// ## 返回值
256 ///
257 /// - `Ok(Arc<MountFS>)`: 挂载成功后返回挂载的文件系统。
258 /// - `Err(SystemError)`: 挂载失败时返回错误。
259 pub fn do_mount(fs: Arc<dyn FileSystem>, mount_point: &str) -> Result<Arc<MountFS>, SystemError> {
260     let (current_node, rest_path) = user_path_at(
261         &ProcessManager::current_pcb(),
262         AtFlags::AT_FDCWD.bits(),
263         mount_point,
264     )?;
265     let inode = current_node.lookup_follow_symlink(&rest_path, VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
266     if let Some((_, rest, _fs)) = MOUNT_LIST().get_mount_point(mount_point) {
267         if rest.is_empty() {
268             return Err(SystemError::EBUSY);
269         }
270     }
271     // 移至IndexNode.mount()来记录
272     return inode.mount(fs);
273 }
274 
275 /// # do_mount_mkdir - 在指定挂载点创建目录并挂载文件系统
276 ///
277 /// 在指定的挂载点创建一个目录,并将其挂载到文件系统中。如果挂载点已经存在,并且不是空的,
278 /// 则会返回错误。成功时,会返回一个新的挂载文件系统的引用。
279 ///
280 /// ## 参数
281 ///
282 /// - `fs`: FileSystem - 文件系统的引用,用于创建和挂载目录。
283 /// - `mount_point`: &str - 挂载点路径,用于创建和挂载目录。
284 ///
285 /// ## 返回值
286 ///
287 /// - `Ok(Arc<MountFS>)`: 成功挂载文件系统后,返回挂载文件系统的共享引用。
288 /// - `Err(SystemError)`: 挂载失败时,返回系统错误。
289 pub fn do_mount_mkdir(
290     fs: Arc<dyn FileSystem>,
291     mount_point: &str,
292 ) -> Result<Arc<MountFS>, SystemError> {
293     let inode = do_mkdir_at(
294         AtFlags::AT_FDCWD.bits(),
295         mount_point,
296         FileMode::from_bits_truncate(0o755),
297     )?;
298     if let Some((_, rest, _fs)) = MOUNT_LIST().get_mount_point(mount_point) {
299         if rest.is_empty() {
300             return Err(SystemError::EBUSY);
301         }
302     }
303     return inode.mount(fs);
304 }
305 
306 /// # do_umount2 - 执行卸载文件系统的函数
307 ///
308 /// 这个函数用于卸载指定的文件系统。
309 ///
310 /// ## 参数
311 ///
312 /// - dirfd: i32 - 目录文件描述符,用于指定要卸载的文件系统的根目录。
313 /// - target: &str - 要卸载的文件系统的目标路径。
314 /// - _flag: UmountFlag - 卸载标志,目前未使用。
315 ///
316 /// ## 返回值
317 ///
318 /// - Ok(Arc<MountFS>): 成功时返回文件系统的 Arc 引用。
319 /// - Err(SystemError): 出错时返回系统错误。
320 ///
321 /// ## 错误处理
322 ///
323 /// 如果指定的路径没有对应的文件系统,或者在尝试卸载时发生错误,将返回错误。
324 pub fn do_umount2(
325     dirfd: i32,
326     target: &str,
327     _flag: UmountFlag,
328 ) -> Result<Arc<MountFS>, SystemError> {
329     let (work, rest) = user_path_at(&ProcessManager::current_pcb(), dirfd, target)?;
330     let path = work.absolute_path()? + &rest;
331     let do_umount = || -> Result<Arc<MountFS>, SystemError> {
332         if let Some(fs) = MOUNT_LIST().remove(path) {
333             // Todo: 占用检测
334             fs.umount()?;
335             return Ok(fs);
336         }
337         return Err(SystemError::EINVAL);
338     };
339     return do_umount();
340 }
341