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