RustForge

rust-kernel

Rustbelt: a hobby x86_64 kernel written in Rust

rust-kernel / src / dev.rs
9320 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
//! /dev: device files. (Unix's big idea: devices look like files, so `cat`,
//! `>` and every program that reads or writes files can use them.)
//!
//!   /dev/null      reads as empty, swallows writes
//!   /dev/random    random bytes (virtio-rng; /dev/urandom is the same --
//!   /dev/urandom   on modern Linux they only differ before boot-time seeding)
//!   /dev/console   the console terminal (keyboard + screen)
//!   /dev/hvc0      the virtio console: a second terminal
//!   /dev/tty       your controlling terminal, whichever it is (tty.rs)
//!   /dev/ptmx      opening it creates a pseudo-terminal: you get the
//!   /dev/pts/N     master end, and its slave end appears as /dev/pts/N
//!   /dev/fb0       the virtio-gpu framebuffer: pixels at byte offsets,
//!                  plus ioctls (see syscall.rs) for its size, flushing,
//!                  filling rectangles and moving the text console
//!
//! A tiny file system (`DevFs`) mounted at /dev lists them; opening one
//! gives a device-specific `File` (via `Inode::open_device`) instead of the
//! usual read-the-inode file. Linux does the same with "character device"
//! inodes whose `open` is routed to a driver.

use crate::errno::Errno;
use crate::fs::file::{File, KIND_DEVICE, SEEK_CUR, SEEK_END, SEEK_SET, Stat};
use crate::fs::{DirEntry, FileSystem, Inode, InodeKind};
use crate::tty;
use crate::virtio::{console, gpu, rng};
use alloc::{string::String, sync::Arc, vec::Vec};
use spin::Mutex;

pub struct DevFs;

impl FileSystem for DevFs {
    fn name(&self) -> &'static str {
        "devfs"
    }
    fn root(&self) -> Arc<dyn Inode> {
        Arc::new(DevDir)
    }
}

/// The devices that exist on this machine.
fn names() -> Vec<&'static str> {
    let mut names = alloc::vec!["console", "null", "ptmx", "pts", "random", "tty", "urandom"];
    if console::present() {
        names.push("hvc0");
    }
    if gpu::framebuffer().is_some() {
        names.push("fb0");
    }
    names.sort();
    names
}

struct DevDir;

impl Inode for DevDir {
    fn kind(&self) -> InodeKind {
        InodeKind::Directory
    }
    fn size(&self) -> usize {
        names().len()
    }
    fn lookup(&self, name: &str) -> Result<Arc<dyn Inode>, Errno> {
        let name = names().into_iter().find(|n| *n == name).ok_or(Errno::ENOENT)?;
        if name == "pts" {
            return Ok(Arc::new(PtsDir));
        }
        Ok(Arc::new(DevNode(name)))
    }
    fn list(&self) -> Result<Vec<DirEntry>, Errno> {
        let kind = |n| if n == "pts" { InodeKind::Directory } else { InodeKind::Device };
        Ok(names().into_iter().map(|n| DirEntry { name: String::from(n), kind: kind(n), ino: 0 }).collect())
    }
}

/// /dev/pts: one entry per pseudo-terminal (named by number).
struct PtsDir;

impl Inode for PtsDir {
    fn kind(&self) -> InodeKind {
        InodeKind::Directory
    }
    fn size(&self) -> usize {
        tty::pty_count()
    }
    fn lookup(&self, name: &str) -> Result<Arc<dyn Inode>, Errno> {
        let n: usize = name.parse().map_err(|_| Errno::ENOENT)?;
        if !tty::pty_numbers().contains(&n) {
            return Err(Errno::ENOENT);
        }
        Ok(Arc::new(PtsNode(n)))
    }
    fn list(&self) -> Result<Vec<DirEntry>, Errno> {
        Ok(tty::pty_numbers().into_iter().map(|n| DirEntry { name: alloc::format!("{}", n), kind: InodeKind::Device, ino: 0 }).collect())
    }
}

struct PtsNode(usize);

impl Inode for PtsNode {
    fn kind(&self) -> InodeKind {
        InodeKind::Device
    }
    fn size(&self) -> usize {
        0
    }
    fn mode(&self) -> u32 {
        0o620
    }
    fn open_device(&self) -> Result<Option<Arc<dyn File>>, Errno> {
        tty::open_pts(self.0).map(Some)
    }
}

/// One device's directory entry.
struct DevNode(&'static str);

impl Inode for DevNode {
    fn kind(&self) -> InodeKind {
        InodeKind::Device
    }
    fn size(&self) -> usize {
        match self.0 {
            "fb0" => gpu::framebuffer().map_or(0, |f| f.size_bytes()),
            _ => 0,
        }
    }
    fn mode(&self) -> u32 {
        0o666
    }
    fn open_device(&self) -> Result<Option<Arc<dyn File>>, Errno> {
        Ok(Some(match self.0 {
            "null" => Arc::new(Null),
            "random" | "urandom" => Arc::new(Random),
            "console" => tty::console_file(),
            "hvc0" => tty::open_hvc(),
            "tty" => tty::open_ctty()?,
            "ptmx" => tty::open_ptmx()?,
            "fb0" => Arc::new(Framebuffer::new(gpu::framebuffer().ok_or(Errno::ENODEV)?)),
            _ => return Ok(None),
        }))
    }
}

fn device_stat(size: usize) -> Result<Stat, Errno> {
    Ok(Stat { kind: KIND_DEVICE, size: size as u64, mode: 0o666 })
}

struct Null;

impl File for Null {
    fn read(&self, _buf: &mut [u8]) -> Result<usize, Errno> {
        Ok(0)
    }
    fn write(&self, buf: &[u8]) -> Result<usize, Errno> {
        Ok(buf.len())
    }
    fn stat(&self) -> Result<Stat, Errno> {
        device_stat(0)
    }
    fn proc_link(&self) -> Option<String> {
        Some(String::from("/dev/null"))
    }
}

struct Random;

impl File for Random {
    fn read(&self, buf: &mut [u8]) -> Result<usize, Errno> {
        let n = buf.len().min(65536);
        rng::fill(&mut buf[..n]);
        Ok(n)
    }
    /// Linux mixes written bytes into its pool; we have no pool, so we
    /// just accept them.
    fn write(&self, buf: &[u8]) -> Result<usize, Errno> {
        Ok(buf.len())
    }
    fn stat(&self) -> Result<Stat, Errno> {
        device_stat(0)
    }
    fn proc_link(&self) -> Option<String> {
        Some(String::from("/dev/urandom")) // (or /dev/random: the same device)
    }
}

/// /dev/fb0: the framebuffer as a file of `stride * height * 4` bytes.
/// Writing changes pixels in memory; they reach the screen on the FLUSH
/// ioctl or when the file is closed (we remember which rows changed).
pub struct Framebuffer {
    pub info: gpu::FbInfo,
    offset: Mutex<usize>,
    dirty: Mutex<Option<(u32, u32)>>, // pixel rows [first, last)
}

impl Framebuffer {
    fn new(info: gpu::FbInfo) -> Framebuffer {
        Framebuffer { info, offset: Mutex::new(0), dirty: Mutex::new(None) }
    }

    fn bytes(&self) -> &'static mut [u8] {
        unsafe { core::slice::from_raw_parts_mut(self.info.base as *mut u8, self.info.size_bytes()) }
    }

    /// Remember that pixel rows [y0, y1) changed.
    pub fn mark_dirty(&self, y0: u32, y1: u32) {
        let mut dirty = self.dirty.lock();
        *dirty = Some(match *dirty {
            Some((a, b)) => (a.min(y0), b.max(y1)),
            None => (y0, y1),
        });
    }

    /// Send the changed rows to the screen.
    pub fn flush(&self) -> bool {
        match self.dirty.lock().take() {
            Some((y0, y1)) => gpu::flush(0, y0, self.info.width, y1 - y0),
            None => true,
        }
    }

    /// Fill a rectangle with one colour (clipped to the screen).
    pub fn fill(&self, x: u32, y: u32, w: u32, h: u32, color: u32) {
        let (x0, y0) = (x.min(self.info.width), y.min(self.info.height));
        let (x1, y1) = (x.saturating_add(w).min(self.info.width), y.saturating_add(h).min(self.info.height));
        for row in y0..y1 {
            let start = (row * self.info.stride) as usize;
            let line = unsafe { core::slice::from_raw_parts_mut(self.info.pixels().add(start), self.info.width as usize) };
            line[x0 as usize..x1 as usize].fill(color);
        }
        if y1 > y0 {
            self.mark_dirty(y0, y1);
        }
    }
}

impl File for Framebuffer {
    fn read(&self, buf: &mut [u8]) -> Result<usize, Errno> {
        let mut offset = self.offset.lock();
        let src = self.bytes();
        let n = buf.len().min(src.len().saturating_sub(*offset));
        buf[..n].copy_from_slice(&src[*offset..*offset + n]);
        *offset += n;
        Ok(n)
    }
    fn write(&self, buf: &[u8]) -> Result<usize, Errno> {
        let mut offset = self.offset.lock();
        let dst = self.bytes();
        if *offset >= dst.len() && !buf.is_empty() {
            return Err(Errno::ENOSPC); // past the end of the screen
        }
        let n = buf.len().min(dst.len() - *offset);
        dst[*offset..*offset + n].copy_from_slice(&buf[..n]);
        let row_bytes = self.info.stride as usize * 4;
        if n > 0 {
            self.mark_dirty((*offset / row_bytes) as u32, ((*offset + n - 1) / row_bytes + 1) as u32);
        }
        *offset += n;
        Ok(n)
    }
    fn seek(&self, offset: i64, whence: u64) -> Result<u64, Errno> {
        let mut pos = self.offset.lock();
        let base = match whence {
            SEEK_SET => 0,
            SEEK_CUR => *pos as i64,
            SEEK_END => self.info.size_bytes() as i64,
            _ => return Err(Errno::EINVAL),
        };
        let new = base.checked_add(offset).filter(|&p| p >= 0).ok_or(Errno::EINVAL)?;
        *pos = new as usize;
        Ok(new as u64)
    }
    fn stat(&self) -> Result<Stat, Errno> {
        device_stat(self.info.size_bytes())
    }
    fn proc_link(&self) -> Option<String> {
        Some(String::from("/dev/fb0"))
    }
    fn as_framebuffer(&self) -> Option<&Framebuffer> {
        Some(self)
    }
}

impl Drop for Framebuffer {
    fn drop(&mut self) {
        self.flush(); // like close() on Linux's deferred-io framebuffers
    }
}