Skip to content

Commit 195ed5f

Browse files
authored
Merge pull request #19 from LinkWanna/main
[doc] add arceos virtual filesystem doc
2 parents 6e111f7 + 1041edb commit 195ed5f

2 files changed

Lines changed: 311 additions & 1 deletion

File tree

docs/arceos-modules/fs/vfs.md

Lines changed: 311 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,315 @@
11
# ArceOS 文件系统实现
22

3+
在 ArceOS 中,文件系统至少分为三层:
4+
5+
1. **文件系统实现层**:包括具体的文件系统实现,如 `ramfs``devfs``fatfs``ext4`
6+
2. **文件系统兼容层**:提供了一个统一的对象 `dyn VfsNodeOps` 供上层调用,下层的具体的文件系统只需要实现 `VfsOps``VfsNodeOps` trait 即可接入 ArceOS 的文件系统框架中
7+
3. **用户接口层**:最终提供给用户的文件系统 API
8+
9+
![结构图](../../static/arceos-modules/fs/文件系统结构图.png)
10+
311
## 文件系统兼容层
412

5-
## 接入不同文件系统
13+
ArceOS 提供了一个文件系统的兼容层,它向底层的具体的文件系统提供了一个统一的接口,使得文件系统只需要实现具体的 `trait` 即可接入 ArceOS 的文件系统框架中。
14+
15+
大致可以划分为以下两个部分:
16+
17+
1. `axfs_vfs` 主要为下层具体的文件系统提供需要实现的接口。
18+
2. `axfs` 封装 `axfs_vfs` 中的 `VfsOps``VfsNodeOps` trait,面向用户提供文件系统更高层次的抽象。
19+
20+
### 虚拟文件系统接口
21+
22+
`axfs_vfs`模块中有两个核心的 trait,分别是 `VfsOps``VfsNodeOps`,这两个 trait 的实现是文件系统接入 ArceOS 的关键。
23+
24+
- **trait VfsNodeOps**:定义了文件系统节点的基本操作,如打开、读取、写入、删除等,是文件系统中节点(文件/目录)的核心接口:
25+
26+
```rust
27+
/// Node (file/directory) operations.
28+
pub trait VfsNodeOps: Send + Sync {
29+
/// Do something when the node is opened.
30+
fn open(&self) -> VfsResult;
31+
/// Do something when the node is closed.
32+
fn release(&self) -> VfsResult;
33+
/// Get the attributes of the node.
34+
fn get_attr(&self) -> VfsResult<VfsNodeAttr>;
35+
36+
37+
// file operations:
38+
39+
/// Read data from the file at the given offset.
40+
fn read_at(&self, _offset: u64, _buf: &mut [u8]) -> VfsResult<usize>;
41+
/// Write data to the file at the given offset.
42+
fn write_at(&self, _offset: u64, _buf: &[u8]) -> VfsResult<usize>;
43+
/// Flush the file, synchronize the data to disk.
44+
fn fsync(&self) -> VfsResult;
45+
/// Truncate the file to the given size.
46+
fn truncate(&self, _size: u64) -> VfsResult;
47+
48+
49+
// directory operations:
50+
51+
/// Get the parent directory of this directory.
52+
///
53+
/// Return `None` if the node is a file.
54+
fn parent(&self) -> Option<VfsNodeRef>;
55+
/// Lookup the node with given `path` in the directory.
56+
///
57+
/// Return the node if found.
58+
fn lookup(self: Arc<Self>, _path: &str) -> VfsResult<VfsNodeRef>;
59+
/// Create a new node with the given `path` in the directory
60+
///
61+
/// Return [`Ok(())`](Ok) if it already exists.
62+
fn create(&self, _path: &str, _ty: VfsNodeType) -> VfsResult;
63+
/// Remove the node with the given `path` in the directory.
64+
fn remove(&self, _path: &str) -> VfsResult;
65+
/// Read directory entries into `dirents`, starting from `start_idx`.
66+
fn read_dir(&self, _start_idx: usize, _dirents: &mut [VfsDirEntry]) -> VfsResult<usize>;
67+
/// Renames or moves existing file or directory.
68+
fn rename(&self, _src_path: &str, _dst_path: &str) -> VfsResult;
69+
70+
71+
/// Convert `&self` to [`&dyn Any`][1] that can use
72+
/// [`Any::downcast_ref`][2].
73+
///
74+
/// [1]: core::any::Any
75+
/// [2]: core::any::Any#method.downcast_ref
76+
fn as_any(&self) -> &dyn core::any::Any;
77+
}
78+
```
79+
80+
上面的代码可以分为四个部分:
81+
82+
1. 节点操作:`open``release``get_attr`
83+
2. 文件操作:`read_at``write_at``fsync``truncate`
84+
3. 目录操作:`parent``lookup``create``remove``read_dir``rename`
85+
4. 其他操作:`as_any`
86+
87+
这里解释其中的几个函数:
88+
89+
1. `get_attr`:获取节点的属性,返回 `VfsNodeAttr`,包含节点的文件类型、大小、读写权限等信息
90+
2. `truncate`:调整文件的大小到指定大小,如果指定大小小于当前文件大小,则会丢弃多余的部分;若果指定大小大于当前文件大小,则会在文件末尾添加空字节(`\0`
91+
3. `lookup`:在当前目录下查找指定路径的节点,返回节点的引用
92+
4. `read_dir`:读取当前目录下的 `VfsDirEntry`,返回读取的数量
93+
5. `as_any`:将当前节点转换为 `&dyn Any`,以便于后续的类型转换
94+
95+
---
96+
97+
- **trait VfsOps**:定义了文件系统的基本操作,如挂载、卸载、获取根节点等,是文件系统的入口接口:
98+
99+
```rust
100+
/// Filesystem operations.
101+
pub trait VfsOps: Send + Sync {
102+
/// Do something when the filesystem is mounted.
103+
fn mount(&self, _path: &str, _mount_point: VfsNodeRef) -> VfsResult;
104+
/// Do something when the filesystem is unmounted.
105+
fn umount(&self) -> VfsResult;
106+
/// Format the filesystem.
107+
fn format(&self) -> VfsResult;
108+
/// Get the attributes of the filesystem.
109+
fn statfs(&self) -> VfsResult<FileSystemInfo>;
110+
/// Get the root directory of the filesystem.
111+
fn root_dir(&self) -> VfsNodeRef;
112+
}
113+
```
114+
115+
上面的代码,这里解释其中的三个函数:
116+
117+
- `format`:对磁盘进行文件系统格式化
118+
- `statfs`:获取文件系统的基本信息(目前没有被使用)
119+
- `root_dir`:获取当前文件系统的根目录
120+
121+
### 用户视角的文件系统
122+
123+
现在 `axfs_vfs` 已经定义了文件系统的基本操作,接下来我们需要将虚拟文件系统提供的抽象封装成用户可以直接使用的接口。
124+
125+
`axfs` 模块中定义了 `File``Directory` 结构体,分别表示打开的文件和目录对象,调用该模块的用户会直接使用这两个结构体来进行文件和目录的操作。
126+
127+
这两个结构体是对 `VfsNodeRef` 的封装,它们在封装的同时也增加了一些功能:
128+
129+
1. 使用 `WithCap` 包装,增加了对文件和目录的权限控制功能,内部简单添加了可读、可写、可执行的权限控制功能,具体参考[cap_access](https://github.com/arceos-org/cap_access)
130+
2. `is_append`:表示文件是否以追加模式打开。例如 `open("/tmp/xxx", "a")` 打开文件时,`is_append``true`,并且 `offset` 指向文件末尾。
131+
3. `offset`:表示文件的读写位置。
132+
4. `entry_idx`:表示目录的读写位置。
133+
134+
```rust
135+
/// A wrapper of [`Arc<dyn VfsNodeOps>`].
136+
pub type VfsNodeRef = Arc<dyn VfsNodeOps>;
137+
138+
139+
/// An opened file object, with open permissions and a cursor.
140+
pub struct File {
141+
node: WithCap<VfsNodeRef>,
142+
is_append: bool,
143+
offset: u64,
144+
}
145+
146+
/// An opened directory object, with open permissions and a cursor for
147+
/// [`read_dir`](Directory::read_dir).
148+
pub struct Directory {
149+
node: WithCap<VfsNodeRef>,
150+
entry_idx: usize,
151+
}
152+
```
153+
154+
现在只要有根目录,用户就可以通过 `File``Directory` 结构体来完成针对文件和目录的操作了。
155+
156+
157+
## 接入不同文件系统
158+
159+
ArceOS 目前已经可以使用`ramfs``devfs``fatfs``ext4` 文件系统了,前两个是虚拟文件系统,是基于内存和设备的文件系统,后两个是基于磁盘的文件系统。
160+
161+
现在以 `fatfs` 为例,介绍如何接入一个新的文件系统,其中 `fatfs` 的具体实现请参考 [rust-fatfs](https://github.com/rafalh/rust-fatfs) 。当然,由于代码量较大,这里只介绍如何接入文件系统的核心部分,具体的实现请参考 `arceos/modules/fs/fatfs.rs`
162+
163+
### 封装原始数据结构
164+
165+
当前 `trait``fatfs` 的结构体都不在当前模块中,因此不可能直接进行 `impl`,同时由于我们需要添加 `Mutex` 来实现多线程安全,所以我们必须要对 `fatfs` 的数据结构进行一层封装。
166+
```rust
167+
pub struct FatFileSystem {
168+
inner: fatfs::FileSystem<Disk, NullTimeProvider, LossyOemCpConverter>,
169+
root_dir: UnsafeCell<Option<VfsNodeRef>>,
170+
}
171+
172+
/// A wrapper of [`fatfs::File`].
173+
pub struct FileWrapper<'a, IO: IoTrait>(Mutex<File<'a, IO, NullTimeProvider, LossyOemCpConverter>>);
174+
/// A wrapper of [`fatfs::Dir`].
175+
pub struct DirWrapper<'a, IO: IoTrait>(Dir<'a, IO, NullTimeProvider, LossyOemCpConverter>);
176+
177+
pub trait IoTrait: Read + Write + Seek {}
178+
```
179+
180+
### 适配虚拟文件系统
181+
182+
这里给出 `FileWrapper` 的实现,`DirWrapper` 的实现也是类似的,同时这里还需要注意以下两点:
183+
184+
首先,第二行 `axfs_vfs::impl_vfs_non_dir_default! {}` 提供了非目录节点的默认实现,主要是 `lookup``create``remove``read_dir` 的实现。
185+
186+
其次,`fatfs` 中不支持权限控制,所以我们直接将权限设置为 `0o755`,即 `rwxr-xr-x`
187+
188+
```rust
189+
impl<IO: IoTrait> VfsNodeOps for FileWrapper<'static, IO> {
190+
axfs_vfs::impl_vfs_non_dir_default! {}
191+
192+
fn get_attr(&self) -> VfsResult<VfsNodeAttr> {
193+
let size = self.0.lock().seek(SeekFrom::End(0)).map_err(as_vfs_err)?;
194+
let blocks = (size + BLOCK_SIZE as u64 - 1) / BLOCK_SIZE as u64;
195+
// FAT fs doesn't support permissions, we just set everything to 755
196+
let perm = VfsNodePerm::from_bits_truncate(0o755);
197+
Ok(VfsNodeAttr::new(perm, VfsNodeType::File, size, blocks))
198+
}
199+
200+
fn read_at(&self, offset: u64, buf: &mut [u8]) -> VfsResult<usize> {
201+
let mut file = self.0.lock();
202+
file.seek(SeekFrom::Start(offset)).map_err(as_vfs_err)?;
203+
file.read(buf).map_err(as_vfs_err)
204+
}
205+
206+
fn write_at(&self, offset: u64, buf: &[u8]) -> VfsResult<usize> {
207+
let mut file = self.0.lock();
208+
file.seek(SeekFrom::Start(offset)).map_err(as_vfs_err)?;
209+
file.write(buf).map_err(as_vfs_err)
210+
}
211+
212+
fn truncate(&self, size: u64) -> VfsResult {
213+
let mut file = self.0.lock();
214+
file.seek(SeekFrom::Start(size)).map_err(as_vfs_err)?;
215+
file.truncate().map_err(as_vfs_err)
216+
}
217+
}
218+
```
219+
220+
### 定义文件系统操作对象
221+
222+
`fatfs` 的定义中,需要一个实现 `Read``Write``Seek` trait 的结构体来给 `fatfs` 进行操作,这里我们使用 `Disk` 设备来作为被操作的对象。
223+
224+
下面是 `Disk``Read``Write``Seek` trait 的实现:
225+
226+
```rust
227+
impl fatfs::IoBase for Disk {
228+
type Error = ();
229+
}
230+
231+
impl IoTrait for Disk {}
232+
233+
impl Read for Disk {
234+
fn read(&mut self, mut buf: &mut [u8]) -> Result<usize, Self::Error> {
235+
let mut read_len = 0;
236+
while !buf.is_empty() {
237+
match self.read_one(buf) {
238+
Ok(0) => break,
239+
Ok(n) => {
240+
let tmp = buf;
241+
buf = &mut tmp[n..];
242+
read_len += n;
243+
}
244+
Err(_) => return Err(()),
245+
}
246+
}
247+
Ok(read_len)
248+
}
249+
}
250+
251+
impl Write for Disk {
252+
fn write(&mut self, mut buf: &[u8]) -> Result<usize, Self::Error> {
253+
let mut write_len = 0;
254+
while !buf.is_empty() {
255+
match self.write_one(buf) {
256+
Ok(0) => break,
257+
Ok(n) => {
258+
buf = &buf[n..];
259+
write_len += n;
260+
}
261+
Err(_) => return Err(()),
262+
}
263+
}
264+
Ok(write_len)
265+
}
266+
fn flush(&mut self) -> Result<(), Self::Error> {
267+
Ok(())
268+
}
269+
}
270+
271+
impl Seek for Disk {
272+
fn seek(&mut self, pos: SeekFrom) -> Result<u64, Self::Error> {
273+
let size = self.size();
274+
let new_pos = match pos {
275+
SeekFrom::Start(pos) => Some(pos),
276+
SeekFrom::Current(off) => self.position().checked_add_signed(off),
277+
SeekFrom::End(off) => size.checked_add_signed(off),
278+
}
279+
.ok_or(())?;
280+
if new_pos > size {
281+
warn!("Seek beyond the end of the block device");
282+
}
283+
self.set_position(new_pos);
284+
Ok(new_pos)
285+
}
286+
}
287+
```
288+
289+
!!! caution "文件系统读写对象"
290+
291+
我们当然也可以将文件作为读写对象,具体的实现可以参考 `arceos/modules/fs/fatfs.rs` 中的 `struct FatFileSystemFromFile`。
292+
293+
### 文件系统挂载
294+
295+
完成了对 `fatfs` 的封装后,启用 `fatfs` 特性,我们就可以在内核中挂载 `fatfs` 文件系统:
296+
```rust
297+
// modules/axfs/src/root.rs
298+
// fn init_rootfs(disk: crate::dev::Disk);
299+
cfg_if::cfg_if! {
300+
if #[cfg(feature = "myfs")] { // override the default filesystem
301+
let main_fs = fs::myfs::new_myfs(disk);
302+
} else if #[cfg(feature = "lwext4_rs")] {
303+
static EXT4_FS: LazyInit<Arc<fs::lwext4_rust::Ext4FileSystem>> = LazyInit::new();
304+
EXT4_FS.init_once(Arc::new(fs::lwext4_rust::Ext4FileSystem::new(disk)));
305+
let main_fs = EXT4_FS.clone();
306+
} else if #[cfg(feature = "fatfs")] {
307+
static FAT_FS: LazyInit<Arc<fs::fatfs::FatFileSystem>> = LazyInit::new();
308+
FAT_FS.init_once(Arc::new(fs::fatfs::FatFileSystem::new(disk)));
309+
FAT_FS.init();
310+
let main_fs = FAT_FS.clone();
311+
}
312+
}
313+
314+
let root_dir = RootDirectory::new(main_fs);
315+
```
54.9 KB
Loading

0 commit comments

Comments
 (0)