Skip to main content

dope_core/driver/settings/
mod.rs

1use std::num;
2
3pub use config::Config;
4pub(crate) use config::plan::{Plan, Ready};
5use demands::slots;
6use o3::{base::num::bounded, depot, depot::capacity};
7pub use receive::Receive;
8pub use resource::Resource;
9pub use routes::Routes;
10
11use crate::{
12    driver::route::{self, SLOT_MASK, indices::SlotIndex, table},
13    io::{datagram::payload, socket::option, transfer},
14};
15
16pub mod claim;
17mod config;
18pub mod demands;
19pub mod errors;
20mod receive;
21mod resource;
22mod routes;
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub struct DomainSum {
26    current: Domain,
27    added: Domain,
28}
29
30impl DomainSum {
31    pub const fn parts(&self) -> (&Domain, &Domain) {
32        (&self.current, &self.added)
33    }
34}
35
36#[derive(Clone, Copy, PartialEq, Eq)]
37#[repr(transparent)]
38pub struct Datagram(Receive);
39
40impl Datagram {
41    /// Constructs a datagram layout whose bounds are checked during compilation.
42    ///
43    pub const fn fixed<const ENTRIES: u16, const PAYLOAD: u32>() -> Self {
44        const {
45            let len = transfer::NonZero::from_payload(payload::Len::fixed::<PAYLOAD>());
46            assert!((ENTRIES as u64) * (len.into_nonzero().get() as u64) <= isize::MAX as u64);
47            let entries = Buffers::fixed::<ENTRIES>();
48            Self(Receive::from_parts(entries, len))
49        }
50    }
51
52    pub const fn new(entries: Buffers, payload: payload::Len) -> Self {
53        let len = transfer::NonZero::from_payload(payload);
54        Self(Receive::from_parts(entries, len))
55    }
56
57    pub const fn receive(self) -> Receive {
58        self.0
59    }
60}
61
62const _: () = {
63    assert!(std::mem::size_of::<Datagram>() == std::mem::size_of::<Receive>());
64    assert!(std::mem::align_of::<Datagram>() == std::mem::align_of::<Receive>());
65};
66
67const MIN_SUBMISSION_CAPACITY: u32 = (option::MAX_STREAM_OPTIONS + 1) as u32;
68const MAX_SUBMISSION_CAPACITY: u32 = 32_768;
69const MAX_COMPLETION_CAPACITY: u32 = 65_536;
70pub(crate) const MAX_FILE_CAPACITY: u32 = SLOT_MASK as u32 + 1;
71
72/// Backend-neutral intent for making completed work visible to the driver.
73#[derive(Clone, Copy, PartialEq, Eq)]
74#[repr(u8)]
75pub enum Progress {
76    /// Avoid voluntarily deferring backend completion work.
77    Prompt,
78    /// Permit a backend to coalesce completion work until the next driver entry.
79    BatchedWhenSupported,
80}
81
82/// Static driver policy with a validated receive-buffer layout.
83///
84/// Invalid layouts cannot become profile constants:
85///
86pub trait Profile {
87    const QUEUES: QueueLayout;
88    const SCHEDULER: Schedule = Schedule::DEFAULT;
89    const COMPLETION_PROGRESS: Progress = Progress::BatchedWhenSupported;
90    /// Backend descriptor baseline. Topology-owned accept and outbound demand
91    /// is composed separately through [`Resource`].
92    const FILES: FileSlots = FileSlots::fixed::<0, 256>();
93    const RECEIVE: Receive = Receive::DEFAULT;
94    /// Stable resident-accounting domains available to one driver scope.
95    const RESIDENT_DOMAINS: Domain = Domain::ZERO;
96}
97
98#[derive(Clone, Copy, PartialEq, Eq, Debug)]
99#[repr(transparent)]
100pub struct Buffers(num::NonZero<u16>);
101
102impl Buffers {
103    const MAX: u32 = 32_768;
104
105    const fn fixed<const COUNT: u16>() -> Self {
106        const {
107            assert!(COUNT >= 2 && COUNT as u32 <= Self::MAX);
108            Self(num::NonZero::<u16>::MIN.saturating_add(COUNT - 1))
109        }
110    }
111
112    pub const fn into_nonzero(self) -> num::NonZero<u16> {
113        self.0
114    }
115
116    pub(crate) const fn get(self) -> u16 {
117        self.0.get()
118    }
119}
120
121impl TryFrom<u32> for Buffers {
122    type Error = errors::Config;
123
124    fn try_from(entries: u32) -> Result<Self, Self::Error> {
125        if !(2..=Self::MAX).contains(&entries) {
126            return Err(errors::Config::ReceiveEntriesOutOfRange {
127                actual: entries,
128                minimum: 2,
129                maximum: Self::MAX,
130            });
131        }
132        Ok(Self(
133            num::NonZero::<u16>::MIN.saturating_add(entries as u16 - 1),
134        ))
135    }
136}
137
138#[derive(Clone, Copy, Debug, PartialEq, Eq)]
139pub struct QueueLayout {
140    submissions: Submission,
141    completions: Completion,
142}
143
144impl QueueLayout {
145    /// Creates a queue layout validated during compilation.
146    pub const fn fixed<const SUBMISSIONS: u32, const COMPLETIONS: u32>() -> Self {
147        const {
148            assert!(SUBMISSIONS >= MIN_SUBMISSION_CAPACITY);
149            assert!(SUBMISSIONS <= MAX_SUBMISSION_CAPACITY);
150            assert!(SUBMISSIONS.is_power_of_two());
151            assert!(COMPLETIONS != 0);
152            assert!(COMPLETIONS <= MAX_COMPLETION_CAPACITY);
153            assert!(COMPLETIONS.is_power_of_two());
154            assert!(COMPLETIONS >= SUBMISSIONS);
155            QueueLayout {
156                submissions: Submission(bounded::raw::U32::clamp(SUBMISSIONS as usize)),
157                completions: Completion(bounded::raw::U32::clamp(COMPLETIONS as usize)),
158            }
159        }
160    }
161
162    /// Enlarges submission capacity and keeps the completion queue at least as large.
163    pub fn resolve(self, need: demands::Submit) -> Result<Self, errors::Claim> {
164        let wanted = self.submissions().max(need.get());
165        let submit = wanted
166            .checked_next_power_of_two()
167            .ok_or(errors::Claim::QueueSubmissionsPowerOfTwoOverflow { requested: wanted })?;
168        if submit > MAX_SUBMISSION_CAPACITY {
169            return Err(errors::Config::QueueSubmissionsOutOfRange {
170                actual: submit,
171                minimum: MIN_SUBMISSION_CAPACITY,
172                maximum: MAX_SUBMISSION_CAPACITY,
173            }
174            .into());
175        }
176
177        let complete = self.completions().max(submit);
178
179        Ok(Self {
180            submissions: Submission(bounded::raw::U32::clamp(submit as usize)),
181            completions: Completion(bounded::raw::U32::clamp(complete as usize)),
182        })
183    }
184
185    pub const fn submission(self) -> Submission {
186        self.submissions
187    }
188
189    pub(crate) const fn completion(self) -> Completion {
190        self.completions
191    }
192
193    pub(crate) const fn submissions(self) -> u32 {
194        self.submissions.get()
195    }
196
197    pub(crate) const fn completions(self) -> u32 {
198        self.completions.get()
199    }
200}
201
202/// A descriptor-slot layout representable by every backend target table.
203#[derive(Clone, Copy, PartialEq, Eq)]
204pub struct FileSlots {
205    accept: table::Capacity,
206    table: bounded::raw::NonZeroU32<1, MAX_FILE_CAPACITY>,
207}
208
209impl FileSlots {
210    /// Creates a descriptor-slot layout validated during compilation.
211    ///
212    ///
213    pub const fn fixed<const ACCEPT: u32, const OUTBOUND: u32>() -> Self {
214        const { assert!(OUTBOUND != 0) };
215        const {
216            match Self::try_new(ACCEPT, OUTBOUND) {
217                Ok(slots) => slots,
218                Err(_) => panic!("capacity"),
219            }
220        }
221    }
222
223    /// Resolves descriptor demand against this validated baseline.
224    pub fn resolve(self, need: demands::Files) -> Result<Self, errors::Config> {
225        let accept = self.accept().raw().max(need.accepted().get());
226        let outbound = self.outbound().raw().max(need.outbound().get());
227        Self::try_new(accept, outbound)
228    }
229
230    const fn try_new(accept: u32, outbound: u32) -> Result<Self, errors::Config> {
231        let total = accept as usize + outbound as usize;
232        match bounded::raw::NonZeroU32::from_usize(total) {
233            Some(table) => Ok(Self {
234                accept: table::Capacity(capacity::Count::new(accept)),
235                table,
236            }),
237            None => Err(errors::Config::DescriptorCapacityOutOfRange {
238                accepted: accept,
239                outbound,
240                actual: total as u64,
241                minimum: 1,
242                maximum: MAX_FILE_CAPACITY,
243            }),
244        }
245    }
246
247    #[must_use]
248    pub const fn capacity(self) -> table::Capacity {
249        table::Capacity(capacity::Count::new(self.table.get()))
250    }
251
252    #[must_use]
253    pub const fn accept(self) -> table::Capacity {
254        self.accept
255    }
256
257    #[must_use]
258    pub const fn outbound(self) -> table::Capacity {
259        table::Capacity(capacity::Count::new(self.table.get() - self.accept.raw()))
260    }
261
262    pub(crate) fn accept_slot(self) -> Option<SlotIndex> {
263        let span = self.accept.span()?;
264        Some(SlotIndex::from_field(u64::from(span.get())))
265    }
266
267    pub(crate) const fn bound(self) -> bounded::raw::U32<1, MAX_FILE_CAPACITY> {
268        self.table.into_u32()
269    }
270}
271
272/// Representable number of resident-accounting domains in one driver scope.
273///
274#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
275#[repr(transparent)]
276pub struct Domain(u32);
277
278impl Domain {
279    pub const ZERO: Self = Self(0);
280    pub const ONE: Self = Self(1);
281    pub const MAX: Self = Self(u32::MAX);
282
283    /// Creates a count across the complete `u32` representation.
284    pub const fn fixed<const COUNT: u32>() -> Self {
285        Self(COUNT)
286    }
287
288    /// Resolves additive resident-domain demand against this baseline.
289    #[must_use]
290    pub const fn resolve(self, need: Self) -> Self {
291        if self.0 >= need.0 { self } else { need }
292    }
293
294    pub const fn combine(self, next: Self) -> Result<Self, DomainSum> {
295        match self.0.checked_add(next.0) {
296            Some(total) => Ok(Self(total)),
297            None => Err(DomainSum {
298                current: self,
299                added: next,
300            }),
301        }
302    }
303
304    #[must_use]
305    pub const fn get(self) -> u32 {
306        self.0
307    }
308}
309
310const _: () = {
311    assert!(std::mem::size_of::<Domain>() == std::mem::size_of::<u32>());
312    assert!(std::mem::align_of::<Domain>() == std::mem::align_of::<u32>());
313};
314
315#[derive(Clone, Copy, PartialEq, Eq, Debug)]
316#[repr(transparent)]
317pub struct Submission(bounded::raw::U32<MIN_SUBMISSION_CAPACITY, MAX_SUBMISSION_CAPACITY>);
318
319impl Submission {
320    pub(crate) const fn get(self) -> u32 {
321        self.0.get()
322    }
323}
324
325#[derive(Clone, Copy, PartialEq, Eq, Debug)]
326#[repr(transparent)]
327pub(crate) struct Completion(pub(crate) bounded::raw::U32<1, MAX_COMPLETION_CAPACITY>);
328
329impl Completion {
330    pub(crate) const fn get(self) -> u32 {
331        self.0.get()
332    }
333}
334
335const _: () = {
336    assert!(std::mem::size_of::<Completion>() == std::mem::size_of::<u32>());
337    assert!(std::mem::align_of::<Completion>() == std::mem::align_of::<u32>());
338};
339
340impl From<FileSlots> for (table::Capacity, table::Capacity) {
341    fn from(layout: FileSlots) -> Self {
342        (layout.capacity(), layout.accept)
343    }
344}
345
346// SAFETY: Completion retains one immutable bounded queue capacity in every copy.
347unsafe impl depot::raw::Count for Completion {
348    const MAX: u32 = MAX_COMPLETION_CAPACITY;
349
350    fn count(self) -> capacity::Count {
351        capacity::Count::new(self.0.get())
352    }
353}
354
355/// The inclusive bounds of a contiguous, nonempty set of application routes.
356#[derive(Clone, Copy)]
357pub struct RouteSpan {
358    first: u8,
359    last: u8,
360}
361
362impl RouteSpan {
363    pub const fn has_route(self, route: route::Route) -> bool {
364        self.first <= route.raw() && route.raw() <= self.last
365    }
366}
367
368/// Ready and timer slot counts, added for claims and resolved against a baseline.
369#[derive(Clone, Copy, Default, Eq, PartialEq)]
370#[repr(C)]
371pub struct Schedule {
372    ready: slots::Slots,
373    timers: slots::Slots,
374}
375
376impl Schedule {
377    pub const ZERO: Self = Self::new(slots::Slots::ZERO, slots::Slots::ZERO);
378    pub const DEFAULT: Self = Self::fixed::<1024, 1024>();
379
380    pub const fn new(ready: slots::Slots, timers: slots::Slots) -> Self {
381        Self { ready, timers }
382    }
383
384    pub const fn fixed<const READY: u32, const TIMERS: u32>() -> Self {
385        Self::new(
386            slots::Slots::fixed::<READY>(),
387            slots::Slots::fixed::<TIMERS>(),
388        )
389    }
390
391    #[must_use]
392    pub const fn resolve(self, need: Self) -> Self {
393        Self {
394            ready: self.ready.max(need.ready),
395            timers: self.timers.max(need.timers),
396        }
397    }
398
399    #[must_use]
400    pub const fn ready(self) -> slots::Slots {
401        self.ready
402    }
403
404    #[must_use]
405    pub const fn timers(self) -> slots::Slots {
406        self.timers
407    }
408
409    pub(in crate::driver::settings) fn merge(self, next: Self) -> Result<Self, errors::Claim> {
410        let ready = self
411            .ready
412            .checked_add(next.ready)
413            .map_err(errors::Claim::SchedulerReadyOverflow)?;
414        let timers = self
415            .timers
416            .checked_add(next.timers)
417            .map_err(errors::Claim::SchedulerTimersOverflow)?;
418        Ok(Self::new(ready, timers))
419    }
420}