Skip to main content

dope_uring/raw/
mod.rs

1mod create;
2mod open;
3mod source;
4
5use std::{
6    mem,
7    num::NonZero,
8    os::fd::{AsFd, AsRawFd as _, BorrowedFd, OwnedFd},
9    ptr,
10};
11
12use dope_sys::{
13    Errno,
14    io::{
15        fd,
16        file::{self, metadata, watch::Event},
17        pipe,
18        reactor::{complete, submit},
19        socket::addr,
20    },
21    kernel,
22};
23use o3::{alloc::BoxArrayExt as _, base::marker::ThreadBound};
24
25use crate::{
26    Backend,
27    reactor::{op::sockets, sq},
28};
29
30#[repr(transparent)]
31pub struct Metadata(pub(crate) mem::MaybeUninit<libc::statx>);
32
33impl Metadata {
34    pub const UNINIT: Self = Self(mem::MaybeUninit::uninit());
35    pub(crate) const MASK: u32 = libc::STATX_TYPE | libc::STATX_SIZE;
36
37    /// # Safety
38    /// A successful native operation initialized this output and ended access.
39    pub unsafe fn try_result(
40        &self,
41    ) -> Result<(file::Kind, file::Offset, Option<metadata::Identity>), metadata::Error> {
42        // SAFETY: the successful native writer initialized the complete statx.
43        let raw = unsafe { self.0.assume_init_ref() };
44        if let Some(missing) = NonZero::new(Self::MASK & !raw.stx_mask) {
45            return Err(metadata::Error::Missing(missing));
46        }
47        let size =
48            file::Offset::new(raw.stx_size).ok_or(metadata::Error::Overflow(raw.stx_size))?;
49        let identity = (raw.stx_mask & libc::STATX_INO != 0).then_some(metadata::Identity {
50            device: libc::makedev(raw.stx_dev_major, raw.stx_dev_minor),
51            inode: raw.stx_ino,
52        });
53        Ok((file::Kind::from_mode(raw.stx_mode.into()), size, identity))
54    }
55}
56
57const _: () = {
58    assert!(mem::size_of::<Metadata>() == 256);
59    assert!(mem::align_of::<Metadata>() == 8);
60};
61
62pub(crate) fn pipe(flags: libc::c_int) -> Result<(OwnedFd, OwnedFd), pipe::Error> {
63    let mut fds = mem::MaybeUninit::<[OwnedFd; 2]>::uninit();
64    // SAFETY: OwnedFd has RawFd's representation. Zero transfers both new descriptors.
65    unsafe {
66        let status = libc::pipe2(fds.as_mut_ptr().cast(), flags);
67        kernel::raw::Status::new(status)
68            .try_zero::<Backend, Errno>()
69            .map_err(pipe::Error::Open)?;
70        Ok(fds.assume_init().into())
71    }
72}
73
74/// Transfers an anonymous writable mapping, including a successful null address.
75pub(crate) fn try_map<const FLAGS: libc::c_int>(
76    bytes: NonZero<usize>,
77) -> Result<*mut libc::c_void, Errno> {
78    const { assert!(FLAGS & !libc::MAP_NORESERVE == 0) };
79    // SAFETY: mmap validates this nonempty anonymous mapping request.
80    let address = unsafe {
81        libc::mmap(
82            ptr::null_mut(),
83            bytes.get(),
84            libc::PROT_READ | libc::PROT_WRITE,
85            libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | FLAGS,
86            -1,
87            0,
88        )
89    };
90    if address == libc::MAP_FAILED {
91        // SAFETY: mmap just failed on this thread without an intervening call.
92        Err(unsafe { kernel::raw::Code::last::<Backend>().into() })
93    } else {
94        Ok(address)
95    }
96}
97
98/// # Safety
99/// `address` and `bytes` name one complete live mapping owned by the caller.
100/// Success consumes the mapping; failure leaves ownership with the caller.
101pub(crate) unsafe fn try_unmap<E: From<Errno>>(
102    address: *mut libc::c_void,
103    bytes: NonZero<usize>,
104) -> Result<(), E> {
105    // SAFETY: this complete live mapping belongs to the caller; munmap returns zero or -1.
106    unsafe { kernel::raw::Status::new(libc::munmap(address, bytes.get())).try_zero::<Backend, E>() }
107}
108
109/// A deferred request whose host retains every encoded address.
110#[derive(Debug)]
111pub struct Deferred {
112    slot: sq::Fixed,
113    address: *const (),
114    length: addr::Socklen,
115    _thread: ThreadBound,
116}
117
118impl Deferred {
119    /// # Safety
120    /// Retain the address through completion or until this unsubmitted connect is dropped.
121    pub unsafe fn new(slot: sq::Fixed, address: addr::Addr<'_>) -> Self {
122        let (address, length) = address.parts();
123        Self {
124            slot,
125            address,
126            length,
127            _thread: ThreadBound::NEW,
128        }
129    }
130
131    pub(crate) fn submit<T: complete::raw::Token>(
132        self,
133        vacancy: sq::raw::Vacancy<'_, T>,
134        token: T,
135    ) {
136        let mut entry = sq::Entry::new(sockets::CONNECT, sq::Descriptor::Fixed(self.slot));
137        let fields = entry.fields();
138        fields.command.address = self.address as u64;
139        fields.command.offset = (self.length.get() as u64).to_ne_bytes();
140        // SAFETY: construction retained this address through completion.
141        unsafe { submit::raw::Vacancy::push(vacancy, sq::Borrowed::new(entry), token) };
142    }
143}
144
145const CAPACITY: usize = 32 * 1024;
146
147pub struct Stream {
148    file: OwnedFd,
149    buffer: Box<[mem::MaybeUninit<u8>; CAPACITY]>,
150    offset: usize,
151    filled: usize,
152    _thread: ThreadBound,
153}
154
155#[repr(transparent)]
156pub struct Watch {
157    file: OwnedFd,
158    thread: ThreadBound,
159}
160
161impl Watch {
162    /// Observes moved-in entries and invalidation of one fixed directory.
163    pub fn try_new(path: &std::ffi::CStr) -> Result<Self, Errno> {
164        // SAFETY: init transfers one descriptor or leaves this thread's errno.
165        let file = unsafe {
166            <OwnedFd as fd::raw::Adopt>::try_adopt::<Backend, Errno>(libc::inotify_init1(
167                libc::IN_NONBLOCK | libc::IN_CLOEXEC,
168            ))
169        }?;
170        // SAFETY: the descriptor and terminated path stay live for this one registration.
171        let raw = unsafe {
172            libc::inotify_add_watch(
173                file.as_raw_fd(),
174                path.as_ptr(),
175                libc::IN_MOVED_TO
176                    | libc::IN_MOVE_SELF
177                    | libc::IN_DELETE_SELF
178                    | libc::IN_ONLYDIR
179                    | libc::IN_DONT_FOLLOW,
180            )
181        };
182        // SAFETY: add_watch returns a nonnegative watch id or -1 with unchanged errno.
183        unsafe { kernel::raw::Status::new(raw).try_value::<Backend, Errno>() }?;
184        Ok(Self {
185            file,
186            thread: ThreadBound::NEW,
187        })
188    }
189}
190
191impl AsFd for Watch {
192    fn as_fd(&self) -> BorrowedFd<'_> {
193        self.file.as_fd()
194    }
195}
196
197pub struct Events<'a>(&'a [u8]);
198
199impl<'a> Iterator for Events<'a> {
200    type Item = Event<'a>;
201
202    fn next(&mut self) -> Option<Self::Item> {
203        if self.0.is_empty() {
204            return None;
205        }
206        const HEADER: usize = mem::size_of::<libc::inotify_event>();
207        // SAFETY: the retained native prefix consists of complete initialized records.
208        let event = unsafe {
209            self.0
210                .as_ptr()
211                .cast::<libc::inotify_event>()
212                .read_unaligned()
213        };
214        // SAFETY: the native length bounds this complete record within the admitted read.
215        let (record, rest) = unsafe { self.0.split_at_unchecked(HEADER + event.len as usize) };
216        self.0 = rest;
217        Some(match event.mask & !libc::IN_ISDIR {
218            libc::IN_MOVED_TO => Event::MovedIn(&record[HEADER..]),
219            libc::IN_Q_OVERFLOW => Event::Overflow,
220            // SAFETY: every admitted native record carries a nonzero event mask.
221            _ => Event::Invalidated(unsafe { NonZero::new_unchecked(event.mask) }),
222        })
223    }
224}
225
226// SAFETY: the stream exclusively owns its descriptor and buffer. Refilling only
227// writes the buffer after the previous Entry borrow has ended.
228// Watch owns its fixed descriptor; events retain the caller's admitted byte borrow.
229unsafe impl file::raw::Directory for Backend {
230    type Stream = Stream;
231    type Watch = Watch;
232    type Events<'a> = Events<'a>;
233
234    unsafe fn watch_events<'a>(_: &Self::Watch, bytes: &'a [u8]) -> Self::Events<'a> {
235        Events(bytes)
236    }
237
238    fn from_fd<E: From<Errno>>(file: OwnedFd) -> Result<Stream, file::OpenError<E>> {
239        Ok(Stream {
240            file,
241            buffer: Box::try_uninit().map_err(file::OpenError::Allocation)?,
242            offset: 0,
243            filled: 0,
244            _thread: ThreadBound::NEW,
245        })
246    }
247
248    fn descriptor(stream: &Stream) -> kernel::raw::Descriptor {
249        // SAFETY: the stream exclusively owns this live nonnegative descriptor.
250        unsafe { kernel::raw::Descriptor::new(stream.file.as_raw_fd()) }
251    }
252
253    fn next(stream: &mut Stream) -> Result<Option<file::Entry<'_>>, Errno> {
254        if stream.offset == stream.filled {
255            // SAFETY: the exclusively borrowed buffer supplies exactly CAPACITY
256            // writable bytes; getdents64 reports complete native directory records.
257            let result = unsafe {
258                libc::syscall(
259                    libc::SYS_getdents64,
260                    stream.file.as_raw_fd(),
261                    stream.buffer.as_mut_ptr(),
262                    CAPACITY,
263                )
264            };
265            // SAFETY: the exact syscall operand bounds every successful count by
266            // CAPACITY; failure leaves this thread's positive errno unchanged.
267            let count = unsafe {
268                kernel::raw::Status::from_count(result as libc::ssize_t).try_count::<Self, Errno>()
269            };
270            stream.filled = match count {
271                Ok(count) => count.get(),
272                Err(Errno::NOT_FOUND) => 0,
273                Err(error) => return Err(error),
274            };
275            stream.offset = 0;
276            if stream.filled == 0 {
277                return Ok(None);
278            }
279        }
280        // SAFETY: the completed batch retains this record's initialized native
281        // fields and terminated name. Each positive d_reclen advances to the next
282        // complete record or filled; the cursor cannot leave the completed batch.
283        // Padding remains MaybeUninit and is never read or exposed as bytes.
284        let pointer = unsafe {
285            stream
286                .buffer
287                .as_ptr()
288                .add(stream.offset)
289                .cast::<libc::dirent64>()
290        };
291        stream.offset += unsafe { (&raw const (*pointer).d_reclen).read_unaligned() } as usize;
292        let kind = unsafe { (&raw const (*pointer).d_type).read() };
293        let name = unsafe { std::ffi::CStr::from_ptr((&raw const (*pointer).d_name).cast()) };
294        Ok(Some(file::Entry {
295            name,
296            kind: file::Kind::from_dirent(kind),
297        }))
298    }
299}