Skip to main content

dope_core/io/socket/option/
mod.rs

1use dope_sys::io::reactor::event::{Entry, kind};
2use o3::mem::slot;
3use std::{mem, num::NonZero, time};
4
5use dope_sys::{
6    engine::admit,
7    io::socket::option::{Kind, Value},
8};
9
10use crate::{
11    Backend, Errno,
12    driver::{self, life::native::host::Host, retained::flight, route},
13    io::{fd::handles, socket::pending},
14};
15
16mod kinds;
17
18pub(super) use kinds::Mask;
19pub(crate) use kinds::NonEmpty;
20
21/// Maximum number of distinct options represented by a stream-option set.
22pub(crate) const MAX_STREAM_OPTIONS: usize = 7;
23
24/// An explicit binary socket-option command.
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26#[repr(u8)]
27pub enum Switch {
28    Off,
29    On,
30}
31
32/// A socket-buffer request representable by the kernel ABI.
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34#[repr(transparent)]
35pub struct Buffer(Value);
36
37/// A positive, whole-second keep-alive period representable by the kernel ABI.
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39#[repr(transparent)]
40pub struct Period(NonZero<u32>);
41
42/// A positive keep-alive retry count representable by the kernel ABI.
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44#[repr(transparent)]
45pub struct Retries(NonZero<u32>);
46
47impl Switch {
48    pub(crate) const fn value(self) -> Value {
49        match self {
50            Self::Off => Value::ZERO,
51            Self::On => Value::from_enabled(true),
52        }
53    }
54}
55
56impl Buffer {
57    const fn value(self) -> Value {
58        self.0
59    }
60}
61
62impl Period {
63    const fn value(self) -> Value {
64        Value::new(self.0.get() as i32)
65    }
66}
67
68impl Retries {
69    const fn value(self) -> Value {
70        Value::new(self.0.get() as i32)
71    }
72}
73
74/// Validated, allocation-free stream options owning every scalar retained by
75/// an asynchronous kernel submission.
76#[derive(Clone, Copy)]
77pub struct Set {
78    recv_buffer: Value,
79    send_buffer: Value,
80    keep_alive_idle: Value,
81    keep_alive_interval: Value,
82    keep_alive_retries: Value,
83    present: Mask,
84    enabled: Mask,
85}
86
87/// Invalid allocation-free socket-option configuration.
88#[derive(Clone, Copy, PartialEq, Eq, Debug)]
89#[repr(u8)]
90pub enum Error {
91    Buffer {
92        actual: usize,
93        maximum: usize,
94    },
95    Period {
96        actual: time::Duration,
97        maximum: time::Duration,
98    },
99    Retries {
100        actual: u32,
101        maximum: u32,
102    },
103}
104
105impl Default for Set {
106    fn default() -> Self {
107        Self::EMPTY
108    }
109}
110
111/// Result of submitting a strongly ordered socket-tuning plan.
112pub enum Tuning<'d, P = pending::raw::Owner<'d, kind::Tuning>> {
113    /// All options were applied synchronously.
114    Applied(handles::Descriptor<'d>),
115    /// The descriptor and its exact completion/cancellation authority remain
116    /// indivisible until the operation resolves.
117    Pending(P),
118}
119
120impl Set {
121    /// Admits already-validated, structurally distinct stream options.
122    pub fn new(
123        recv: Option<Buffer>,
124        send: Option<Buffer>,
125        no_delay: Option<Switch>,
126        alive: Option<Switch>,
127        idle: Option<Period>,
128        interval: Option<Period>,
129        retries: Option<Retries>,
130    ) -> Self {
131        let mut set = Self::EMPTY;
132        if let Some(value) = recv {
133            set.set(Kind::RecvBuffer, value.value());
134        }
135        if let Some(value) = send {
136            set.set(Kind::SendBuffer, value.value());
137        }
138        if let Some(value) = no_delay {
139            set.set(Kind::NoDelay, value.value());
140        }
141        if let Some(value) = alive {
142            set.set(Kind::KeepAlive, value.value());
143        }
144        if let Some(value) = idle {
145            set.set(Kind::KeepAliveIdle, value.value());
146        }
147        if let Some(value) = interval {
148            set.set(Kind::KeepAliveInterval, value.value());
149        }
150        if let Some(value) = retries {
151            set.set(Kind::KeepAliveRetries, value.value());
152        }
153        set
154    }
155
156    pub const EMPTY: Self = Self {
157        recv_buffer: Value::ZERO,
158        send_buffer: Value::ZERO,
159        keep_alive_idle: Value::ZERO,
160        keep_alive_interval: Value::ZERO,
161        keep_alive_retries: Value::ZERO,
162        present: Mask::EMPTY,
163        enabled: Mask::EMPTY,
164    };
165
166    pub(crate) fn non_empty(&self) -> Option<NonEmpty<'_>> {
167        NonEmpty::new(self, self.present)
168    }
169
170    fn value(&self, kind: Kind) -> Value {
171        match kind {
172            Kind::NoDelay | Kind::KeepAlive => Value::from_enabled(self.enabled.contains(kind)),
173            Kind::RecvBuffer => self.recv_buffer,
174            Kind::SendBuffer => self.send_buffer,
175            Kind::KeepAliveIdle => self.keep_alive_idle,
176            Kind::KeepAliveInterval => self.keep_alive_interval,
177            Kind::KeepAliveRetries => self.keep_alive_retries,
178        }
179    }
180
181    fn set(&mut self, kind: Kind, value: Value) {
182        self.present.insert(kind);
183        match kind {
184            Kind::NoDelay | Kind::KeepAlive if !value.is_zero() => self.enabled.insert(kind),
185            Kind::NoDelay | Kind::KeepAlive => {}
186            Kind::RecvBuffer => self.recv_buffer = value,
187            Kind::SendBuffer => self.send_buffer = value,
188            Kind::KeepAliveIdle => self.keep_alive_idle = value,
189            Kind::KeepAliveInterval => self.keep_alive_interval = value,
190            Kind::KeepAliveRetries => self.keep_alive_retries = value,
191        }
192    }
193}
194
195impl TryFrom<usize> for Buffer {
196    type Error = Error;
197
198    fn try_from(actual: usize) -> Result<Self, Self::Error> {
199        let maximum = i32::MAX as usize;
200        if actual <= maximum {
201            Ok(Self(Value::new(actual as i32)))
202        } else {
203            Err(Error::Buffer { actual, maximum })
204        }
205    }
206}
207
208impl TryFrom<time::Duration> for Period {
209    type Error = Error;
210
211    fn try_from(actual: time::Duration) -> Result<Self, Self::Error> {
212        let maximum = time::Duration::from_secs(i32::MAX as u64);
213        if actual.is_zero() || actual > maximum {
214            return Err(Error::Period { actual, maximum });
215        }
216        let seconds = actual.as_secs() + u64::from(actual.subsec_nanos() != 0);
217        Ok(Self(NonZero::<u32>::MIN.saturating_add(seconds as u32 - 1)))
218    }
219}
220
221impl TryFrom<u32> for Retries {
222    type Error = Error;
223
224    fn try_from(actual: u32) -> Result<Self, Self::Error> {
225        let maximum = i32::MAX as u32;
226        if actual == 0 || actual > maximum {
227            return Err(Error::Retries { actual, maximum });
228        }
229        Ok(Self(NonZero::<u32>::MIN.saturating_add(actual - 1)))
230    }
231}
232
233const _: () = {
234    assert!(mem::size_of::<Switch>() == mem::size_of::<bool>());
235    assert!(mem::align_of::<Switch>() == mem::align_of::<bool>());
236    assert!(mem::size_of::<Buffer>() == mem::size_of::<Value>());
237    assert!(mem::size_of::<Period>() == mem::size_of::<Value>());
238    assert!(mem::size_of::<Retries>() == mem::size_of::<Value>());
239    assert!(mem::size_of::<Option<Period>>() == mem::size_of::<Period>());
240    assert!(mem::size_of::<Option<Retries>>() == mem::size_of::<Retries>());
241    assert!(mem::size_of::<Set>() == 24);
242};
243
244impl<'d> Tuning<'d> {
245    pub fn complete<'slot>(
246        owner: slot::Occupied<'slot, pending::raw::Owner<'d, kind::Tuning>>,
247        done: &Entry<flight::Complete<'d>, kind::Tuning, Result<u32, Errno>>,
248    ) -> pending::raw::Completion<'slot, 'd, pending::raw::Owner<'d, kind::Tuning>, Result<(), Errno>>
249    {
250        let (fd, result) = pending::raw::Owner::complete(owner, done)?;
251        Ok((fd, result.and(Ok(()))))
252    }
253
254    pub fn try_new<Tag: route::Tag + route::Select<kind::Tuning>>(
255        driver: &mut driver::Local<'d>,
256        slots: &flight::raw::Slots<'d, Tag>,
257        target: route::Target<'d, Tag>,
258        fd: handles::Descriptor<'d>,
259        opts: Set,
260    ) -> Result<Self, pending::Rejection<'d>> {
261        let slot = fd.slot();
262        // SAFETY: these exact driver-branded owners retain the native slot and
263        // flight until terminal completion; native admission cannot reenter slots.
264        unsafe {
265            admit::raw::Socket::<Host<Backend>, MAX_STREAM_OPTIONS>::tune(
266                &mut *driver.backend,
267                (slots, target.operation::<kind::Tuning>()),
268                (fd, driver.driver.brand),
269                slot,
270                opts.non_empty().map(NonEmpty::split),
271                &mut driver.retry,
272            )
273        }
274    }
275}
276
277impl<'d> From<(handles::Descriptor<'d>, driver::Invariant<'d>)> for Tuning<'d> {
278    fn from((fd, _): (handles::Descriptor<'d>, driver::Invariant<'d>)) -> Self {
279        Self::Applied(fd)
280    }
281}
282
283impl<'d, P>
284    From<(
285        (handles::Descriptor<'d>, driver::Invariant<'d>),
286        flight::Flight<'d, kind::Tuning>,
287        P,
288    )> for Tuning<'d, pending::raw::Owner<'d, kind::Tuning, P>>
289{
290    fn from(
291        ((fd, _), flight, permit): (
292            (handles::Descriptor<'d>, driver::Invariant<'d>),
293            flight::Flight<'d, kind::Tuning>,
294            P,
295        ),
296    ) -> Self {
297        Self::Pending(pending::raw::Owner::new(fd, flight, permit))
298    }
299}