dope-uring 0.77.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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
use crate::{
    Backend,
    driver::{Identity, Key, NativeSlot, tuning::Progress},
    reactor::{Held, mappings, register::owned, ring::Ready, sq},
};
use dope_sys::{
    Errno,
    engine::{
        self, Drain, Mode, Pending as _,
        admit::{self, Admit, Context},
        ring::{self, Backend as _},
        shutdown::{Cause, Shutdown},
    },
    io::{
        Cleanup, Close,
        reactor::{
            Full, complete,
            event::{self, fault},
            submit::Queue as _,
        },
        request,
        socket::{Create, option::tuning},
    },
    memory::{
        self,
        buffer::{self, provided},
    },
    ring::{
        Source,
        ready::{self, Complete as _, Ready as _},
    },
    table::{
        self, reclaim,
        token::{self, Codec, Tuning, host},
    },
};
use o3::{
    buffer::storage::provided::native,
    mem::{self, slot},
};
use std::{convert::Infallible, mem::MaybeUninit, num, ops::ControlFlow, os::fd, time};
mod parts;
mod retire;
mod sealed;

type NativeKey<C> = <Identity<C> as host::Context>::Key;
type NativeControl<C> = <Identity<C> as token::Context>::Control;
type NativeReturned<C> = <Identity<C> as host::Context>::Returned;
type Closing<C> = Held<
    <Ready<<C as ring::Context>::Token, <C as ring::Context>::Layout> as Close>::State,
    <<C as ring::Context>::Tuning as tuning::raw::Quiesce>::Storage,
>;
type Subject<C, F> = fault::Subject<
    <F as host::Flight>::Token,
    NativeControl<C>,
    fault::Echo<NativeKey<C>>,
    NativeSlot<C>,
>;
type Violation<C, F, S, N, H, J> = fault::Violation<
    S,
    fault::Echo<NativeKey<C>>,
    <F as host::Flight>::Length,
    N,
    crate::error::Returned,
    NativeSlot<C>,
    <NativeSlot<C> as TryFrom<u32>>::Error,
    H,
    J,
>;
type NativeFault<C, F, S, N, H, J> =
    fault::Fault<<F as host::Flight>::Observation, Subject<C, F>, Violation<C, F, S, N, H, J>>;
type Decoded<T, C, F, S, N, H, J> = Result<Result<T, Errno>, Violation<C, F, S, N, H, J>>;
type Dispatched<H, F> = Result<(ControlFlow<H, Drain>, ControlFlow<()>), fault::Dispatch<F>>;
type NativeReport<F, P, K, M, T, V, X> = event::Reclaimed<
    <F as host::Flight>::Fault,
    P,
    K,
    <F as host::Flight>::Token,
    T,
    <F as host::Flight>::AcceptFailure,
    fault::Echo<<F as host::Flight>::Key>,
    <F as host::Flight>::Length,
    M,
    V,
    X,
>;

/// The registered ring keeps every pinned option value alive until teardown.
pub struct Engine<C: ring::Context> {
    pub(in crate::driver) ring: Ready<C::Token, C::Layout>,
    pub(in crate::driver) tuning: C::Tuning,
}

impl<C: ring::Context> engine::Buffer for Engine<C> {
    type Layout = C::Layout;
    type Token =
        <Backend as provided::Source>::Complete<<C::Layout as memory::raw::Receive>::Extent>;
    type Context = <Backend as provided::Source>::Context<C::Layout>;
    type Retained = ();
    type Arena<T> = native::raw::Arena<T>;
    type Root<'d, T>
        = native::raw::Root<'d, T>
    where
        T: 'd,
        Self::Retained: 'd;
}

impl<C, O, H: fd::AsFd> engine::Install<O, H> for Engine<C>
where
    C: ring::Context + Context<Native = Backend>,
    O: Into<<C::Inputs as request::Context>::Target>,
{
    type Error = <Ready<C::Token, C::Layout> as ready::Ready>::InstallError;

    fn install(&mut self, slot: O, handle: H) -> Result<(), Self::Error> {
        self.ring.install(
            <Backend as request::Source<C::Inputs>>::target(slot.into()),
            fd::AsFd::as_fd(&handle),
        )
    }
}

impl<C: ring::Context> ring::Backend<C> for Engine<C> {
    type Ring = Ready<C::Token, C::Layout>;

    fn new(ring: Self::Ring, tuning: C::Tuning) -> Self {
        Self { ring, tuning }
    }

    fn ring(&mut self) -> &mut Self::Ring {
        &mut self.ring
    }

    fn tuning(&mut self) -> &mut C::Tuning {
        &mut self.tuning
    }

    fn split(&mut self) -> (&mut Self::Ring, &mut C::Tuning) {
        (&mut self.ring, &mut self.tuning)
    }
}

impl<C> Admit<C> for Engine<C>
where
    C: ring::Context + Context<Native = Backend, Key = Key<C::Token>>,
{
    type Admission<'a>
        = sq::raw::Vacancy<'a, C::Token>
    where
        Self: 'a;

    fn try_admit(&mut self) -> Result<Self::Admission<'_>, Full> {
        self.ring.submission().try_one()
    }
}

impl<C> admit::Backend<C> for Engine<C>
where
    C: ring::Context + Context<Native = Backend, Key = Key<C::Token>>,
    C::Tuning: Progress<C::Token>,
{
    fn try_cancel<const FAMILY: u8>(
        &mut self,
        key: C::Key,
        pending: bool,
        slot: Option<&<C::Inputs as request::Context>::Target>,
    ) -> Result<admit::Cancelled, admit::Error<Infallible>> {
        use crate::driver::tuning;

        if !pending {
            return Ok(admit::Cancelled::Completed);
        }
        let vacant = self
            .ring
            .submission()
            .try_one()
            .map_err(admit::Error::Full)?;
        if let Some(slot) = slot {
            let slot = <Backend as request::Source<C::Inputs>>::target(*slot);
            if self.tuning.cancel_at(slot, Some(key)).is_break() {
                let control = tuning::token::<C::Token>(slot);
                let target = C::Token::tuning(control);
                let complete = C::Token::cancel_tune(control);
                vacant.cancel::<true>(target, complete);
                return Ok(admit::Cancelled::Submitted);
            }
        }
        vacant.cancel::<false>(C::Token::flight(key), C::Token::cancel_key(key));
        Ok(admit::Cancelled::Submitted)
    }
}

impl<C, S> engine::Cancel<S, <Backend as admit::Native>::Permit> for Engine<C>
where
    C: ring::Context,
    C::Tuning: Progress<C::Token>,
    S: Into<num::NonZero<u32>>,
    <C::Token as Codec>::Tuning: Tuning<Slot = S>,
{
    fn cancel(&mut self, _: &<Backend as admit::Native>::Permit, slot: S) -> Result<(), Full> {
        let vacancy = self.ring.submission().try_one()?;
        let target = <C::Token as Codec>::Tuning::new(slot);
        let index: num::NonZero<u32> = target.slot().into();
        let bytes = (index.get() - 1).to_le_bytes();
        let fixed = sq::Fixed::new([bytes[0], bytes[1], bytes[2]]);
        let _ = self.tuning.cancel_at(fixed, None);
        vacancy.cancel::<true>(C::Token::tuning(target), C::Token::cancel_tune(target));
        Ok(())
    }
}

impl<C: ring::Context> complete::Observe for Engine<C> {
    type Observation = C::Observation;
}

impl<C: ring::Context> Close for Engine<C> {
    type State = Closing<C>;

    fn try_close(self) -> Result<(), Self::State> {
        use dope_sys::io::socket::option::tuning::raw::Quiesce as _;

        let Self { ring, tuning } = self;
        match ring.try_close() {
            Ok(()) => Ok(()),
            Err(ring) => Err(Closing::<C>::new(ring, tuning.into_storage())),
        }
    }
}

impl<C: ring::Context> Shutdown for Engine<C> {
    type State = owned::Closing<mappings::Region, Closing<C>>;

    fn try_shutdown(self, context: <Self as engine::Buffer>::Context) -> Result<(), Self::State> {
        match self.try_close() {
            Ok(()) => context
                .try_close()
                .map_err(|state| owned::Closing(Cleanup::Storage(state))),
            Err(backend) => Err(owned::Closing(Cleanup::Owner((
                backend,
                context.into_region(),
            )))),
        }
    }
}

impl<C: ring::Context> Engine<C> {
    /// Accepted slots belong to the kernel; no local availability proof exists.
    pub const fn can_accept(&self) -> bool {
        false
    }
}

impl<C: ring::Context> engine::raw::Poll for Engine<C>
where
    C::Tuning: Progress<C::Token>,
{
    type Context = C;
    type Error = <Backend as Source>::Poll;

    unsafe fn wait<'a, Tag>(
        &'a mut self,
        quota: mem::raw::Shared<'_, Tag>,
        timeout: Option<time::Duration>,
        busy: bool,
    ) -> Result<(), Self::Error>
    where
        C: 'a,
    {
        drop(quota);
        if busy || self.tuning.has_pending() || timeout.is_some_and(|span| span.is_zero()) {
            self.ring.commit()
        } else {
            self.ring.try_wait(timeout)
        }
    }
}

impl<C, const OPTIONS: usize> Engine<C>
where
    C: ring::Context<Tuning = crate::driver::raw::Table<NativeKey<C>, OPTIONS>>,
{
    pub fn dispatch<'d, 'p, Q, O, M, D, A, B, Tag, F, S, N, H, J>(
        mode: &mut M,
        quota: &mem::raw::Shared<'_, Tag>,
        work: M::Work,
        pending: &mut M::Pending<'p>,
        observer: &O,
    ) -> Dispatched<M::Held, F::Fault>
    where
        'd: 'p,
        B: native::raw::Context + 'd,
        NativeSlot<C>: TryFrom<u32>,
        F: host::Flight<Key = NativeKey<C>, Fault = NativeFault<C, F, S, N, H, J>>,
        F::Observation: for<'a> From<&'a crate::Observed<C::Token>>,
        F::AcceptFailure: From<Errno>,
        F::SocketFailure: From<Create>,
        S: From<native::raw::Index>,
        D: host::raw::Drain<Key = NativeKey<C>, Flight<'d> = F> + 'd,
        A: table::Slots<F, Index = NativeSlot<C>, Capacity = H> + AsRef<D::Driver<'d>>,
        A::Retirement: reclaim::Queue<Returned = NativeReturned<C>, Class = J>,
        D::Driver<'d>: buffer::Access<native::raw::Root<'d, B>, F::Exhausted, Capacity = N>,
        M: Mode<'d, Q, O, Event = event::raw::Completion<'d, F>>
            + engine::raw::Owner<'d, Self, D, A>,
    {
        let mut status = ControlFlow::Continue(());
        let result = {
            let mut budget;
            {
                let loan = sealed::Loan::new(mode);
                loan.backend.ring.acquire();
                budget = quota.lease_up_to::<event::raw::Completion<'d, F>>(quota.remaining());
                if *loan.pending
                    && let Some(take) = budget.take()
                {
                    take.commit();
                    *loan.pending = false;
                    status = M::observed(observer);
                }
            }
            loop {
                let Some(take) = budget.take() else {
                    break Ok(ControlFlow::Continue(()));
                };
                let mut output = MaybeUninit::uninit();
                let event = match sealed::Packet::<'d, C, B, F>::deliver::<Q, O, M, D, A, _>(
                    &mut sealed::Loan::new(mode),
                    take,
                    &mut status,
                    observer,
                    slot::raw::Vacant::new(&mut output),
                ) {
                    Some(Ok(Some(event))) => event,
                    Some(Ok(None)) => continue,
                    Some(Err(cause)) => break Err(cause),
                    None => break Ok(ControlFlow::Continue(())),
                };
                if let ControlFlow::Break(value) = M::emit(mode, event, work, pending) {
                    break Ok(ControlFlow::Break(value));
                }
            }
        };
        let backend = sealed::Loan::new(mode).backend;
        let complete = backend.ring().refresh();
        backend.ring().flush();
        let events = match result {
            Ok(ControlFlow::Break(value)) => ControlFlow::Break(value),
            Ok(ControlFlow::Continue(())) => {
                let pending = complete.get() != 0
                    || <C::Tuning as Progress<C::Token>>::has_pending(backend.tuning());
                ControlFlow::Continue(if pending {
                    Drain::Pending
                } else {
                    Drain::Drained
                })
            }
            Err(fault) => return Err(fault::Dispatch::new(Drain::Pending, fault)),
        };
        Ok((events, status))
    }

    pub fn finish<
        'd,
        const STOP: bool,
        const RESUME: bool,
        O,
        D,
        A,
        B,
        F,
        S,
        N,
        H,
        J,
        P,
        K,
        M,
        T,
        V,
        X,
    >(
        owner: &mut O,
    ) -> Result<(), Cause<F::Fault, P>>
    where
        B: native::raw::Context + 'd,
        NativeSlot<C>: TryFrom<u32>,
        F: host::Flight<
                Key = NativeKey<C>,
                Fault = NativeFault<C, F, S, N, H, J>,
                Reported = NativeReport<F, P, K, M, T, V, X>,
            >,
        F::Observation: for<'a> From<&'a crate::Observed<C::Token>>,
        F::Fault: Copy,
        F::AcceptFailure: From<Errno>,
        F::SocketFailure: From<Create>,
        S: From<native::raw::Index>,
        X: From<Create>,
        P: From<<Backend as Source>::Poll>,
        D: host::raw::Drain<Key = NativeKey<C>, Flight<'d> = F, Reported = F::Reported> + 'd,
        A: table::Slots<F, Index = NativeSlot<C>, Capacity = H, Physical = T, Reclaimed = V>
            + AsRef<D::Driver<'d>>,
        A::Retirement: reclaim::Queue<Returned = NativeReturned<C>, Class = J>,
        D::Driver<'d>: buffer::Access<native::raw::Root<'d, B>, F::Exhausted, Capacity = N>,
        Self: table::Retire<'d, A::Retirement>,
        F::Reported:
            From<<<Self as table::Retire<'d, A::Retirement>>::Output as IntoIterator>::Item>,
        O: engine::raw::Owner<'d, Self, D, A>,
    {
        let mut loan = sealed::Loan::new(owner);
        if STOP {
            <C::Tuning as Progress<C::Token>>::cancel_all(&mut loan.backend.tuning);
            loan.backend
                .ring
                .submit()
                .map_err(|cause| Cause::File(cause.into()))?;
            loan.backend
                .ring
                .cancel_all()
                .map_err(|cause| Cause::File(cause.into()))?;
            loan.drain::<RESUME, true, B>()?;
            if !tuning::raw::Quiesce::is_quiescent(&loan.backend.tuning) {
                return Err(Cause::Tuning);
            }
        }
        loan.finish::<STOP, RESUME, B>()
    }
}

impl<C: ring::Context> Engine<C>
where
    C::Tuning: Progress<C::Token>,
{
    pub fn commit<'d, O, D, A, Tag>(
        owner: &mut O,
        quota: mem::raw::Shared<'_, Tag>,
        retry: bool,
    ) -> Result<bool, <Backend as Source>::Poll>
    where
        O: engine::raw::Owner<'d, Self, D, A>,
        D: host::raw::Drain + 'd,
        A: AsRef<D::Driver<'d>>,
        D::Driver<'d>: engine::Pending,
    {
        let loan = sealed::Loan::new(owner);
        drop(quota);
        let busy = retry || loan.fds.as_ref().has_deferred() || loan.backend.tuning.has_pending();
        loan.backend.ring.commit()?;
        Ok(busy || !loan.backend.ring.submission().is_empty())
    }
}