dope-core 0.72.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
use std::mem;

use dope_sys::{
    engine,
    engine::admit,
    io::{
        reactor::{
            Full,
            ready::{delivery, store::Quota},
        },
        request::{Lower, Source},
        socket::option::{tuning, tuning::device},
    },
    kernel,
    memory::buffer,
    table::permit::Queue as _,
};
use o3::depot::arena::slab::Vacancy;
use schedule::state::{lanes, scope};

use crate::{
    Engine, driver,
    driver::{
        life,
        life::native::{request::permits, resolver::Resolver},
        receive, result,
        retained::{flight, flight::cancel},
        route,
        route::{indices, kind},
        schedule,
    },
    io::{
        fd::handles,
        socket::{install::slot, option, peer, pending},
    },
};

pub(crate) mod create;
pub(in crate::driver) mod drain;
pub(crate) mod host;
pub(crate) mod request;
pub(crate) mod resolver;
mod retired;

/// Exclusive native authority borrowed from one driver-local scope.
///
/// Its parts can only enter native code through the same `Local` root.
#[repr(transparent)]
pub(crate) struct Access<'a, 'd> {
    local: &'a mut life::Local<'d>,
}

impl<'a, 'd> Access<'a, 'd> {
    pub(in crate::driver) fn new(local: &'a mut life::Local<'d>) -> Self {
        Self { local }
    }

    pub(crate) fn try_admit(self) -> Result<permits::Admission<'a, 'd>, Full> {
        let permit = match admit::Admit::try_admit(&mut *self.local.backend) {
            Ok(permit) => permit,
            Err(full) => {
                self.local.retry = true;
                return Err(full);
            }
        };
        Ok(permits::Admission::new(
            permit,
            route::Brand::new(self.local.driver.brand),
        ))
    }

    pub(crate) fn try_cancel<C: kind::Class>(
        self,
        flight: &mut flight::Flight<'d, C>,
    ) -> Result<admit::Cancelled, cancel::Error> {
        let echo = flight.key();
        let pending = flight.is_pending();
        match C::KIND {
            kind::Kind::Accept => self.cancel::<admit::Pending<0>>(echo, pending, None),
            kind::Kind::Recv => self.cancel::<admit::Pending<1>>(echo, pending, None),
            kind::Kind::Send | kind::Kind::Connect => {
                self.cancel::<admit::Pending<2>>(echo, pending, None)
            }
            kind::Kind::Unspecified
            | kind::Kind::Socket
            | kind::Kind::Shutdown
            | kind::Kind::Open
            | kind::Kind::OneShot
            | kind::Kind::TaskQueue
            | kind::Kind::Tuning
            | kind::Kind::Write
            | kind::Kind::Read
            | kind::Kind::Sync => self.cancel::<admit::Immediate>(echo, pending, None),
        }
    }

    pub(crate) fn try_stop_at(
        self,
        flight: &mut flight::Flight<'d, kind::Connect>,
        fd: &handles::Descriptor<'d>,
    ) -> Result<admit::Cancelled, cancel::Error> {
        self.cancel::<admit::Pending<2>>(flight.key(), flight.is_pending(), Some(fd.slot()))
    }

    fn cancel<P: admit::Plan>(
        self,
        echo: flight::raw::Echo,
        pending: bool,
        slot: Option<handles::PhysicalSlot>,
    ) -> Result<admit::Cancelled, cancel::Error> {
        let native: Result<P::Guard<'_, host::Host<crate::Backend>, Engine>, _> = match slot {
            Some(slot) => admit::Reserve::try_at(&mut *self.local.backend, echo, pending, &slot),
            None => admit::Reserve::try_new(&mut *self.local.backend, echo, pending),
        };
        let native = native.map_err(|error| {
            if matches!(error, admit::Error::Full(_)) {
                self.local.retry = true;
            }
            cancel::Error::new(echo, error)
        })?;
        Ok(admit::Submission::submit(native))
    }

    fn submitted<T>(
        &mut self,
        result: Result<T, device::Failure<handles::Descriptor<'d>, Vacancy>>,
    ) -> Result<T, pending::Rejection<'d>> {
        result.map_err(|error| {
            if matches!(&error, device::Failure::Reserve(tuning::Error::Full(..))) {
                self.local.retry = true;
            }
            error.into()
        })
    }

    pub(crate) fn resolve(self) -> Resolver<'a, 'd> {
        Resolver::new(self.local)
    }

    pub(crate) fn reclaim(&mut self, limit: usize) {
        let driver = self.local.driver;
        let owners = driver.owners();
        let mut count = 0;
        while count < limit {
            let Some(token) = owners.pop_returned() else {
                break;
            };
            // SAFETY: Local pairs this backend with its branded receive owners.
            // pop_returned transfers the unique slot after its last projection.
            unsafe { buffer::raw::Release::release(&mut *self.local.backend, token) };
            count += 1;
        }
        if count != 0
            && let Ok(permit) = crate::Permits::try_acquire()
        {
            receive::Proof::release(&permit, driver.exhausted(), driver);
        }
    }

    pub(crate) fn install<H, E>(
        self,
        hold: slot::Reserved<'d>,
        handle: H,
    ) -> Result<handles::Descriptor<'d>, result::Kernel>
    where
        Engine: engine::Install<handles::OwnedSlot, H, Error = E>,
        E: Into<<crate::Backend as kernel::Source>::Failure<indices::SlotIndex>>,
    {
        let state = &mut *self.local.backend;
        let slot = handles::OwnedSlot::from(hold.slot());
        if let Err(error) = engine::Install::install(state, slot, handle) {
            drop(hold);
            let cause: <crate::Backend as kernel::Source>::Failure<indices::SlotIndex> =
                error.into();
            return Err(result::Kernel::native(cause));
        }
        let (driver, slot) = hold.commit();
        Ok(handles::Descriptor::from_slot(slot, driver))
    }
}

const _: () = {
    assert!(mem::size_of::<Access<'static, 'static>>() == mem::size_of::<usize>());
};

impl AsMut<Engine> for Access<'_, '_> {
    fn as_mut(&mut self) -> &mut Engine {
        &mut self.local.backend
    }
}

/// Owns the routed option request throughout native application and settlement.
pub(crate) struct Apply<'a, 'd, Tag, V: Value = ()>
where
    Tag: route::Tag + route::Select<kind::Tuning>,
    'd: 'a,
{
    native: Access<'a, 'd>,
    slots: &'a flight::Slots<'d, Tag>,
    target: route::Target<'d, Tag>,
    fd: handles::Descriptor<'d>,
    opts: V::Options,
}

pub(crate) trait Value: Sized {
    type Options;
    type Output<'d>;

    fn options(value: &Self::Options) -> Option<option::NonEmpty<'_>>;
    fn finish<'d>(
        value: device::Finish<
            handles::Descriptor<'d>,
            flight::Reserved<'d, kind::Tuning>,
            <Engine as engine::Cancel<indices::SlotIndex>>::Permit,
            Self,
        >,
    ) -> Self::Output<'d>;
}

impl Value for () {
    type Options = option::Set;
    type Output<'d> = option::Tuning<'d>;

    fn options(value: &Self::Options) -> Option<option::NonEmpty<'_>> {
        value.non_empty()
    }

    fn finish<'d>(
        value: device::Finish<
            handles::Descriptor<'d>,
            flight::Reserved<'d, kind::Tuning>,
            <Engine as engine::Cancel<indices::SlotIndex>>::Permit,
        >,
    ) -> Self::Output<'d> {
        pending::Tuning::from_native(value)
    }
}

impl Value for u32 {
    type Options = ();
    type Output<'d> = peer::Query<'d>;

    fn options(_: &Self::Options) -> Option<option::NonEmpty<'_>> {
        None
    }

    fn finish<'d>(
        value: device::Finish<
            handles::Descriptor<'d>,
            flight::Reserved<'d, kind::Tuning>,
            <Engine as engine::Cancel<indices::SlotIndex>>::Permit,
            Self,
        >,
    ) -> Self::Output<'d> {
        peer::Query::from_native(value)
    }
}

impl<'a, 'd, Tag, V: Value> Apply<'a, 'd, Tag, V>
where
    Tag: route::Tag + route::Select<kind::Tuning>,
    'd: 'a,
{
    pub(crate) fn new(
        native: Access<'a, 'd>,
        slots: &'a flight::Slots<'d, Tag>,
        target: route::Target<'d, Tag>,
        fd: handles::Descriptor<'d>,
        opts: V::Options,
    ) -> Self {
        Self {
            native,
            slots,
            target,
            fd,
            opts,
        }
    }
}

// SAFETY: Local and the invariant descriptor lifetime bind one driver. Domain
// checked this descriptor's index inside the immutable FileSlots extent; both
// native targets below come from it. A ring backend creates its pinned tuning
// table with that same extent. There pending::Tuning owns the fd until
// cqe::Tuned::complete clears its state before completion. Drop leaves the
// Domain retirement queued while Engine::retire waits for that state's terminal;
// only then may close completion recycle the slot. Readiness options are applied
// synchronously. Local retains the backend throughout both native paths.
unsafe impl<'a, 'd, Tag, B, V: Value> device::raw::Host<B, { option::MAX_STREAM_OPTIONS }>
    for Apply<'a, 'd, Tag, V>
where
    Tag: route::Tag + route::Select<kind::Tuning>,
    'd: 'a,
    Access<'a, 'd>: AsMut<B>,
{
    type File = handles::Descriptor<'d>;
    type Slot = <<crate::Backend as Source<request::Context>>::Raw as Lower>::Target;
    type Index = indices::SlotIndex;
    type Reserve = flight::Request<'a, 'd, Tag, kind::Tuning>;
    type Options<'o> = option::NonEmpty<'o>;
    type Permit = <Engine as engine::Cancel<indices::SlotIndex>>::Permit;
    type Value = V;
    type Output = V::Output<'d>;
    type Error = pending::Rejection<'d>;

    fn direct(
        mut self,
        run: impl for<'o> FnOnce(
            &mut B,
            Self::File,
            Self::Slot,
            Option<Self::Options<'o>>,
        ) -> Result<(Self::File, V), (Self::File, dope_sys::Errno)>,
    ) -> Result<Self::Output, Self::Error> {
        let slot = <crate::Backend as Source<request::Context>>::target(self.fd.slot());
        let options = V::options(&self.opts);
        let (fd, value) = run(self.native.as_mut(), self.fd, slot, options)
            .map_err(|(fd, errno)| device::Failure::<_, Vacancy>::Option(fd, errno))?;
        Ok(V::finish(device::Finish::Applied(fd, value)))
    }

    fn with(
        self,
        run: impl for<'o> FnOnce(
            &mut B,
            Self::File,
            Self::Slot,
            Self::Index,
            Option<Self::Options<'o>>,
            Self::Reserve,
        ) -> Result<
            device::Finish<Self::File, flight::Reserved<'d, kind::Tuning>, Self::Permit, V>,
            device::Failure<Self::File, Vacancy>,
        >,
    ) -> Result<Self::Output, Self::Error> {
        let Self {
            mut native,
            slots,
            target,
            fd,
            opts,
        } = self;
        let slot = <crate::Backend as Source<request::Context>>::target(fd.slot());
        let index = fd.index();
        let reserve = flight::Request::new(slots, target.operation::<kind::Tuning>());
        let opts = V::options(&opts);
        let result = run(native.as_mut(), fd, slot, index, opts, reserve);
        Ok(V::finish(native.submitted(result)?))
    }
}

/// The only authority handed from common reactor maintenance to a backend.
pub(crate) struct Backend<'turn, 'd> {
    work: scope::Reactor<'turn, 'd>,
}

impl<'turn, 'd> Backend<'turn, 'd> {
    pub(crate) fn new(work: scope::Reactor<'turn, 'd>) -> Self {
        Self { work }
    }

    fn share<const N: usize, const I: usize>(&self, cursor: usize) -> usize {
        const {
            assert!(N != 0);
            assert!(I < N);
            assert!(N <= usize::MAX - I);
        }
        let total = self.remaining();
        let base = total / N;
        let extra = total % N;
        let span = (I + N - (cursor % N)) % N;
        base + if span < extra { 1 } else { 0 }
    }
}

impl<'d> delivery::Quota<driver::Context<'_, 'd>> for Backend<'_, 'd> {
    /// Returns native buffers and notifies current receive waiters.
    fn reclaim(&self, ctx: &mut driver::Context<'_, 'd>) {
        ctx.native().reclaim(schedule::LIMIT);

        let keep = self.share::<{ scope::REACTORS }, 1>(self.work.cursor());

        let limit = self.remaining().saturating_sub(keep);
        {
            let mut budget = self.work.budget::<drain::Lane>(limit);
            drain::Drain::reclaim(ctx, &mut budget);
        }
    }
}

impl<'turn, 'd> Quota for Backend<'turn, 'd> {
    type Budget<'a, Lane>
        = lanes::Budget<'a, 'd, Lane>
    where
        Self: 'a;

    fn remaining(&self) -> usize {
        self.work.remaining()
    }

    fn refund(self) {
        drop(self.work);
    }

    fn budget<Lane>(&self, limit: usize) -> Self::Budget<'_, Lane> {
        self.work.budget(limit)
    }
}