core.rs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. use core::{hint::spin_loop, sync::atomic::Ordering};
  2. use alloc::{string::ToString, sync::Arc};
  3. use system_error::SystemError;
  4. use crate::{
  5. driver::{base::block::disk_info::Partition, disk::ahci},
  6. filesystem::{
  7. devfs::devfs_init,
  8. fat::fs::FATFileSystem,
  9. procfs::procfs_init,
  10. ramfs::RamFS,
  11. sysfs::sysfs_init,
  12. vfs::{mount::MountFS, syscall::ModeType, AtomicInodeId, FileSystem, FileType},
  13. },
  14. kdebug, kerror, kinfo,
  15. process::ProcessManager,
  16. };
  17. use super::{
  18. file::FileMode,
  19. mount::MountFSInode,
  20. utils::{rsplit_path, user_path_at},
  21. IndexNode, InodeId, VFS_MAX_FOLLOW_SYMLINK_TIMES,
  22. };
  23. /// @brief 原子地生成新的Inode号。
  24. /// 请注意,所有的inode号都需要通过该函数来生成.全局的inode号,除了以下两个特殊的以外,都是唯一的
  25. /// 特殊的两个inode号:
  26. /// [0]: 对应'.'目录项
  27. /// [1]: 对应'..'目录项
  28. pub fn generate_inode_id() -> InodeId {
  29. static INO: AtomicInodeId = AtomicInodeId::new(InodeId::new(1));
  30. return INO.fetch_add(InodeId::new(1), Ordering::SeqCst);
  31. }
  32. static mut __ROOT_INODE: Option<Arc<dyn IndexNode>> = None;
  33. /// @brief 获取全局的根节点
  34. #[inline(always)]
  35. #[allow(non_snake_case)]
  36. pub fn ROOT_INODE() -> Arc<dyn IndexNode> {
  37. unsafe {
  38. return __ROOT_INODE.as_ref().unwrap().clone();
  39. }
  40. }
  41. /// 初始化虚拟文件系统
  42. #[inline(never)]
  43. pub fn vfs_init() -> Result<(), SystemError> {
  44. // 使用Ramfs作为默认的根文件系统
  45. let ramfs = RamFS::new();
  46. let mount_fs = MountFS::new(ramfs, None);
  47. let root_inode = mount_fs.root_inode();
  48. unsafe {
  49. __ROOT_INODE = Some(root_inode.clone());
  50. }
  51. // 创建文件夹
  52. root_inode
  53. .create("proc", FileType::Dir, ModeType::from_bits_truncate(0o755))
  54. .expect("Failed to create /proc");
  55. root_inode
  56. .create("dev", FileType::Dir, ModeType::from_bits_truncate(0o755))
  57. .expect("Failed to create /dev");
  58. root_inode
  59. .create("sys", FileType::Dir, ModeType::from_bits_truncate(0o755))
  60. .expect("Failed to create /sys");
  61. kdebug!("dir in root:{:?}", root_inode.list());
  62. procfs_init().expect("Failed to initialize procfs");
  63. devfs_init().expect("Failed to initialize devfs");
  64. sysfs_init().expect("Failed to initialize sysfs");
  65. let root_entries = ROOT_INODE().list().expect("VFS init failed");
  66. if !root_entries.is_empty() {
  67. kinfo!("Successfully initialized VFS!");
  68. }
  69. return Ok(());
  70. }
  71. /// @brief 真正执行伪文件系统迁移的过程
  72. ///
  73. /// @param mountpoint_name 在根目录下的挂载点的名称
  74. /// @param inode 原本的挂载点的inode
  75. fn do_migrate(
  76. new_root_inode: Arc<dyn IndexNode>,
  77. mountpoint_name: &str,
  78. fs: &MountFS,
  79. ) -> Result<(), SystemError> {
  80. let r = new_root_inode.find(mountpoint_name);
  81. let mountpoint = if let Ok(r) = r {
  82. r
  83. } else {
  84. new_root_inode
  85. .create(
  86. mountpoint_name,
  87. FileType::Dir,
  88. ModeType::from_bits_truncate(0o755),
  89. )
  90. .unwrap_or_else(|_| panic!("Failed to create '/{mountpoint_name}' in migrating"))
  91. };
  92. // 迁移挂载点
  93. let inode = mountpoint.arc_any().downcast::<MountFSInode>().unwrap();
  94. inode.do_mount(inode.inode_id(), fs.self_ref())?;
  95. return Ok(());
  96. }
  97. /// @brief 迁移伪文件系统的inode
  98. /// 请注意,为了避免删掉了伪文件系统内的信息,因此没有在原root inode那里调用unlink.
  99. fn migrate_virtual_filesystem(new_fs: Arc<dyn FileSystem>) -> Result<(), SystemError> {
  100. kinfo!("VFS: Migrating filesystems...");
  101. // ==== 在这里获取要被迁移的文件系统的inode ===
  102. let binding = ROOT_INODE().find("proc").expect("ProcFS not mounted!").fs();
  103. let proc: &MountFS = binding.as_any_ref().downcast_ref::<MountFS>().unwrap();
  104. let binding = ROOT_INODE().find("dev").expect("DevFS not mounted!").fs();
  105. let dev: &MountFS = binding.as_any_ref().downcast_ref::<MountFS>().unwrap();
  106. let binding = ROOT_INODE().find("sys").expect("SysFs not mounted!").fs();
  107. let sys: &MountFS = binding.as_any_ref().downcast_ref::<MountFS>().unwrap();
  108. let new_fs = MountFS::new(new_fs, None);
  109. // 获取新的根文件系统的根节点的引用
  110. let new_root_inode = new_fs.root_inode();
  111. // 把上述文件系统,迁移到新的文件系统下
  112. do_migrate(new_root_inode.clone(), "proc", proc)?;
  113. do_migrate(new_root_inode.clone(), "dev", dev)?;
  114. do_migrate(new_root_inode.clone(), "sys", sys)?;
  115. unsafe {
  116. // drop旧的Root inode
  117. let old_root_inode = __ROOT_INODE.take().unwrap();
  118. drop(old_root_inode);
  119. // 设置全局的新的ROOT Inode
  120. __ROOT_INODE = Some(new_root_inode);
  121. }
  122. kinfo!("VFS: Migrate filesystems done!");
  123. return Ok(());
  124. }
  125. pub fn mount_root_fs() -> Result<(), SystemError> {
  126. kinfo!("Try to mount FAT32 as root fs...");
  127. let partiton: Arc<Partition> = ahci::get_disks_by_name("ahci_disk_0".to_string())
  128. .unwrap()
  129. .0
  130. .lock()
  131. .partitions[0]
  132. .clone();
  133. let fatfs: Result<Arc<FATFileSystem>, SystemError> = FATFileSystem::new(partiton);
  134. if fatfs.is_err() {
  135. kerror!(
  136. "Failed to initialize fatfs, code={:?}",
  137. fatfs.as_ref().err()
  138. );
  139. loop {
  140. spin_loop();
  141. }
  142. }
  143. let fatfs: Arc<FATFileSystem> = fatfs.unwrap();
  144. let r = migrate_virtual_filesystem(fatfs);
  145. if r.is_err() {
  146. kerror!("Failed to migrate virtual filesystem to FAT32!");
  147. loop {
  148. spin_loop();
  149. }
  150. }
  151. kinfo!("Successfully migrate rootfs to FAT32!");
  152. return Ok(());
  153. }
  154. /// @brief 创建文件/文件夹
  155. pub fn do_mkdir(path: &str, _mode: FileMode) -> Result<u64, SystemError> {
  156. let path = path.trim();
  157. let inode: Result<Arc<dyn IndexNode>, SystemError> = ROOT_INODE().lookup(path);
  158. if let Err(errno) = inode {
  159. // 文件不存在,且需要创建
  160. if errno == SystemError::ENOENT {
  161. let (filename, parent_path) = rsplit_path(path);
  162. // 查找父目录
  163. let parent_inode: Arc<dyn IndexNode> =
  164. ROOT_INODE().lookup(parent_path.unwrap_or("/"))?;
  165. // 创建文件夹
  166. let _create_inode: Arc<dyn IndexNode> = parent_inode.create(
  167. filename,
  168. FileType::Dir,
  169. ModeType::from_bits_truncate(0o755),
  170. )?;
  171. } else {
  172. // 不需要创建文件,因此返回错误码
  173. return Err(errno);
  174. }
  175. }
  176. return Ok(0);
  177. }
  178. /// @brief 删除文件夹
  179. pub fn do_remove_dir(dirfd: i32, path: &str) -> Result<u64, SystemError> {
  180. let path = path.trim();
  181. let pcb = ProcessManager::current_pcb();
  182. let (inode_begin, remain_path) = user_path_at(&pcb, dirfd, path)?;
  183. let (filename, parent_path) = rsplit_path(&remain_path);
  184. // 最后一项文件项为.时返回EINVAL
  185. if filename == "." {
  186. return Err(SystemError::EINVAL);
  187. }
  188. // 查找父目录
  189. let parent_inode: Arc<dyn IndexNode> = inode_begin
  190. .lookup_follow_symlink(parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
  191. if parent_inode.metadata()?.file_type != FileType::Dir {
  192. return Err(SystemError::ENOTDIR);
  193. }
  194. // 在目标点为symlink时也返回ENOTDIR
  195. let target_inode = parent_inode.find(filename)?;
  196. if target_inode.metadata()?.file_type != FileType::Dir {
  197. return Err(SystemError::ENOTDIR);
  198. }
  199. // 删除文件夹
  200. parent_inode.rmdir(filename)?;
  201. return Ok(0);
  202. }
  203. /// @brief 删除文件
  204. pub fn do_unlink_at(dirfd: i32, path: &str) -> Result<u64, SystemError> {
  205. let path = path.trim();
  206. let pcb = ProcessManager::current_pcb();
  207. let (inode_begin, remain_path) = user_path_at(&pcb, dirfd, path)?;
  208. let inode: Result<Arc<dyn IndexNode>, SystemError> =
  209. inode_begin.lookup_follow_symlink(&remain_path, VFS_MAX_FOLLOW_SYMLINK_TIMES);
  210. if inode.is_err() {
  211. let errno = inode.clone().unwrap_err();
  212. // 文件不存在,且需要创建
  213. if errno == SystemError::ENOENT {
  214. return Err(SystemError::ENOENT);
  215. }
  216. }
  217. // 禁止在目录上unlink
  218. if inode.unwrap().metadata()?.file_type == FileType::Dir {
  219. return Err(SystemError::EPERM);
  220. }
  221. let (filename, parent_path) = rsplit_path(path);
  222. // 查找父目录
  223. let parent_inode: Arc<dyn IndexNode> = inode_begin
  224. .lookup_follow_symlink(parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?;
  225. if parent_inode.metadata()?.file_type != FileType::Dir {
  226. return Err(SystemError::ENOTDIR);
  227. }
  228. // 删除文件
  229. parent_inode.unlink(filename)?;
  230. return Ok(0);
  231. }
  232. // @brief mount filesystem
  233. pub fn do_mount(fs: Arc<dyn FileSystem>, mount_point: &str) -> Result<usize, SystemError> {
  234. ROOT_INODE()
  235. .lookup_follow_symlink(mount_point, VFS_MAX_FOLLOW_SYMLINK_TIMES)?
  236. .mount(fs)?;
  237. Ok(0)
  238. }