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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
use crate::{
    Backend,
    driver::{
        engine::{
            Engine, NativeFault, NativeKey, NativeReport, NativeReturned, NativeSlot,
            envelope::{self, Envelope},
        },
        tuning::Progress,
    },
};
use dope_sys::{
    Errno,
    engine::{register, ring, shutdown::Cause},
    io::{
        fd::Fd,
        reactor::{
            complete::{Decode, Outcome as _, flags::Flow},
            event::{self, Connect, fault, kind},
            submit::{self, Control, Poll as _, Ready as _},
        },
        socket::{
            self,
            option::tuning::{self, Occupied as _},
        },
    },
    kernel::Returned as _,
    memory::buffer,
    ring::{
        Source, enter,
        ready::{Complete as _, Ready as _},
    },
    table::{
        self,
        reclaim::{self, Queue as _},
        token::{
            self, Codec as _,
            frame::{self, Decode as _},
            host,
        },
    },
};
use o3::{buffer::storage::provided::native, mem::slot};
use std::mem::MaybeUninit;

pub(super) struct Drain<'a, 'd, C: ring::Context, D, A, R> {
    pub(super) backend: &'a mut Engine<C>,
    pub(super) flights: &'d D,
    pub(super) fds: A,
    pub(super) report: &'a mut R,
    pub(super) source: &'a mut Option<register::Source<'d>>,
    pub(super) pending: &'a mut bool,
}

impl<'d, C, D, A, R, F, S, N, H, J, P, K, M, T, V, X, const OPTIONS: usize>
    Drain<'_, 'd, C, D, A, R>
where
    C: ring::Context<Tuning = crate::driver::raw::Table<NativeKey<C>, OPTIONS>>,
    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<socket::Create>,
    S: From<native::raw::Index>,
    X: From<socket::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>,
    R: event::Report<Event = F::Reported>,
{
    pub(super) fn finish<const STOP: bool, const RESUME: bool, B>(
        &mut self,
    ) -> Result<(), Cause<F::Fault, P>>
    where
        B: native::raw::Context + 'd,
        D::Driver<'d>: buffer::Access<native::raw::Root<'d, B>, F::Exhausted, Capacity = N>,
        Engine<C>: table::Retire<'d, A::Retirement>,
        F::Reported:
            From<<<Engine<C> as table::Retire<'d, A::Retirement>>::Output as IntoIterator>::Item>,
    {
        if STOP {
            <C::Tuning as Progress<C::Token>>::cancel_all(&mut self.backend.tuning);
            self.backend
                .ring
                .submit()
                .map_err(|cause| Cause::File(cause.into()))?;
            self.backend
                .ring
                .cancel_all()
                .map_err(|cause| Cause::File(cause.into()))?;
            self.drain::<RESUME, true, B>()?;
            if !tuning::raw::Quiesce::is_quiescent(&self.backend.tuning) {
                return Err(Cause::Tuning);
            }
        }
        let view = self.fds.retirement();
        let mut queued = view.pending();
        'retire: loop {
            table::Retire::drain(self.backend, view, queued, self.report);
            self.backend
                .ring
                .submit()
                .map_err(|cause| Cause::File(cause.into()))?;
            if RESUME && !STOP {
                loop {
                    self.drain::<RESUME, false, B>()?;
                    let source = *self.source;
                    let (ring, tuning) = (&mut self.backend.ring, &mut self.backend.tuning);
                    let Some(vacancy) =
                        ring.try_idle().map_err(|cause| Cause::File(cause.into()))?
                    else {
                        continue;
                    };
                    if self.flights.is_pending() {
                        drop(vacancy);
                        ring.try_wait(None)
                            .map_err(|cause| Cause::File(cause.into()))?;
                        continue;
                    }
                    if view.has_inflight() {
                        drop(vacancy);
                        ring.try_wait(None)
                            .map_err(|cause| Cause::File(cause.into()))?;
                        queued = view.pending();
                        continue 'retire;
                    }
                    queued = view.pending();
                    if queued.is_some() {
                        drop(vacancy);
                        continue 'retire;
                    }
                    if !tuning::raw::Quiesce::is_quiescent(tuning) {
                        return Err(Cause::Tuning);
                    }
                    if let Some(source) = source {
                        let entry = <Backend as Control>::Poll::new(source, C::Token::shutdown());
                        // SAFETY: the same generation retains the source through this idle vacancy.
                        unsafe { submit::raw::Vacancy::borrow(vacancy, entry.entry()) }.push();
                    }
                    return Ok(());
                }
            }
            self.drain::<RESUME, true, B>()?;
            if view.has_inflight() {
                self.backend
                    .ring
                    .try_wait(None)
                    .map_err(|cause| Cause::File(cause.into()))?;
                queued = view.pending();
                continue;
            }
            queued = view.pending();
            if queued.is_none() {
                break;
            }
        }
        self.backend.ring.flush();
        if tuning::raw::Quiesce::is_quiescent(&self.backend.tuning) {
            Ok(())
        } else {
            Err(Cause::Tuning)
        }
    }

    fn drain<const RESUME: bool, const WAIT: bool, B>(&mut self) -> Result<(), Cause<F::Fault, P>>
    where
        B: native::raw::Context + 'd,
        D::Driver<'d>: buffer::Access<native::raw::Root<'d, B>, F::Exhausted, Capacity = N>,
    {
        loop {
            self.backend.ring.acquire();
            loop {
                let mut first = None;
                loop {
                    let mut storage = MaybeUninit::uninit();
                    let mut packet = match Envelope::<'d, C, B, F>::next(
                        slot::raw::Vacant::new(&mut storage),
                        self.backend,
                    ) {
                        Some(Some(packet)) => packet,
                        Some(None) => continue,
                        None => break,
                    };
                    let packet = packet.get_mut();
                    let result = match packet.admit(&self.fds) {
                        Ok(()) => self.complete::<RESUME, B>(packet),
                        Err(cause) => Err(cause),
                    };
                    if let Err(cause) = result {
                        packet.release(self.backend, self.fds.as_ref());
                        first.get_or_insert(cause);
                        self.report.report(event::Reclaimed::Fault(cause));
                    }
                }
                if let Some(cause) = first {
                    self.backend.ring.publish();
                    return Err(Cause::Completion(cause));
                }
                if self.backend.ring.refresh().get() == 0 {
                    break;
                }
            }
            if !WAIT {
                return Ok(());
            }
            match self
                .backend
                .ring
                .advance()
                .map_err(|cause| Cause::File(cause.into()))?
            {
                enter::Progress::Entered => continue,
                enter::Progress::Idle if !self.flights.is_pending() => return Ok(()),
                enter::Progress::Idle => {}
            }
            self.backend
                .ring
                .try_wait(None)
                .map_err(|cause| Cause::File(cause.into()))?;
        }
    }

    fn complete<const RESUME: bool, B>(
        &mut self,
        packet: &mut Envelope<'d, C, B, F>,
    ) -> Result<(), F::Fault>
    where
        B: native::raw::Context + 'd,
        D::Driver<'d>: buffer::Access<native::raw::Root<'d, B>, F::Exhausted, Capacity = N>,
    {
        let flight = match packet.parts.raw.token.decode() {
            token::Decoded::Flight(key) => {
                // SAFETY: the paired CQ supplied this result; reclamation preserves its flow.
                let Some(flight) = (unsafe { self.flights.bind(key, self.fds.as_ref()) }) else {
                    return Err(packet.parts.unbound());
                };
                flight
            }
            token::Decoded::Framework(control) => {
                match packet.parts.frame(control) {
                    frame::Control::Tuning(tune) => {
                        let control = control.control();
                        let Some(state) =
                            packet
                                .parts
                                .advance(&mut self.backend.tuning, tune, control)?
                        else {
                            return Ok(());
                        };
                        let result = packet.parts.tuning_value(&state, control)?;
                        let target = state.target();
                        // SAFETY: this paired tuning terminal retains its original target.
                        let Some(flight) =
                            (unsafe { self.flights.bind(target, self.fds.as_ref()) })
                        else {
                            state.clear();
                            let echo = fault::Echo::new(target);
                            return Err(packet.parts.reject(
                                fault::Subject::Tuning { echo, control },
                                fault::Violation::Stale(echo),
                            ));
                        };
                        let observed = flight.kind();
                        let event = match observed.into() {
                            kind::Shape::Connect(_) => {
                                let failed = state.is_failed();
                                state.clear();
                                event::Reclaimed::Connect {
                                    echo: fault::Echo::new(flight.end(Flow::Last)),
                                    result: match result {
                                        Ok(_) => Ok(()),
                                        Err(error) => Err(envelope::classify(error, failed)),
                                    },
                                }
                            }
                            kind::Shape::Tuning(_) => {
                                state.clear();
                                event::Reclaimed::Tuning {
                                    echo: fault::Echo::new(flight.end(Flow::Last)),
                                    result: match result {
                                        Ok(_) => Ok(()),
                                        Err(error) => Err(error),
                                    },
                                }
                            }
                            _ => {
                                state.clear();
                                let echo = fault::Echo::new(flight.end(Flow::Last));
                                return Err(packet.parts.reject(
                                    fault::Subject::Tuning { echo, control },
                                    fault::Violation::Tuning(observed),
                                ));
                            }
                        };
                        self.report.report(event);
                        return Ok(());
                    }
                    frame::Control::Shutdown => {
                        let outcome = packet.parts.raw.outcome;
                        if let Err(cause) = outcome.stopped() {
                            return Err(packet.parts.reject(
                                fault::Subject::Control(control.control()),
                                fault::Violation::Outcome(cause),
                            ));
                        }
                        if self.source.is_some() && outcome.is_error() {
                            return Ok(());
                        }
                        let owned = self.source.take().is_some();
                        if RESUME && owned {
                            *self.pending = true;
                        } else {
                            self.report.report(event::Reclaimed::Shutdown);
                        }
                    }
                    frame::Control::ClosePrep => {
                        return match packet.parts.raw.outcome.aborted() {
                            Ok(()) => Ok(()),
                            Err(cause) => Err(packet.parts.reject(
                                fault::Subject::Control(control.control()),
                                fault::Violation::Outcome(cause),
                            )),
                        };
                    }
                    frame::Control::Unknown => return Err(packet.parts.control(control)),
                }
                return Ok(());
            }
            token::Decoded::Close(returned) => return packet.parts.returned(returned, &self.fds),
            token::Decoded::CancelFlight(key) => {
                return packet
                    .parts
                    .cancel(&mut self.backend.tuning, host::Cancel::Flight(key));
            }
            token::Decoded::CancelTuning(tune) => {
                return packet
                    .parts
                    .cancel(&mut self.backend.tuning, host::Cancel::Tuning(tune));
            }
            token::Decoded::Invalid => return Err(packet.parts.unbound()),
        };
        let event = match flight.kind().into() {
            kind::Shape::Socket(proof) => {
                let outcome = match packet.parts.unit() {
                    Ok(outcome) => outcome,
                    Err(cause) => return Err(packet.parts.reject_bound(flight, cause)),
                };
                let creation = match self.fds.creation(flight.target(proof)) {
                    Some(creation) => creation,
                    None => return Err(packet.parts.reject_bound(flight, fault::Violation::Slot)),
                };
                let echo = fault::Echo::new(flight.end(Flow::Last));
                let slot = *creation.as_ref();
                let result = match outcome {
                    Ok(()) => {
                        self.fds.reclaim(creation);
                        Ok(())
                    }
                    Err(errno) => {
                        self.fds.fail_create(creation);
                        Err(X::from(socket::Create::socket(errno)))
                    }
                };
                event::Reclaimed::Socket {
                    echo,
                    slot: slot.into(),
                    result,
                    close: None,
                }
            }
            kind::Shape::Open(proof) => {
                // SAFETY: this retiring flight owns the open result through close.
                let opened = match unsafe { packet.open() } {
                    Ok(value) => value,
                    Err(cause) => return Err(packet.parts.reject_bound(flight, cause)),
                };
                let subject = fault::Subject::Target(flight.target(proof).into());
                let echo = fault::Echo::new(flight.end(Flow::Last));
                let (result, close) = match opened {
                    Ok(file) => (Ok(()), Some(<Backend as Fd>::close::<Errno>(file))),
                    Err(errno) => (Err(errno), None),
                };
                let event = event::Reclaimed::Open {
                    echo,
                    result,
                    close,
                };
                if let Some(Err(errno)) = close {
                    let cause = packet
                        .parts
                        .reject(subject, fault::Violation::Cleanup(errno));
                    self.report.report(event);
                    return Err(cause);
                }
                event
            }
            kind::Shape::Accept(_) => {
                let outcome = match packet.accepting(&self.fds) {
                    Ok(outcome) => outcome,
                    Err(cause) => return Err(packet.parts.reject_bound(flight, cause)),
                };
                let flow = packet.parts.flow();
                let echo = fault::Echo::new(flight.end(flow));
                let result = match outcome {
                    Ok(accepted) => Ok(self.fds.abandon(accepted)),
                    Err(error) => Err(F::AcceptFailure::from(error)),
                };
                event::Reclaimed::Accept { echo, result, flow }
            }
            kind::Shape::Recv(_) => {
                let empty = packet.buffer.is_none();
                let outcome = match packet.parts.raw.outcome.decode() {
                    Decode::Value(value) => {
                        if (value.get() == 0) != empty {
                            return Err(packet
                                .parts
                                .reject_bound(flight, fault::Violation::Buffer));
                        }
                        Ok(value)
                    }
                    Decode::Error(errno) => {
                        if !empty {
                            return Err(packet
                                .parts
                                .reject_bound(flight, fault::Violation::Buffer));
                        }
                        Err(errno)
                    }
                    Decode::Invalid(invalid) => {
                        return Err(packet.parts.reject_bound(
                            flight,
                            fault::Violation::Outcome(crate::error::Returned::invalid(invalid)),
                        ));
                    }
                };
                let flow = packet.parts.flow();
                let echo = fault::Echo::new(flight.end(flow));
                let result = outcome.map(|value| value.get() as usize);
                packet.release(self.backend, self.fds.as_ref());
                event::Reclaimed::Recv { echo, result, flow }
            }
            kind::Shape::Send(_) | kind::Shape::SendOwned(_) => {
                let (echo, result) = packet.ended(flight, packet.parts.bytes())?;
                event::Reclaimed::Send { echo, result }
            }
            kind::Shape::Write(_) => {
                let (echo, result) = packet.ended(flight, packet.parts.bytes())?;
                event::Reclaimed::Write { echo, result }
            }
            kind::Shape::Read(_) => {
                let (echo, result) = packet.ended(flight, packet.parts.bytes())?;
                event::Reclaimed::Read { echo, result }
            }
            kind::Shape::Connect(_) => {
                let (echo, result) = packet.ended(flight, packet.parts.unit())?;
                event::Reclaimed::Connect {
                    echo,
                    result: result.map_err(Connect::Connect),
                }
            }
            kind::Shape::Sync(_) => {
                let (echo, result) = packet.ended(flight, packet.parts.unit())?;
                event::Reclaimed::Sync { echo, result }
            }
            kind::Shape::Tuning(_) => {
                let (echo, result) = packet.ended(flight, packet.parts.unit())?;
                event::Reclaimed::Tuning { echo, result }
            }
        };
        self.report.report(event);
        Ok(())
    }
}