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
use alloc::{sync::Arc, vec::Vec};
use core::{any::Any, task::Context};
use ax_fs::CachedFile;
use ax_memory_addr::{PhysAddr, PhysAddrRange};
use axfs_ng_vfs::{
DeviceId, FileNodeOps, FilesystemOps, Metadata, MetadataUpdate, NodeFlags, NodeOps,
NodePermission, NodeType, VfsError, VfsResult,
};
use axpoll::{IoEvents, Pollable};
use inherit_methods_macro::inherit_methods;
use super::{SimpleFs, SimpleFsNode};
/// Mmap behavior for devices.
#[derive(Clone)]
pub enum DeviceMmap {
/// The device is not mappable (→ ENODEV, matches Linux).
None,
/// Maps to a physical address range. The optional retainer keeps
/// driver-owned backing pages alive for as long as any VMA built
/// from this mapping exists — pinned by the resulting
/// [`LinearBackend`] so userspace can't observe freed memory if
/// the device drops the buffer before munmap.
Physical(PhysAddrRange, Option<Arc<dyn Any + Send + Sync>>),
/// Maps to an already offset-resolved physical address range.
///
/// This is for file descriptors whose mmap offset is a selector rather than
/// a byte offset into a linear device, such as io_uring ring offsets.
PhysicalResolved(PhysAddrRange, Option<Arc<dyn Any + Send + Sync>>),
/// Maps to an explicit physical page list for this exact mmap request.
/// The producer has already applied the requested offset and length, so
/// mmap callers must map these pages in order without adding the offset
/// again. This covers layouts that are not a single contiguous physical
/// range, such as BPF ringbuf maps that expose mirrored data pages.
PhysicalPages(Vec<PhysAddr>, Option<Arc<dyn Any + Send + Sync>>),
/// Maps to a cached file.
Cache(CachedFile),
}
/// Trait for device operations.
pub trait DeviceOps: Send + Sync {
/// Reads data from the device at the specified offset.
fn read_at(&self, buf: &mut [u8], offset: u64) -> VfsResult<usize>;
/// Writes data to the device at the specified offset.
fn write_at(&self, buf: &[u8], offset: u64) -> VfsResult<usize>;
/// Manipulates the underlying device parameters of special files.
fn ioctl(&self, _cmd: u32, _arg: usize) -> VfsResult<usize> {
Err(VfsError::NotATty)
}
/// Casts the device operations to a dynamic type.
fn as_any(&self) -> &dyn Any;
/// Casts the device operations to a [`Pollable`].
fn as_pollable(&self) -> Option<&dyn Pollable> {
None
}
/// Returns the memory mapping behavior of the device for the given offset.
///
/// # Arguments
/// * `offset` - The offset from the start of the device
/// * `length` - The length of the mapping
fn mmap(&self, _offset: u64, _length: u64) -> DeviceMmap {
DeviceMmap::None
}
/// Returns the flags for the device node.
fn flags(&self) -> NodeFlags {
NodeFlags::empty()
}
/// Called when the device is opened. `exclusive` is true if O_EXCL was set.
fn open(&self, _exclusive: bool) -> VfsResult<()> {
Ok(())
}
/// Called when the last file descriptor to this device is closed.
fn close(&self, _exclusive: bool) {}
}
/// A device node in the filesystem.
pub struct Device {
node: SimpleFsNode,
ops: Arc<dyn DeviceOps>,
}
impl Device {
/// Creates a new device.
pub fn new(
fs: Arc<SimpleFs>,
node_type: NodeType,
device_id: DeviceId,
ops: Arc<dyn DeviceOps>,
) -> Arc<Self> {
let node = SimpleFsNode::new(fs, node_type, NodePermission::default());
node.metadata.lock().rdev = device_id;
Arc::new(Self { node, ops })
}
/// Returns the inner device operations.
pub fn inner(&self) -> &Arc<dyn DeviceOps> {
&self.ops
}
/// Updates the device ID.
pub fn set_device_id(&self, device_id: DeviceId) {
self.node.metadata.lock().rdev = device_id;
}
/// Returns the memory mapping behavior of the device for the given offset.
pub fn mmap(&self, offset: u64, length: u64) -> DeviceMmap {
self.ops.mmap(offset, length)
}
}
#[inherit_methods(from = "self.node")]
impl NodeOps for Device {
fn inode(&self) -> u64;
fn metadata(&self) -> VfsResult<Metadata>;
fn update_metadata(&self, update: MetadataUpdate) -> VfsResult<()>;
fn filesystem(&self) -> &dyn FilesystemOps;
fn sync(&self, _data_only: bool) -> VfsResult<()> {
Err(VfsError::InvalidInput)
}
fn into_any(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> {
self
}
fn len(&self) -> VfsResult<u64> {
Ok(0)
}
fn flags(&self) -> NodeFlags {
self.ops.flags()
}
}
impl FileNodeOps for Device {
fn read_at(&self, buf: &mut [u8], offset: u64) -> VfsResult<usize> {
self.ops.read_at(buf, offset)
}
fn write_at(&self, buf: &[u8], offset: u64) -> VfsResult<usize> {
self.ops.write_at(buf, offset)
}
fn append(&self, _buf: &[u8]) -> VfsResult<(usize, u64)> {
Err(VfsError::NotATty)
}
fn set_len(&self, _len: u64) -> VfsResult<()> {
// If can write...
if self.write_at(b"", 0).is_ok() {
Ok(())
} else {
Err(VfsError::BadFileDescriptor)
}
}
fn set_symlink(&self, _target: &str) -> VfsResult<()> {
Err(VfsError::BadFileDescriptor)
}
fn ioctl(&self, cmd: u32, arg: usize) -> VfsResult<usize> {
self.ops.ioctl(cmd, arg)
}
}
impl Pollable for Device {
fn poll(&self) -> IoEvents {
if let Some(pollable) = self.ops.as_pollable() {
pollable.poll()
} else {
IoEvents::IN | IoEvents::OUT
}
}
fn register(&self, context: &mut Context<'_>, events: IoEvents) {
if let Some(pollable) = self.ops.as_pollable() {
pollable.register(context, events);
}
}
}