Skip to main content

dope_uring/reactor/sq/
raw.rs

1use std::{marker, mem, ops, ptr, sync::atomic};
2
3use dope_sys::{
4    io::{
5        reactor::{Full, complete, submit},
6        socket::{addr, option, option::tuning},
7    },
8    kernel,
9};
10use o3::{
11    base::{marker::ThreadBound, num::bounded},
12    depot::capacity,
13};
14
15use crate::{
16    error,
17    reactor::{op::sockets, ring, sq},
18};
19
20/// A deferred request whose host retains every encoded address.
21#[derive(Debug)]
22pub struct Deferred {
23    slot: sq::Fixed,
24    address: *const (),
25    length: addr::Socklen,
26    _thread: ThreadBound,
27}
28
29impl Deferred {
30    /// # Safety
31    /// Retain the address through completion or until this unsubmitted connect is dropped.
32    pub unsafe fn new(slot: sq::Fixed, address: addr::Addr<'_>) -> Self {
33        let (address, length) = address.parts();
34        Self {
35            slot,
36            address,
37            length,
38            _thread: ThreadBound::NEW,
39        }
40    }
41
42    pub(super) fn into_parts(self) -> (sq::Fixed, *const (), addr::Socklen) {
43        (self.slot, self.address, self.length)
44    }
45}
46
47pub struct Queue<'a, T>(&'a mut State, marker::PhantomData<fn(T) -> T>);
48
49#[must_use = "reserved submission capacity must be prepared or released"]
50pub struct Vacancy<'queue, T>(&'queue mut State, marker::PhantomData<fn(T) -> T>);
51
52#[must_use = "reserved submission capacity must be initialized or released"]
53pub struct Reservation<'queue, T, const N: usize> {
54    queue: Queue<'queue, T>,
55    count: capacity::Limit<N>,
56}
57
58#[must_use = "prepared submission entries must be pushed or released"]
59pub struct Prepared<'queue, 'entries, E, const N: usize> {
60    state: &'queue mut State,
61    entries: ptr::NonNull<E>,
62    count: capacity::Limit<N>,
63    lifetime: marker::PhantomData<&'entries [E]>,
64}
65
66#[derive(Clone, Copy, Eq, PartialEq)]
67#[repr(transparent)]
68pub(crate) struct Word(u64);
69
70impl Word {
71    pub(crate) fn encode<T: complete::raw::Token>(token: T) -> Self {
72        const { assert!(mem::size_of::<T>() == mem::size_of::<u64>()) };
73        const { assert!(mem::align_of::<T>() <= mem::align_of::<u64>()) };
74        // SAFETY: the trait contract proves the source is eight initialized bytes.
75        Self(unsafe { ptr::from_ref(&token).cast::<u64>().read_unaligned() })
76    }
77
78    pub(crate) fn decode<T: complete::raw::Token>(self) -> T {
79        const { assert!(mem::size_of::<T>() == mem::size_of::<u64>()) };
80        const { assert!(mem::align_of::<T>() <= mem::align_of::<u64>()) };
81        // SAFETY: the trait contract admits every 64-bit representation.
82        unsafe { ptr::from_ref(&self.0).cast::<T>().read_unaligned() }
83    }
84
85    pub(crate) const fn new(raw: u64) -> Self {
86        Self(raw)
87    }
88
89    pub(crate) const fn get(self) -> u64 {
90        self.0
91    }
92}
93
94const _: () = {
95    assert!(mem::size_of::<Word>() == mem::size_of::<u64>());
96    assert!(mem::align_of::<Word>() == mem::align_of::<u64>());
97};
98
99#[derive(Debug)]
100struct Cursor {
101    head: u32,
102    tail: u32,
103    published_tail: u32,
104}
105
106#[derive(Debug)]
107pub(crate) struct State {
108    head: ptr::NonNull<atomic::AtomicU32>,
109    tail: ptr::NonNull<atomic::AtomicU32>,
110    flags: ptr::NonNull<atomic::AtomicU32>,
111    entries: ptr::NonNull<sq::Entry>,
112    axis: ring::Axis,
113    cursor: Cursor,
114}
115
116impl<'queue, T> Queue<'queue, T> {
117    pub(crate) const fn new(state: &'queue mut State) -> Self {
118        Self(state, marker::PhantomData)
119    }
120
121    pub(crate) fn try_acquire_pending(self) -> Result<Vacancy<'queue, T>, sq::Pending> {
122        // SAFETY: construction binds this atomic to the live ring mapping.
123        let head = unsafe { self.0.head.as_ref() }.load(atomic::Ordering::Acquire);
124        let pending = self.0.cursor.tail.wrapping_sub(head);
125        if pending == self.0.axis.entries().get() {
126            return Err(sq::Pending::from_raw(pending));
127        }
128        self.0.cursor.head = head;
129        Ok(Vacancy(self.0, marker::PhantomData))
130    }
131
132    /// Retains this queue through the commit decision; Idle proves zero pending SQEs.
133    /// The exclusive owner and nonzero ring size preserve its first vacancy.
134    pub(crate) fn try_idle(
135        self,
136        binding: ring::ffi::Binding<'queue>,
137    ) -> Result<Option<Vacancy<'queue, T>>, kernel::Errno<error::Enter>> {
138        use dope_sys::ring::enter::{Enter as _, Progress};
139
140        let progress = ring::Enter::<T>::new(&mut *self.0, binding).try_commit()?;
141        Ok(match progress {
142            Progress::Idle => Some(Vacancy(self.0, marker::PhantomData)),
143            Progress::Entered => None,
144        })
145    }
146}
147
148impl<'queue, T: complete::raw::Token> submit::Queue<'queue, T> for Queue<'queue, T> {
149    type Owned = sq::Owned<T>;
150    type Vacancy = Vacancy<'queue, T>;
151    type Reserved<const N: usize> = Reservation<'queue, T, N>;
152    type Prepared<'e, E: 'e, const N: usize> = Prepared<'queue, 'e, E, N>;
153
154    /// Publishes every locally appended SQE and refreshes the cached kernel
155    /// head. Normal submission does this through `Ring::enter`; callers only
156    /// need this method when retrying a locally full queue without entering.
157    fn refresh(&mut self) {
158        self.0.publish();
159    }
160
161    fn len(&self) -> bounded::U32<0, { u32::MAX }> {
162        self.0.pending().into()
163    }
164
165    fn is_empty(&self) -> bool {
166        self.0.is_empty()
167    }
168
169    fn try_one(self) -> Result<Vacancy<'queue, T>, Full> {
170        if !self.0.has_capacity(capacity::Limit::<1>::fixed::<1>()) {
171            return Err(Full);
172        }
173        Ok(Vacancy(self.0, marker::PhantomData))
174    }
175
176    fn try_acquire(self) -> Result<Vacancy<'queue, T>, Full> {
177        match self.try_acquire_pending() {
178            Ok(vacancy) => Ok(vacancy),
179            Err(_) => Err(Full),
180        }
181    }
182
183    fn try_reserve<const N: usize>(
184        self,
185        count: capacity::Limit<N>,
186    ) -> Result<Reservation<'queue, T, N>, Full> {
187        if !self.0.has_capacity(count) {
188            return Err(Full);
189        }
190        Ok(Reservation { queue: self, count })
191    }
192
193    fn prepare<'entries, const N: usize>(
194        self,
195        entries: &'entries [sq::Owned<T>; N],
196    ) -> Result<Prepared<'queue, 'entries, sq::Owned<T>, N>, Full> {
197        let count = capacity::Limit::<N>::fixed::<N>();
198        if !self.0.has_capacity(count) {
199            return Err(Full);
200        }
201        Ok(Prepared {
202            state: self.0,
203            entries: ptr::NonNull::from(entries).cast(),
204            count,
205            lifetime: marker::PhantomData,
206        })
207    }
208}
209
210impl<T: complete::raw::Token> Vacancy<'_, T> {
211    pub fn cancel<const ALL: bool>(self, target: T, complete: T) {
212        self.0.entry().cancel::<ALL, _>(target, complete);
213        self.0.advance();
214    }
215}
216
217impl<'queue, T: complete::raw::Token> submit::raw::Vacancy<'queue, T> for Vacancy<'queue, T> {
218    type Entry = sq::Entry;
219    type Owned = sq::Owned<T>;
220    type Borrowed<'r> = sq::Borrowed<'r>;
221    type Submit<'r> = sq::Submit<'r, T>;
222    type Prepared<'e, E: 'e> = Prepared<'queue, 'e, E, 1>;
223
224    fn push_owned(self, entry: sq::Entry, token: T) {
225        *self.0.entry() = entry.with_token(token);
226        self.0.advance();
227    }
228
229    /// # Safety
230    /// Every encoded address must remain live through terminal completion or quiescence.
231    unsafe fn push<'resources>(self, entry: sq::Borrowed<'resources>, token: T) {
232        self.push_owned(entry.0, token);
233    }
234
235    /// # Safety
236    /// Every encoded address must remain live through terminal completion or quiescence.
237    unsafe fn borrow<'entries, 'resources>(
238        self,
239        entry: &'entries Self::Submit<'resources>,
240    ) -> Self::Prepared<'entries, Self::Submit<'resources>> {
241        Prepared::one(self.0, entry)
242    }
243
244    fn prepare<'entries>(
245        self,
246        entry: &'entries sq::Owned<T>,
247    ) -> Prepared<'queue, 'entries, sq::Owned<T>, 1> {
248        Prepared::one(self.0, entry)
249    }
250}
251
252impl<'queue, 'entries, E> Prepared<'queue, 'entries, E, 1> {
253    fn one(state: &'queue mut State, entry: &'entries E) -> Self {
254        Self {
255            state,
256            entries: ptr::NonNull::from(entry),
257            count: capacity::Limit::fixed::<1>(),
258            lifetime: marker::PhantomData,
259        }
260    }
261}
262
263impl<E, const N: usize> submit::Ready for Prepared<'_, '_, E, N> {
264    fn push(self) {
265        self.state.push(self.entries, self.count);
266    }
267}
268
269const _: () = {
270    assert!(mem::size_of::<Vacancy<'static, ()>>() == mem::size_of::<usize>());
271    assert!(mem::size_of::<Result<Vacancy<'static, ()>, Full>>() == mem::size_of::<usize>());
272    assert!(mem::size_of::<Reservation<'static, (), 7>>() == 2 * mem::size_of::<usize>());
273    assert!(
274        mem::size_of::<Option<Reservation<'static, (), 8>>>()
275            == mem::size_of::<Reservation<'static, (), 8>>()
276    );
277    assert!(
278        mem::size_of::<Prepared<'static, 'static, sq::Owned<()>, 7>>()
279            == 3 * mem::size_of::<usize>()
280    );
281};
282
283impl State {
284    /// # Safety
285    /// Both mappings and parameters must describe one live kernel-created
286    /// ring and outlive this state.
287    pub(crate) unsafe fn new(
288        ring: &ring::ffi::Map,
289        entries: &ring::ffi::Map,
290        layout: ring::Submit,
291    ) -> Self {
292        let head = ring.at(layout.head());
293        let tail = ring.at(layout.tail());
294        let flags = ring.at(layout.flags());
295        let head_at = unsafe { head.as_ref().load(atomic::Ordering::Acquire) };
296        let tail_at = unsafe { tail.as_ref().load(atomic::Ordering::Relaxed) };
297        Self {
298            head,
299            tail,
300            flags,
301            entries: entries.at(layout.entries()),
302            axis: layout.axis(),
303            cursor: Cursor {
304                head: head_at,
305                tail: tail_at,
306                published_tail: tail_at,
307            },
308        }
309    }
310
311    pub(crate) fn publish(&mut self) {
312        if self.cursor.tail != self.cursor.published_tail {
313            // SAFETY: construction binds this atomic to the live ring mapping.
314            unsafe { self.tail.as_ref() }.store(self.cursor.tail, atomic::Ordering::Release);
315            self.cursor.published_tail = self.cursor.tail;
316        }
317        // SAFETY: construction binds both atomics to this live ring mapping.
318        self.cursor.head = unsafe { self.head.as_ref() }.load(atomic::Ordering::Acquire);
319    }
320
321    pub(crate) fn pending(&self) -> sq::Pending {
322        sq::Pending::from_raw(self.cursor.tail.wrapping_sub(self.cursor.head))
323    }
324
325    pub(crate) fn is_empty(&self) -> bool {
326        self.cursor.tail == self.cursor.head
327    }
328
329    pub(crate) fn has_capacity<const N: usize>(&self, required: capacity::Limit<N>) -> bool {
330        let pending: bounded::U32<0, { u32::MAX }> = self.pending().into();
331        self.axis.entries().get() - pending.get() >= required.count().get()
332    }
333
334    fn push<E, const N: usize>(&mut self, entries: ptr::NonNull<E>, count: capacity::Limit<N>) {
335        const { assert!(mem::size_of::<E>() == mem::size_of::<sq::Entry>()) };
336        const { assert!(mem::align_of::<E>() == mem::align_of::<sq::Entry>()) };
337        if N == 1 {
338            self.push_one(entries);
339            return;
340        }
341        let start = (self.cursor.tail & self.axis.mask()) as usize;
342        let len = count.get();
343        let first = len.min(self.axis.entries().get() as usize - start);
344        // SAFETY: the aggregate capacity check reserves both destination
345        // spans, mapped SQEs cannot alias the caller-owned source slice, and
346        // `first` bounds both regions. copy_nonoverlapping lets the compiler
347        // select the target's optimal fixed-size or vectorized bulk copy.
348        unsafe {
349            ptr::copy_nonoverlapping(
350                entries.as_ptr().cast::<sq::Entry>(),
351                self.entries.as_ptr().add(start),
352                first,
353            );
354        }
355        let rest = len - first;
356        if rest != 0 {
357            // SAFETY: the remaining reserved slots wrap exactly once to the
358            // start of the power-of-two SQ mapping and do not overlap source.
359            unsafe {
360                ptr::copy_nonoverlapping(
361                    entries.as_ptr().add(first).cast::<sq::Entry>(),
362                    self.entries.as_ptr(),
363                    rest,
364                );
365            }
366        }
367        self.cursor.tail = self.cursor.tail.wrapping_add(count.count().get());
368    }
369
370    fn push_one<E>(&mut self, entry: ptr::NonNull<E>) {
371        const { assert!(mem::size_of::<E>() == mem::size_of::<sq::Entry>()) };
372        const { assert!(mem::align_of::<E>() == mem::align_of::<sq::Entry>()) };
373        // SAFETY: the admitted destination cannot overlap the caller-owned SQE.
374        unsafe {
375            ptr::copy_nonoverlapping(entry.as_ptr().cast::<sq::Entry>(), self.entry(), 1);
376        }
377        self.advance();
378    }
379
380    fn entry(&mut self) -> &mut sq::Entry {
381        let index = (self.cursor.tail & self.axis.mask()) as usize;
382        // SAFETY: the exact one-slot reservation and ring mask prove this slot
383        // is free and in bounds. Publication follows complete initialization.
384        unsafe { &mut *self.entries.as_ptr().add(index) }
385    }
386
387    fn advance(&mut self) {
388        self.cursor.tail = self.cursor.tail.wrapping_add(1);
389    }
390
391    /// Samples kernel-owned flags for this single-issuer ring.
392    pub(crate) fn flags(&self) -> u32 {
393        // SAFETY: construction binds this atomic to the live SQ ring mapping.
394        unsafe { self.flags.as_ref() }.load(atomic::Ordering::Acquire)
395    }
396}
397
398impl<T: complete::raw::Token, const N: usize> tuning::raw::Chain<T, N> for Reservation<'_, T, N> {
399    type Target = sq::Fixed;
400
401    unsafe fn submit(
402        self,
403        values: &mut [libc::c_int; N],
404        mut options: impl option::Cursor,
405        slot: Self::Target,
406        token: T,
407    ) {
408        let Self { queue, count } = self;
409        for value in values.iter_mut().take(count.get()) {
410            let entry = Self::option(slot, options.pop(), value, token);
411            queue.0.push_one(ptr::NonNull::from(&entry));
412        }
413    }
414}
415
416impl<T: complete::raw::Token, const N: usize> Reservation<'_, T, N> {
417    fn option<'a>(
418        slot: sq::Fixed,
419        step: impl option::Step,
420        value: &'a mut libc::c_int,
421        token: T,
422    ) -> sq::Submit<'a, T> {
423        let (kind, linked) = match step.kind() {
424            ops::ControlFlow::Continue(kind) => (kind, true),
425            ops::ControlFlow::Break(kind) => (kind, false),
426        };
427        *value = step.value().raw();
428        let entry = sockets::set_option(slot, kind, value).user_data(token);
429        if linked {
430            entry.flags(sq::Flags::LINK)
431        } else {
432            entry
433        }
434    }
435}