16b4e7a29SLoGin use core::{hint::spin_loop, sync::atomic::Ordering}; 2004e86ffSlogin 3b5b571e0SLoGin use alloc::{string::ToString, sync::Arc}; 491e9d4abSLoGin use system_error::SystemError; 5004e86ffSlogin 6004e86ffSlogin use crate::{ 782df0a13Shmt driver::{base::block::disk_info::Partition, disk::ahci}, 8004e86ffSlogin filesystem::{ 9b087521eSChiichen devfs::devfs_init, 10004e86ffSlogin fat::fs::FATFileSystem, 11b087521eSChiichen procfs::procfs_init, 12004e86ffSlogin ramfs::RamFS, 13b087521eSChiichen sysfs::sysfs_init, 146b4e7a29SLoGin vfs::{mount::MountFS, syscall::ModeType, AtomicInodeId, FileSystem, FileType}, 15004e86ffSlogin }, 16b087521eSChiichen kdebug, kerror, kinfo, 17bf4a4899SLoGin process::ProcessManager, 18004e86ffSlogin }; 19004e86ffSlogin 20bf4a4899SLoGin use super::{ 21bf4a4899SLoGin file::FileMode, 22dfe53cf0SGnoCiYeH mount::MountFSInode, 23bf4a4899SLoGin utils::{rsplit_path, user_path_at}, 2482df0a13Shmt IndexNode, InodeId, VFS_MAX_FOLLOW_SYMLINK_TIMES, 25bf4a4899SLoGin }; 26004e86ffSlogin 27004e86ffSlogin /// @brief 原子地生成新的Inode号。 28004e86ffSlogin /// 请注意,所有的inode号都需要通过该函数来生成.全局的inode号,除了以下两个特殊的以外,都是唯一的 29004e86ffSlogin /// 特殊的两个inode号: 30004e86ffSlogin /// [0]: 对应'.'目录项 31004e86ffSlogin /// [1]: 对应'..'目录项 32004e86ffSlogin pub fn generate_inode_id() -> InodeId { 336b4e7a29SLoGin static INO: AtomicInodeId = AtomicInodeId::new(InodeId::new(1)); 346b4e7a29SLoGin return INO.fetch_add(InodeId::new(1), Ordering::SeqCst); 35004e86ffSlogin } 36004e86ffSlogin 377ae679ddSLoGin static mut __ROOT_INODE: Option<Arc<dyn IndexNode>> = None; 38004e86ffSlogin 39004e86ffSlogin /// @brief 获取全局的根节点 40004e86ffSlogin #[inline(always)] 41004e86ffSlogin #[allow(non_snake_case)] 42004e86ffSlogin pub fn ROOT_INODE() -> Arc<dyn IndexNode> { 43004e86ffSlogin unsafe { 44004e86ffSlogin return __ROOT_INODE.as_ref().unwrap().clone(); 45004e86ffSlogin } 46004e86ffSlogin } 47004e86ffSlogin 485b59005fSLoGin /// 初始化虚拟文件系统 495b59005fSLoGin #[inline(never)] 505b59005fSLoGin pub fn vfs_init() -> Result<(), SystemError> { 51004e86ffSlogin // 使用Ramfs作为默认的根文件系统 52004e86ffSlogin let ramfs = RamFS::new(); 53004e86ffSlogin let mount_fs = MountFS::new(ramfs, None); 547ae679ddSLoGin let root_inode = mount_fs.root_inode(); 55004e86ffSlogin 56004e86ffSlogin unsafe { 577ae679ddSLoGin __ROOT_INODE = Some(root_inode.clone()); 58004e86ffSlogin } 59004e86ffSlogin 60004e86ffSlogin // 创建文件夹 61004e86ffSlogin root_inode 626b4e7a29SLoGin .create("proc", FileType::Dir, ModeType::from_bits_truncate(0o755)) 63004e86ffSlogin .expect("Failed to create /proc"); 64004e86ffSlogin root_inode 656b4e7a29SLoGin .create("dev", FileType::Dir, ModeType::from_bits_truncate(0o755)) 66004e86ffSlogin .expect("Failed to create /dev"); 67dd9f1fc1STingHuang root_inode 686b4e7a29SLoGin .create("sys", FileType::Dir, ModeType::from_bits_truncate(0o755)) 69dd9f1fc1STingHuang .expect("Failed to create /sys"); 70*c719ddc6SSaga1718 71b087521eSChiichen kdebug!("dir in root:{:?}", root_inode.list()); 72004e86ffSlogin 73b087521eSChiichen procfs_init().expect("Failed to initialize procfs"); 74004e86ffSlogin 75b087521eSChiichen devfs_init().expect("Failed to initialize devfs"); 76004e86ffSlogin 77b087521eSChiichen sysfs_init().expect("Failed to initialize sysfs"); 78dd9f1fc1STingHuang 797ae679ddSLoGin let root_entries = ROOT_INODE().list().expect("VFS init failed"); 80b5b571e0SLoGin if !root_entries.is_empty() { 81004e86ffSlogin kinfo!("Successfully initialized VFS!"); 82004e86ffSlogin } 835b59005fSLoGin return Ok(()); 84004e86ffSlogin } 85004e86ffSlogin 86004e86ffSlogin /// @brief 真正执行伪文件系统迁移的过程 87004e86ffSlogin /// 88004e86ffSlogin /// @param mountpoint_name 在根目录下的挂载点的名称 89004e86ffSlogin /// @param inode 原本的挂载点的inode 90004e86ffSlogin fn do_migrate( 91004e86ffSlogin new_root_inode: Arc<dyn IndexNode>, 92004e86ffSlogin mountpoint_name: &str, 93004e86ffSlogin fs: &MountFS, 94676b8ef6SMork ) -> Result<(), SystemError> { 95004e86ffSlogin let r = new_root_inode.find(mountpoint_name); 96b5b571e0SLoGin let mountpoint = if let Ok(r) = r { 97b5b571e0SLoGin r 98b5b571e0SLoGin } else { 99004e86ffSlogin new_root_inode 1006b4e7a29SLoGin .create( 1016b4e7a29SLoGin mountpoint_name, 1026b4e7a29SLoGin FileType::Dir, 1036b4e7a29SLoGin ModeType::from_bits_truncate(0o755), 1046b4e7a29SLoGin ) 105b5b571e0SLoGin .unwrap_or_else(|_| panic!("Failed to create '/{mountpoint_name}' in migrating")) 106004e86ffSlogin }; 107004e86ffSlogin // 迁移挂载点 108dfe53cf0SGnoCiYeH let inode = mountpoint.arc_any().downcast::<MountFSInode>().unwrap(); 109dfe53cf0SGnoCiYeH inode.do_mount(inode.inode_id(), fs.self_ref())?; 110dfe53cf0SGnoCiYeH 111004e86ffSlogin return Ok(()); 112004e86ffSlogin } 113004e86ffSlogin 114004e86ffSlogin /// @brief 迁移伪文件系统的inode 115004e86ffSlogin /// 请注意,为了避免删掉了伪文件系统内的信息,因此没有在原root inode那里调用unlink. 116676b8ef6SMork fn migrate_virtual_filesystem(new_fs: Arc<dyn FileSystem>) -> Result<(), SystemError> { 117004e86ffSlogin kinfo!("VFS: Migrating filesystems..."); 118004e86ffSlogin 119004e86ffSlogin // ==== 在这里获取要被迁移的文件系统的inode === 120004e86ffSlogin let binding = ROOT_INODE().find("proc").expect("ProcFS not mounted!").fs(); 121004e86ffSlogin let proc: &MountFS = binding.as_any_ref().downcast_ref::<MountFS>().unwrap(); 122004e86ffSlogin let binding = ROOT_INODE().find("dev").expect("DevFS not mounted!").fs(); 123004e86ffSlogin let dev: &MountFS = binding.as_any_ref().downcast_ref::<MountFS>().unwrap(); 124dd9f1fc1STingHuang let binding = ROOT_INODE().find("sys").expect("SysFs not mounted!").fs(); 125dd9f1fc1STingHuang let sys: &MountFS = binding.as_any_ref().downcast_ref::<MountFS>().unwrap(); 126004e86ffSlogin 127004e86ffSlogin let new_fs = MountFS::new(new_fs, None); 128004e86ffSlogin // 获取新的根文件系统的根节点的引用 1297ae679ddSLoGin let new_root_inode = new_fs.root_inode(); 130004e86ffSlogin 131004e86ffSlogin // 把上述文件系统,迁移到新的文件系统下 132004e86ffSlogin do_migrate(new_root_inode.clone(), "proc", proc)?; 133004e86ffSlogin do_migrate(new_root_inode.clone(), "dev", dev)?; 134dd9f1fc1STingHuang do_migrate(new_root_inode.clone(), "sys", sys)?; 135*c719ddc6SSaga1718 136004e86ffSlogin unsafe { 137004e86ffSlogin // drop旧的Root inode 1387ae679ddSLoGin let old_root_inode = __ROOT_INODE.take().unwrap(); 139004e86ffSlogin drop(old_root_inode); 140004e86ffSlogin 141004e86ffSlogin // 设置全局的新的ROOT Inode 1427ae679ddSLoGin __ROOT_INODE = Some(new_root_inode); 143004e86ffSlogin } 144004e86ffSlogin 145004e86ffSlogin kinfo!("VFS: Migrate filesystems done!"); 146004e86ffSlogin 147004e86ffSlogin return Ok(()); 148004e86ffSlogin } 149004e86ffSlogin 1501496ba7bSLoGin pub fn mount_root_fs() -> Result<(), SystemError> { 151004e86ffSlogin kinfo!("Try to mount FAT32 as root fs..."); 152b087521eSChiichen let partiton: Arc<Partition> = ahci::get_disks_by_name("ahci_disk_0".to_string()) 153004e86ffSlogin .unwrap() 154004e86ffSlogin .0 155004e86ffSlogin .lock() 156004e86ffSlogin .partitions[0] 157004e86ffSlogin .clone(); 158004e86ffSlogin 159676b8ef6SMork let fatfs: Result<Arc<FATFileSystem>, SystemError> = FATFileSystem::new(partiton); 160004e86ffSlogin if fatfs.is_err() { 161004e86ffSlogin kerror!( 162004e86ffSlogin "Failed to initialize fatfs, code={:?}", 163004e86ffSlogin fatfs.as_ref().err() 164004e86ffSlogin ); 165004e86ffSlogin loop { 166004e86ffSlogin spin_loop(); 167004e86ffSlogin } 168004e86ffSlogin } 169004e86ffSlogin let fatfs: Arc<FATFileSystem> = fatfs.unwrap(); 170004e86ffSlogin let r = migrate_virtual_filesystem(fatfs); 171004e86ffSlogin if r.is_err() { 172004e86ffSlogin kerror!("Failed to migrate virtual filesystem to FAT32!"); 173004e86ffSlogin loop { 174004e86ffSlogin spin_loop(); 175004e86ffSlogin } 176004e86ffSlogin } 177004e86ffSlogin kinfo!("Successfully migrate rootfs to FAT32!"); 178004e86ffSlogin 1791496ba7bSLoGin return Ok(()); 180004e86ffSlogin } 181004e86ffSlogin 182004e86ffSlogin /// @brief 创建文件/文件夹 183676b8ef6SMork pub fn do_mkdir(path: &str, _mode: FileMode) -> Result<u64, SystemError> { 18482df0a13Shmt let path = path.trim(); 185004e86ffSlogin 186676b8ef6SMork let inode: Result<Arc<dyn IndexNode>, SystemError> = ROOT_INODE().lookup(path); 187004e86ffSlogin 188b5b571e0SLoGin if let Err(errno) = inode { 189004e86ffSlogin // 文件不存在,且需要创建 190676b8ef6SMork if errno == SystemError::ENOENT { 191004e86ffSlogin let (filename, parent_path) = rsplit_path(path); 192004e86ffSlogin // 查找父目录 193004e86ffSlogin let parent_inode: Arc<dyn IndexNode> = 194004e86ffSlogin ROOT_INODE().lookup(parent_path.unwrap_or("/"))?; 195004e86ffSlogin // 创建文件夹 1966b4e7a29SLoGin let _create_inode: Arc<dyn IndexNode> = parent_inode.create( 1976b4e7a29SLoGin filename, 1986b4e7a29SLoGin FileType::Dir, 1996b4e7a29SLoGin ModeType::from_bits_truncate(0o755), 2006b4e7a29SLoGin )?; 201004e86ffSlogin } else { 202004e86ffSlogin // 不需要创建文件,因此返回错误码 203004e86ffSlogin return Err(errno); 204004e86ffSlogin } 205004e86ffSlogin } 206004e86ffSlogin 207004e86ffSlogin return Ok(0); 208004e86ffSlogin } 209004e86ffSlogin 210821bb9a2SXshine /// @brief 删除文件夹 211bf4a4899SLoGin pub fn do_remove_dir(dirfd: i32, path: &str) -> Result<u64, SystemError> { 21282df0a13Shmt let path = path.trim(); 213004e86ffSlogin 214bf4a4899SLoGin let pcb = ProcessManager::current_pcb(); 2150fb515b0SLoGin let (inode_begin, remain_path) = user_path_at(&pcb, dirfd, path)?; 216bf4a4899SLoGin let (filename, parent_path) = rsplit_path(&remain_path); 2175eeefb8cSChenzx 2185eeefb8cSChenzx // 最后一项文件项为.时返回EINVAL 2195eeefb8cSChenzx if filename == "." { 2205eeefb8cSChenzx return Err(SystemError::EINVAL); 2215eeefb8cSChenzx } 2225eeefb8cSChenzx 223004e86ffSlogin // 查找父目录 224bf4a4899SLoGin let parent_inode: Arc<dyn IndexNode> = inode_begin 225bf4a4899SLoGin .lookup_follow_symlink(parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?; 226004e86ffSlogin 227004e86ffSlogin if parent_inode.metadata()?.file_type != FileType::Dir { 228676b8ef6SMork return Err(SystemError::ENOTDIR); 229004e86ffSlogin } 230004e86ffSlogin 2315eeefb8cSChenzx // 在目标点为symlink时也返回ENOTDIR 2325eeefb8cSChenzx let target_inode = parent_inode.find(filename)?; 233004e86ffSlogin if target_inode.metadata()?.file_type != FileType::Dir { 234676b8ef6SMork return Err(SystemError::ENOTDIR); 235004e86ffSlogin } 236004e86ffSlogin 237004e86ffSlogin // 删除文件夹 238004e86ffSlogin parent_inode.rmdir(filename)?; 239004e86ffSlogin 240004e86ffSlogin return Ok(0); 241004e86ffSlogin } 242004e86ffSlogin 243004e86ffSlogin /// @brief 删除文件 244bf4a4899SLoGin pub fn do_unlink_at(dirfd: i32, path: &str) -> Result<u64, SystemError> { 24582df0a13Shmt let path = path.trim(); 24682df0a13Shmt 247bf4a4899SLoGin let pcb = ProcessManager::current_pcb(); 2480fb515b0SLoGin let (inode_begin, remain_path) = user_path_at(&pcb, dirfd, path)?; 249bf4a4899SLoGin let inode: Result<Arc<dyn IndexNode>, SystemError> = 250bf4a4899SLoGin inode_begin.lookup_follow_symlink(&remain_path, VFS_MAX_FOLLOW_SYMLINK_TIMES); 251004e86ffSlogin 252004e86ffSlogin if inode.is_err() { 253004e86ffSlogin let errno = inode.clone().unwrap_err(); 254004e86ffSlogin // 文件不存在,且需要创建 255676b8ef6SMork if errno == SystemError::ENOENT { 256676b8ef6SMork return Err(SystemError::ENOENT); 257004e86ffSlogin } 258004e86ffSlogin } 259004e86ffSlogin // 禁止在目录上unlink 260004e86ffSlogin if inode.unwrap().metadata()?.file_type == FileType::Dir { 261676b8ef6SMork return Err(SystemError::EPERM); 262004e86ffSlogin } 263004e86ffSlogin 264004e86ffSlogin let (filename, parent_path) = rsplit_path(path); 265004e86ffSlogin // 查找父目录 266bf4a4899SLoGin let parent_inode: Arc<dyn IndexNode> = inode_begin 267bf4a4899SLoGin .lookup_follow_symlink(parent_path.unwrap_or("/"), VFS_MAX_FOLLOW_SYMLINK_TIMES)?; 268004e86ffSlogin 269004e86ffSlogin if parent_inode.metadata()?.file_type != FileType::Dir { 270676b8ef6SMork return Err(SystemError::ENOTDIR); 271004e86ffSlogin } 272004e86ffSlogin 273004e86ffSlogin // 删除文件 274004e86ffSlogin parent_inode.unlink(filename)?; 275004e86ffSlogin 276004e86ffSlogin return Ok(0); 277004e86ffSlogin } 2781d37ca6dSDonkey Kane 2791d37ca6dSDonkey Kane // @brief mount filesystem 2801d37ca6dSDonkey Kane pub fn do_mount(fs: Arc<dyn FileSystem>, mount_point: &str) -> Result<usize, SystemError> { 2811d37ca6dSDonkey Kane ROOT_INODE() 282b5b571e0SLoGin .lookup_follow_symlink(mount_point, VFS_MAX_FOLLOW_SYMLINK_TIMES)? 2831d37ca6dSDonkey Kane .mount(fs)?; 2841d37ca6dSDonkey Kane Ok(0) 2851d37ca6dSDonkey Kane } 286