RustForge

rust-kernel

Rustbelt: a hobby x86_64 kernel written in Rust

rust-kernel / src / fs / ramfs.rs
6029 bytes ยท raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
//! ramfs: a file system that lives entirely on the heap (like Linux's ramfs /
//! tmpfs without the size limit). The simplest possible `FileSystem`: a tree
//! of nodes; files are a `Vec<u8>`, directories a sorted map name -> node.
//! Since stage 16 every node also remembers its permission bits (chmod)
//! and its three times (utimensat, and writes update the modification time).

use super::{now_timespec, DirEntry, FileSystem, Inode, InodeKind, MODE_SET};
use crate::errno::Errno;
use alloc::{collections::BTreeMap, string::String, sync::Arc, vec::Vec};
use spin::Mutex;

pub struct RamFs {
    root: Arc<RamInode>,
}

impl RamFs {
    pub fn new() -> Arc<Self> {
        Arc::new(RamFs { root: Arc::new(RamInode::new(Node::Dir(Mutex::new(BTreeMap::new())))) })
    }
}

impl FileSystem for RamFs {
    fn name(&self) -> &'static str {
        "ramfs"
    }
    fn root(&self) -> Arc<dyn Inode> {
        self.root.clone()
    }
}

pub enum Node {
    File(Mutex<Vec<u8>>),
    Dir(Mutex<BTreeMap<String, Arc<RamInode>>>),
}

/// What `stat` shows besides the contents (stage 16).
struct Meta {
    /// 0 = never chmod'ed (stat shows the default 0o644 / 0o755);
    /// otherwise the bits | MODE_SET.
    mode: u32,
    /// atime, mtime, ctime as [seconds, nanoseconds].
    times: [[i64; 2]; 3],
}

pub struct RamInode {
    node: Node,
    meta: Mutex<Meta>,
}

impl RamInode {
    fn new(node: Node) -> RamInode {
        let now = now_timespec();
        RamInode { node, meta: Mutex::new(Meta { mode: 0, times: [now; 3] }) }
    }

    /// The contents changed: new modification and status-change time.
    fn touch(&self) {
        let now = now_timespec();
        let mut meta = self.meta.lock();
        meta.times[1] = now;
        meta.times[2] = now;
    }
}

impl Inode for RamInode {
    fn kind(&self) -> InodeKind {
        match &self.node {
            Node::File(_) => InodeKind::File,
            Node::Dir(_) => InodeKind::Directory,
        }
    }

    fn size(&self) -> usize {
        match &self.node {
            Node::File(data) => data.lock().len(),
            Node::Dir(entries) => entries.lock().len(),
        }
    }

    fn read_at(&self, offset: usize, buf: &mut [u8]) -> Result<usize, Errno> {
        let Node::File(data) = &self.node else { return Err(Errno::EISDIR) };
        let data = data.lock();
        if offset >= data.len() {
            return Ok(0); // EOF
        }
        let n = buf.len().min(data.len() - offset);
        buf[..n].copy_from_slice(&data[offset..offset + n]);
        Ok(n)
    }

    fn write_at(&self, offset: usize, buf: &[u8]) -> Result<usize, Errno> {
        let Node::File(data) = &self.node else { return Err(Errno::EISDIR) };
        let mut data = data.lock();
        let end = offset.checked_add(buf.len()).ok_or(Errno::EINVAL)?;
        if data.len() < end {
            data.resize(end, 0); // writing past the end grows the file (gap = zeros)
        }
        data[offset..end].copy_from_slice(buf);
        drop(data);
        self.touch();
        Ok(buf.len())
    }

    fn lookup(&self, name: &str) -> Result<Arc<dyn Inode>, Errno> {
        let Node::Dir(entries) = &self.node else { return Err(Errno::ENOTDIR) };
        let node = entries.lock().get(name).cloned().ok_or(Errno::ENOENT)?;
        Ok(node)
    }

    fn create(&self, name: &str, kind: InodeKind) -> Result<Arc<dyn Inode>, Errno> {
        let Node::Dir(entries) = &self.node else { return Err(Errno::ENOTDIR) };
        if name.is_empty() || name.contains('/') || name.len() > 255 {
            return Err(Errno::EINVAL);
        }
        let mut entries = entries.lock();
        if entries.contains_key(name) {
            return Err(Errno::EEXIST);
        }
        let node = Arc::new(RamInode::new(match kind {
            InodeKind::File => Node::File(Mutex::new(Vec::new())),
            InodeKind::Directory => Node::Dir(Mutex::new(BTreeMap::new())),
            InodeKind::Symlink | InodeKind::Device => return Err(Errno::EOPNOTSUPP), // ramfs has neither
        }));
        entries.insert(String::from(name), node.clone());
        Ok(node)
    }

    fn list(&self) -> Result<Vec<DirEntry>, Errno> {
        let Node::Dir(entries) = &self.node else { return Err(Errno::ENOTDIR) };
        let entries = entries.lock();
        Ok(entries.iter().map(|(name, node)| DirEntry { name: name.clone(), kind: node.kind() }).collect())
    }

    fn truncate(&self) -> Result<(), Errno> {
        let Node::File(data) = &self.node else { return Err(Errno::EISDIR) };
        data.lock().clear();
        self.touch();
        Ok(())
    }

    fn set_len(&self, len: usize) -> Result<(), Errno> {
        let Node::File(data) = &self.node else { return Err(Errno::EISDIR) };
        data.lock().resize(len, 0); // shorter: cut; longer: zeros
        self.touch();
        Ok(())
    }

    fn mode(&self) -> u32 {
        self.meta.lock().mode
    }

    fn set_mode(&self, mode: u32) -> Result<(), Errno> {
        let mut meta = self.meta.lock();
        meta.mode = (mode & 0o7777) | MODE_SET;
        meta.times[2] = now_timespec();
        Ok(())
    }

    fn times(&self) -> Option<[[i64; 2]; 3]> {
        Some(self.meta.lock().times)
    }

    fn set_times(&self, atime: Option<[i64; 2]>, mtime: Option<[i64; 2]>) -> Result<(), Errno> {
        let mut meta = self.meta.lock();
        if let Some(t) = atime {
            meta.times[0] = t;
        }
        if let Some(t) = mtime {
            meta.times[1] = t;
        }
        meta.times[2] = now_timespec();
        Ok(())
    }

    fn remove(&self, name: &str) -> Result<(), Errno> {
        let Node::Dir(entries) = &self.node else { return Err(Errno::ENOTDIR) };
        let mut entries = entries.lock();
        let node = entries.get(name).ok_or(Errno::ENOENT)?;
        if let Node::Dir(children) = &node.node {
            if !children.lock().is_empty() {
                return Err(Errno::ENOTEMPTY);
            }
        }
        entries.remove(name);
        Ok(())
    }
}