dope-uring 0.76.0

Owned io_uring backend for dope
Documentation
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
use std::{marker, mem, num, ops::ControlFlow, pin};

use dope_sys::{
    io::{
        reactor::{Full, submit::Queue as _},
        socket::option::tuning,
    },
    table::token::Codec,
};
use o3::alloc;

use crate::{
    driver::{
        Key,
        tuning::{Progress, token},
    },
    reactor::{cq, op::sockets, sq},
};

#[derive(Debug)]
pub struct State<E, const N: usize> {
    target: Option<E>,
    values: [libc::c_int; N],
    status: Status,
    /// Initialized by `begin`, read once after all option completions succeed.
    connect: mem::MaybeUninit<crate::raw::Deferred>,
    next: Option<sq::Fixed>,
    _pin: marker::PhantomPinned,
}

/// Progress and cancellation of the current option flight.
#[derive(Debug)]
struct Status {
    retiring: bool,
    stopped: bool,
    phase: Phase,
    /// Remaining scalar option completions, live while the option stage runs.
    count: num::NonZero<u32>,
    /// Aggregated option-stage failure, if any.
    error: Option<cq::Outcome>,
}

impl<E, const N: usize> Default for State<E, N> {
    fn default() -> Self {
        Self {
            target: None,
            values: [0; N],
            status: Status {
                retiring: false,
                stopped: false,
                phase: Phase::Idle,
                count: num::NonZero::<u32>::MIN,
                error: None,
            },
            connect: mem::MaybeUninit::uninit(),
            next: None,
            _pin: marker::PhantomPinned,
        }
    }
}

#[derive(Debug)]
pub struct Table<E, const N: usize> {
    states: Box<[State<E, N>]>,
    ready: Option<sq::Fixed>,
    tail: Option<sq::Fixed>,
}

#[derive(Clone, Copy, Debug)]
enum Phase {
    /// No scalar option completions remain; the target and ready links retain later ownership.
    Idle,
    /// Scalar options in flight; the flight submits no deferred CONNECT.
    Options,
    /// Scalar options in flight, then one deferred CONNECT held in `connect`.
    OptionsConnect,
    /// One native peer-credential query owns the scalar storage.
    Peer,
}

pub struct Occupied<'a, E, const N: usize> {
    state: &'a mut State<E, N>,
    target: E,
}

pub(crate) enum Retirement<'a> {
    Ready,
    Pending,
    Cancel(Cancelling<'a>),
}

/// The exact active chain which must terminate before this slot can close.
pub(crate) struct Cancelling<'a> {
    status: &'a mut Status,
    slot: sq::Fixed,
}

impl<E, const N: usize> Table<E, N> {
    pub(crate) fn retirement(&mut self, slot: sq::Fixed) -> Retirement<'_> {
        let Some(state) = self.states.get_mut(slot.index() as usize) else {
            return Retirement::Ready;
        };
        if state.target.is_none() {
            return Retirement::Ready;
        }
        if state.status.retiring {
            return Retirement::Pending;
        }
        Retirement::Cancel(Cancelling {
            status: &mut state.status,
            slot,
        })
    }
}

impl Cancelling<'_> {
    /// Without LINK/FORCE_ASYNC, Linux v6.12 io_submit_sqes -> io_submit_sqe -> io_queue_sqe issues io_async_cancel synchronously (IOU_OK; liburing prep_cancel.3 NOTES).
    /// It matches before a later close/new chain in that SQ; only its CQ may outlive slot reuse, where retry_cancel changes no target or owner.
    pub(crate) fn try_submit<T: Codec>(self, queue: sq::raw::Queue<'_, T>) -> Result<(), Full> {
        let vacancy = queue.try_one()?;
        let target = token::<T>(self.slot);
        vacancy.cancel::<true>(T::tuning(target), T::cancel_tune(target));
        self.status.retiring = true;
        self.status.stopped = true;
        Ok(())
    }
}

impl<E, const N: usize> Table<E, N> {
    /// # Safety
    /// The retained descriptor indexes this table's immutable allocation.
    pub(crate) unsafe fn admitted(&mut self, slot: sq::Fixed) -> pin::Pin<&mut State<E, N>> {
        // SAFETY: the box never replaces or moves any slot; the descriptor proves this index.
        unsafe { pin::Pin::new_unchecked(self.states.get_unchecked_mut(slot.index() as usize)) }
    }
}

impl<E, const N: usize> tuning::Create for Table<E, N> {
    fn try_new(capacity: num::NonZero<u32>) -> Result<Self, alloc::Error> {
        use alloc::BoxSliceExt as _;
        const {
            assert!(mem::align_of::<Self>() == mem::align_of::<Box<[State<E, N>]>>());
        };

        let states = Box::<[State<E, N>]>::try_default(capacity.get() as usize)?;
        Ok(Self {
            states,
            ready: None,
            tail: None,
        })
    }
}

impl<E: Copy, const N: usize> tuning::Table<E, N> for Table<E, N> {
    type State = State<E, N>;
    type Occupied<'a>
        = Occupied<'a, E, N>
    where
        Self: 'a;

    fn bind(&mut self, index: u32) -> Result<Self::Occupied<'_>, tuning::Missing> {
        let state = self
            .states
            .get_mut(index as usize)
            .ok_or(tuning::Missing::Slot)?;
        state.occupied().ok_or(tuning::Missing::Vacant)
    }

    fn get(&mut self, index: u32) -> Option<pin::Pin<&mut Self::State>> {
        let state = self.states.get_mut(index as usize)?;
        // SAFETY: the boxed slice owns this slot until destruction and never moves it.
        Some(unsafe { pin::Pin::new_unchecked(state) })
    }

    fn retry_cancel(&mut self, index: u32) {
        if let Some(state) = self.states.get_mut(index as usize) {
            state.status.retiring = false;
        }
    }
}

// SAFETY: each target covers its outstanding chain; moving the box preserves every pinned slot.
unsafe impl<E, const N: usize> tuning::raw::Quiesce for Table<E, N> {
    type Storage = Box<[State<E, N>]>;

    fn is_quiescent(&self) -> bool {
        self.states.iter().all(|state| state.target.is_none())
    }

    fn into_storage(self) -> Self::Storage {
        self.states
    }
}

impl<E: Copy, const N: usize> tuning::Occupied<E> for Occupied<'_, E, N> {
    fn target(&self) -> E {
        self.target
    }

    fn is_failed(&self) -> bool {
        self.state.status.error.is_some()
    }

    fn output(&self) -> (usize, u32) {
        let state = &*self.state;
        match state.status.phase {
            Phase::Peer => (mem::size_of::<libc::ucred>(), state.values[1] as u32),
            _ => (0, 0),
        }
    }

    /// Only the aggregated option terminal or the later CONNECT terminal reaches
    /// the host. Every option CQE is counted even when submission splits links.
    fn clear(self) {
        let state = self.state;
        state.target = None;
        state.status.retiring = false;
        state.status.stopped = false;
        state.status.phase = Phase::Idle;
    }
}

const _: () = {
    assert!(std::mem::size_of::<Table<u64, 7>>() == 3 * std::mem::size_of::<usize>());
    assert!(mem::size_of::<Status>() == 16);
    assert!(mem::size_of::<State<num::NonZero<u64>, 7>>() == 72);
};

impl<E, const N: usize> State<E, N> {
    fn start(&mut self, target: E, count: num::NonZero<u32>, phase: Phase) {
        self.target = Some(target);
        self.status = Status {
            count,
            phase,
            retiring: false,
            stopped: false,
            error: None,
        };
        self.next = None;
    }

    /// # Safety
    /// No previous native operation uses this state. Retain its values and any
    /// deferred terminal address until the complete two-stage flight terminates.
    pub(crate) unsafe fn begin(
        self: pin::Pin<&mut Self>,
        target: E,
        count: num::NonZero<u32>,
        terminal: Option<crate::raw::Deferred>,
    ) -> &mut [libc::c_int; N] {
        // SAFETY: the caller proves no previous chain remains; only fields are
        // mutated, and the pinned array stays at its original address.
        let state = unsafe { self.get_unchecked_mut() };
        let phase = match terminal {
            Some(entry) => {
                state.connect.write(entry);
                Phase::OptionsConnect
            }
            None => Phase::Options,
        };
        state.start(target, count, phase);
        &mut state.values
    }
}

impl<E: Copy, const N: usize> Table<E, N> {
    pub fn complete(
        &mut self,
        index: u32,
        outcome: &mut cq::Outcome,
    ) -> Result<Option<Occupied<'_, E, N>>, tuning::Missing> {
        use dope_sys::io::reactor::complete::Outcome as _;

        let index = index as usize;
        if index >= self.states.len() {
            return Err(tuning::Missing::Slot);
        }
        let states = Box::as_mut_ptr(&mut self.states).cast::<State<E, N>>();
        // SAFETY: the bounds above admit this slot in our exclusive fixed allocation.
        let state = unsafe { &mut *states.add(index) };
        if matches!(state.status.phase, Phase::Options | Phase::OptionsConnect)
            && outcome.unit().is_ok()
        {
            if !outcome.is_zero()
                && (state.status.error.is_none()
                    || state.status.error
                        == Some(cq::Outcome::from_error(dope_sys::Errno::CANCELED)))
            {
                state.status.error = Some(*outcome);
            }
            if let Some(count) = num::NonZero::new(state.status.count.get() - 1) {
                state.status.count = count;
                return Ok(None);
            }
            if let Some(failure) = state.status.error {
                *outcome = failure;
            } else if state.status.stopped {
                *outcome = cq::Outcome::from_error(dope_sys::Errno::CANCELED);
            } else if matches!(state.status.phase, Phase::OptionsConnect) {
                state.status.phase = Phase::Idle;
                let bytes = (index as u32).to_le_bytes();
                let slot = sq::Fixed::new([bytes[0], bytes[1], bytes[2]]);
                if let Some(tail) = self.tail {
                    // SAFETY: a ready tail was previously admitted. Its completed option
                    // flight is distinct from this slot, which is only now becoming ready.
                    unsafe { (*states.add(tail.index() as usize)).next = Some(slot) };
                } else {
                    self.ready = Some(slot);
                }
                self.tail = Some(slot);
                return Ok(None);
            }
            state.status.phase = Phase::Idle;
        }
        state.occupied().map(Some).ok_or(tuning::Missing::Vacant)
    }
}

impl<E: Copy, const N: usize> State<E, N> {
    fn occupied(&mut self) -> Option<Occupied<'_, E, N>> {
        Some(Occupied {
            target: self.target?,
            state: self,
        })
    }

    /// # Safety
    /// Retain the admitted descriptor, pinned output and target through terminal completion.
    pub(crate) unsafe fn peer<T: Codec>(
        self: pin::Pin<&mut Self>,
        ready: sq::raw::Vacancy<'_, T>,
        slot: sq::Fixed,
        target: E,
        token: T,
    ) {
        use dope_sys::io::reactor::submit::{Ready as _, raw::Vacancy as _};
        // SAFETY: the caller retains the pinned, vacant scalar output until completion.
        let state = unsafe { self.get_unchecked_mut() };
        state.start(target, num::NonZero::<u32>::MIN, Phase::Peer);
        let request = sockets::peer_uid(slot, &mut state.values).user_data(token);
        // SAFETY: the request borrows the retained pinned output and ready owns capacity.
        unsafe { ready.borrow(&request) }.push();
    }
}

// SAFETY: projection never moves the values, and only the consumed terminal
// owner can clear the echo that marks their linked chain occupied.
unsafe impl<E: Copy, const N: usize> tuning::raw::State<E, N> for State<E, N> {
    type Occupied<'a>
        = Occupied<'a, E, N>
    where
        Self: 'a;

    fn bind(self: pin::Pin<&mut Self>) -> Option<Self::Occupied<'_>> {
        const {
            assert!(
                mem::size_of::<Occupied<'_, E, N>>() == mem::size_of::<(pin::Pin<&mut Self>, E)>()
            );
            assert!(
                mem::align_of::<Occupied<'_, E, N>>()
                    == mem::align_of::<(pin::Pin<&mut Self>, E)>()
            );
        };
        // SAFETY: the exclusive occupied loan can clear metadata but cannot move the slot.
        unsafe { self.get_unchecked_mut() }.occupied()
    }

    unsafe fn values(
        self: pin::Pin<&mut Self>,
        target: E,
        count: num::NonZero<u32>,
    ) -> &mut [libc::c_int; N] {
        // SAFETY: the caller proves this exact option count and retains the
        // pinned owner until every corresponding native CQE has arrived.
        unsafe { self.begin(target, count, None) }
    }
}

impl<T: Codec, const N: usize> Progress<T> for Table<Key<T>, N> {
    fn next(&mut self, queue: sq::raw::Queue<'_, T>) -> Option<Option<T::Tuning>> {
        let slot = self.ready?;
        // SAFETY: `ready` holds a slot admitted by `get`; only scalar state
        // and the deferred request move, retaining every pinned option value.
        let state = unsafe { self.states.get_unchecked_mut(slot.index() as usize) };
        let stopped = state.status.stopped;
        if !stopped {
            let vacancy = queue.try_acquire().ok()?;
            // SAFETY: `complete` links only an initialized, unread CONNECT.
            // This consumes it once; its host retains every encoded address
            // until the terminal CQE, including after this link is released.
            let entry = unsafe { state.connect.assume_init_read() };
            entry.submit(vacancy, T::tuning(token::<T>(slot)));
        }
        self.ready = state.next.take();
        if self.ready.is_none() {
            self.tail = None;
        }
        Some(if stopped {
            Some(token::<T>(slot))
        } else {
            None
        })
    }

    fn has_pending(&self) -> bool {
        self.ready.is_some()
    }

    fn cancel_all(&mut self) {
        for state in &mut self.states {
            if state.target.is_some() {
                state.status.stopped = true;
            }
        }
    }

    fn cancel_at(&mut self, slot: sq::Fixed, target: Option<Key<T>>) -> ControlFlow<()> {
        match self.states.get_mut(slot.index() as usize) {
            Some(State {
                target: Some(current),
                status,
                ..
            }) if target.is_none() || target == Some(*current) => {
                status.stopped = true;
                ControlFlow::Break(())
            }
            _ => ControlFlow::Continue(()),
        }
    }
}