mod.rs 28 KB

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