dope-core 0.77.0

Owned native I/O and completion driver 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
use std::marker;

use dope_sys::{
    engine::admit::{self, Guard},
    io::{
        reactor::event::{
            Report,
            kind::{self, Native, Send},
        },
        request::Source,
        socket::addr,
    },
};
use o3::{alloc, depot::arena::slab, mem::slot};

use crate::{
    Backend,
    driver::{
        self,
        life::{
            finish::Finish,
            native::{self, host::Host},
        },
        result,
        retained::flight::{self, GENERATION_BITS, INDEX_BITS, Target, storage},
        route::{self, indices::SlotIndex, kind::Class},
    },
    io::{
        event::{Member, net::Owned},
        fd::handles,
        fs,
        socket::{self, msg, option, peer, pending},
        transfer,
    },
};

/// Prepares this driver's arena while retaining its exclusive preparation loan.
pub(in crate::driver) fn prepare<'a, 'd, Tags, const GROUPS: usize, B>(
    local: &'a mut driver::Local<'d>,
    need: flight::Need<Tags, GROUPS, B>,
) -> Result<flight::Prepared<'a, 'd, Tags, GROUPS, B>, alloc::Error> {
    // SAFETY: this consumed Context exclusively lends preparation for 'a.
    // Its arena already lives for 'd; Prepared retains the short loan while
    // topology mutation remains inside the original directory's UnsafeCell.
    let prepared = unsafe {
        local
            .flights
            .0
            .try_batch::<GROUPS, B>(need.into_caps().map(flight::Capacity::get))?
    };
    Ok(flight::Prepared {
        prepared,
        driver: local.driver.brand,
        tags: marker::PhantomData,
    })
}

#[doc(hidden)]
#[repr(transparent)]
pub struct Slots<'d, Tag: route::Tag> {
    slots: storage::raw::Slots<'d, Target, INDEX_BITS, GENERATION_BITS>,
    driver: driver::Invariant<'d>,
    tag: marker::PhantomData<Tag>,
}

pub(crate) struct Front<'slot, 'd, Tag: route::Tag, C: Class> {
    slot: storage::raw::Front<'slot, 'd, Target, INDEX_BITS, GENERATION_BITS>,
    target: Target,
    driver: driver::Invariant<'d>,
    class: marker::PhantomData<(Tag, C)>,
}

impl<'d, Tag: route::Tag, C: Class> From<Front<'_, 'd, Tag, C>> for flight::Reserved<'d, C> {
    fn from(front: Front<'_, 'd, Tag, C>) -> Self {
        Self {
            reservation: front.slot.reserve(front.target),
            driver: front.driver,
            class: marker::PhantomData,
        }
    }
}

impl<'d, Tag: route::Tag> Slots<'d, Tag> {
    /// # Safety
    /// No access to this group's free list may occur before this loan ends.
    pub(crate) unsafe fn front<C: Class + kind::Flight>(
        &self,
        target: route::Operation<'d, Tag, C>,
    ) -> Result<Front<'_, 'd, Tag, C>, slab::Vacancy> {
        Ok(Front {
            // SAFETY: the caller retains exclusive admission until reserve.
            slot: unsafe { self.slots.front()? },
            target: Target::new(target),
            driver: self.driver,
            class: marker::PhantomData,
        })
    }
    pub(crate) fn admit<'a, C: Class + kind::Flight>(
        &self,
        driver: &'a mut driver::Local<'d>,
        target: route::Operation<'d, Tag, C>,
    ) -> Result<(driver::Admission<'a>, flight::Reserved<'d, C>), result::SubmitError> {
        // SAFETY: the fixed native queue admission cannot reenter the flight free list.
        let front = unsafe { self.front(target) }?;
        let native = driver.try_admit()?;
        Ok((native, front.into()))
    }

    pub(in crate::driver::retained::flight) fn new(
        slots: storage::raw::Slots<'d, Target, INDEX_BITS, GENERATION_BITS>,
        driver: driver::Invariant<'d>,
    ) -> Self {
        Self {
            slots,
            driver,
            tag: marker::PhantomData,
        }
    }
}
impl<'d, Tag: route::Tag + route::Select<kind::Recv>> Slots<'d, Tag> {
    pub fn recv(
        &self,
        driver: &mut driver::Local<'d>,
        fd: &handles::Descriptor<'d>,
        target: route::Target<'d, Tag>,
    ) -> Result<flight::Flight<'d, kind::Recv>, result::SubmitError> {
        let (native, reserved) = self.admit(driver, target.operation::<kind::Recv>())?;
        Guard::<Host<Backend>>::recv(native, fd.slot(), flight::Echo::from(&reserved));
        Ok(reserved.into())
    }
}

impl<'d, Tag: route::Tag + route::Select<kind::Send>> Slots<'d, Tag> {
    pub fn shutdown(
        &self,
        driver: &mut driver::Local<'d>,
        fd: &handles::Descriptor<'d>,
        target: route::Target<'d, Tag>,
    ) -> Result<flight::Flight<'d, kind::Send>, result::SubmitError> {
        let (native, reserved) = self.admit(driver, target.operation::<kind::Send>())?;
        Guard::<Host<Backend>>::shutdown(native, fd.slot(), flight::Echo::from(&reserved));
        Ok(reserved.into())
    }
}

impl<'d, Tag: route::Tag> Slots<'d, Tag> {
    pub fn recv_dgram(
        &self,
        driver: &mut driver::Local<'d>,
        fd: &handles::Datagram<'d>,
        target: route::Operation<'d, Tag, kind::Recv>,
    ) -> Result<flight::Flight<'d, kind::Recv>, result::SubmitError> {
        let (native, reserved) = self.admit(driver, target)?;
        Guard::<Host<Backend>>::recv_msg(native, fd, flight::Echo::from(&reserved));
        Ok(reserved.into())
    }
}

impl<'d, Tag: route::Tag> Slots<'d, Tag> {
    pub fn accept(
        &self,
        driver: &mut driver::Local<'d>,
        fd: &handles::Descriptor<'d>,
        target: route::Operation<'d, Tag, kind::Accept>,
    ) -> Result<flight::Flight<'d, kind::Accept>, result::SubmitError> {
        let (native, reserved) = self.admit(driver, target)?;
        Guard::<Host<Backend>>::accept_multi(native, fd.slot(), flight::Echo::from(&reserved));
        Ok(reserved.into())
    }
}

impl<'d, Tag: route::Tag> Slots<'d, Tag> {
    /// # Safety
    /// Descriptor, target and slots belong to this driver. Keep the descriptor alive and the
    /// bytes fixed and immutable through terminal completion or quiescence.
    pub unsafe fn try_send<'r>(
        &self,
        context: &mut driver::Local<'d>,
        fd: &'r handles::Descriptor<'d>,
        buffer: transfer::View<'r>,
        target: route::Target<'d, Tag>,
    ) -> Result<flight::Flight<'d, kind::Send>, result::SubmitError>
    where
        'd: 'r,
        Tag: route::Select<kind::Send>,
    {
        let (native, reserved) = self.admit(context, target.operation::<kind::Send>())?;
        // SAFETY: the caller retains this descriptor and immutable prefix.
        unsafe {
            admit::raw::Retain::<Host<Backend>>::send(
                native,
                <Backend as Source<native::Context>>::target(fd.slot()),
                buffer.into_prefix(),
                flight::Echo::from(&reserved),
            );
        }
        Ok(reserved.into())
    }

    /// # Safety
    /// Descriptor, target and slots belong to this driver. Keep the descriptor alive and the
    /// message graph fixed and immutable through terminal completion or quiescence.
    pub unsafe fn try_send_msg<'r>(
        &self,
        context: &mut driver::Local<'d>,
        fd: &'r handles::Descriptor<'d>,
        message: msg::Message<'r>,
        target: route::Target<'d, Tag>,
    ) -> Result<flight::Flight<'d, kind::Send>, result::SubmitError>
    where
        'd: 'r,
        Tag: route::Select<kind::Send>,
    {
        let (native, reserved) = self.admit(context, target.operation::<kind::Send>())?;
        // SAFETY: the caller retains this descriptor and immutable message graph.
        unsafe {
            admit::raw::Retain::<Host<Backend>>::send_msg(
                native,
                <Backend as Source<native::Context>>::target(fd.slot()),
                message,
                flight::Echo::from(&reserved),
            );
        }
        Ok(reserved.into())
    }

    /// # Safety
    /// Listener, target and slots belong to this driver. Keep the listener alive and the
    /// exclusive peer output fixed through terminal completion or quiescence.
    pub(in crate::driver::retained) unsafe fn try_accept(
        &self,
        context: &mut driver::Local<'d>,
        fd: &handles::Descriptor<'d>,
        peer: &mut addr::Storage,
        target: route::Operation<'d, Tag, kind::Accept>,
    ) -> Result<flight::Flight<'d, kind::Accept>, result::SubmitError> {
        let (native, reserved) = self.admit(context, target)?;
        // SAFETY: the caller retains this listener and exclusive peer output.
        unsafe {
            admit::raw::Retain::<Host<Backend>>::accept(
                native,
                <Backend as Source<native::Context>>::target(fd.slot()),
                peer,
                flight::Echo::from(&reserved),
            );
        }
        Ok(reserved.into())
    }

    /// # Safety
    /// Target and slots belong to this driver. Retain every file borrow through completion or quiescence.
    pub unsafe fn try_file<'r, C: Class + kind::Flight>(
        &self,
        context: &mut driver::Local<'d>,
        entry: fs::Submission<'r, 'd, Tag, C>,
    ) -> Result<flight::Flight<'d, C>, result::SubmitError>
    where
        'd: 'r,
    {
        let (raw, target) = entry.into_parts();
        let (native, reserved) = self.admit(context, target)?;
        // SAFETY: the caller retains every file request borrow through completion.
        unsafe {
            admit::raw::Retain::<Host<Backend>>::file(native, raw, flight::Echo::from(&reserved))
        };
        Ok(reserved.into())
    }
}

impl<'d, Tag: route::Tag> Slots<'d, Tag> {
    pub fn tune(
        &self,
        driver: &mut driver::Local<'d>,
        target: route::Target<'d, Tag>,
        fd: handles::Descriptor<'d>,
        options: option::Set,
    ) -> Result<option::Tuning<'d>, pending::Rejection<'d>>
    where
        Tag: route::Select<kind::Tuning>,
    {
        let slot = fd.slot();
        // SAFETY: the submitted descriptor and its branded flight stay owned through completion.
        // The native queue cannot reenter the free list or relocate its pinned option values.
        unsafe {
            admit::raw::Socket::<Host<Backend>, { option::MAX_STREAM_OPTIONS }>::tune(
                &mut *driver.backend,
                (self, target.operation::<kind::Tuning>()),
                (fd, driver.driver.brand),
                slot,
                options.non_empty().map(option::NonEmpty::split),
                &mut driver.retry,
            )
        }
    }

    pub fn peer(
        &self,
        driver: &mut driver::Local<'d>,
        target: route::Target<'d, Tag>,
        fd: handles::Descriptor<'d>,
    ) -> Result<peer::Query<'d>, pending::Rejection<'d>>
    where
        Tag: route::Select<kind::Tuning>,
    {
        let slot = fd.slot();
        // SAFETY: the same branded descriptor and flight retain the native output until completion.
        // The native queue cannot reenter this group's free list.
        unsafe {
            admit::raw::Socket::<Host<Backend>, { option::MAX_STREAM_OPTIONS }>::peer(
                &mut *driver.backend,
                (self, target.operation::<kind::Tuning>()),
                (fd, driver.driver.brand),
                slot,
                &mut driver.retry,
            )
        }
    }

    /// # Safety
    /// The descriptor, target and slots belong to this driver's scope. Retain the
    /// exact address and descriptor through terminal completion or quiescence.
    pub unsafe fn try_connect<A>(
        &self,
        context: &mut driver::Local<'d>,
        target: route::Target<'d, Tag>,
        fd: &handles::Descriptor<'d>,
        options: &option::Set,
        address: &A,
    ) -> Result<flight::Flight<'d, kind::Connect>, pending::Cause>
    where
        Tag: route::Select<kind::Connect>,
        A: socket::Prepared,
    {
        // SAFETY: the caller retains the original descriptor and address for this
        // driver's typed flight. Native submission borrows both without relocation.
        unsafe {
            admit::raw::Socket::<Host<Backend>, { option::MAX_STREAM_OPTIONS }>::connect(
                &mut *context.backend,
                (self, target.operation::<kind::Connect>()),
                fd.slot(),
                options.non_empty().map(option::NonEmpty::split),
                address.view().native(),
                &mut context.retry,
            )
        }
    }
}

/// Owns initialized operation backing in the same physical native flight cells.
pub struct Backing<'d, Tag: route::Tag, B> {
    slots: storage::raw::Slots<'d, Target, INDEX_BITS, GENERATION_BITS>,
    driver: driver::Invariant<'d>,
    owner: marker::PhantomData<(Tag, B)>,
}

impl<'d, Tag: route::Tag, B> Backing<'d, Tag, B> {
    pub(super) fn new(
        slots: storage::raw::Slots<'d, Target, INDEX_BITS, GENERATION_BITS>,
        driver: driver::Invariant<'d>,
    ) -> Self {
        Self {
            slots,
            driver,
            owner: marker::PhantomData,
        }
    }

    pub fn front(&mut self) -> Result<Vacant<'_, 'd, Tag, B>, slab::Vacancy> {
        Ok(Vacant {
            // SAFETY: this exclusive typed owner loan excludes group access.
            slot: unsafe { self.slots.front()? },
            owner: marker::PhantomData,
        })
    }

    pub fn complete<'slot, 'event, S: route::Selection>(
        &'slot mut self,
        done: Member<'event, 'd, Owned<'d>, S>,
    ) -> Result<
        Option<slot::Occupied<'slot, storage::raw::Retiring<B, true>>>,
        Member<'event, 'd, Owned<'d>, S>,
    > {
        match done.get().completion.sink().attachment(&self.slots) {
            Some(true) => {}
            Some(false) => return Ok(None),
            None => return Err(done),
        }
        let (complete, ()) = done.take().0.completion.into_parts();
        // SAFETY: same-group admission proves B's allocation layout; ATTACHED
        // retains initialization after any intervening quiescent Finish.
        Ok(Some(unsafe {
            storage::raw::Retiring::occupy(complete.into_pointer())
        }))
    }

    pub fn finish<'slot>(
        &'slot mut self,
        proof: &Finish<'_, 'd, impl Report<Event = crate::Reported>>,
    ) -> storage::raw::Drain<'slot, B> {
        self.driver = proof.brand();
        // SAFETY: the matching driver is quiescent. The mutable group loan
        // transfers only each backing's authority, preserving held completion loans.
        unsafe { storage::raw::Drain::new(&mut self.slots) }
    }
}

impl<Tag: route::Tag, B> Drop for Backing<'_, Tag, B> {
    fn drop(&mut self) {
        // SAFETY: unsafe native submission requires retaining this entire graph
        // through terminal completion or quiescence. No loan survives this owner.
        for entry in unsafe { storage::raw::Drain::<B>::new(&mut self.slots) } {
            drop(entry);
        }
    }
}

pub struct Vacant<'slot, 'd, Tag: route::Tag, B> {
    pub(super) slot: storage::raw::Front<'slot, 'd, Target, INDEX_BITS, GENERATION_BITS>,
    pub(super) owner: marker::PhantomData<(&'slot mut B, Tag)>,
}

impl<'slot, 'd, Tag: route::Tag, B> Vacant<'slot, 'd, Tag, B> {
    pub fn slot(&self) -> SlotIndex {
        // SAFETY: the admitted native index is bounded by the same SLOT_BITS.
        unsafe { SlotIndex::encode(self.slot.index()) }
    }

    pub fn as_mut_ptr(&mut self) -> *mut B {
        // SAFETY: the matching Prepared admitted this Cell<B> layout, and the
        // mutable Retained loan excludes every other claim of this free cell.
        unsafe { self.slot.backing::<B>() }
    }

    /// # Safety
    /// This front's backing must be fully initialized; no raw access may remain.
    pub unsafe fn occupy(
        self,
        target: route::Operation<'d, Tag, Send>,
    ) -> slot::Occupied<'slot, storage::raw::Retiring<B, true>> {
        let mut target = Target::new(target);
        target.kind = Native::SendOwned;
        let pointer = self.slot.occupy(target);
        // SAFETY: the caller initialized this exact backing before publication.
        unsafe { storage::raw::Retiring::occupy(pointer) }
    }
}