RustForge

rust-kernel

Rustbelt: a hobby x86_64 kernel written in Rust

rust-kernel / src / fs / ramfs.rs
11893 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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
//! 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).
//! Stage 17 adds symlinks, hard links (two directory entries holding the
//! same `Arc`), owners (chown) and renames that just move the `Arc`.

use super::{now_timespec, DirEntry, FileSystem, Inode, InodeKind, StatFs, MODE_SET, RAMFS_MAGIC};
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()
    }
    /// A ramfs can grow until memory runs out, so that's its "size" (Linux's
    /// ramfs says 0 for everything; numbers are friendlier to `df`).
    fn statfs(&self) -> StatFs {
        let (total, free) = crate::memory::frame_totals();
        StatFs {
            magic: RAMFS_MAGIC,
            block_size: 4096,
            blocks: total,
            free_blocks: free,
            avail_blocks: free,
            files: total,
            free_files: free,
            name_max: 255,
            read_only: false,
        }
    }
}

pub enum Node {
    File(Mutex<Vec<u8>>),
    Dir(Mutex<BTreeMap<String, Arc<RamInode>>>),
    /// A symlink's target (stage 17).
    Symlink(String),
}

/// 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],
    /// Owner and group (stage 17: chown; new files get the creator's).
    uid: u32,
    gid: u32,
    /// Directory entries naming this node (hard links; directories count
    /// their subdirectories' ".." on top, see `nlink`).
    links: u32,
}

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], uid: 0, gid: 0, links: 1 }) }
    }

    fn entries(&self) -> Result<&Mutex<BTreeMap<String, Arc<RamInode>>>, Errno> {
        match &self.node {
            Node::Dir(entries) => Ok(entries),
            _ => Err(Errno::ENOTDIR),
        }
    }

    /// A directory entry pointing at `node` went away.
    fn unlinked(node: &RamInode) {
        let mut meta = node.meta.lock();
        meta.links = meta.links.saturating_sub(1);
        meta.times[2] = now_timespec();
    }

    /// The status-change time (ctime) is now.
    fn changed(&self) {
        self.meta.lock().times[2] = now_timespec();
    }

    /// 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,
            Node::Symlink(_) => InodeKind::Symlink,
        }
    }

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

    fn readlink(&self) -> Result<String, Errno> {
        match &self.node {
            Node::Symlink(target) => Ok(target.clone()),
            _ => Err(Errno::EINVAL),
        }
    }

    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) };
        check_name(name)?;
        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), // symlinks: `symlink`
        }));
        entries.insert(String::from(name), node.clone());
        drop(entries);
        self.touch();
        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(), ino: node.ino_number() }).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);
            }
        }
        if let Some(node) = entries.remove(name) {
            Self::unlinked(&node);
        }
        drop(entries);
        self.touch();
        Ok(())
    }

    // --- stage 17 ----------------------------------------------------------

    fn ino(&self) -> Option<u64> {
        Some(self.ino_number())
    }

    fn nlink(&self) -> Option<u64> {
        let links = self.meta.lock().links as u64;
        Some(match &self.node {
            // "." plus each subdirectory's ".." (like a disk file system)
            Node::Dir(entries) => links + 1 + entries.lock().values().filter(|n| matches!(n.node, Node::Dir(_))).count() as u64,
            _ => links,
        })
    }

    fn owner(&self) -> (u32, u32) {
        let meta = self.meta.lock();
        (meta.uid, meta.gid)
    }

    fn set_owner(&self, uid: Option<u32>, gid: Option<u32>) -> Result<(), Errno> {
        let mut meta = self.meta.lock();
        if let Some(uid) = uid {
            meta.uid = uid;
        }
        if let Some(gid) = gid {
            meta.gid = gid;
        }
        meta.times[2] = now_timespec();
        Ok(())
    }

    fn symlink(&self, name: &str, target: &str) -> Result<Arc<dyn Inode>, Errno> {
        check_name(name)?;
        let mut entries = self.entries()?.lock();
        if entries.contains_key(name) {
            return Err(Errno::EEXIST);
        }
        let node = Arc::new(RamInode::new(Node::Symlink(String::from(target))));
        entries.insert(String::from(name), node.clone());
        drop(entries);
        self.touch();
        Ok(node)
    }

    fn link(&self, name: &str, target: &Arc<dyn Inode>) -> Result<(), Errno> {
        check_name(name)?;
        let node = super::downcast::<RamInode>(target).ok_or(Errno::EXDEV)?;
        let mut entries = self.entries()?.lock();
        if entries.contains_key(name) {
            return Err(Errno::EEXIST);
        }
        {
            let mut meta = node.meta.lock();
            meta.links += 1;
            meta.times[2] = now_timespec();
        }
        entries.insert(String::from(name), node);
        drop(entries);
        self.touch();
        Ok(())
    }

    /// Move the `Arc` from one map to the other. With two directories, the
    /// two locks are taken in address order, so two renames going opposite
    /// ways can't each hold one lock and wait for the other.
    fn rename_entry(&self, old: &str, new_dir: &Arc<dyn Inode>, new: &str) -> Result<(), Errno> {
        check_name(new)?;
        let target = super::downcast::<RamInode>(new_dir).ok_or(Errno::EXDEV)?;
        let same = core::ptr::eq(self, &*target);
        let (src, dst) = (self.entries()?, target.entries()?);
        let replaced;
        if same {
            let mut map = src.lock();
            let node = map.remove(old).ok_or(Errno::ENOENT)?;
            replaced = map.insert(String::from(new), node);
        } else {
            let self_first = (self as *const RamInode) < Arc::as_ptr(&target);
            let (mut a, mut b) = if self_first {
                let a = src.lock();
                (a, dst.lock())
            } else {
                let b = dst.lock();
                (src.lock(), b)
            };
            let node = a.remove(old).ok_or(Errno::ENOENT)?;
            node.changed();
            replaced = b.insert(String::from(new), node);
        }
        if let Some(gone) = replaced {
            Self::unlinked(&gone);
        }
        self.touch();
        target.touch();
        Ok(())
    }

    fn as_any(self: Arc<Self>) -> Option<Arc<dyn core::any::Any + Send + Sync>> {
        Some(self)
    }
}

impl RamInode {
    /// Inode number: the node's address (unique while it exists).
    fn ino_number(&self) -> u64 {
        self as *const RamInode as u64
    }
}

fn check_name(name: &str) -> Result<(), Errno> {
    match name {
        "" | "." | ".." => Err(Errno::EINVAL),
        _ if name.contains('/') => Err(Errno::EINVAL),
        _ if name.len() > 255 => Err(Errno::ENAMETOOLONG),
        _ => Ok(()),
    }
}