dope-uring 0.2.3

Thin io_uring adaptor with "Manifolds"
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
mod buf;
pub mod config;
mod cqe;
mod current;
pub mod handle;
mod provided;
mod recv_msg_out;
mod request;
mod resources;
mod ring;
mod submit;
mod wire;

use std::io;
use std::marker::PhantomData;
use std::os::fd::AsRawFd;
use std::time::Duration;

use io_uring::{opcode, types};

use dope_core::addr::SockAddr;
use dope_core::driver::DriverOps;
use dope_core::submit::SendMsgPacket;

use crate::sys::Sqe;
use crate::sys::fd::FdUringExt;
use crate::sys::token::Token;
use crate::{Fd, FixedFd};

pub use self::buf::{FixedBufGuard, FixedBufWrite, ProvidedBuf};
pub use self::cqe::{CqeKind, CqeRouter, CqeView};
pub use self::current::{CurrentSlot, current, current_driver_mut, set_current};
pub use self::provided::ProvidedRing;
pub use self::recv_msg_out::RecvMsgOut;
pub use self::request::Request;

pub type DriverRef<'a> = &'a Driver;

pub(crate) use self::request::{RequestId, Requests};
pub(crate) use self::resources::Resources;
pub use self::ring::Ring;

use self::cqe::{RawCqe, make_view};
use self::wire::Wire;

pub struct Driver {
    pub(crate) requests: Requests,
    pub(crate) ring: Ring,
    pub(crate) resources: Resources,
    pub(crate) provided: ProvidedRing,
    pub(in crate::driver) cqe_scratch: Vec<self::cqe::RawCqe>,

    _not_send: PhantomData<*const ()>,
}

impl Drop for Driver {
    fn drop(&mut self) {
        let self_ptr = self as *mut Driver;
        if let Some(slot) = self::current::current()
            && slot.driver().as_ptr() == self_ptr
        {
            self::current::set_current(None);
        }
    }
}

impl Driver {
    pub(crate) fn new(ring: Ring, cfg: crate::DriverConfig, capacity: usize) -> io::Result<Self> {
        let provided = ProvidedRing::new(&ring, cfg.provided_buf_entries, cfg.provided_buf_len)
            .map_err(|e| {
                io::Error::other(format!(
                    "dope: required capability setup failed (provided buffer ring): {e}"
                ))
            })?;
        let resources = Resources::new(&ring, &cfg)?;
        Ok(Self {
            requests: Requests::with_capacity(capacity),
            ring,
            resources,
            provided,
            cqe_scratch: Vec::with_capacity(capacity),
            _not_send: PhantomData,
        })
    }

    #[inline(always)]
    pub fn has_pending(&mut self) -> bool {
        self.ring.has_submission() || self.ring.has_completion()
    }

    #[inline(always)]
    pub fn has_completion(&mut self) -> bool {
        self.ring.has_completion()
    }

    #[inline(always)]
    pub fn park(&mut self) -> io::Result<()> {
        self.ring.submit_and_wait(1)
    }

    #[inline(always)]
    pub fn park_for(&mut self, duration: Duration) -> io::Result<()> {
        self.ring.submit_with_timeout(1, duration)
    }
}

impl Driver {
    fn submit_retry_error(e: &io::Error) -> bool {
        matches!(e.raw_os_error(), Some(libc::EAGAIN) | Some(libc::EBUSY))
    }

    pub(super) fn submit_retry(&mut self) -> io::Result<usize> {
        match self.ring.submit() {
            Ok(submitted) => Ok(submitted),
            Err(ref e) if Self::submit_retry_error(e) => {
                self.tick()?;
                Ok(0)
            }
            Err(e) => Err(e),
        }
    }

    #[inline(always)]
    fn drive_loop(
        &mut self,
        mut on_completion: impl FnMut(&mut Self) -> io::Result<()>,
    ) -> io::Result<bool> {
        let mut any = false;
        for _ in 0..256 {
            let mut progressed = false;
            if self.ring.has_submission() {
                let submitted = self.submit_retry()?;
                if submitted != 0 {
                    progressed = true;
                }
            }
            if self.ring.has_completion() {
                on_completion(self)?;
                progressed = true;
            }
            if !progressed {
                break;
            }
            any = true;
        }
        Ok(any)
    }

    pub fn drive(&mut self) -> io::Result<bool> {
        self.drive_loop(Self::tick)
    }

    pub fn drive_with<H: CqeRouter>(&mut self, handler: &mut H) -> io::Result<bool> {
        self.drive_loop(|s| {
            s.dispatch_cqes(handler);
            Ok(())
        })
    }

    pub(crate) fn tick(&mut self) -> io::Result<()> {
        let Self {
            requests,
            ring,
            provided,
            ..
        } = self;
        let mut cq = ring.completion();
        for item in &mut cq {
            let result = item.result();
            let flags = item.flags();
            if let Wire::Request(id) = wire::decode_wire(item.user_data()) {
                requests.on_request(id, result, flags);
            }
        }
        cq.sync();
        let _ = provided.flush();
        Ok(())
    }

    #[inline(always)]
    pub fn cancel_write(&mut self, token: Token) {
        self.ring.submit_cancel(wire::write(token));
    }

    #[inline(always)]
    pub fn cancel_accept(&mut self, token: Token) {
        self.ring.submit_cancel(wire::accept(token));
    }

    fn drain_to_scratch(&mut self) {
        let Self {
            ring, cqe_scratch, ..
        } = self;
        cqe_scratch.clear();
        let mut cq = ring.completion();
        for item in &mut cq {
            cqe_scratch.push(RawCqe {
                user_data: item.user_data(),
                result: item.result(),
                flags: item.flags(),
            });
        }
        cq.sync();
    }

    pub fn dispatch_cqes<H: CqeRouter>(&mut self, handler: &mut H) {
        self.drain_to_scratch();
        let mut scratch = std::mem::take(&mut self.cqe_scratch);
        for raw in scratch.drain(..) {
            let wire = wire::decode_wire(raw.user_data);
            match wire {
                Wire::Request(id) => self.requests.on_request(id, raw.result, raw.flags),
                Wire::Ignore => {}
                Wire::Accept(_) | Wire::Recv(_) | Wire::Write(_) => {
                    handler.on_cqe(self, make_view(wire, raw.result, raw.flags));
                }
            }
        }
        self.cqe_scratch = scratch;
        let _ = self.provided.flush();
    }
}

impl Driver {
    pub fn submit_only(&mut self) -> io::Result<()> {
        if self.ring.submission_len() == 0 {
            return Ok(());
        }
        for _ in 0..256 {
            if self.ring.submission_len() == 0 {
                return Ok(());
            }
            self.submit_retry()?;
        }
        Ok(())
    }

    pub(crate) fn submit_sqe_op(&mut self, sqe: crate::Sqe) -> io::Result<RequestId> {
        if self.ring.is_full() {
            self.submit_only()?;
        }
        let index = self.requests.insert();
        let sqe = sqe.user_data(wire::request(index));
        if !self.ring.push(&sqe) {
            self.requests.rollback(index);
            return Err(io::Error::new(
                io::ErrorKind::WouldBlock,
                "SQ full after flush",
            ));
        }
        Ok(index)
    }
}

impl Driver {
    #[inline(always)]
    pub(crate) fn try_submit_op<O, F>(
        &mut self,
        op: O,
        sqe_builder: F,
    ) -> Result<Request<O>, (io::Error, O)>
    where
        O: Unpin + 'static,
        F: FnOnce(&mut O) -> Sqe,
    {
        let mut boxed = Box::new(op);
        let sqe = sqe_builder(&mut *boxed);
        Request::submit_boxed(self, boxed, sqe).map_err(|(e, b)| (e, *b))
    }

    #[inline(always)]
    pub(crate) fn try_submit_op_boxed<O, F>(
        &mut self,
        mut boxed: Box<O>,
        sqe_builder: F,
    ) -> Result<Request<O>, (io::Error, Box<O>)>
    where
        O: Unpin + 'static,
        F: FnOnce(&mut O) -> Sqe,
    {
        let sqe = sqe_builder(&mut *boxed);
        Request::submit_boxed(self, boxed, sqe)
    }

    pub fn try_submit_sendmsg_raw_boxed<P>(
        &mut self,
        fd: Fd,
        packet: Box<P>,
    ) -> Result<Request<P>, (io::Error, Box<P>)>
    where
        P: SendMsgPacket + Unpin + 'static,
    {
        let raw = fd.as_raw_fd();
        self.try_submit_op_boxed(packet, move |packet| {
            io_uring::opcode::SendMsg::new(io_uring::types::Fd(raw), packet.msg_ptr()).build()
        })
    }
}

impl DriverOps for Driver {
    type Token = Token;
    type ProvidedRing = ProvidedRing;
    type IoRequest<O: Unpin + 'static> = Request<O>;

    #[inline(always)]
    fn provided_ring(&mut self) -> &mut Self::ProvidedRing {
        &mut self.provided
    }

    #[inline(always)]
    fn buf_group(&self) -> u16 {
        self.provided.group().0
    }

    #[inline(always)]
    fn arm_recv_multi(&mut self, token: Self::Token, fd: FixedFd, buf_group: u16) -> bool {
        let sqe = opcode::RecvMulti::new(types::Fixed(fd.fixed_index()), buf_group)
            .build()
            .user_data(wire::recv(token));
        self.ring.try_push_arm(sqe)
    }

    #[inline(always)]
    unsafe fn arm_recv_msg_multi(
        &mut self,
        token: Self::Token,
        fd: FixedFd,
        buf_group: u16,
        msghdr: *const libc::msghdr,
    ) -> bool {
        let sqe = opcode::RecvMsgMulti::new(types::Fixed(fd.fixed_index()), msghdr, buf_group)
            .build()
            .user_data(wire::recv(token));
        self.ring.try_push_arm(sqe)
    }

    #[inline(always)]
    fn arm_accept_multi(&mut self, token: Self::Token, fd: Fd) -> bool {
        let sqe = opcode::AcceptMulti::new(fd.uring())
            .flags(libc::SOCK_CLOEXEC)
            .build()
            .user_data(wire::accept(token));
        self.ring.try_push_arm(sqe)
    }

    #[inline(always)]
    fn submit_send_tagged(
        &mut self,
        token: Self::Token,
        fd: FixedFd,
        ptr: *const u8,
        len: u32,
    ) -> bool {
        let sqe = opcode::Send::new(types::Fixed(fd.fixed_index()), ptr, len)
            .build()
            .user_data(wire::write(token));
        self.ring.push(&sqe)
    }

    #[inline(always)]
    unsafe fn submit_send_msg_tagged(
        &mut self,
        token: Self::Token,
        fd: FixedFd,
        msg: *const libc::msghdr,
    ) -> bool {
        let sqe = opcode::SendMsg::new(types::Fixed(fd.fixed_index()), msg)
            .build()
            .user_data(wire::write(token));
        self.ring.push(&sqe)
    }

    #[inline(always)]
    fn cancel_recv(&mut self, token: Self::Token) {
        self.ring.submit_cancel(wire::recv(token));
    }

    fn try_submit_connect_raw(
        &mut self,
        fd: Fd,
        addr: SockAddr,
    ) -> Result<Self::IoRequest<SockAddr>, (io::Error, SockAddr)> {
        let raw = fd.as_raw_fd();
        self.try_submit_op(addr, move |addr| {
            io_uring::opcode::Connect::new(
                io_uring::types::Fd(raw),
                addr.addr_ptr(),
                addr.addr_len(),
            )
            .build()
        })
    }

    fn try_submit_sendmsg_raw<P: SendMsgPacket + Unpin + 'static>(
        &mut self,
        fd: Fd,
        packet: P,
    ) -> Result<Self::IoRequest<P>, (io::Error, P)> {
        let raw = fd.as_raw_fd();
        self.try_submit_op(packet, move |packet| {
            io_uring::opcode::SendMsg::new(io_uring::types::Fd(raw), packet.msg_ptr()).build()
        })
    }

    fn try_submit_send_raw<B: AsRef<[u8]> + Unpin + 'static>(
        &mut self,
        fd: Fd,
        buf: B,
    ) -> Result<Self::IoRequest<B>, (io::Error, B)> {
        let raw = fd.as_raw_fd();
        self.try_submit_op(buf, move |buf| {
            let slice = buf.as_ref();
            io_uring::opcode::Send::new(
                io_uring::types::Fd(raw),
                slice.as_ptr(),
                slice.len() as u32,
            )
            .build()
        })
    }
}