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