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