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
use std::{cell, marker, num};

use o3::mem::Lease;

use crate::driver::schedule::{
    app, ready,
    ready::{Resident, Slots, Staged, state, task},
};

pub mod raw;

/// One queued activation with the emitting task generation.
pub struct Wake<'d, I> {
    local: I,
    key: ready::Key<'d>,
}

impl<'d, I: raw::Index> Wake<'d, I> {
    pub const fn local(&self) -> I {
        self.local
    }

    pub(super) fn identify(self, task: &ready::TaskKey<'d>) -> Option<ready::Key<'d>> {
        use dope_sys::table::permit;
        let id = permit::raw::Key::identity(self.key.raw());
        (id == permit::raw::Key::identity(task.key().raw())).then_some(self.key)
    }
}

/// Borrowed edge to one driver-owned ready topology.
#[must_use = "an edge must be installed or explicitly dropped"]
pub struct Edge<'queue, 'd, I: raw::Index> {
    endpoint: &'queue Endpoint<'d, I>,
    local: I,
}

impl<'queue, 'd, I: raw::Index> Edge<'queue, 'd, I> {
    pub(super) const fn new(endpoint: &'queue Endpoint<'d, I>, local: I) -> Self {
        Self { endpoint, local }
    }

    #[doc(hidden)]
    pub const fn local(&self) -> I {
        self.local
    }

    pub(in crate::driver::schedule::ready::task) fn into_parts(
        self,
    ) -> (&'queue Endpoint<'d, I>, I) {
        (self.endpoint, self.local)
    }
}

/// Driver-owned stable task-ready topology.
pub struct Endpoint<'d, I: raw::Index> {
    owner: Lease<ready::TopologyKey<'d>>,
    local: marker::PhantomData<fn(I) -> I>,
}

impl<'d, I: raw::Index> Endpoint<'d, I> {
    pub fn try_new(parent: task::Parent<'d>) -> Result<Self, task::Error> {
        let driver = parent.driver();
        let entries = &driver.ready().arena().entries;
        let key = match entries.pool.try_topology(&entries.slots) {
            Ok(key) => key,
            Err(error) => {
                return Err(task::Error::Capacity {
                    requested: num::NonZero::<usize>::MIN,
                    available: error.available(),
                });
            }
        };
        Ok(Self {
            owner: Lease::new(key, driver),
            local: marker::PhantomData,
        })
    }

    pub fn attach(&self, local: I) -> Edge<'_, 'd, I> {
        Edge::new(self, local)
    }

    pub fn drain(&self) -> Option<Drain<'_, 'd, I>> {
        let side = self.topology().begin()?;
        Some(Drain {
            endpoint: self,
            side,
        })
    }

    pub fn peek(&self) -> Option<I> {
        self.topology().peek().map(raw::restore)
    }

    pub fn pop(&self) -> Option<I> {
        self.drain()?.pop().map(|wake| wake.local)
    }

    pub fn is_empty(&self) -> bool {
        self.topology().is_empty()
    }

    pub(in crate::driver::schedule::ready::task) fn key(&self) -> &ready::TopologyKey<'d> {
        self.owner.sink()
    }

    fn topology(&self) -> ready::Root<'_> {
        let arena = self.owner.item().ready().arena();
        ready::Root::get(&arena.entries.slots, self.owner.sink())
    }
}

/// Lazily driver-bound owner of one stable task-ready topology.
pub struct Slot<'d, I: raw::Index> {
    pub(in crate::driver::schedule::ready) endpoint: cell::OnceCell<Endpoint<'d, I>>,
}

impl<I: raw::Index> Default for Slot<'_, I> {
    fn default() -> Self {
        Self::new()
    }
}

impl<'d, I: raw::Index> Slot<'d, I> {
    pub const fn new() -> Self {
        Self {
            endpoint: cell::OnceCell::new(),
        }
    }

    pub fn try_attach(
        &self,
        parent: task::Parent<'d>,
        local: I,
    ) -> Result<Edge<'_, 'd, I>, task::Error> {
        let endpoint = match self.endpoint.get() {
            Some(endpoint) => endpoint,
            None => {
                let endpoint = Endpoint::try_new(parent)?;
                self.endpoint.get_or_init(|| endpoint)
            }
        };
        Ok(endpoint.attach(local))
    }

    pub fn drain(&self) -> Option<Drain<'_, 'd, I>> {
        self.endpoint.get()?.drain()
    }

    pub fn peek(&self) -> Option<I> {
        self.endpoint.get()?.peek()
    }

    pub fn pop(&self) -> Option<I> {
        self.endpoint.get()?.pop()
    }

    pub fn is_empty(&self) -> bool {
        self.endpoint.get().is_none_or(Endpoint::is_empty)
    }
}

const ACTIVE_MASK: u64 = 1 << 32;
const PAUSED_MASK: u64 = ACTIVE_MASK << 1;
const DRAINING_MASK: u64 = PAUSED_MASK << 1;
const CLOSED_MASK: u64 = 1 << 35;

#[derive(Clone, Copy)]
struct Lanes<'a>(Resident<'a, state::Topology>);

#[derive(Clone, Copy)]
pub(in crate::driver::schedule::ready) struct Root<'a> {
    slots: &'a Slots,
    lanes: Lanes<'a>,
}

impl<'a> Root<'a> {
    fn new(slots: &'a Slots, root: Resident<'a, state::Topology>) -> Self {
        Self {
            slots,
            lanes: Lanes(root),
        }
    }

    pub(in crate::driver::schedule::ready) fn get(
        slots: &'a Slots,
        key: &ready::TopologyKey<'a>,
    ) -> Self {
        let root = slots.resident(key);
        Self::new(slots, root)
    }

    pub(in crate::driver::schedule::ready) fn at(
        slots: &'a Slots,
        index: ready::RootIndex,
    ) -> Self {
        let root = slots.resident(index);
        Self::new(slots, root)
    }

    pub(in crate::driver::schedule::ready) fn attach(
        self,
        staged: Staged<'a>,
    ) -> ready::TaskKey<'a> {
        self.lanes.attach(staged)
    }

    pub(in crate::driver::schedule::ready) fn detach(
        slots: &'a Slots,
        key: &ready::TaskKey<'a>,
    ) -> Option<ready::ReservedKey<'a>> {
        let index = ready::TaskIndex::new(key);
        let task = slots.resident(index);
        let topology = Self::at(slots, task.record().topology());
        if let Some(queued) = task.state().queued() {
            topology.remove(task, queued);
        }
        let root = topology.lanes.0;
        let next = root.flags().wrapping_sub(1);
        root.set_flags(next);
        if next as u32 == 0 && next & CLOSED_MASK != 0 {
            let index = ready::FreeIndex::from_code(root.index);
            let key = ready::TopologyKey::new(index, root.generation());
            Some(root.unroot(key))
        } else {
            None
        }
    }

    /// Queued tasks retain attachments until unlinking; zero count proves empty lanes.
    /// The shared u32 arena bounds the attachment count.
    pub(in crate::driver::schedule::ready) fn close(
        self,
        key: ready::TopologyKey<'a>,
    ) -> Option<ready::ReservedKey<'a>> {
        if self.lanes.0.flags() as u32 == 0 {
            Some(self.lanes.0.unroot(key))
        } else {
            self.lanes.close();
            None
        }
    }

    pub(in crate::driver::schedule::ready) fn activate(
        slots: &'a Slots,
        task: Resident<'a, state::Task>,
    ) -> Option<ready::Stored> {
        let vacant = task.state().vacant()?;
        let record = task.record();
        let root = Self::at(slots, record.topology());
        let side = Lanes::active(root.lanes.0.flags());
        let index = ready::TaskIndex::from_code(task.index);
        let mut links = root.lanes.links(side);
        task.set_link(ready::Link {
            next: None,
            prev: links.prev,
        });
        if let Some(prev) = links.prev {
            let tail = root.slots.resident(prev);
            let mut link = tail.link();
            link.next = Some(index);
            tail.set_link(link);
        } else {
            links.next = Some(index);
        }
        links.prev = Some(index);
        root.lanes.set_links(side, links);
        vacant.queue(side);
        Some(record.parent())
    }

    pub(in crate::driver::schedule::ready) fn begin(self) -> Option<state::Lane> {
        let root = self.lanes.0;
        let state = root.flags();
        if state & DRAINING_MASK != 0 {
            return None;
        }
        let side = Lanes::front(state);
        if state & PAUSED_MASK == 0 {
            self.lanes.head(side)?;
        }
        self.lanes.begin(state);
        Some(side)
    }

    pub(in crate::driver::schedule::ready) fn finish(self) {
        let state = self.lanes.0.flags();
        self.lanes.0.set_flags(state & !DRAINING_MASK);
    }

    pub(in crate::driver::schedule::ready) fn peek(self) -> Option<u32> {
        self.peek_side(Lanes::front(self.lanes.0.flags()))
    }

    pub(in crate::driver::schedule::ready) fn peek_side(self, side: state::Lane) -> Option<u32> {
        Some(self.head(side)?.record().local())
    }

    fn head(self, side: state::Lane) -> Option<Resident<'a, state::Task>> {
        Some(self.slots.resident(self.lanes.head(side)?))
    }

    pub(in crate::driver::schedule::ready) fn is_empty(self) -> bool {
        self.lanes.is_empty()
    }

    fn remove(self, task: Resident<'a, state::Task>, queued: state::Queued<'a>) {
        let side = queued.lane();
        let link = task.link();
        let mut root = self.lanes.links(side);
        if let Some(prev) = link.prev {
            let prev = self.slots.resident(prev);
            let mut links = prev.link();
            links.next = link.next;
            prev.set_link(links);
        } else {
            root.next = link.next;
        }
        if let Some(next) = link.next {
            let next = self.slots.resident(next);
            let mut links = next.link();
            links.prev = link.prev;
            next.set_link(links);
        } else {
            root.prev = link.prev;
        }
        self.lanes.set_links(side, root);
        queued.clear();
        if root.next.is_none() {
            let root = self.lanes.0;
            let state = root.flags();
            if Lanes::active(state) != side {
                root.set_flags(state & !PAUSED_MASK);
            }
        }
    }
}

impl Lanes<'_> {
    fn begin(self, state: u64) {
        let next = if state & PAUSED_MASK != 0 {
            state | DRAINING_MASK
        } else {
            state ^ (ACTIVE_MASK | PAUSED_MASK | DRAINING_MASK)
        };
        self.0.set_flags(next);
    }

    /// The root and Staged own distinct slots, bounding the prior count below u32::MAX - 1.
    fn attach<'d>(self, staged: Staged<'d>) -> ready::TaskKey<'d> {
        let state = self.0.flags();
        self.0.set_flags(state + 1);
        staged.attach()
    }

    fn close(self) {
        let state = self.0.flags();
        self.0.set_flags(state | CLOSED_MASK);
    }

    fn links(self, side: state::Lane) -> ready::Link {
        self.0.links(side)
    }

    fn set_links(self, side: state::Lane, links: ready::Link) {
        self.0.set_links(side, links);
    }

    fn head(self, side: state::Lane) -> Option<ready::TaskIndex> {
        self.links(side).next
    }

    fn active(state: u64) -> state::Lane {
        state::Lane::from_bit(state & ACTIVE_MASK != 0)
    }

    fn front(state: u64) -> state::Lane {
        Self::active(state ^ (state >> 1))
    }

    fn is_empty(self) -> bool {
        self.head(state::Lane::First).is_none() && self.head(state::Lane::Second).is_none()
    }
}

/// Exclusive drain of one stable lane. Task membership is resolved and consumed
/// within each operation, so cancelling a task cannot invalidate a retained head.
pub struct Drain<'queue, 'd, I: raw::Index> {
    endpoint: &'queue Endpoint<'d, I>,
    side: state::Lane,
}

impl<'d, I: raw::Index> Drain<'_, 'd, I> {
    pub fn peek(&self) -> Option<I> {
        self.endpoint
            .topology()
            .peek_side(self.side)
            .map(raw::restore)
    }

    pub fn pop(&mut self) -> Option<Wake<'d, I>> {
        let root = self.endpoint.topology();
        Some(self.take(root, root.head(self.side)?))
    }

    fn take(&self, root: Root<'_>, task: Resident<'_, state::Task>) -> Wake<'d, I> {
        let wake = Wake {
            local: raw::restore(task.record().local()),
            key: ready::Key::from_index(task.index, task.generation()),
        };
        root.remove(task, task.state().bind(self.side));
        wake
    }
}

impl<I: raw::Index> Drop for Drain<'_, '_, I> {
    fn drop(&mut self) {
        self.endpoint.topology().finish();
    }
}

impl<'d, I: raw::Index> Drain<'_, 'd, I> {
    pub fn next<'turn>(
        &mut self,
        work: app::Work<'turn, 'd>,
    ) -> app::Next<'turn, 'd, Wake<'d, I>, I> {
        let topology = self.endpoint.topology();
        let Some(task) = topology.head(self.side) else {
            return app::Next::Empty;
        };
        let Some(permit) = work.permit() else {
            return app::Next::Exhausted(raw::restore(task.record().local()));
        };
        app::Next::Item(self.take(topology, task), permit)
    }
}