mod.rs 30 KB

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