1use alloc::boxed::Box;
2use alloc::sync::Arc;
3use alloc::vec::Vec;
4use core::future::{self, Future};
5use core::mem::MaybeUninit;
6use core::task::Poll::{Pending, Ready};
7use core::time::Duration;
8
9use async_trait::async_trait;
10#[cfg(any(feature = "tcp", feature = "udp"))]
11use smoltcp::wire::{IpEndpoint, IpListenEndpoint};
12
13use crate::arch::kernel::core_local::core_scheduler;
14use crate::executor::block_on;
15use crate::fs::{DirectoryEntry, FileAttr, SeekWhence};
16use crate::io;
17
18mod eventfd;
19#[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
20pub(crate) mod socket;
21pub(crate) mod stdio;
22
23pub(crate) const STDIN_FILENO: FileDescriptor = 0;
24pub(crate) const STDOUT_FILENO: FileDescriptor = 1;
25pub(crate) const STDERR_FILENO: FileDescriptor = 2;
26
27#[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
28#[derive(Debug)]
29pub(crate) enum Endpoint {
30 #[cfg(any(feature = "tcp", feature = "udp"))]
31 Ip(IpEndpoint),
32 #[cfg(feature = "vsock")]
33 Vsock(socket::vsock::VsockEndpoint),
34}
35
36#[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
37#[derive(Debug)]
38pub(crate) enum ListenEndpoint {
39 #[cfg(any(feature = "tcp", feature = "udp"))]
40 Ip(IpListenEndpoint),
41 #[cfg(feature = "vsock")]
42 Vsock(socket::vsock::VsockListenEndpoint),
43}
44
45#[allow(dead_code)]
46#[derive(Debug, PartialEq)]
47pub(crate) enum SocketOption {
48 TcpNoDelay,
49}
50
51pub(crate) type FileDescriptor = i32;
52
53bitflags! {
54 #[derive(Debug, Copy, Clone, Default)]
56 pub struct OpenOption: i32 {
57 const O_RDONLY = 0o0000;
58 const O_WRONLY = 0o0001;
59 const O_RDWR = 0o0002;
60 const O_CREAT = 0o0100;
61 const O_EXCL = 0o0200;
62 const O_TRUNC = 0o1000;
63 const O_APPEND = StatusFlags::O_APPEND.bits();
64 const O_NONBLOCK = StatusFlags::O_NONBLOCK.bits();
65 const O_DIRECT = 0o40000;
66 const O_DIRECTORY = 0o200_000;
67 }
68}
69
70bitflags! {
71 #[derive(Debug, Copy, Clone, Default)]
73 pub struct StatusFlags: i32 {
74 const O_APPEND = 0o2000;
75 const O_NONBLOCK = 0o4000;
76 }
77}
78
79bitflags! {
80 #[derive(Debug, Copy, Clone, Default)]
81 pub struct PollEvent: i16 {
82 const POLLIN = 0x1;
83 const POLLPRI = 0x2;
84 const POLLOUT = 0x4;
85 const POLLERR = 0x8;
86 const POLLHUP = 0x10;
87 const POLLNVAL = 0x20;
88 const POLLRDNORM = 0x040;
89 const POLLRDBAND = 0x080;
90 const POLLWRNORM = 0x0100;
91 const POLLWRBAND = 0x0200;
92 const POLLRDHUP = 0x2000;
93 }
94}
95
96#[repr(C)]
97#[derive(Debug, Default, Copy, Clone)]
98pub struct PollFd {
99 pub fd: i32,
101 pub events: PollEvent,
103 pub revents: PollEvent,
105}
106
107bitflags! {
108 #[derive(Debug, Default, Copy, Clone)]
109 pub struct EventFlags: i16 {
110 const EFD_SEMAPHORE = 0o1;
111 const EFD_NONBLOCK = 0o4000;
112 const EFD_CLOEXEC = 0o40000;
113 }
114}
115
116bitflags! {
117 #[derive(Debug, Copy, Clone)]
118 pub struct AccessPermission: u32 {
119 const S_IFMT = 0o170_000;
120 const S_IFSOCK = 0o140_000;
121 const S_IFLNK = 0o120_000;
122 const S_IFREG = 0o100_000;
123 const S_IFBLK = 0o060_000;
124 const S_IFDIR = 0o040_000;
125 const S_IFCHR = 0o020_000;
126 const S_IFIFO = 0o010_000;
127 const S_IRUSR = 0o400;
128 const S_IWUSR = 0o200;
129 const S_IXUSR = 0o100;
130 const S_IRWXU = 0o700;
131 const S_IRGRP = 0o040;
132 const S_IWGRP = 0o020;
133 const S_IXGRP = 0o010;
134 const S_IRWXG = 0o070;
135 const S_IROTH = 0o004;
136 const S_IWOTH = 0o002;
137 const S_IXOTH = 0o001;
138 const S_IRWXO = 0o007;
139 const _ = !0;
141 }
142}
143
144impl Default for AccessPermission {
145 fn default() -> Self {
146 AccessPermission::from_bits(0o666).unwrap()
147 }
148}
149
150#[async_trait]
151pub(crate) trait ObjectInterface: Sync + Send + core::fmt::Debug {
152 async fn poll(&self, _event: PollEvent) -> io::Result<PollEvent> {
154 Ok(PollEvent::empty())
155 }
156
157 async fn read(&self, _buf: &mut [MaybeUninit<u8>]) -> io::Result<usize> {
160 Err(io::Error::ENOSYS)
161 }
162
163 async fn write(&self, _buf: &[u8]) -> io::Result<usize> {
166 Err(io::Error::ENOSYS)
167 }
168
169 async fn lseek(&self, _offset: isize, _whence: SeekWhence) -> io::Result<isize> {
171 Err(io::Error::EINVAL)
172 }
173
174 async fn fstat(&self) -> io::Result<FileAttr> {
176 Err(io::Error::EINVAL)
177 }
178
179 async fn readdir(&self) -> io::Result<Vec<DirectoryEntry>> {
183 Err(io::Error::EINVAL)
184 }
185
186 #[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
188 async fn accept(&self) -> io::Result<(Arc<dyn ObjectInterface>, Endpoint)> {
189 Err(io::Error::EINVAL)
190 }
191
192 #[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
194 async fn connect(&self, _endpoint: Endpoint) -> io::Result<()> {
195 Err(io::Error::EINVAL)
196 }
197
198 #[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
200 async fn bind(&self, _name: ListenEndpoint) -> io::Result<()> {
201 Err(io::Error::EINVAL)
202 }
203
204 #[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
206 async fn listen(&self, _backlog: i32) -> io::Result<()> {
207 Err(io::Error::EINVAL)
208 }
209
210 #[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
212 async fn setsockopt(&self, _opt: SocketOption, _optval: bool) -> io::Result<()> {
213 Err(io::Error::ENOTSOCK)
214 }
215
216 #[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
218 async fn getsockopt(&self, _opt: SocketOption) -> io::Result<bool> {
219 Err(io::Error::ENOTSOCK)
220 }
221
222 #[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
224 async fn getsockname(&self) -> io::Result<Option<Endpoint>> {
225 Ok(None)
226 }
227
228 #[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
230 #[allow(dead_code)]
231 async fn getpeername(&self) -> io::Result<Option<Endpoint>> {
232 Ok(None)
233 }
234
235 #[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
237 async fn recvfrom(&self, _buffer: &mut [MaybeUninit<u8>]) -> io::Result<(usize, Endpoint)> {
238 Err(io::Error::ENOSYS)
239 }
240
241 #[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
249 async fn sendto(&self, _buffer: &[u8], _endpoint: Endpoint) -> io::Result<usize> {
250 Err(io::Error::ENOSYS)
251 }
252
253 #[cfg(any(feature = "tcp", feature = "udp", feature = "vsock"))]
255 async fn shutdown(&self, _how: i32) -> io::Result<()> {
256 Err(io::Error::ENOSYS)
257 }
258
259 async fn status_flags(&self) -> io::Result<StatusFlags> {
261 Err(io::Error::ENOSYS)
262 }
263
264 async fn set_status_flags(&self, _status_flags: StatusFlags) -> io::Result<()> {
266 Err(io::Error::ENOSYS)
267 }
268
269 async fn isatty(&self) -> io::Result<bool> {
271 Ok(false)
272 }
273
274 #[cfg(any(feature = "tcp", feature = "udp"))]
276 async fn inet_domain(&self) -> io::Result<i32> {
277 Err(io::Error::EINVAL)
278 }
279}
280
281pub(crate) fn read(fd: FileDescriptor, buf: &mut [MaybeUninit<u8>]) -> io::Result<usize> {
282 let obj = get_object(fd)?;
283
284 if buf.is_empty() {
285 return Ok(0);
286 }
287
288 block_on(obj.read(buf), None)
289}
290
291pub(crate) fn lseek(fd: FileDescriptor, offset: isize, whence: SeekWhence) -> io::Result<isize> {
292 let obj = get_object(fd)?;
293
294 block_on(obj.lseek(offset, whence), None)
295}
296
297pub(crate) fn write(fd: FileDescriptor, buf: &[u8]) -> io::Result<usize> {
298 let obj = get_object(fd)?;
299
300 if buf.is_empty() {
301 return Ok(0);
302 }
303
304 block_on(obj.write(buf), None)
305}
306
307async fn poll_fds(fds: &mut [PollFd]) -> io::Result<u64> {
308 future::poll_fn(|cx| {
309 let mut counter: u64 = 0;
310
311 for i in &mut *fds {
312 let fd = i.fd;
313 i.revents = PollEvent::empty();
314 let mut pinned_obj = core::pin::pin!(core_scheduler().get_object(fd));
315 if let Ready(Ok(obj)) = pinned_obj.as_mut().poll(cx) {
316 let mut pinned = core::pin::pin!(obj.poll(i.events));
317 if let Ready(Ok(e)) = pinned.as_mut().poll(cx) {
318 if !e.is_empty() {
319 counter += 1;
320 i.revents = e;
321 }
322 }
323 }
324 }
325
326 if counter > 0 {
327 Ready(Ok(counter))
328 } else {
329 Pending
330 }
331 })
332 .await
333}
334
335pub fn poll(fds: &mut [PollFd], timeout: Option<Duration>) -> io::Result<u64> {
342 let result = block_on(poll_fds(fds), timeout);
343 if let Err(ref e) = result {
344 if timeout.is_some() {
345 if *e == io::Error::EAGAIN {
347 return Ok(0);
348 }
349 }
350 }
351
352 result
353}
354
355pub fn fstat(fd: FileDescriptor) -> io::Result<FileAttr> {
356 let obj = get_object(fd)?;
357 block_on(obj.fstat(), None)
358}
359
360pub fn eventfd(initval: u64, flags: EventFlags) -> io::Result<FileDescriptor> {
379 let obj = self::eventfd::EventFd::new(initval, flags);
380
381 let fd = block_on(core_scheduler().insert_object(Arc::new(obj)), None)?;
382
383 Ok(fd)
384}
385
386pub(crate) fn get_object(fd: FileDescriptor) -> io::Result<Arc<dyn ObjectInterface>> {
387 block_on(core_scheduler().get_object(fd), None)
388}
389
390pub(crate) fn insert_object(obj: Arc<dyn ObjectInterface>) -> io::Result<FileDescriptor> {
391 block_on(core_scheduler().insert_object(obj), None)
392}
393
394pub(crate) fn dup_object(fd: FileDescriptor) -> io::Result<FileDescriptor> {
399 block_on(core_scheduler().dup_object(fd), None)
400}
401
402pub(crate) fn dup_object2(fd1: FileDescriptor, fd2: FileDescriptor) -> io::Result<FileDescriptor> {
403 block_on(core_scheduler().dup_object2(fd1, fd2), None)
404}
405
406pub(crate) fn remove_object(fd: FileDescriptor) -> io::Result<Arc<dyn ObjectInterface>> {
407 block_on(core_scheduler().remove_object(fd), None)
408}
409
410pub(crate) fn isatty(fd: FileDescriptor) -> io::Result<bool> {
411 let obj = get_object(fd)?;
412 block_on(obj.isatty(), None)
413}