core.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. use core::{
  2. hint::spin_loop,
  3. ptr::null_mut,
  4. sync::atomic::{AtomicUsize, Ordering},
  5. };
  6. use alloc::{boxed::Box, format, string::ToString, sync::Arc};
  7. use crate::{
  8. arch::asm::current::current_pcb,
  9. driver::disk::ahci::{self},
  10. filesystem::{
  11. devfs::DevFS,
  12. fat::fs::FATFileSystem,
  13. procfs::ProcFS,
  14. ramfs::RamFS,
  15. vfs::{file::File, mount::MountFS, FileSystem, FileType},
  16. },
  17. include::bindings::bindings::PAGE_4K_SIZE,
  18. io::SeekFrom,
  19. kerror, kinfo,
  20. syscall::SystemError,
  21. };
  22. use super::{file::FileMode, utils::rsplit_path, IndexNode, InodeId};
  23. /// @brief 原子地生成新的Inode号。
  24. /// 请注意,所有的inode号都需要通过该函数来生成.全局的inode号,除了以下两个特殊的以外,都是唯一的
  25. /// 特殊的两个inode号:
  26. /// [0]: 对应'.'目录项
  27. /// [1]: 对应'..'目录项
  28. pub fn generate_inode_id() -> InodeId {
  29. static INO: AtomicUsize = AtomicUsize::new(1);
  30. return INO.fetch_add(1, Ordering::SeqCst);
  31. }
  32. static mut __ROOT_INODE: *mut Arc<dyn IndexNode> = null_mut();
  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. #[no_mangle]
  42. pub extern "C" fn vfs_init() -> i32 {
  43. // 使用Ramfs作为默认的根文件系统
  44. let ramfs = RamFS::new();
  45. let mount_fs = MountFS::new(ramfs, None);
  46. let root_inode = Box::leak(Box::new(mount_fs.root_inode()));
  47. unsafe {
  48. __ROOT_INODE = root_inode;
  49. }
  50. // 创建文件夹
  51. root_inode
  52. .create("proc", FileType::Dir, 0o777)
  53. .expect("Failed to create /proc");
  54. root_inode
  55. .create("dev", FileType::Dir, 0o777)
  56. .expect("Failed to create /dev");
  57. // // 创建procfs实例
  58. let procfs: Arc<ProcFS> = ProcFS::new();
  59. // procfs挂载
  60. let _t = root_inode
  61. .find("proc")
  62. .expect("Cannot find /proc")
  63. .mount(procfs)
  64. .expect("Failed to mount procfs.");
  65. kinfo!("ProcFS mounted.");
  66. // 创建 devfs 实例
  67. let devfs: Arc<DevFS> = DevFS::new();
  68. // devfs 挂载
  69. let _t = root_inode
  70. .find("dev")
  71. .expect("Cannot find /dev")
  72. .mount(devfs)
  73. .expect("Failed to mount devfs");
  74. kinfo!("DevFS mounted.");
  75. let root_inode = ROOT_INODE().list().expect("VFS init failed");
  76. if root_inode.len() > 0 {
  77. kinfo!("Successfully initialized VFS!");
  78. }
  79. return 0;
  80. }
  81. /// @brief 真正执行伪文件系统迁移的过程
  82. ///
  83. /// @param mountpoint_name 在根目录下的挂载点的名称
  84. /// @param inode 原本的挂载点的inode
  85. fn do_migrate(
  86. new_root_inode: Arc<dyn IndexNode>,
  87. mountpoint_name: &str,
  88. fs: &MountFS,
  89. ) -> Result<(), SystemError> {
  90. let r = new_root_inode.find(mountpoint_name);
  91. let mountpoint = if r.is_err() {
  92. new_root_inode
  93. .create(mountpoint_name, FileType::Dir, 0o777)
  94. .expect(format!("Failed to create '/{mountpoint_name}'").as_str())
  95. } else {
  96. r.unwrap()
  97. };
  98. // 迁移挂载点
  99. mountpoint
  100. .mount(fs.inner_filesystem())
  101. .expect(format!("Failed to migrate {mountpoint_name}").as_str());
  102. return Ok(());
  103. }
  104. /// @brief 迁移伪文件系统的inode
  105. /// 请注意,为了避免删掉了伪文件系统内的信息,因此没有在原root inode那里调用unlink.
  106. fn migrate_virtual_filesystem(new_fs: Arc<dyn FileSystem>) -> Result<(), SystemError> {
  107. kinfo!("VFS: Migrating filesystems...");
  108. // ==== 在这里获取要被迁移的文件系统的inode ===
  109. let binding = ROOT_INODE().find("proc").expect("ProcFS not mounted!").fs();
  110. let proc: &MountFS = binding.as_any_ref().downcast_ref::<MountFS>().unwrap();
  111. let binding = ROOT_INODE().find("dev").expect("DevFS not mounted!").fs();
  112. let dev: &MountFS = binding.as_any_ref().downcast_ref::<MountFS>().unwrap();
  113. let new_fs = MountFS::new(new_fs, None);
  114. // 获取新的根文件系统的根节点的引用
  115. let new_root_inode = Box::leak(Box::new(new_fs.root_inode()));
  116. // 把上述文件系统,迁移到新的文件系统下
  117. do_migrate(new_root_inode.clone(), "proc", proc)?;
  118. do_migrate(new_root_inode.clone(), "dev", dev)?;
  119. unsafe {
  120. // drop旧的Root inode
  121. let old_root_inode: Box<Arc<dyn IndexNode>> = Box::from_raw(__ROOT_INODE);
  122. __ROOT_INODE = null_mut();
  123. drop(old_root_inode);
  124. // 设置全局的新的ROOT Inode
  125. __ROOT_INODE = new_root_inode;
  126. }
  127. kinfo!("VFS: Migrate filesystems done!");
  128. return Ok(());
  129. }
  130. #[no_mangle]
  131. pub extern "C" fn mount_root_fs() -> i32 {
  132. kinfo!("Try to mount FAT32 as root fs...");
  133. let partiton: Arc<crate::io::disk_info::Partition> =
  134. ahci::get_disks_by_name("ahci_disk_0".to_string())
  135. .unwrap()
  136. .0
  137. .lock()
  138. .partitions[0]
  139. .clone();
  140. let fatfs: Result<Arc<FATFileSystem>, SystemError> = FATFileSystem::new(partiton);
  141. if fatfs.is_err() {
  142. kerror!(
  143. "Failed to initialize fatfs, code={:?}",
  144. fatfs.as_ref().err()
  145. );
  146. loop {
  147. spin_loop();
  148. }
  149. }
  150. let fatfs: Arc<FATFileSystem> = fatfs.unwrap();
  151. let r = migrate_virtual_filesystem(fatfs);
  152. if r.is_err() {
  153. kerror!("Failed to migrate virtual filesystem to FAT32!");
  154. loop {
  155. spin_loop();
  156. }
  157. }
  158. kinfo!("Successfully migrate rootfs to FAT32!");
  159. return 0;
  160. }
  161. /// @brief 为当前进程打开一个文件
  162. pub fn do_open(path: &str, mode: FileMode) -> Result<i32, SystemError> {
  163. // 文件名过长
  164. if path.len() > PAGE_4K_SIZE as usize {
  165. return Err(SystemError::ENAMETOOLONG);
  166. }
  167. let inode: Result<Arc<dyn IndexNode>, SystemError> = ROOT_INODE().lookup(path);
  168. let inode: Arc<dyn IndexNode> = if inode.is_err() {
  169. let errno = inode.unwrap_err();
  170. // 文件不存在,且需要创建
  171. if mode.contains(FileMode::O_CREAT)
  172. && !mode.contains(FileMode::O_DIRECTORY)
  173. && errno == SystemError::ENOENT
  174. {
  175. let (filename, parent_path) = rsplit_path(path);
  176. // 查找父目录
  177. let parent_inode: Arc<dyn IndexNode> =
  178. ROOT_INODE().lookup(parent_path.unwrap_or("/"))?;
  179. // 创建文件
  180. let inode: Arc<dyn IndexNode> = parent_inode.create(filename, FileType::File, 0o777)?;
  181. inode
  182. } else {
  183. // 不需要创建文件,因此返回错误码
  184. return Err(errno);
  185. }
  186. } else {
  187. inode.unwrap()
  188. };
  189. let file_type: FileType = inode.metadata()?.file_type;
  190. // 如果要打开的是文件夹,而目标不是文件夹
  191. if mode.contains(FileMode::O_DIRECTORY) && file_type != FileType::Dir {
  192. return Err(SystemError::ENOTDIR);
  193. }
  194. // 如果O_TRUNC,并且,打开模式包含O_RDWR或O_WRONLY,清空文件
  195. if mode.contains(FileMode::O_TRUNC)
  196. && (mode.contains(FileMode::O_RDWR) || mode.contains(FileMode::O_WRONLY))
  197. && file_type == FileType::File
  198. {
  199. inode.truncate(0)?;
  200. }
  201. // 创建文件对象
  202. let mut file: File = File::new(inode, mode)?;
  203. // 打开模式为“追加”
  204. if mode.contains(FileMode::O_APPEND) {
  205. file.lseek(SeekFrom::SeekEnd(0))?;
  206. }
  207. // 把文件对象存入pcb
  208. return current_pcb().alloc_fd(file, None);
  209. }
  210. /// @brief 根据文件描述符,读取文件数据。尝试读取的数据长度与buf的长度相同。
  211. ///
  212. /// @param fd 文件描述符编号
  213. /// @param buf 输出缓冲区。
  214. ///
  215. /// @return Ok(usize) 成功读取的数据的字节数
  216. /// @return Err(SystemError) 读取失败,返回posix错误码
  217. pub fn do_read(fd: i32, buf: &mut [u8]) -> Result<usize, SystemError> {
  218. let file: Option<&mut File> = current_pcb().get_file_mut_by_fd(fd);
  219. if file.is_none() {
  220. return Err(SystemError::EBADF);
  221. }
  222. let file: &mut File = file.unwrap();
  223. return file.read(buf.len(), buf);
  224. }
  225. /// @brief 根据文件描述符,向文件写入数据。尝试写入的数据长度与buf的长度相同。
  226. ///
  227. /// @param fd 文件描述符编号
  228. /// @param buf 输入缓冲区。
  229. ///
  230. /// @return Ok(usize) 成功写入的数据的字节数
  231. /// @return Err(SystemError) 写入失败,返回posix错误码
  232. pub fn do_write(fd: i32, buf: &[u8]) -> Result<usize, SystemError> {
  233. let file: Option<&mut File> = current_pcb().get_file_mut_by_fd(fd);
  234. if file.is_none() {
  235. return Err(SystemError::EBADF);
  236. }
  237. let file: &mut File = file.unwrap();
  238. return file.write(buf.len(), buf);
  239. }
  240. /// @brief 调整文件操作指针的位置
  241. ///
  242. /// @param fd 文件描述符编号
  243. /// @param seek 调整的方式
  244. ///
  245. /// @return Ok(usize) 调整后,文件访问指针相对于文件头部的偏移量
  246. /// @return Err(SystemError) 调整失败,返回posix错误码
  247. pub fn do_lseek(fd: i32, seek: SeekFrom) -> Result<usize, SystemError> {
  248. let file: Option<&mut File> = current_pcb().get_file_mut_by_fd(fd);
  249. if file.is_none() {
  250. return Err(SystemError::EBADF);
  251. }
  252. let file: &mut File = file.unwrap();
  253. return file.lseek(seek);
  254. }
  255. /// @brief 创建文件/文件夹
  256. pub fn do_mkdir(path: &str, _mode: FileMode) -> Result<u64, SystemError> {
  257. // 文件名过长
  258. if path.len() > PAGE_4K_SIZE as usize {
  259. return Err(SystemError::ENAMETOOLONG);
  260. }
  261. let inode: Result<Arc<dyn IndexNode>, SystemError> = ROOT_INODE().lookup(path);
  262. if inode.is_err() {
  263. let errno = inode.unwrap_err();
  264. // 文件不存在,且需要创建
  265. if errno == SystemError::ENOENT {
  266. let (filename, parent_path) = rsplit_path(path);
  267. // 查找父目录
  268. let parent_inode: Arc<dyn IndexNode> =
  269. ROOT_INODE().lookup(parent_path.unwrap_or("/"))?;
  270. // 创建文件夹
  271. let _create_inode: Arc<dyn IndexNode> =
  272. parent_inode.create(filename, FileType::Dir, 0o777)?;
  273. } else {
  274. // 不需要创建文件,因此返回错误码
  275. return Err(errno);
  276. }
  277. }
  278. return Ok(0);
  279. }
  280. /// @breif 删除文件夹
  281. pub fn do_remove_dir(path: &str) -> Result<u64, SystemError> {
  282. // 文件名过长
  283. if path.len() > PAGE_4K_SIZE as usize {
  284. return Err(SystemError::ENAMETOOLONG);
  285. }
  286. let inode: Result<Arc<dyn IndexNode>, SystemError> = ROOT_INODE().lookup(path);
  287. if inode.is_err() {
  288. let errno = inode.unwrap_err();
  289. // 文件不存在
  290. if errno == SystemError::ENOENT {
  291. return Err(SystemError::ENOENT);
  292. }
  293. }
  294. let (filename, parent_path) = rsplit_path(path);
  295. // 查找父目录
  296. let parent_inode: Arc<dyn IndexNode> = ROOT_INODE().lookup(parent_path.unwrap_or("/"))?;
  297. if parent_inode.metadata()?.file_type != FileType::Dir {
  298. return Err(SystemError::ENOTDIR);
  299. }
  300. let target_inode: Arc<dyn IndexNode> = parent_inode.find(filename)?;
  301. if target_inode.metadata()?.file_type != FileType::Dir {
  302. return Err(SystemError::ENOTDIR);
  303. }
  304. // 删除文件夹
  305. parent_inode.rmdir(filename)?;
  306. return Ok(0);
  307. }
  308. /// @brief 删除文件
  309. pub fn do_unlink_at(path: &str, _mode: FileMode) -> Result<u64, SystemError> {
  310. // 文件名过长
  311. if path.len() > PAGE_4K_SIZE as usize {
  312. return Err(SystemError::ENAMETOOLONG);
  313. }
  314. let inode: Result<Arc<dyn IndexNode>, SystemError> = ROOT_INODE().lookup(path);
  315. if inode.is_err() {
  316. let errno = inode.clone().unwrap_err();
  317. // 文件不存在,且需要创建
  318. if errno == SystemError::ENOENT {
  319. return Err(SystemError::ENOENT);
  320. }
  321. }
  322. // 禁止在目录上unlink
  323. if inode.unwrap().metadata()?.file_type == FileType::Dir {
  324. return Err(SystemError::EPERM);
  325. }
  326. let (filename, parent_path) = rsplit_path(path);
  327. // 查找父目录
  328. let parent_inode: Arc<dyn IndexNode> = ROOT_INODE().lookup(parent_path.unwrap_or("/"))?;
  329. if parent_inode.metadata()?.file_type != FileType::Dir {
  330. return Err(SystemError::ENOTDIR);
  331. }
  332. // 删除文件
  333. parent_inode.unlink(filename)?;
  334. return Ok(0);
  335. }