mod.rs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074
  1. pub mod fcntl;
  2. pub mod file;
  3. pub mod mount;
  4. pub mod open;
  5. pub mod stat;
  6. pub mod syscall;
  7. pub mod utils;
  8. pub mod vcore;
  9. use ::core::{any::Any, fmt::Debug, sync::atomic::AtomicUsize};
  10. use alloc::{string::String, sync::Arc, vec::Vec};
  11. use derive_builder::Builder;
  12. use intertrait::CastFromSync;
  13. use system_error::SystemError;
  14. use crate::{
  15. driver::base::{
  16. block::block_device::BlockDevice, char::CharDevice, device::device_number::DeviceNumber,
  17. },
  18. ipc::pipe::LockedPipeInode,
  19. libs::{
  20. casting::DowncastArc,
  21. spinlock::{SpinLock, SpinLockGuard},
  22. },
  23. mm::{fault::PageFaultMessage, VmFaultReason},
  24. net::event_poll::EPollItem,
  25. time::PosixTimeSpec,
  26. };
  27. use self::{file::FileMode, syscall::ModeType, utils::DName, vcore::generate_inode_id};
  28. pub use self::{file::FilePrivateData, mount::MountFS, vcore::ROOT_INODE};
  29. use super::page_cache::PageCache;
  30. /// vfs容许的最大的路径名称长度
  31. pub const MAX_PATHLEN: usize = 1024;
  32. // 定义inode号
  33. int_like!(InodeId, AtomicInodeId, usize, AtomicUsize);
  34. /// 文件的类型
  35. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  36. pub enum FileType {
  37. /// 文件
  38. File,
  39. /// 文件夹
  40. Dir,
  41. /// 块设备
  42. BlockDevice,
  43. /// 字符设备
  44. CharDevice,
  45. /// 帧缓冲设备
  46. FramebufferDevice,
  47. /// kvm设备
  48. KvmDevice,
  49. /// 管道文件
  50. Pipe,
  51. /// 符号链接
  52. SymLink,
  53. /// 套接字
  54. Socket,
  55. }
  56. impl From<FileType> for ModeType {
  57. fn from(val: FileType) -> Self {
  58. match val {
  59. FileType::File => ModeType::S_IFREG,
  60. FileType::Dir => ModeType::S_IFDIR,
  61. FileType::BlockDevice => ModeType::S_IFBLK,
  62. FileType::CharDevice => ModeType::S_IFCHR,
  63. FileType::SymLink => ModeType::S_IFLNK,
  64. FileType::Socket => ModeType::S_IFSOCK,
  65. FileType::Pipe => ModeType::S_IFIFO,
  66. FileType::KvmDevice => ModeType::S_IFCHR,
  67. FileType::FramebufferDevice => ModeType::S_IFCHR,
  68. }
  69. }
  70. }
  71. #[allow(dead_code)]
  72. #[derive(Debug, Clone)]
  73. pub enum SpecialNodeData {
  74. /// 管道文件
  75. Pipe(Arc<LockedPipeInode>),
  76. /// 字符设备
  77. CharDevice(Arc<dyn CharDevice>),
  78. /// 块设备
  79. BlockDevice(Arc<dyn BlockDevice>),
  80. }
  81. /* these are defined by POSIX and also present in glibc's dirent.h */
  82. /// 完整含义请见 http://www.gnu.org/software/libc/manual/html_node/Directory-Entries.html
  83. #[allow(dead_code)]
  84. pub const DT_UNKNOWN: u16 = 0;
  85. /// 命名管道,或者FIFO
  86. pub const DT_FIFO: u16 = 1;
  87. // 字符设备
  88. pub const DT_CHR: u16 = 2;
  89. // 目录
  90. pub const DT_DIR: u16 = 4;
  91. // 块设备
  92. pub const DT_BLK: u16 = 6;
  93. // 常规文件
  94. pub const DT_REG: u16 = 8;
  95. // 符号链接
  96. pub const DT_LNK: u16 = 10;
  97. // 是一个socket
  98. pub const DT_SOCK: u16 = 12;
  99. // 这个是抄Linux的,还不知道含义
  100. #[allow(dead_code)]
  101. pub const DT_WHT: u16 = 14;
  102. #[allow(dead_code)]
  103. pub const DT_MAX: u16 = 16;
  104. /// vfs容许的最大的符号链接跳转次数
  105. pub const VFS_MAX_FOLLOW_SYMLINK_TIMES: usize = 8;
  106. impl FileType {
  107. pub fn get_file_type_num(&self) -> u16 {
  108. return match self {
  109. FileType::File => DT_REG,
  110. FileType::Dir => DT_DIR,
  111. FileType::BlockDevice => DT_BLK,
  112. FileType::CharDevice => DT_CHR,
  113. FileType::KvmDevice => DT_CHR,
  114. FileType::Pipe => DT_FIFO,
  115. FileType::SymLink => DT_LNK,
  116. FileType::Socket => DT_SOCK,
  117. FileType::FramebufferDevice => DT_CHR,
  118. };
  119. }
  120. }
  121. bitflags! {
  122. /// @brief inode的状态(由poll方法返回)
  123. pub struct PollStatus: u8 {
  124. const WRITE = 1u8 << 0;
  125. const READ = 1u8 << 1;
  126. const ERROR = 1u8 << 2;
  127. }
  128. }
  129. /// The pollable inode trait
  130. pub trait PollableInode: Any + Sync + Send + Debug + CastFromSync {
  131. /// Return the poll status of the inode
  132. fn poll(&self, private_data: &FilePrivateData) -> Result<usize, SystemError>;
  133. /// Add an epoll item to the inode
  134. fn add_epitem(
  135. &self,
  136. epitem: Arc<EPollItem>,
  137. private_data: &FilePrivateData,
  138. ) -> Result<(), SystemError>;
  139. /// Remove epitems associated with the epoll
  140. fn remove_epitem(
  141. &self,
  142. epitm: &Arc<EPollItem>,
  143. private_data: &FilePrivateData,
  144. ) -> Result<(), SystemError>;
  145. }
  146. pub trait IndexNode: Any + Sync + Send + Debug + CastFromSync {
  147. fn mmap(&self, _start: usize, _len: usize, _offset: usize) -> Result<(), SystemError> {
  148. return Err(SystemError::ENOSYS);
  149. }
  150. fn read_sync(&self, _offset: usize, _buf: &mut [u8]) -> Result<usize, SystemError> {
  151. return Err(SystemError::ENOSYS);
  152. }
  153. fn write_sync(&self, _offset: usize, _buf: &[u8]) -> Result<usize, SystemError> {
  154. return Err(SystemError::ENOSYS);
  155. }
  156. /// @brief 打开文件
  157. ///
  158. /// @return 成功:Ok()
  159. /// 失败:Err(错误码)
  160. fn open(
  161. &self,
  162. _data: SpinLockGuard<FilePrivateData>,
  163. _mode: &FileMode,
  164. ) -> Result<(), SystemError> {
  165. // 若文件系统没有实现此方法,则返回“不支持”
  166. return Err(SystemError::ENOSYS);
  167. }
  168. /// @brief 关闭文件
  169. ///
  170. /// @return 成功:Ok()
  171. /// 失败:Err(错误码)
  172. fn close(&self, _data: SpinLockGuard<FilePrivateData>) -> Result<(), SystemError> {
  173. // 若文件系统没有实现此方法,则返回“不支持”
  174. return Err(SystemError::ENOSYS);
  175. }
  176. /// @brief 在inode的指定偏移量开始,读取指定大小的数据
  177. ///
  178. /// @param offset 起始位置在Inode中的偏移量
  179. /// @param len 要读取的字节数
  180. /// @param buf 缓冲区. 请注意,必须满足@buf.len()>=@len
  181. /// @param _data 各文件系统系统所需私有信息
  182. ///
  183. /// @return 成功:Ok(读取的字节数)
  184. /// 失败:Err(Posix错误码)
  185. fn read_at(
  186. &self,
  187. offset: usize,
  188. len: usize,
  189. buf: &mut [u8],
  190. _data: SpinLockGuard<FilePrivateData>,
  191. ) -> Result<usize, SystemError>;
  192. /// @brief 在inode的指定偏移量开始,写入指定大小的数据(从buf的第0byte开始写入)
  193. ///
  194. /// @param offset 起始位置在Inode中的偏移量
  195. /// @param len 要写入的字节数
  196. /// @param buf 缓冲区. 请注意,必须满足@buf.len()>=@len
  197. /// @param _data 各文件系统系统所需私有信息
  198. ///
  199. /// @return 成功:Ok(写入的字节数)
  200. /// 失败:Err(Posix错误码)
  201. fn write_at(
  202. &self,
  203. offset: usize,
  204. len: usize,
  205. buf: &[u8],
  206. _data: SpinLockGuard<FilePrivateData>,
  207. ) -> Result<usize, SystemError>;
  208. /// # 在inode的指定偏移量开始,读取指定大小的数据,忽略PageCache
  209. ///
  210. /// ## 参数
  211. ///
  212. /// - `offset`: 起始位置在Inode中的偏移量
  213. /// - `len`: 要读取的字节数
  214. /// - `buf`: 缓冲区
  215. /// - `data`: 各文件系统系统所需私有信息
  216. ///
  217. /// ## 返回值
  218. ///
  219. /// - `Ok(usize)``: Ok(读取的字节数)
  220. /// - `Err(SystemError)``: Err(Posix错误码)
  221. fn read_direct(
  222. &self,
  223. _offset: usize,
  224. _len: usize,
  225. _buf: &mut [u8],
  226. _data: SpinLockGuard<FilePrivateData>,
  227. ) -> Result<usize, SystemError> {
  228. return Err(SystemError::ENOSYS);
  229. }
  230. /// # 在inode的指定偏移量开始,写入指定大小的数据,忽略PageCache
  231. ///
  232. /// ## 参数
  233. ///
  234. /// - `offset`: 起始位置在Inode中的偏移量
  235. /// - `len`: 要读取的字节数
  236. /// - `buf`: 缓冲区
  237. /// - `data`: 各文件系统系统所需私有信息
  238. ///
  239. /// ## 返回值
  240. ///
  241. /// - `Ok(usize)``: Ok(读取的字节数)
  242. /// - `Err(SystemError)``: Err(Posix错误码)
  243. fn write_direct(
  244. &self,
  245. _offset: usize,
  246. _len: usize,
  247. _buf: &[u8],
  248. _data: SpinLockGuard<FilePrivateData>,
  249. ) -> Result<usize, SystemError> {
  250. return Err(SystemError::ENOSYS);
  251. }
  252. /// @brief 获取inode的元数据
  253. ///
  254. /// @return 成功:Ok(inode的元数据)
  255. /// 失败:Err(错误码)
  256. fn metadata(&self) -> Result<Metadata, SystemError> {
  257. // 若文件系统没有实现此方法,则返回“不支持”
  258. return Err(SystemError::ENOSYS);
  259. }
  260. /// @brief 设置inode的元数据
  261. ///
  262. /// @return 成功:Ok()
  263. /// 失败:Err(错误码)
  264. fn set_metadata(&self, _metadata: &Metadata) -> Result<(), SystemError> {
  265. // 若文件系统没有实现此方法,则返回“不支持”
  266. return Err(SystemError::ENOSYS);
  267. }
  268. /// @brief 重新设置文件的大小
  269. ///
  270. /// 如果文件大小增加,则文件内容不变,但是文件的空洞部分会被填充为0
  271. /// 如果文件大小减小,则文件内容会被截断
  272. ///
  273. /// @return 成功:Ok()
  274. /// 失败:Err(错误码)
  275. fn resize(&self, _len: usize) -> Result<(), SystemError> {
  276. // 若文件系统没有实现此方法,则返回“不支持”
  277. return Err(SystemError::ENOSYS);
  278. }
  279. /// @brief 在当前目录下创建一个新的inode
  280. ///
  281. /// @param name 目录项的名字
  282. /// @param file_type 文件类型
  283. /// @param mode 权限
  284. ///
  285. /// @return 创建成功:返回Ok(新的inode的Arc指针)
  286. /// @return 创建失败:返回Err(错误码)
  287. fn create(
  288. &self,
  289. name: &str,
  290. file_type: FileType,
  291. mode: ModeType,
  292. ) -> Result<Arc<dyn IndexNode>, SystemError> {
  293. // 若文件系统没有实现此方法,则默认调用其create_with_data方法。如果仍未实现,则会得到一个Err(-ENOSYS)的返回值
  294. return self.create_with_data(name, file_type, mode, 0);
  295. }
  296. /// @brief 在当前目录下创建一个新的inode,并传入一个简单的data字段,方便进行初始化。
  297. ///
  298. /// @param name 目录项的名字
  299. /// @param file_type 文件类型
  300. /// @param mode 权限
  301. /// @param data 用于初始化该inode的数据。(为0则表示忽略此字段)对于不同的文件系统来说,代表的含义可能不同。
  302. ///
  303. /// @return 创建成功:返回Ok(新的inode的Arc指针)
  304. /// @return 创建失败:返回Err(错误码)
  305. fn create_with_data(
  306. &self,
  307. _name: &str,
  308. _file_type: FileType,
  309. _mode: ModeType,
  310. _data: usize,
  311. ) -> Result<Arc<dyn IndexNode>, SystemError> {
  312. // 若文件系统没有实现此方法,则返回“不支持”
  313. return Err(SystemError::ENOSYS);
  314. }
  315. /// @brief 在当前目录下,创建一个名为Name的硬链接,指向另一个IndexNode
  316. ///
  317. /// @param name 硬链接的名称
  318. /// @param other 要被指向的IndexNode的Arc指针
  319. ///
  320. /// @return 成功:Ok()
  321. /// 失败:Err(错误码)
  322. fn link(&self, _name: &str, _other: &Arc<dyn IndexNode>) -> Result<(), SystemError> {
  323. // 若文件系统没有实现此方法,则返回“不支持”
  324. return Err(SystemError::ENOSYS);
  325. }
  326. /// @brief 在当前目录下,删除一个名为Name的硬链接
  327. ///
  328. /// @param name 硬链接的名称
  329. ///
  330. /// @return 成功:Ok()
  331. /// 失败:Err(错误码)
  332. fn unlink(&self, _name: &str) -> Result<(), SystemError> {
  333. // 若文件系统没有实现此方法,则返回“不支持”
  334. return Err(SystemError::ENOSYS);
  335. }
  336. /// @brief 删除文件夹
  337. ///
  338. /// @param name 文件夹名称
  339. ///
  340. /// @return 成功 Ok(())
  341. /// @return 失败 Err(错误码)
  342. fn rmdir(&self, _name: &str) -> Result<(), SystemError> {
  343. return Err(SystemError::ENOSYS);
  344. }
  345. /// 将指定的`old_name`子目录项移动到target目录下, 并予以`new_name`。
  346. ///
  347. /// # Behavior
  348. /// 如果old_name所指向的inode与target的相同,那么则直接**执行重命名的操作**。
  349. fn move_to(
  350. &self,
  351. _old_name: &str,
  352. _target: &Arc<dyn IndexNode>,
  353. _new_name: &str,
  354. ) -> Result<(), SystemError> {
  355. // 若文件系统没有实现此方法,则返回“不支持”
  356. return Err(SystemError::ENOSYS);
  357. }
  358. /// @brief 寻找一个名为Name的inode
  359. ///
  360. /// @param name 要寻找的inode的名称
  361. ///
  362. /// @return 成功:Ok()
  363. /// 失败:Err(错误码)
  364. fn find(&self, _name: &str) -> Result<Arc<dyn IndexNode>, SystemError> {
  365. // 若文件系统没有实现此方法,则返回“不支持”
  366. return Err(SystemError::ENOSYS);
  367. }
  368. /// @brief 根据inode号,获取子目录项的名字
  369. ///
  370. /// @param ino inode号
  371. ///
  372. /// @return 成功:Ok()
  373. /// 失败:Err(错误码)
  374. fn get_entry_name(&self, _ino: InodeId) -> Result<String, SystemError> {
  375. // 若文件系统没有实现此方法,则返回“不支持”
  376. return Err(SystemError::ENOSYS);
  377. }
  378. /// @brief 根据inode号,获取子目录项的名字和元数据
  379. ///
  380. /// @param ino inode号
  381. ///
  382. /// @return 成功:Ok(String, Metadata)
  383. /// 失败:Err(错误码)
  384. fn get_entry_name_and_metadata(&self, ino: InodeId) -> Result<(String, Metadata), SystemError> {
  385. // 如果有条件,请在文件系统中使用高效的方式实现本接口,而不是依赖这个低效率的默认实现。
  386. let name = self.get_entry_name(ino)?;
  387. let entry = self.find(&name)?;
  388. return Ok((name, entry.metadata()?));
  389. }
  390. /// @brief io control接口
  391. ///
  392. /// @param cmd 命令
  393. /// @param data 数据
  394. ///
  395. /// @return 成功:Ok()
  396. /// 失败:Err(错误码)
  397. fn ioctl(
  398. &self,
  399. _cmd: u32,
  400. _data: usize,
  401. _private_data: &FilePrivateData,
  402. ) -> Result<usize, SystemError> {
  403. // 若文件系统没有实现此方法,则返回“不支持”
  404. return Err(SystemError::ENOSYS);
  405. }
  406. /// @brief 获取inode所在的文件系统的指针
  407. fn fs(&self) -> Arc<dyn FileSystem>;
  408. /// @brief 本函数用于实现动态转换。
  409. /// 具体的文件系统在实现本函数时,最简单的方式就是:直接返回self
  410. fn as_any_ref(&self) -> &dyn Any;
  411. /// @brief 列出当前inode下的所有目录项的名字
  412. fn list(&self) -> Result<Vec<String>, SystemError>;
  413. /// # mount - 挂载文件系统
  414. ///
  415. /// 将给定的文件系统挂载到当前的文件系统节点上。
  416. ///
  417. /// 该函数是`MountFS`结构体的实例方法,用于将一个新的文件系统挂载到调用它的`MountFS`实例上。
  418. ///
  419. /// ## 参数
  420. ///
  421. /// - `fs`: `Arc<dyn FileSystem>` - 要挂载的文件系统的共享引用。
  422. ///
  423. /// ## 返回值
  424. ///
  425. /// - `Ok(Arc<MountFS>)`: 新的挂载文件系统的共享引用。
  426. /// - `Err(SystemError)`: 挂载过程中出现的错误。
  427. ///
  428. /// ## 错误处理
  429. ///
  430. /// - 如果文件系统不是目录类型,则返回`SystemError::ENOTDIR`错误。
  431. /// - 如果当前路径已经是挂载点,则返回`SystemError::EBUSY`错误。
  432. ///
  433. /// ## 副作用
  434. ///
  435. /// - 该函数会在`MountFS`实例上创建一个新的挂载点。
  436. /// - 该函数会在全局的挂载列表中记录新的挂载关系。
  437. fn mount(&self, _fs: Arc<dyn FileSystem>) -> Result<Arc<MountFS>, SystemError> {
  438. return Err(SystemError::ENOSYS);
  439. }
  440. /// # mount_from - 从给定的目录挂载已有挂载信息的文件系统
  441. ///
  442. /// 这个函数将一个已有挂载信息的文件系统从给定的目录挂载到当前目录。
  443. ///
  444. /// ## 参数
  445. ///
  446. /// - `from`: Arc<dyn IndexNode> - 要挂载的目录的引用。
  447. ///
  448. /// ## 返回值
  449. ///
  450. /// - Ok(Arc<MountFS>): 挂载的新文件系统的引用。
  451. /// - Err(SystemError): 如果发生错误,返回系统错误。
  452. ///
  453. /// ## 错误处理
  454. ///
  455. /// - 如果给定的目录不是目录类型,返回`SystemError::ENOTDIR`。
  456. /// - 如果当前目录已经是挂载点的根目录,返回`SystemError::EBUSY`。
  457. ///
  458. /// ## 副作用
  459. ///
  460. /// - 系统初始化用,其他情况不应调用此函数
  461. fn mount_from(&self, _des: Arc<dyn IndexNode>) -> Result<Arc<MountFS>, SystemError> {
  462. return Err(SystemError::ENOSYS);
  463. }
  464. /// # umount - 卸载当前Inode下的文件系统
  465. ///
  466. /// 该函数是特定于`MountFS`实现的,其他文件系统不应实现此函数。
  467. ///
  468. /// ## 参数
  469. ///
  470. /// 无
  471. ///
  472. /// ## 返回值
  473. ///
  474. /// - Ok(Arc<MountFS>): 卸载的文件系统的引用。
  475. /// - Err(SystemError): 如果发生错误,返回系统错误。
  476. ///
  477. /// ## 行为
  478. ///
  479. /// - 查找路径
  480. /// - 定位到父文件系统的挂载点
  481. /// - 将挂载点与子文件系统的根进行叠加
  482. /// - 判断是否为子文件系统的根
  483. /// - 调用父文件系统挂载点的`_umount`方法进行卸载
  484. fn umount(&self) -> Result<Arc<MountFS>, SystemError> {
  485. return Err(SystemError::ENOSYS);
  486. }
  487. /// # absolute_path 获取目录项绝对路径
  488. ///
  489. /// ## 参数
  490. ///
  491. /// 无
  492. ///
  493. /// ## 返回值
  494. ///
  495. /// - Ok(String): 路径
  496. /// - Err(SystemError): 文件系统不支持dname parent api
  497. ///
  498. /// ## Behavior
  499. ///
  500. /// 该函数只能被MountFS实现,其他文件系统不应实现这个函数
  501. ///
  502. /// # Performance
  503. ///
  504. /// 这是一个O(n)的路径查询,并且在未实现DName缓存的文件系统中,性能极差;
  505. /// 即使实现了DName也尽量不要用。
  506. fn absolute_path(&self) -> Result<String, SystemError> {
  507. return Err(SystemError::ENOSYS);
  508. }
  509. /// @brief 截断当前inode到指定的长度。如果当前文件长度小于len,则不操作。
  510. ///
  511. /// @param len 要被截断到的目标长度
  512. fn truncate(&self, _len: usize) -> Result<(), SystemError> {
  513. return Err(SystemError::ENOSYS);
  514. }
  515. /// @brief 将当前inode的内容同步到具体设备上
  516. fn sync(&self) -> Result<(), SystemError> {
  517. return Ok(());
  518. }
  519. /// ## 创建一个特殊文件节点
  520. /// - _filename: 文件名
  521. /// - _mode: 权限信息
  522. fn mknod(
  523. &self,
  524. _filename: &str,
  525. _mode: ModeType,
  526. _dev_t: DeviceNumber,
  527. ) -> Result<Arc<dyn IndexNode>, SystemError> {
  528. return Err(SystemError::ENOSYS);
  529. }
  530. /// # mkdir - 新建名称为`name`的目录项
  531. ///
  532. /// 当目录下已有名称为`name`的文件夹时,返回该目录项的引用;否则新建`name`文件夹,并返回该引用。
  533. ///
  534. /// 该函数会检查`name`目录是否已存在,如果存在但类型不为文件夹,则会返回`EEXIST`错误。
  535. ///
  536. /// # 参数
  537. ///
  538. /// - `name`: &str - 要新建的目录项的名称。
  539. /// - `mode`: ModeType - 设置目录项的权限模式。
  540. ///
  541. /// # 返回值
  542. ///
  543. /// - `Ok(Arc<dyn IndexNode>)`: 成功时返回`name`目录项的共享引用。
  544. /// - `Err(SystemError)`: 出错时返回错误信息。
  545. fn mkdir(&self, name: &str, mode: ModeType) -> Result<Arc<dyn IndexNode>, SystemError> {
  546. match self.find(name) {
  547. Ok(inode) => {
  548. if inode.metadata()?.file_type == FileType::Dir {
  549. Ok(inode)
  550. } else {
  551. Err(SystemError::EEXIST)
  552. }
  553. }
  554. Err(SystemError::ENOENT) => self.create(name, FileType::Dir, mode),
  555. Err(err) => Err(err),
  556. }
  557. }
  558. /// ## 返回特殊文件的inode
  559. fn special_node(&self) -> Option<SpecialNodeData> {
  560. None
  561. }
  562. /// # dname - 返回目录名
  563. ///
  564. /// 此函数用于返回一个目录名。
  565. ///
  566. /// ## 参数
  567. ///
  568. /// 无
  569. ///
  570. /// ## 返回值
  571. /// - Ok(DName): 成功时返回一个目录名。
  572. /// - Err(SystemError): 如果系统不支持此操作,则返回一个系统错误。
  573. fn dname(&self) -> Result<DName, SystemError> {
  574. return Err(SystemError::ENOSYS);
  575. }
  576. /// # parent - 返回父目录的引用
  577. ///
  578. /// 当该目录是当前文件系统的根目录时,返回自身的引用。
  579. ///
  580. /// ## 参数
  581. ///
  582. /// 无
  583. ///
  584. /// ## 返回值
  585. ///
  586. /// - Ok(Arc<dyn IndexNode>): A reference to the parent directory
  587. /// - Err(SystemError): If there is an error in finding the parent directory
  588. fn parent(&self) -> Result<Arc<dyn IndexNode>, SystemError> {
  589. return self.find("..");
  590. }
  591. fn page_cache(&self) -> Option<Arc<PageCache>> {
  592. log::error!(
  593. "function page_cache() has not yet been implemented for inode:{}",
  594. crate::libs::name::get_type_name(&self)
  595. );
  596. None
  597. }
  598. /// Transform the inode to a pollable inode
  599. ///
  600. /// If the inode is not pollable, return an error
  601. fn as_pollable_inode(&self) -> Result<&dyn PollableInode, SystemError> {
  602. Err(SystemError::ENOSYS)
  603. }
  604. }
  605. impl DowncastArc for dyn IndexNode {
  606. fn as_any_arc(self: Arc<Self>) -> Arc<dyn Any> {
  607. self
  608. }
  609. }
  610. impl dyn IndexNode {
  611. /// @brief 将当前Inode转换为一个具体的结构体(类型由T指定)
  612. /// 如果类型正确,则返回Some,否则返回None
  613. pub fn downcast_ref<T: IndexNode>(&self) -> Option<&T> {
  614. return self.as_any_ref().downcast_ref::<T>();
  615. }
  616. /// @brief 查找文件(不考虑符号链接)
  617. ///
  618. /// @param path 文件路径
  619. ///
  620. /// @return Ok(Arc<dyn IndexNode>) 要寻找的目录项的inode
  621. /// @return Err(SystemError) 错误码
  622. pub fn lookup(&self, path: &str) -> Result<Arc<dyn IndexNode>, SystemError> {
  623. return self.lookup_follow_symlink(path, 0);
  624. }
  625. pub fn lookup_follow_symlink(
  626. &self,
  627. path: &str,
  628. max_follow_times: usize,
  629. ) -> Result<Arc<dyn IndexNode>, SystemError> {
  630. return self.do_lookup_follow_symlink(path, max_follow_times, true);
  631. }
  632. pub fn lookup_follow_symlink2(
  633. &self,
  634. path: &str,
  635. max_follow_times: usize,
  636. follow_final_symlink: bool,
  637. ) -> Result<Arc<dyn IndexNode>, SystemError> {
  638. return self.do_lookup_follow_symlink(path, max_follow_times, follow_final_symlink);
  639. }
  640. /// # 查找文件
  641. /// 查找指定路径的文件,考虑符号链接的存在,并可选择是否返回最终路径的符号链接文件本身。
  642. ///
  643. /// ## 参数
  644. /// - `path`: 文件路径
  645. /// - `max_follow_times`: 最大经过的符号链接的数量
  646. /// - `follow_final_symlink`: 是否跟随最后的符号链接
  647. ///
  648. /// ## 返回值
  649. /// - `Ok(Arc<dyn IndexNode>)`: 要寻找的目录项的inode
  650. /// - `Err(SystemError)`: 错误码,表示查找过程中遇到的错误
  651. ///
  652. /// ## Safety
  653. /// 此函数在处理符号链接时可能会遇到循环引用的情况,`max_follow_times` 参数用于限制符号链接的跟随次数以避免无限循环。
  654. #[inline(never)]
  655. pub fn do_lookup_follow_symlink(
  656. &self,
  657. path: &str,
  658. max_follow_times: usize,
  659. follow_final_symlink: bool,
  660. ) -> Result<Arc<dyn IndexNode>, SystemError> {
  661. if self.metadata()?.file_type != FileType::Dir {
  662. return Err(SystemError::ENOTDIR);
  663. }
  664. // 处理绝对路径
  665. // result: 上一个被找到的inode
  666. // rest_path: 还没有查找的路径
  667. let (mut result, mut rest_path) = if let Some(rest) = path.strip_prefix('/') {
  668. (ROOT_INODE().clone(), String::from(rest))
  669. } else {
  670. // 是相对路径
  671. (self.find(".")?, String::from(path))
  672. };
  673. // 逐级查找文件
  674. while !rest_path.is_empty() {
  675. // 当前这一级不是文件夹
  676. if result.metadata()?.file_type != FileType::Dir {
  677. return Err(SystemError::ENOTDIR);
  678. }
  679. let name;
  680. // 寻找“/”
  681. match rest_path.find('/') {
  682. Some(pos) => {
  683. name = String::from(&rest_path[0..pos]);
  684. rest_path = String::from(&rest_path[pos + 1..]);
  685. }
  686. None => {
  687. name = rest_path;
  688. rest_path = String::new();
  689. }
  690. }
  691. // 遇到连续多个"/"的情况
  692. if name.is_empty() {
  693. continue;
  694. }
  695. let inode = result.find(&name)?;
  696. let file_type = inode.metadata()?.file_type;
  697. // 如果已经是路径的最后一个部分,并且不希望跟随最后的符号链接
  698. if rest_path.is_empty() && !follow_final_symlink && file_type == FileType::SymLink {
  699. // 返回符号链接本身
  700. return Ok(inode);
  701. }
  702. // 跟随符号链接跳转
  703. if file_type == FileType::SymLink && max_follow_times > 0 {
  704. let mut content = [0u8; 256];
  705. // 读取符号链接
  706. let len = inode.read_at(
  707. 0,
  708. 256,
  709. &mut content,
  710. SpinLock::new(FilePrivateData::Unused).lock(),
  711. )?;
  712. // 将读到的数据转换为utf8字符串(先转为str,再转为String)
  713. let link_path = String::from(
  714. ::core::str::from_utf8(&content[..len]).map_err(|_| SystemError::EINVAL)?,
  715. );
  716. let new_path = link_path + "/" + &rest_path;
  717. // 继续查找符号链接
  718. return result.lookup_follow_symlink2(
  719. &new_path,
  720. max_follow_times - 1,
  721. follow_final_symlink,
  722. );
  723. } else {
  724. result = inode;
  725. }
  726. }
  727. return Ok(result);
  728. }
  729. }
  730. /// IndexNode的元数据
  731. ///
  732. /// 对应Posix2008中的sys/stat.h中的定义 https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_stat.h.html
  733. #[derive(Debug, PartialEq, Eq, Clone, Builder)]
  734. #[builder(no_std, setter(into))]
  735. pub struct Metadata {
  736. /// 当前inode所在的文件系统的设备号
  737. /// todo:更改为DeviceNumber结构体
  738. pub dev_id: usize,
  739. /// inode号
  740. pub inode_id: InodeId,
  741. /// Inode的大小
  742. /// 文件:文件大小(单位:字节)
  743. /// 目录:目录项中的文件、文件夹数量
  744. pub size: i64,
  745. /// Inode所在的文件系统中,每个块的大小
  746. pub blk_size: usize,
  747. /// Inode所占的块的数目
  748. pub blocks: usize,
  749. /// inode最后一次被访问的时间
  750. pub atime: PosixTimeSpec,
  751. /// inode的文件数据最后一次修改的时间
  752. pub mtime: PosixTimeSpec,
  753. /// inode的元数据、权限或文件内容最后一次发生改变的时间
  754. pub ctime: PosixTimeSpec,
  755. /// inode的创建时间
  756. pub btime: PosixTimeSpec,
  757. /// 文件类型
  758. pub file_type: FileType,
  759. /// 权限
  760. pub mode: ModeType,
  761. /// 硬链接的数量
  762. pub nlinks: usize,
  763. /// User ID
  764. pub uid: usize,
  765. /// Group ID
  766. pub gid: usize,
  767. /// 文件指向的设备的id(对于设备文件系统来说)
  768. pub raw_dev: DeviceNumber,
  769. }
  770. impl Default for Metadata {
  771. fn default() -> Self {
  772. return Self {
  773. dev_id: 0,
  774. inode_id: InodeId::new(0),
  775. size: 0,
  776. blk_size: 0,
  777. blocks: 0,
  778. atime: PosixTimeSpec::default(),
  779. mtime: PosixTimeSpec::default(),
  780. ctime: PosixTimeSpec::default(),
  781. btime: PosixTimeSpec::default(),
  782. file_type: FileType::File,
  783. mode: ModeType::empty(),
  784. nlinks: 1,
  785. uid: 0,
  786. gid: 0,
  787. raw_dev: DeviceNumber::default(),
  788. };
  789. }
  790. }
  791. #[derive(Debug, Clone)]
  792. pub struct SuperBlock {
  793. // type of filesystem
  794. pub magic: Magic,
  795. // optimal transfer block size
  796. pub bsize: u64,
  797. // total data blocks in filesystem
  798. pub blocks: u64,
  799. // free block in system
  800. pub bfree: u64,
  801. // 可供非特权用户使用的空闲块
  802. pub bavail: u64,
  803. // total inodes in filesystem
  804. pub files: u64,
  805. // free inodes in filesystem
  806. pub ffree: u64,
  807. // filesysytem id
  808. pub fsid: u64,
  809. // Max length of filename
  810. pub namelen: u64,
  811. // fragment size
  812. pub frsize: u64,
  813. // mount flags of filesystem
  814. pub flags: u64,
  815. }
  816. impl SuperBlock {
  817. pub fn new(magic: Magic, bsize: u64, namelen: u64) -> Self {
  818. Self {
  819. magic,
  820. bsize,
  821. blocks: 0,
  822. bfree: 0,
  823. bavail: 0,
  824. files: 0,
  825. ffree: 0,
  826. fsid: 0,
  827. namelen,
  828. frsize: 0,
  829. flags: 0,
  830. }
  831. }
  832. }
  833. bitflags! {
  834. pub struct Magic: u64 {
  835. const DEVFS_MAGIC = 0x1373;
  836. const FAT_MAGIC = 0xf2f52011;
  837. const KER_MAGIC = 0x3153464b;
  838. const PROC_MAGIC = 0x9fa0;
  839. const RAMFS_MAGIC = 0x858458f6;
  840. const MOUNT_MAGIC = 61267;
  841. }
  842. }
  843. /// @brief 所有文件系统都应该实现的trait
  844. pub trait FileSystem: Any + Sync + Send + Debug {
  845. /// @brief 获取当前文件系统的root inode的指针
  846. fn root_inode(&self) -> Arc<dyn IndexNode>;
  847. /// @brief 获取当前文件系统的信息
  848. fn info(&self) -> FsInfo;
  849. /// @brief 本函数用于实现动态转换。
  850. /// 具体的文件系统在实现本函数时,最简单的方式就是:直接返回self
  851. fn as_any_ref(&self) -> &dyn Any;
  852. fn name(&self) -> &str;
  853. fn super_block(&self) -> SuperBlock;
  854. unsafe fn fault(&self, _pfm: &mut PageFaultMessage) -> VmFaultReason {
  855. panic!(
  856. "fault() has not yet been implemented for filesystem: {}",
  857. crate::libs::name::get_type_name(&self)
  858. )
  859. }
  860. unsafe fn map_pages(
  861. &self,
  862. _pfm: &mut PageFaultMessage,
  863. _start_pgoff: usize,
  864. _end_pgoff: usize,
  865. ) -> VmFaultReason {
  866. panic!(
  867. "map_pages() has not yet been implemented for filesystem: {}",
  868. crate::libs::name::get_type_name(&self)
  869. )
  870. }
  871. }
  872. impl DowncastArc for dyn FileSystem {
  873. fn as_any_arc(self: Arc<Self>) -> Arc<dyn Any> {
  874. self
  875. }
  876. }
  877. #[derive(Debug)]
  878. pub struct FsInfo {
  879. /// 文件系统所在的块设备的id
  880. pub blk_dev_id: usize,
  881. /// 文件名的最大长度
  882. pub max_name_len: usize,
  883. }
  884. /// @brief
  885. #[repr(C)]
  886. #[derive(Debug)]
  887. pub struct Dirent {
  888. d_ino: u64, // 文件序列号
  889. d_off: i64, // dir偏移量
  890. d_reclen: u16, // 目录下的记录数
  891. d_type: u8, // entry的类型
  892. d_name: u8, // 文件entry的名字(是一个零长数组), 本字段仅用于占位
  893. }
  894. impl Metadata {
  895. pub fn new(file_type: FileType, mode: ModeType) -> Self {
  896. Metadata {
  897. dev_id: 0,
  898. inode_id: generate_inode_id(),
  899. size: 0,
  900. blk_size: 0,
  901. blocks: 0,
  902. atime: PosixTimeSpec::default(),
  903. mtime: PosixTimeSpec::default(),
  904. ctime: PosixTimeSpec::default(),
  905. btime: PosixTimeSpec::default(),
  906. file_type,
  907. mode,
  908. nlinks: 1,
  909. uid: 0,
  910. gid: 0,
  911. raw_dev: DeviceNumber::default(),
  912. }
  913. }
  914. }
  915. pub struct FileSystemMaker {
  916. function: &'static FileSystemNewFunction,
  917. name: &'static str,
  918. }
  919. impl FileSystemMaker {
  920. pub const fn new(
  921. name: &'static str,
  922. function: &'static FileSystemNewFunction,
  923. ) -> FileSystemMaker {
  924. FileSystemMaker { function, name }
  925. }
  926. pub fn call(
  927. &self,
  928. data: Option<&dyn FileSystemMakerData>,
  929. ) -> Result<Arc<dyn FileSystem>, SystemError> {
  930. (self.function)(data)
  931. }
  932. }
  933. pub trait FileSystemMakerData: Send + Sync {
  934. fn as_any(&self) -> &dyn Any;
  935. }
  936. pub type FileSystemNewFunction =
  937. fn(data: Option<&dyn FileSystemMakerData>) -> Result<Arc<dyn FileSystem>, SystemError>;
  938. #[macro_export]
  939. macro_rules! define_filesystem_maker_slice {
  940. ($name:ident) => {
  941. #[::linkme::distributed_slice]
  942. pub static $name: [FileSystemMaker] = [..];
  943. };
  944. () => {
  945. compile_error!("define_filesystem_maker_slice! requires at least one argument: slice_name");
  946. };
  947. }
  948. /// 调用指定数组中的所有初始化器
  949. #[macro_export]
  950. macro_rules! producefs {
  951. ($initializer_slice:ident,$filesystem:ident,$raw_data : ident) => {
  952. match $initializer_slice.iter().find(|&m| m.name == $filesystem) {
  953. Some(maker) => {
  954. let mount_data = match $filesystem {
  955. "overlay" => OverlayMountData::from_row($raw_data).ok(),
  956. _ => None,
  957. };
  958. let data: Option<&dyn FileSystemMakerData> =
  959. mount_data.as_ref().map(|d| d as &dyn FileSystemMakerData);
  960. maker.call(data)
  961. }
  962. None => {
  963. log::error!("mismatch filesystem type : {}", $filesystem);
  964. Err(SystemError::EINVAL)
  965. }
  966. }
  967. };
  968. }
  969. define_filesystem_maker_slice!(FSMAKER);