Skip to main content

ntex_net/uring/
reactor.rs

1use std::cell::{Cell, UnsafeCell};
2use std::ops::{Deref, DerefMut};
3use std::os::fd::{AsRawFd, RawFd};
4use std::panic::{self, AssertUnwindSafe};
5use std::time::{Duration, Instant};
6use std::{collections::VecDeque, fmt, io, mem, net, ptr, rc::Rc};
7
8#[cfg(unix)]
9use std::os::unix::net::UnixStream as OsUnixStream;
10
11use ntex_io::Io;
12use ntex_io_uring::cqueue::{self, Entry as CEntry, more};
13use ntex_io_uring::opcode::{AsyncCancel, AsyncCancel2};
14use ntex_io_uring::squeue::{Entry as SEntry, PushError, SubmissionQueue};
15use ntex_io_uring::types::{CancelBuilder, SubmitArgs, Timespec};
16use ntex_io_uring::{EnterFlags, IoUring, Probe, Submitter};
17use ntex_rt::{DriverType, Notify, PollResult, Runtime};
18use ntex_service::cfg::SharedCfg;
19use socket2::{Protocol, SockAddr, Socket, Type};
20
21use super::{
22    TcpStream, UnixStream,
23    notifier::{self, Notifier, NotifierRead},
24    stream::StreamOps,
25};
26use crate::channel::Receiver;
27
28pub trait Handler {
29    /// Operation is completed.
30    fn completed(&mut self, id: usize, flags: u32, result: io::Result<usize>);
31
32    /// Operation is canceled.
33    fn canceled(&mut self, id: usize);
34
35    /// The driver's turn has completed.
36    fn tick(&mut self);
37
38    /// Number of submitted operations without their final completion.
39    ///
40    /// The driver waits for them on shutdown, see [`cleanup`](Self::cleanup).
41    fn in_flight(&self) -> usize {
42        0
43    }
44
45    /// Clean up the handle before dropping the driver.
46    ///
47    /// Called on shutdown, after the operations counted by
48    /// [`in_flight`](Self::in_flight) completed.
49    fn cleanup(&mut self);
50
51    /// Operations are still in flight when the driver stops.
52    ///
53    /// Called instead of [`cleanup`](Self::cleanup). The handler is leaked
54    /// afterwards, so memory referenced by the operations stays valid. It must
55    /// not release anything the kernel may still use. Descriptors may be
56    /// closed, the shutdown flushed every submission and the kernel holds its
57    /// own file reference for each issued operation.
58    fn abandon(&mut self) {}
59}
60
61/// Api for io-uring reactor.
62pub struct ReactorApi {
63    batch: u64,
64    inner: Rc<ReactorInner>,
65}
66
67impl ReactorApi {
68    #[inline]
69    /// Check if the ring was set up with `IORING_SETUP_SINGLE_ISSUER`, so the
70    /// kernel is 6.0 or greater and supports `IORING_RECVSEND_POLL_FIRST` (5.19)
71    pub fn is_new(&self) -> bool {
72        self.inner.flags.get().contains(Flags::NEW)
73    }
74
75    fn submit_inner<F>(&self, f: F)
76    where
77        F: FnOnce(&mut SEntry),
78    {
79        self.inner.push(f);
80    }
81
82    #[inline]
83    /// Submit request to the driver.
84    ///
85    /// `f` initializes a zeroed submission entry in place with an opcode.
86    ///
87    /// # Safety
88    ///
89    /// The kernel uses the entry after this call returns. Every buffer,
90    /// address and file descriptor the entry refers to must stay valid, and
91    /// must not move, until the handler receives the completion for `id`.
92    /// Canceling the request does not end this, the completion still arrives.
93    ///
94    /// `f` runs while the entry is borrowed from the submission queue, it
95    /// must not submit or cancel requests on this reactor. Debug builds panic
96    /// if it does.
97    pub unsafe fn submit<F>(&self, id: u32, f: F)
98    where
99        F: FnOnce(&mut SEntry),
100    {
101        self.submit_inner(|en| {
102            f(en);
103            en.set_user_data(u64::from(id) | self.batch);
104        });
105    }
106
107    #[inline]
108    /// Attempt to cancel an already issued request.
109    pub fn cancel(&self, id: u32) {
110        self.submit_inner(|en| {
111            AsyncCancel::new(en, u64::from(id) | self.batch).user_data(Reactor::CANCEL);
112        });
113    }
114
115    /// Get whether a specific io-uring opcode is supported.
116    pub fn is_supported(&self, opcode: u8) -> bool {
117        self.inner.probe.is_supported(opcode)
118    }
119
120    /// Id of the handler, unique within the reactor.
121    pub fn id(&self) -> u16 {
122        (self.batch >> Reactor::BATCH) as u16
123    }
124
125    /// Registers a provided buffer ring.
126    ///
127    /// # Safety
128    ///
129    /// The ring at `ring_addr` with `entries` entries must stay valid until
130    /// it is unregistered with
131    /// [`unregister_buf_ring`](Self::unregister_buf_ring).
132    pub unsafe fn register_buf_ring(
133        &self,
134        ring_addr: u64,
135        entries: u16,
136        bgid: u16,
137    ) -> io::Result<()> {
138        // SAFETY: The caller guarantees the ring remains valid until it is unregistered.
139        unsafe {
140            self.inner
141                .ring
142                .submitter()
143                .register_buf_ring_with_flags(ring_addr, entries, bgid, 0)
144        }
145    }
146
147    /// Unregisters a provided buffer ring.
148    pub fn unregister_buf_ring(&self, bgid: u16) -> io::Result<()> {
149        self.inner.ring.submitter().unregister_buf_ring(bgid)
150    }
151
152    /// Registers an empty file table with `nr` slots, kernel 5.19 or greater.
153    ///
154    /// The ring has one table, it is released with the ring.
155    pub fn register_files_sparse(&self, nr: u32) -> io::Result<()> {
156        self.inner.ring.submitter().register_files_sparse(nr)
157    }
158
159    /// Replaces slots of the file table starting at `offset`, `-1` clears a slot.
160    ///
161    /// Issued operations keep the file they resolved, a replaced or cleared
162    /// file is released once they complete.
163    pub fn register_files_update(&self, offset: u32, fds: &[RawFd]) -> io::Result<usize> {
164        self.inner
165            .ring
166            .submitter()
167            .register_files_update(offset, fds)
168    }
169}
170
171/// io-uring reactor.
172pub struct Reactor {
173    fd: RawFd,
174    hid: Cell<u64>,
175    notifier: Notifier,
176    #[allow(clippy::box_collection)]
177    handlers: Cell<Option<Box<Vec<HandlerItem>>>>,
178    inner: Rc<ReactorInner>,
179}
180
181struct HandlerItem {
182    hnd: Box<dyn Handler>,
183    modified: bool,
184}
185
186impl HandlerItem {
187    fn tick(&mut self) {
188        if self.modified {
189            self.modified = false;
190            self.hnd.tick();
191        }
192    }
193}
194
195/// Handlers taken out of the reactor, put back when dropped.
196///
197/// Handlers own the memory of their in-flight operations. Put back while
198/// unwinding, they are released by the reactor shutdown once the kernel is
199/// done with it, instead of being dropped with the panic.
200#[allow(clippy::box_collection)]
201struct TakenHandlers<'a> {
202    slot: &'a Cell<Option<Box<Vec<HandlerItem>>>>,
203    handlers: Option<Box<Vec<HandlerItem>>>,
204}
205
206impl<'a> TakenHandlers<'a> {
207    #[allow(clippy::box_collection)]
208    fn new(slot: &'a Cell<Option<Box<Vec<HandlerItem>>>>) -> Self {
209        let handlers = Some(slot.take().unwrap_or_default());
210        Self { slot, handlers }
211    }
212}
213
214impl Deref for TakenHandlers<'_> {
215    type Target = Vec<HandlerItem>;
216
217    fn deref(&self) -> &Self::Target {
218        self.handlers.as_ref().unwrap()
219    }
220}
221
222impl DerefMut for TakenHandlers<'_> {
223    fn deref_mut(&mut self) -> &mut Self::Target {
224        self.handlers.as_mut().unwrap()
225    }
226}
227
228impl Drop for TakenHandlers<'_> {
229    fn drop(&mut self) {
230        self.slot.set(self.handlers.take());
231    }
232}
233
234bitflags::bitflags! {
235    #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
236    struct Flags: u8 {
237        /// Ring set up with `IORING_SETUP_SINGLE_ISSUER`, kernel 6.0 or greater
238        const NEW      = 0b0000_0001;
239    }
240}
241
242struct ReactorInner {
243    probe: Probe,
244    flags: Cell<Flags>,
245    ring: IoUring<SEntry, CEntry>,
246    changes: UnsafeCell<VecDeque<mem::MaybeUninit<SEntry>>>,
247    notify_read: NotifierRead,
248    #[cfg(debug_assertions)]
249    pushing: Cell<bool>,
250}
251
252#[cfg(debug_assertions)]
253struct PushGuard<'a>(&'a Cell<bool>);
254
255#[cfg(debug_assertions)]
256impl Drop for PushGuard<'_> {
257    fn drop(&mut self) {
258        self.0.set(false);
259    }
260}
261
262impl ReactorInner {
263    fn push<F>(&self, f: F)
264    where
265        F: FnOnce(&mut SEntry),
266    {
267        // `f` runs while the entry is borrowed from a queue, see `submit`
268        #[cfg(debug_assertions)]
269        let _guard = {
270            assert!(
271                !self.pushing.replace(true),
272                "submit or cancel called from a `submit` callback"
273            );
274            PushGuard(&self.pushing)
275        };
276
277        // SAFETY: Submission is thread-local and non-reentrant; zeroing initializes every SQE field
278        // before `f` uses it, and only the run loop publishes the queue tail.
279        unsafe {
280            let changes = &mut *self.changes.get();
281            // the queue tail is published by the run loop submit
282            let f = if changes.is_empty() {
283                match self.ring.submission_unsynced().push(f) {
284                    Ok(()) => return,
285                    Err(PushError(f)) => f,
286                }
287            } else {
288                f
289            };
290            changes.push_back(mem::MaybeUninit::uninit());
291            let entry = changes.back_mut().unwrap();
292            ptr::write_bytes(entry.as_mut_ptr(), 0, 1);
293            f(entry.assume_init_mut());
294        }
295    }
296}
297
298impl Drop for ReactorInner {
299    fn drop(&mut self) {
300        self.notify_read.stop(&self.ring);
301    }
302}
303
304impl Reactor {
305    const NOTIFY: u64 = notifier::NOTIFY;
306    const CANCEL: u64 = u64::MAX - 1;
307    const BATCH: u64 = 48;
308    const BATCH_MASK: u64 = 0xFFFF_0000_0000_0000;
309    const DATA_MASK: u64 = 0x0000_FFFF_FFFF_FFFF;
310    const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(1);
311    /// Completions handled before running tasks. Smaller chunks keep
312    /// sockets hot in the cache between read completion and write, about
313    /// 15% faster than handling the whole queue at once.
314    const CQES_PER_POLL: usize = 16;
315
316    /// Default submission queue size, the completion queue is twice as large.
317    ///
318    /// Submissions are flushed mid-turn and on queue overflow, a small ring
319    /// keeps both queues in cache.
320    // Unused when the polling, tokio or compio runtime is selected.
321    #[allow(dead_code)]
322    pub(crate) const DEFAULT_ENTRIES: u32 = 256;
323
324    /// Create io-uring driver
325    pub fn new(capacity: u32) -> io::Result<Self> {
326        let build = |no_sqarray: bool| {
327            let mut builder = IoUring::builder();
328            builder
329                .setup_coop_taskrun()
330                .setup_single_issuer()
331                .setup_defer_taskrun();
332            if no_sqarray {
333                // available since 6.6
334                builder.setup_no_sqarray();
335            }
336            builder.build(capacity)
337        };
338
339        // Create ring
340        let (new, ring) = if let Ok(ring) = build(true) {
341            log::info!(
342                "New io-uring driver with single-issuer, coop-taskrun, defer-taskrun, no-sqarray"
343            );
344            (true, ring)
345        } else if let Ok(ring) = build(false) {
346            log::info!("New io-uring driver with single-issuer, coop-taskrun, defer-taskrun");
347            (true, ring)
348        } else if let Ok(ring) = IoUring::builder().setup_single_issuer().build(capacity) {
349            log::info!("New io-uring driver with single-issuer");
350            (true, ring)
351        } else {
352            let ring = IoUring::builder().build(capacity)?;
353            log::info!("New io-uring driver");
354            (false, ring)
355        };
356
357        // runtime timers bound the wait, available since 5.11
358        if !ring.params().is_feature_ext_arg() {
359            return Err(io::Error::new(
360                io::ErrorKind::Unsupported,
361                "io-uring driver requires Linux 5.11+ (IORING_FEAT_EXT_ARG)",
362            ));
363        }
364
365        let mut probe = Probe::new();
366        ring.submitter().register_probe(&mut probe)?;
367
368        // Avoid the per-call ring fd lookup in io_uring_enter, available since 5.18.
369        // The registration is per-thread, the reactor is created and driven on the same thread.
370        if let Err(e) = ring.submitter().register_ring_fd() {
371            log::debug!("Cannot register io-uring ring fd: {e}");
372        }
373
374        let fd = ring.as_raw_fd();
375        let inner = Rc::new(ReactorInner {
376            ring,
377            probe,
378            flags: Cell::new(if new { Flags::NEW } else { Flags::empty() }),
379            changes: UnsafeCell::new(VecDeque::with_capacity(32)),
380            notify_read: NotifierRead::new(),
381            #[cfg(debug_assertions)]
382            pushing: Cell::new(false),
383        });
384
385        // Remote notifier
386        let notifier = Notifier::new()?;
387
388        Ok(Self {
389            fd,
390            inner,
391            notifier,
392            hid: Cell::new(0),
393            handlers: Cell::new(Some(Box::new(Vec::new()))),
394        })
395    }
396
397    /// Driver type
398    pub const fn tp(&self) -> DriverType {
399        DriverType::IoUring
400    }
401
402    /// Register updates handler
403    pub fn register<F>(&self, f: F)
404    where
405        F: FnOnce(ReactorApi) -> Box<dyn Handler>,
406    {
407        let id = self.hid.get();
408        let mut handlers = TakenHandlers::new(&self.handlers);
409        handlers.push(HandlerItem {
410            hnd: f(ReactorApi {
411                batch: id << Self::BATCH,
412                inner: self.inner.clone(),
413            }),
414            modified: false,
415        });
416        drop(handlers);
417        self.hid.set(id + 1);
418    }
419
420    fn apply_changes(&self, sq: SubmissionQueue<'_, SEntry>) -> bool {
421        // SAFETY: The thread-local overflow entries are initialized and disjoint from the SQ;
422        // no submission callback runs while they are copied.
423        unsafe {
424            let changes = &mut *self.inner.changes.get();
425            // safety: "changes" contains only initialized entries
426            while let Some(entry) = changes.front() {
427                let res = sq.push(|en| ptr::copy_nonoverlapping(entry.as_ptr(), en, 1));
428                if res.is_err() {
429                    break;
430                }
431                changes.pop_front();
432            }
433
434            let read = &self.inner.notify_read;
435            if changes.is_empty() {
436                read.arm(sq, self.notifier.as_raw_fd());
437            }
438            !changes.is_empty() || read.is_queued()
439        }
440    }
441
442    /// Submit all pending changes to the kernel
443    fn flush(&self, sq: SubmissionQueue<'_, SEntry>, submitter: &Submitter<'_>) {
444        let mut retries = 0;
445        loop {
446            let more_changes = self.apply_changes(sq);
447
448            if let Err(e) = submitter.submit() {
449                match e.raw_os_error() {
450                    Some(libc::ETIME | libc::EBUSY | libc::EAGAIN | libc::EINTR)
451                        if retries < 16 =>
452                    {
453                        retries += 1;
454                        continue;
455                    }
456                    _ => {
457                        log::error!("Cannot submit pending operations: {e:?}");
458                        break;
459                    }
460                }
461            }
462            if !more_changes {
463                break;
464            }
465        }
466    }
467
468    /// Cancels in-flight operations and releases handlers.
469    ///
470    /// Handlers own the buffers, addresses and sockets of their operations.
471    /// A handler is cleaned up only once the kernel is done with all of them,
472    /// otherwise it is abandoned and leaked.
473    fn shutdown(
474        &self,
475        sq: SubmissionQueue<'_, SEntry>,
476        submitter: &Submitter<'_>,
477        cq: &mut cqueue::CompletionQueue<'_, CEntry>,
478    ) {
479        let ring = &self.inner.ring;
480        self.inner.notify_read.stop_arming();
481        // publish the entries consumed in the last turn before entering the kernel
482        cq.sync();
483        // Operations queued during the last turn (`Close` of dropped
484        // streams in particular) have not reached the kernel yet.
485        self.flush(sq, submitter);
486
487        let canceled = submitter.register_sync_cancel(None, CancelBuilder::any());
488        self.inner.notify_read.canceled(ring, &canceled);
489        if let Err(e) = canceled {
490            log::error!("Cannot cancel in-flight operations: {e:?}");
491            if e.raw_os_error() == Some(libc::EINVAL) {
492                // sync cancel is available since 6.0, cancel of any request since 5.19
493                self.inner.push(|en| {
494                    AsyncCancel2::new(en, CancelBuilder::any()).user_data(Self::CANCEL);
495                });
496                self.flush(sq, submitter);
497            }
498        }
499
500        let Some(handlers) = self.handlers.take() else {
501            return;
502        };
503
504        // Completions are counted, not delivered. Handlers would issue new
505        // operations, a resend of canceled output for example.
506        let mut in_flight: Vec<_> = handlers.iter().map(|h| h.hnd.in_flight()).collect();
507        let deadline = Instant::now() + Self::SHUTDOWN_TIMEOUT;
508        loop {
509            cq.sync();
510            for entry in &mut *cq {
511                match entry.user_data() {
512                    Self::CANCEL => {}
513                    Self::NOTIFY => self.inner.notify_read.completed(entry.result()),
514                    // the final completion, a zero-copy send ends with its notification
515                    user_data if !more(entry.flags()) => {
516                        let batch = ((user_data & Self::BATCH_MASK) >> Self::BATCH) as usize;
517                        if let Some(n) = in_flight.get_mut(batch) {
518                            *n = n.saturating_sub(1);
519                        }
520                    }
521                    _ => {}
522                }
523            }
524            cq.sync();
525
526            if in_flight.iter().all(|n| *n == 0) {
527                break;
528            }
529            let timeout = deadline.saturating_duration_since(Instant::now());
530            if timeout.is_zero() {
531                break;
532            }
533            let ts = Timespec::from(timeout);
534            if let Err(e) = submitter.submit_with_args(1, &SubmitArgs::new().timespec(&ts))
535                && !matches!(
536                    e.raw_os_error(),
537                    Some(libc::ETIME | libc::EINTR | libc::EBUSY | libc::EAGAIN)
538                )
539            {
540                log::error!("Cannot wait for in-flight operations: {e:?}");
541                break;
542            }
543        }
544
545        for (mut h, n) in handlers.into_iter().zip(in_flight) {
546            if n == 0 {
547                h.hnd.cleanup();
548            } else {
549                log::error!(
550                    "{n} io-uring operations are in flight on shutdown, leaking their memory"
551                );
552                h.hnd.abandon();
553                mem::forget(h);
554            }
555        }
556    }
557
558    /// Handle up to `CQES_PER_POLL` synced completions, forward changes to
559    /// specific handler. Returns `true` if synced completions remain.
560    ///
561    /// The caller must sync the queue before and after.
562    fn poll_completions(&self, cq: &mut cqueue::CompletionQueue<'_, CEntry>) -> bool {
563        let mut has_more = false;
564
565        if !cqueue::CompletionQueue::<'_, _>::is_empty(cq) {
566            let mut handlers = TakenHandlers::new(&self.handlers);
567            for entry in (&mut *cq).take(Self::CQES_PER_POLL) {
568                let user_data = entry.user_data();
569                match user_data {
570                    Self::CANCEL => {}
571                    Self::NOTIFY => self.inner.notify_read.completed(entry.result()),
572                    _ => {
573                        let batch = ((user_data & Self::BATCH_MASK) >> Self::BATCH) as usize;
574                        let user_data = (user_data & Self::DATA_MASK) as usize;
575
576                        let result = entry.result();
577                        // A canceled zero-copy send still posts a notification,
578                        // the operation must stay alive until it arrives. A
579                        // canceled operation that selected a provided buffer
580                        // completes, the handler must return the buffer.
581                        if result == -libc::ECANCELED
582                            && !more(entry.flags())
583                            && cqueue::buffer_select(entry.flags()).is_none()
584                        {
585                            handlers[batch].modified = true;
586                            handlers[batch].hnd.canceled(user_data);
587                        } else {
588                            // zero-copy notification result is a set of flags
589                            let result = if result < 0 && !cqueue::notif(entry.flags()) {
590                                Err(io::Error::from_raw_os_error(-result))
591                            } else {
592                                #[allow(clippy::cast_sign_loss)]
593                                Ok(result as u32 as _)
594                            };
595                            handlers[batch].modified = true;
596                            handlers[batch]
597                                .hnd
598                                .completed(user_data, entry.flags(), result);
599                        }
600                    }
601                }
602            }
603            has_more = ExactSizeIterator::len(cq) != 0;
604
605            for h in handlers.iter_mut() {
606                h.tick();
607            }
608        }
609        has_more
610    }
611}
612
613/// Submit the queue and post deferred completions without waiting.
614///
615/// With deferred task running only an enter with `GETEVENTS` runs task work,
616/// a plain submit never posts completions that arrived since the last wait.
617fn submit_getevents(
618    sq: SubmissionQueue<'_, SEntry>,
619    submitter: &Submitter<'_>,
620) -> io::Result<usize> {
621    sq.sync();
622    // SAFETY: Valid arguments for an enter without extra arguments.
623    let res = unsafe {
624        submitter.enter::<libc::sigset_t>(sq.len() as u32, 0, EnterFlags::GETEVENTS.bits(), None)
625    };
626    // the kernel consumes entries during the enter, even if it fails
627    sq.sync();
628    res
629}
630
631impl AsRawFd for Reactor {
632    fn as_raw_fd(&self) -> RawFd {
633        self.fd
634    }
635}
636
637// Sockets are left in their mode, which saves the `fcntl` calls of
638// `set_nonblocking()`. The io-uring socket operations do not depend on
639// `O_NONBLOCK`, they never block the submitting thread and wait for readiness
640// themselves. The direct syscalls on a socket (`recv` with `MSG_DONTWAIT`,
641// `shutdown`, socket options) do not block either.
642impl crate::Reactor for Reactor {
643    fn tcp_connect(&self, addr: net::SocketAddr, cfg: SharedCfg) -> Receiver<Io> {
644        let addr = SockAddr::from(addr);
645        let result = Socket::new(addr.domain(), Type::STREAM, Some(Protocol::TCP))
646            .and_then(crate::helpers::prep_tcp_socket)
647            .map(move |sock| (addr, sock));
648
649        match result {
650            Err(err) => Receiver::new(Err(err)),
651            Ok((addr, sock)) => super::connect::ConnectOps::get(self).connect(sock, addr, cfg),
652        }
653    }
654
655    fn unix_connect(&self, addr: std::path::PathBuf, cfg: SharedCfg) -> Receiver<Io> {
656        let result = SockAddr::unix(addr).and_then(|addr| {
657            Socket::new(addr.domain(), Type::STREAM, None).map(move |sock| (addr, sock))
658        });
659
660        match result {
661            Err(err) => Receiver::new(Err(err)),
662            Ok((addr, sock)) => super::connect::ConnectOps::get(self).connect(sock, addr, cfg),
663        }
664    }
665
666    fn from_tcp_stream(&self, stream: net::TcpStream, cfg: SharedCfg) -> io::Result<Io> {
667        Ok(Io::new(
668            TcpStream(Socket::from(stream), StreamOps::get(self)),
669            cfg,
670        ))
671    }
672
673    #[cfg(unix)]
674    fn from_unix_stream(&self, stream: OsUnixStream, cfg: SharedCfg) -> io::Result<Io> {
675        Ok(Io::new(
676            UnixStream(Socket::from(stream), StreamOps::get(self)),
677            cfg,
678        ))
679    }
680
681    fn tcp_listener(&self, sock: net::TcpListener) -> io::Result<crate::Listener> {
682        super::accept::AcceptOps::get(self).listener(sock)
683    }
684
685    fn is_tcp_listener_supported(&self) -> bool {
686        super::accept::AcceptOps::get(self).is_supported()
687    }
688}
689
690impl ntex_rt::Driver for Reactor {
691    /// Poll the driver and handle completed operations.
692    fn run(&self, rt: &Runtime) -> io::Result<()> {
693        let _notifier = self.inner.notify_read.guard(&self.inner.ring);
694        let ring = &self.inner.ring;
695        let sq = ring.submission();
696        // SAFETY: This run loop is the sole completion consumer; callbacks never borrow the CQ.
697        let mut cq = unsafe { ring.completion_shared() };
698        let submitter = ring.submitter();
699        // A panic of a task or a handler must not skip the shutdown, which
700        // releases handlers only after the kernel is done with their memory.
701        let result = panic::catch_unwind(AssertUnwindSafe(|| {
702            loop {
703                // tasks woken until the runtime is polled do not need to notify
704                rt.awake();
705                cq.sync();
706
707                // Run tasks after each chunk of completions, so a task writes
708                // to its socket while the socket is still hot in the cache.
709                // All chunks belong to one runtime turn, and their submissions
710                // share one `io_uring_enter` unless the submission queue fills.
711                let more_cqes = loop {
712                    if !self.poll_completions(&mut cq) {
713                        break false;
714                    }
715                    rt.run_ready();
716
717                    if sq.len() >= 96 {
718                        // flush the full queue without ending the turn; consumed
719                        // entries are published first, the enter posts completions
720                        // that arrived during the turn
721                        cq.sync();
722                        if submit_getevents(sq, &submitter).is_err() {
723                            // the end of the turn retries and reports the error
724                            break true;
725                        }
726                        self.apply_changes(sq);
727                        // SAFETY: No other borrow of the change queue is live.
728                        if unsafe { !(*self.inner.changes.get()).is_empty() } {
729                            break true;
730                        }
731                    }
732                };
733
734                let (more_tasks, timeout) = match rt.poll() {
735                    PollResult::Pending(timeout) => (false, timeout),
736                    PollResult::PollAgain => (true, None),
737                    PollResult::Ready => break Ok(()),
738                };
739                let more_changes = self.apply_changes(sq);
740
741                // Publish the consumed entries before entering the kernel, it
742                // would count them as pending completions and return from the
743                // next wait immediately. Without deferred task running,
744                // completions may arrive during the turn, waiting would return
745                // immediately.
746                cq.sync();
747
748                // submit publishes the queue tail, and skips the syscall if
749                // there is nothing to submit and no deferred completions to post.
750                let result = if more_tasks {
751                    // a task that keeps the runtime busy would starve completions
752                    submit_getevents(sq, &submitter)
753                } else if more_changes
754                    || more_cqes
755                    || !cqueue::CompletionQueue::<'_, _>::is_empty(&cq)
756                {
757                    submitter.submit()
758                } else if let Some(timeout) = timeout {
759                    // wake up for the next batch of runtime timers
760                    let ts = Timespec::from(timeout);
761                    submitter.submit_with_args(1, &SubmitArgs::new().timespec(&ts))
762                } else {
763                    submitter.submit_and_wait(1)
764                };
765
766                if let Err(e) = result {
767                    match e.raw_os_error() {
768                        Some(libc::ETIME | libc::EBUSY | libc::EAGAIN | libc::EINTR) => {
769                            log::debug!("Ring submit interrupted, {e:?}");
770                        }
771                        _ => break Err(e),
772                    }
773                }
774            }
775        }));
776
777        // unwinding out of the shutdown would drop handlers with operations in flight
778        let guard = ntex_rt::AbortOnUnwind("io-uring reactor shutdown panicked");
779        self.shutdown(sq, &submitter, &mut cq);
780        guard.disarm();
781        result.unwrap_or_else(|payload| panic::resume_unwind(payload))
782    }
783
784    /// Get notification handle
785    fn handle(&self) -> Box<dyn Notify> {
786        Box::new(self.notifier.handle())
787    }
788}
789
790impl fmt::Debug for Reactor {
791    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
792        f.debug_struct("Reactor")
793            .field("fd", &self.fd)
794            .field("hid", &self.hid)
795            .field("notifier", &self.notifier)
796            .finish()
797    }
798}
799
800impl fmt::Debug for ReactorApi {
801    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
802        f.debug_struct("ReactorApi")
803            .field("batch", &self.batch)
804            .finish()
805    }
806}
807
808#[cfg(test)]
809mod tests {
810    use std::cell::RefCell;
811    use std::future::pending;
812    use std::os::fd::{FromRawFd, OwnedFd};
813    use std::panic::{AssertUnwindSafe, catch_unwind};
814    use std::sync::Arc;
815    use std::task::{Poll, Waker};
816
817    use ntex_io_uring::opcode::{Nop, Read};
818    use ntex_io_uring::types::Fd;
819    use ntex_rt::syscall;
820
821    use super::notifier::NotifierState;
822    use super::*;
823
824    /// STATEMENT: Queued changes that wrap around the deque storage are submitted in order.
825    ///
826    /// HOW:
827    /// - Fill and drain the change deque so four `Nop` entries wrap its end.
828    /// - Run `apply_changes()` and check the deque is empty and four entries are queued.
829    /// - Submit them and check the completions carry user data `0..4` in order.
830    #[test]
831    fn apply_wrapped_changes() {
832        let Ok(reactor) = Reactor::new(4) else {
833            return;
834        };
835        let ring = &reactor.inner.ring;
836        let sq = ring.submission();
837        // submit the notifier
838        assert!(!reactor.apply_changes(sq));
839        ring.submitter().submit().unwrap();
840        sq.sync();
841        assert_eq!(sq.len(), 0);
842
843        // queued entries wrap around the end of the deque storage; the borrow
844        // ends before `apply_changes()` takes its own
845        {
846            // SAFETY: The test has the only access to the queue; the borrow ends before `apply_changes()`.
847            let changes = unsafe { &mut *reactor.inner.changes.get() };
848            let cap = changes.capacity();
849            let nop = |user_data| {
850                let mut entry = SEntry::default();
851                Nop::new(&mut entry).user_data(user_data);
852                mem::MaybeUninit::new(entry)
853            };
854            for _ in 0..cap - 2 {
855                changes.push_back(nop(0));
856            }
857            for _ in 0..cap - 2 {
858                changes.pop_front();
859            }
860            for i in 0..4 {
861                changes.push_back(nop(i));
862            }
863            assert_eq!(changes.as_slices().0.len(), 2);
864        }
865
866        assert!(!reactor.apply_changes(sq));
867        sq.sync();
868        // SAFETY: No other borrow of the change queue is live.
869        assert!(unsafe { &*reactor.inner.changes.get() }.is_empty());
870        assert_eq!(sq.len(), 4);
871
872        ring.submitter().submit_and_wait(4).unwrap();
873        // SAFETY: The test is the only consumer of the completion queue.
874        let mut cq = unsafe { ring.completion_shared() };
875        cq.sync();
876        let ids: Vec<_> = cq.map(|e| e.user_data()).collect();
877        assert_eq!(ids, [0, 1, 2, 3]);
878    }
879
880    /// STATEMENT: `poll_completions` handles at most `CQES_PER_POLL` synced completions
881    /// and reports whether more remain.
882    ///
883    /// HOW:
884    /// - Submit `CQES_PER_POLL + 4` `Nop` operations to a counting handler and wait for them.
885    /// - Sync once, poll and check `CQES_PER_POLL` completions were handled and `true` returned.
886    /// - Poll again and check the rest were handled, `false` returned and the queue is empty.
887    #[test]
888    fn poll_completions_handles_one_chunk() {
889        struct Count(Rc<Cell<usize>>);
890        impl Handler for Count {
891            fn completed(&mut self, _: usize, _: u32, _: io::Result<usize>) {
892                self.0.set(self.0.get() + 1);
893            }
894            fn canceled(&mut self, _: usize) {}
895            fn tick(&mut self) {}
896            fn cleanup(&mut self) {}
897        }
898
899        let Ok(reactor) = Reactor::new(32) else {
900            return;
901        };
902        let count = Rc::new(Cell::new(0));
903        let mut api = None;
904        reactor.register(|a| {
905            api = Some(a);
906            Box::new(Count(count.clone()))
907        });
908        let api = api.unwrap();
909        let total = Reactor::CQES_PER_POLL + 4;
910        for id in 0..u32::try_from(total).unwrap() {
911            // SAFETY: `Nop` entries reference no memory or descriptors.
912            unsafe {
913                api.submit(id, |en| {
914                    Nop::new(en);
915                });
916            }
917        }
918        reactor
919            .inner
920            .ring
921            .submitter()
922            .submit_and_wait(total)
923            .unwrap();
924
925        // SAFETY: The test is the only consumer of the completion queue.
926        let mut cq = unsafe { reactor.inner.ring.completion_shared() };
927        cq.sync();
928        assert!(reactor.poll_completions(&mut cq));
929        assert_eq!(count.get(), Reactor::CQES_PER_POLL);
930        assert!(!reactor.poll_completions(&mut cq));
931        assert_eq!(count.get(), total);
932        cq.sync();
933        assert!(cq.is_empty());
934    }
935
936    /// STATEMENT: A submission queue filled by a chunk of completions is flushed
937    /// without ending the runtime turn.
938    ///
939    /// HOW:
940    /// - Complete two chunks of `Nop` operations on a ring with one chunk of submission entries.
941    /// - Resubmit a `Nop` for each completion of the first chunk, filling the submission queue.
942    /// - Record `poll_count()` from a task woken by completions and check the task saw
943    ///   both chunks handled within one poll, and that all resubmitted operations complete.
944    #[test]
945    fn full_submission_queue_keeps_turn() {
946        struct Resubmit {
947            api: ReactorApi,
948            count: Rc<Cell<usize>>,
949            budget: usize,
950            waker: Rc<Cell<Option<Waker>>>,
951        }
952        impl Handler for Resubmit {
953            fn completed(&mut self, _: usize, _: u32, _: io::Result<usize>) {
954                self.count.set(self.count.get() + 1);
955                if self.budget > 0 {
956                    self.budget -= 1;
957                    // SAFETY: `Nop` entries reference no memory or descriptors.
958                    unsafe {
959                        self.api.submit(1000, |en| {
960                            Nop::new(en);
961                        });
962                    }
963                }
964                if let Some(waker) = self.waker.take() {
965                    waker.wake();
966                }
967            }
968            fn canceled(&mut self, _: usize) {}
969            fn tick(&mut self) {}
970            fn cleanup(&mut self) {}
971        }
972
973        let chunk = Reactor::CQES_PER_POLL;
974        let Ok(reactor) = Reactor::new(u32::try_from(chunk).unwrap()) else {
975            return;
976        };
977        let ring = &reactor.inner.ring;
978        let count = Rc::new(Cell::new(0));
979        let waker = Rc::new(Cell::new(None));
980        reactor.register(|api| {
981            for id in 0..u32::try_from(2 * chunk).unwrap() {
982                if id == u32::try_from(chunk).unwrap() {
983                    ring.submitter().submit().unwrap();
984                }
985                // SAFETY: `Nop` entries reference no memory or descriptors.
986                unsafe {
987                    api.submit(id, |en| {
988                        Nop::new(en);
989                    });
990                }
991            }
992            Box::new(Resubmit {
993                api,
994                count: count.clone(),
995                budget: chunk,
996                waker: waker.clone(),
997            })
998        });
999        ring.submitter().submit_and_wait(2 * chunk).unwrap();
1000
1001        let rt = Runtime::new(ntex_rt::Driver::handle(&reactor));
1002        let seen = RefCell::new(Vec::new());
1003        rt.block_on(
1004            std::future::poll_fn(|cx| {
1005                waker.set(Some(cx.waker().clone()));
1006                seen.borrow_mut().push((count.get(), rt.poll_count()));
1007                if count.get() == 3 * chunk {
1008                    Poll::Ready(())
1009                } else {
1010                    Poll::Pending
1011                }
1012            }),
1013            &reactor,
1014        );
1015
1016        let seen = seen.into_inner();
1017        let polls = |n| seen.iter().find(|(c, _)| *c == n).map(|(_, p)| *p);
1018        assert!(polls(chunk).is_some(), "{seen:?}");
1019        assert_eq!(polls(chunk), polls(2 * chunk), "{seen:?}");
1020    }
1021
1022    /// STATEMENT: In debug builds, a `submit` or `cancel` from a `submit` callback panics
1023    /// before it touches the entry being built, on the ring and on the overflow path.
1024    ///
1025    /// HOW:
1026    /// - With a free submission queue, submit from the callback of a `submit` and check
1027    ///   it panics with the nested submit message and nothing is queued.
1028    /// - Fill the submission queue so entries go to the overflow deque, cancel from the
1029    ///   callback and check the same panic, leaving only the zeroed outer entry.
1030    /// - Submit once more and check the flag was reset by the unwind.
1031    #[cfg(debug_assertions)]
1032    #[test]
1033    fn nested_submit_panics() {
1034        struct Noop;
1035        impl Handler for Noop {
1036            fn completed(&mut self, _: usize, _: u32, _: io::Result<usize>) {}
1037            fn canceled(&mut self, _: usize) {}
1038            fn tick(&mut self) {}
1039            fn cleanup(&mut self) {}
1040        }
1041
1042        let Ok(reactor) = Reactor::new(4) else {
1043            return;
1044        };
1045        let mut api = None;
1046        reactor.register(|a| {
1047            api = Some(a);
1048            Box::new(Noop)
1049        });
1050        let api = api.unwrap();
1051        let message = |err: Box<dyn std::any::Any + Send>| {
1052            err.downcast_ref::<&str>().copied().unwrap_or_default()
1053        };
1054        let changes = || {
1055            // SAFETY: Called between submissions, when no other borrow of the queue is live.
1056            unsafe { &*reactor.inner.changes.get() }.len()
1057        };
1058        let ring = &reactor.inner.ring;
1059
1060        let err = catch_unwind(AssertUnwindSafe(|| {
1061            // SAFETY: `Nop` entries reference no memory; the nested call panics before submitting.
1062            unsafe {
1063                api.submit(1, |en| {
1064                    Nop::new(en);
1065                    api.submit(2, |en| {
1066                        Nop::new(en);
1067                    });
1068                });
1069            }
1070        }))
1071        .unwrap_err();
1072        assert_eq!(
1073            message(err),
1074            "submit or cancel called from a `submit` callback"
1075        );
1076        assert!(ring.submission().is_empty());
1077        assert_eq!(changes(), 0);
1078
1079        for _ in 0..4 {
1080            reactor.inner.push(|en| {
1081                Nop::new(en);
1082            });
1083        }
1084        assert!(ring.submission().is_full());
1085        let err = catch_unwind(AssertUnwindSafe(|| {
1086            // SAFETY: `Nop` entries reference no memory; the nested cancel panics.
1087            unsafe {
1088                api.submit(1, |en| {
1089                    Nop::new(en);
1090                    api.cancel(2);
1091                });
1092            }
1093        }))
1094        .unwrap_err();
1095        assert_eq!(
1096            message(err),
1097            "submit or cancel called from a `submit` callback"
1098        );
1099        assert_eq!(changes(), 1);
1100
1101        // SAFETY: `Nop` entries reference no memory or descriptors.
1102        unsafe {
1103            api.submit(3, |en| {
1104                Nop::new(en);
1105            });
1106        }
1107        assert_eq!(changes(), 2);
1108    }
1109
1110    #[derive(Default)]
1111    struct Events {
1112        cleanup: Cell<bool>,
1113        abandon: Cell<bool>,
1114    }
1115
1116    struct Tracked {
1117        events: Rc<Events>,
1118        in_flight: usize,
1119    }
1120
1121    impl Handler for Tracked {
1122        fn completed(&mut self, _: usize, _: u32, _: io::Result<usize>) {}
1123        fn canceled(&mut self, _: usize) {}
1124        fn tick(&mut self) {}
1125        fn in_flight(&self) -> usize {
1126            self.in_flight
1127        }
1128        fn abandon(&mut self) {
1129            self.events.abandon.set(true);
1130        }
1131        fn cleanup(&mut self) {
1132            self.events.cleanup.set(true);
1133        }
1134    }
1135
1136    /// STATEMENT: On shutdown, in-flight operations are canceled and their handler is
1137    /// cleaned up and released only after the kernel completed them.
1138    ///
1139    /// HOW:
1140    /// - Register a handler that submits a read from an empty pipe into a buffer it owns.
1141    /// - Run the reactor until the runtime finishes.
1142    /// - Check `cleanup` was called, `abandon` was not, and the handler was dropped.
1143    /// - Write to the pipe and check the byte is still readable, so the read was gone.
1144    #[test]
1145    fn shutdown_cancels_in_flight() {
1146        let Some(reactor) = sync_cancel_reactor() else {
1147            return;
1148        };
1149        let mut fds = [0; 2];
1150        syscall!(libc::pipe(fds.as_mut_ptr())).unwrap();
1151        // SAFETY: `pipe` returned two fresh descriptors that nothing else owns.
1152        let (rd, wr) = unsafe { (OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1])) };
1153
1154        let events = Rc::new(Events::default());
1155        let mut buf = Box::new([0u8; 8]);
1156        let buf_ptr = buf.as_mut_ptr();
1157        let fd = rd.as_raw_fd();
1158        reactor.register(|api| {
1159            // SAFETY: `buf` and `rd` outlive the reactor run, which waits until the read is canceled.
1160            unsafe {
1161                api.submit(1, |en| {
1162                    Read::new(en, Fd(fd), buf_ptr, 8);
1163                });
1164            }
1165            Box::new(Tracked {
1166                events: events.clone(),
1167                in_flight: 1,
1168            })
1169        });
1170        let rt = Runtime::new(ntex_rt::Driver::handle(&reactor));
1171        rt.block_on(async {}, &reactor);
1172
1173        assert!(events.cleanup.get());
1174        assert!(!events.abandon.get());
1175        assert_eq!(Rc::strong_count(&events), 1);
1176        drop(buf);
1177
1178        syscall!(libc::fcntl(fd, libc::F_SETFL, libc::O_NONBLOCK)).unwrap();
1179        syscall!(libc::write(wr.as_raw_fd(), b"x".as_ptr().cast(), 1)).unwrap();
1180        let mut out = [0u8; 8];
1181        let n = syscall!(libc::read(fd, out.as_mut_ptr().cast(), 8)).unwrap();
1182        assert_eq!(&out[..n.cast_unsigned()], b"x");
1183    }
1184
1185    /// STATEMENT: A handler whose operations do not complete within the shutdown
1186    /// timeout is abandoned and leaked instead of released.
1187    ///
1188    /// HOW:
1189    /// - Register a handler that reports one in-flight operation it never submitted.
1190    /// - Run the reactor until the runtime finishes.
1191    /// - Check `abandon` was called, `cleanup` was not, and the handler was not dropped.
1192    #[test]
1193    fn shutdown_leaks_stuck_handler() {
1194        let Ok(reactor) = Reactor::new(8) else {
1195            return;
1196        };
1197        let events = Rc::new(Events::default());
1198        reactor.register(|_| {
1199            Box::new(Tracked {
1200                events: events.clone(),
1201                in_flight: 1,
1202            })
1203        });
1204        let rt = Runtime::new(ntex_rt::Driver::handle(&reactor));
1205        let start = Instant::now();
1206        rt.block_on(async {}, &reactor);
1207
1208        assert!(start.elapsed() >= Reactor::SHUTDOWN_TIMEOUT);
1209        assert!(events.abandon.get());
1210        assert!(!events.cleanup.get());
1211        drop(rt);
1212        drop(reactor);
1213        assert_eq!(Rc::strong_count(&events), 2);
1214    }
1215
1216    /// Panics on completions.
1217    struct PanicOnComplete(Tracked);
1218
1219    impl Handler for PanicOnComplete {
1220        fn completed(&mut self, _: usize, _: u32, _: io::Result<usize>) {
1221            panic!("handler panicked");
1222        }
1223        fn canceled(&mut self, _: usize) {}
1224        fn tick(&mut self) {}
1225        fn in_flight(&self) -> usize {
1226            self.0.in_flight()
1227        }
1228        fn abandon(&mut self) {
1229            self.0.abandon();
1230        }
1231        fn cleanup(&mut self) {
1232            self.0.cleanup();
1233        }
1234    }
1235
1236    /// Registers a handler that reads from an empty pipe into `buf`, after
1237    /// a no-op if `nop` is set, and returns the pipe ends.
1238    fn register_pipe_read(
1239        reactor: &Reactor,
1240        buf: &mut [u8; 8],
1241        nop: bool,
1242        hnd: Box<dyn Handler>,
1243    ) -> (OwnedFd, OwnedFd) {
1244        let mut fds = [0; 2];
1245        syscall!(libc::pipe(fds.as_mut_ptr())).unwrap();
1246        // SAFETY: `pipe` returned two fresh descriptors that nothing else owns.
1247        let (rd, wr) = unsafe { (OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1])) };
1248        let (fd, buf_ptr) = (rd.as_raw_fd(), buf.as_mut_ptr());
1249        reactor.register(|api| {
1250            // SAFETY: the caller keeps `buf` and the pipe alive until the read is canceled.
1251            unsafe {
1252                api.submit(1, |en| {
1253                    Read::new(en, Fd(fd), buf_ptr, 8);
1254                });
1255                if nop {
1256                    api.submit(2, |en| {
1257                        Nop::new(en);
1258                    });
1259                }
1260            }
1261            hnd
1262        });
1263        (rd, wr)
1264    }
1265
1266    /// Checks a byte written to the pipe is still readable, so no read is pending.
1267    fn assert_pipe_unread(rd: &OwnedFd, wr: &OwnedFd) {
1268        let fd = rd.as_raw_fd();
1269        syscall!(libc::fcntl(fd, libc::F_SETFL, libc::O_NONBLOCK)).unwrap();
1270        syscall!(libc::write(wr.as_raw_fd(), b"x".as_ptr().cast(), 1)).unwrap();
1271        let mut out = [0u8; 8];
1272        let n = syscall!(libc::read(fd, out.as_mut_ptr().cast(), 8)).unwrap();
1273        assert_eq!(&out[..n.cast_unsigned()], b"x");
1274    }
1275
1276    /// STATEMENT: A task panic unwinds out of the reactor only after the shutdown
1277    /// canceled in-flight operations and released their handler.
1278    ///
1279    /// HOW:
1280    /// - Register a handler that submits a read from an empty pipe into a buffer it owns.
1281    /// - Run a future that panics, and check the panic reaches the caller.
1282    /// - Check `cleanup` was called, `abandon` was not, and the handler was dropped.
1283    /// - Write to the pipe and check the byte is still readable, so the read was gone.
1284    #[test]
1285    fn task_panic_runs_shutdown() {
1286        let Some(reactor) = sync_cancel_reactor() else {
1287            return;
1288        };
1289        let events = Rc::new(Events::default());
1290        let mut buf = Box::new([0u8; 8]);
1291        let hnd = Box::new(Tracked {
1292            events: events.clone(),
1293            in_flight: 1,
1294        });
1295        let (rd, wr) = register_pipe_read(&reactor, &mut buf, false, hnd);
1296
1297        let rt = Runtime::new(ntex_rt::Driver::handle(&reactor));
1298        let res = catch_unwind(AssertUnwindSafe(|| {
1299            rt.block_on(async { panic!("task panicked") }, &reactor);
1300        }));
1301        assert!(res.is_err());
1302
1303        assert!(events.cleanup.get());
1304        assert!(!events.abandon.get());
1305        assert_eq!(Rc::strong_count(&events), 1);
1306        drop(buf);
1307        assert_pipe_unread(&rd, &wr);
1308    }
1309
1310    /// STATEMENT: A handler panic during completion handling keeps the handlers in
1311    /// the reactor, so the shutdown cancels their in-flight operations before
1312    /// releasing them.
1313    ///
1314    /// HOW:
1315    /// - Register a handler that panics on completion, and submit a no-op and a read
1316    ///   from an empty pipe into a buffer it owns.
1317    /// - Run a pending future, the no-op completion panics, and check the panic
1318    ///   reaches the caller.
1319    /// - Check `cleanup` was called, `abandon` was not, and the handler was dropped.
1320    /// - Write to the pipe and check the byte is still readable, so the read was gone.
1321    #[test]
1322    fn handler_panic_runs_shutdown() {
1323        let Some(reactor) = sync_cancel_reactor() else {
1324            return;
1325        };
1326        let events = Rc::new(Events::default());
1327        let mut buf = Box::new([0u8; 8]);
1328        let hnd = Box::new(PanicOnComplete(Tracked {
1329            events: events.clone(),
1330            in_flight: 1,
1331        }));
1332        let (rd, wr) = register_pipe_read(&reactor, &mut buf, true, hnd);
1333
1334        let rt = Runtime::new(ntex_rt::Driver::handle(&reactor));
1335        let res = catch_unwind(AssertUnwindSafe(|| {
1336            rt.block_on(pending::<()>(), &reactor);
1337        }));
1338        assert!(res.is_err());
1339
1340        assert!(events.cleanup.get());
1341        assert!(!events.abandon.get());
1342        assert_eq!(Rc::strong_count(&events), 1);
1343        drop(buf);
1344        assert_pipe_unread(&rd, &wr);
1345    }
1346
1347    fn sync_cancel_reactor() -> Option<Reactor> {
1348        let reactor = Reactor::new(8).ok()?;
1349        let err = reactor
1350            .inner
1351            .ring
1352            .submitter()
1353            .register_sync_cancel(None, CancelBuilder::user_data(Reactor::NOTIFY))
1354            .unwrap_err();
1355        if err.raw_os_error() != Some(libc::ENOENT) {
1356            eprintln!("Skipping notifier cancellation test: {err}");
1357            return None;
1358        }
1359        Some(reactor)
1360    }
1361
1362    fn assert_notifier_canceled(reactor: &Reactor) {
1363        // Run deferred cancellation completions without submitting other SQEs.
1364        // Only an enter with `GETEVENTS` runs deferred task work, and the
1365        // canceled read posts one completion.
1366        assert!(reactor.inner.ring.submission().is_empty());
1367        reactor.inner.ring.submitter().submit_and_wait(1).unwrap();
1368        let err = reactor
1369            .inner
1370            .ring
1371            .submitter()
1372            .register_sync_cancel(None, CancelBuilder::user_data(Reactor::NOTIFY))
1373            .unwrap_err();
1374        assert_eq!(err.raw_os_error(), Some(libc::ENOENT));
1375    }
1376
1377    // Keep the kernel ring, but destroy the reactor before completing the read.
1378    // Reclaim the deliberately retained allocation only after its CQE arrives.
1379    fn complete_retained_notifier(mut reactor: Reactor) {
1380        assert_eq!(
1381            reactor.inner.notify_read.state.get(),
1382            NotifierState::Retained
1383        );
1384        let buf = ptr::from_ref(reactor.inner.notify_read.buf.as_deref().unwrap()).cast_mut();
1385        let notify = reactor.notifier.handle();
1386        let inner = Rc::get_mut(&mut reactor.inner).unwrap();
1387        let ring = mem::replace(&mut inner.ring, IoUring::new(1).unwrap());
1388        let weak = Rc::downgrade(&reactor.inner);
1389        drop(reactor);
1390        assert!(weak.upgrade().is_none());
1391
1392        notify.notify().unwrap();
1393        ring.submitter().submit_and_wait(1).unwrap();
1394        // SAFETY: The test is the only consumer of the completion queue.
1395        let mut cq = unsafe { ring.completion_shared() };
1396        cq.sync();
1397        let entry = cq.next().unwrap();
1398        assert_eq!(entry.user_data(), Reactor::NOTIFY);
1399        assert_eq!(entry.result(), 8);
1400        // SAFETY: `buf` is the allocation the reactor retained; its read completed with the CQE above.
1401        let buf = unsafe { Box::from_raw(buf) };
1402        // SAFETY: The read completed, so the kernel no longer writes to the cell.
1403        assert_eq!(unsafe { *buf.get() }, 1);
1404    }
1405
1406    /// STATEMENT: A reactor whose notifier read was never submitted is freed when dropped.
1407    ///
1408    /// HOW:
1409    /// - Create a reactor; expect the notifier read queued and the submission queue empty.
1410    /// - Drop the reactor; expect its inner state freed.
1411    #[test]
1412    fn notifier_unrun() {
1413        let Ok(reactor) = Reactor::new(8) else {
1414            return;
1415        };
1416        assert_eq!(reactor.inner.notify_read.state.get(), NotifierState::Queued);
1417        assert!(reactor.inner.ring.submission().is_empty());
1418        let weak = Rc::downgrade(&reactor.inner);
1419        drop(reactor);
1420        assert!(weak.upgrade().is_none());
1421    }
1422
1423    /// STATEMENT: Debug output shows the ring descriptor, the handler counter and the
1424    /// notifier of the reactor, and the operation id batch of a handler api.
1425    ///
1426    /// HOW:
1427    /// - Format a new reactor and check its fields.
1428    /// - Register two handlers, format their apis and check the second batch starts at
1429    ///   `1 << BATCH`, then check the reactor reports the new handler counter.
1430    #[test]
1431    fn debug_output() {
1432        struct Noop;
1433        impl Handler for Noop {
1434            fn completed(&mut self, _: usize, _: u32, _: io::Result<usize>) {}
1435            fn canceled(&mut self, _: usize) {}
1436            fn tick(&mut self) {}
1437            fn cleanup(&mut self) {}
1438        }
1439
1440        let Ok(reactor) = Reactor::new(4) else {
1441            return;
1442        };
1443        let s = format!("{reactor:?}");
1444        assert!(
1445            s.starts_with(&format!(
1446                "Reactor {{ fd: {}, hid: Cell {{ value: 0 }}, notifier: Notifier {{",
1447                reactor.fd
1448            )),
1449            "{s}"
1450        );
1451
1452        let apis = RefCell::new(Vec::new());
1453        for _ in 0..2 {
1454            reactor.register(|api| {
1455                apis.borrow_mut().push(format!("{api:?}"));
1456                Box::new(Noop)
1457            });
1458        }
1459        assert_eq!(
1460            apis.into_inner(),
1461            [
1462                "ReactorApi { batch: 0 }".to_string(),
1463                format!("ReactorApi {{ batch: {} }}", 1u64 << Reactor::BATCH),
1464            ]
1465        );
1466        assert!(format!("{reactor:?}").contains("hid: Cell { value: 2 }"));
1467    }
1468
1469    /// STATEMENT: A notifier read held back by a full submission queue stops without a cancel,
1470    /// and the queued changes still run.
1471    ///
1472    /// HOW:
1473    /// - Queue 8 changes on a ring of 4 entries; expect the read still queued and 4 changes
1474    ///   left over.
1475    /// - Stop the notifier with a cancel that panics; expect it stopped.
1476    /// - Flush and submit; expect all 8 changes completed and nothing left to submit.
1477    #[test]
1478    fn notifier_stops_with_full_queue() {
1479        let Ok(reactor) = Reactor::new(4) else {
1480            return;
1481        };
1482        let sq = reactor.inner.ring.submission();
1483        for _ in 0..8 {
1484            reactor.inner.push(|en| {
1485                Nop::new(en).user_data(Reactor::CANCEL);
1486            });
1487        }
1488        assert!(reactor.apply_changes(sq));
1489        assert_eq!(reactor.inner.notify_read.state.get(), NotifierState::Queued);
1490        reactor
1491            .inner
1492            .notify_read
1493            .stop_with(&reactor.inner.ring, || panic!("read was not queued"));
1494        assert_eq!(
1495            reactor.inner.notify_read.state.get(),
1496            NotifierState::Stopped
1497        );
1498        assert_eq!(sq.len(), 4);
1499        // SAFETY: No other borrow of the change queue is live.
1500        assert_eq!(unsafe { &*reactor.inner.changes.get() }.len(), 4);
1501
1502        let submitter = reactor.inner.ring.submitter();
1503        reactor.flush(sq, &submitter);
1504        submitter.submit_and_wait(8).unwrap();
1505        // SAFETY: The test is the only consumer of the completion queue.
1506        let mut cq = unsafe { reactor.inner.ring.completion_shared() };
1507        cq.sync();
1508        assert_eq!(cq.len(), 8);
1509        assert!(cq.all(|e| e.user_data() == Reactor::CANCEL));
1510        assert!(reactor.inner.ring.submission().is_empty());
1511    }
1512
1513    /// STATEMENT: Stopping a submitted notifier read cancels it, and its canceled completion
1514    /// does not re-arm it.
1515    ///
1516    /// HOW:
1517    /// - Submit the notifier read and stop it; expect it stopped and no read in the kernel.
1518    /// - Poll the canceled completion and stop again with a cancel that panics.
1519    /// - Expect no new submissions.
1520    #[test]
1521    fn notifier_cancellation_does_not_rearm() {
1522        let Some(reactor) = sync_cancel_reactor() else {
1523            return;
1524        };
1525        assert!(!reactor.apply_changes(reactor.inner.ring.submission()));
1526        reactor.inner.ring.submitter().submit().unwrap();
1527        reactor.inner.notify_read.stop(&reactor.inner.ring);
1528        assert_eq!(
1529            reactor.inner.notify_read.state.get(),
1530            NotifierState::Stopped
1531        );
1532        assert_notifier_canceled(&reactor);
1533
1534        // SAFETY: The test is the only consumer of the completion queue.
1535        let mut cq = unsafe { reactor.inner.ring.completion_shared() };
1536        cq.sync();
1537        assert!(!reactor.poll_completions(&mut cq));
1538        cq.sync();
1539        reactor
1540            .inner
1541            .notify_read
1542            .stop_with(&reactor.inner.ring, || panic!("cleanup was not idempotent"));
1543        assert!(!reactor.apply_changes(reactor.inner.ring.submission()));
1544        assert!(reactor.inner.ring.submission().is_empty());
1545    }
1546
1547    /// STATEMENT: Stopping a notifier whose read already completed leaves no read in the
1548    /// kernel.
1549    ///
1550    /// HOW:
1551    /// - Submit the notifier read and complete it with a notification.
1552    /// - Stop the notifier; expect it stopped and no read in the kernel.
1553    #[test]
1554    fn notifier_completed_before_cleanup() {
1555        let Some(reactor) = sync_cancel_reactor() else {
1556            return;
1557        };
1558        assert!(!reactor.apply_changes(reactor.inner.ring.submission()));
1559        reactor.notifier.handle().notify().unwrap();
1560        reactor.inner.ring.submitter().submit_and_wait(1).unwrap();
1561        assert_eq!(reactor.inner.notify_read.state.get(), NotifierState::Active);
1562        reactor.inner.notify_read.stop(&reactor.inner.ring);
1563        assert_eq!(
1564            reactor.inner.notify_read.state.get(),
1565            NotifierState::Stopped
1566        );
1567        assert_notifier_canceled(&reactor);
1568    }
1569
1570    /// STATEMENT: Stopping a notifier whose read is in the submission queue retains its buffer
1571    /// until the read completes.
1572    ///
1573    /// HOW:
1574    /// - Queue the notifier read without submitting it, then stop the notifier.
1575    /// - Expect the read still queued and the notifier retained.
1576    /// - Drop the reactor, notify, and expect the read to complete into the retained buffer.
1577    #[test]
1578    fn notifier_queued_read_is_retained() {
1579        let Some(reactor) = sync_cancel_reactor() else {
1580            return;
1581        };
1582        assert!(!reactor.apply_changes(reactor.inner.ring.submission()));
1583        assert_eq!(reactor.inner.ring.submission().len(), 1);
1584        reactor.inner.notify_read.stop(&reactor.inner.ring);
1585        assert_eq!(reactor.inner.ring.submission().len(), 1);
1586        complete_retained_notifier(reactor);
1587    }
1588
1589    /// STATEMENT: When cancelling the notifier read fails, its buffer is retained until the
1590    /// read completes.
1591    ///
1592    /// HOW:
1593    /// - For `EINVAL`, `ETIME` and `EIO`, submit the read and stop it with a failing cancel.
1594    /// - Stop again with a cancel that panics; expect no new submissions.
1595    /// - Drop the reactor, notify, and expect the read to complete into the retained buffer.
1596    #[test]
1597    fn notifier_cancel_failure_is_retained() {
1598        for errno in [libc::EINVAL, libc::ETIME, libc::EIO] {
1599            let Some(reactor) = sync_cancel_reactor() else {
1600                return;
1601            };
1602            assert!(!reactor.apply_changes(reactor.inner.ring.submission()));
1603            reactor.inner.ring.submitter().submit().unwrap();
1604            reactor
1605                .inner
1606                .notify_read
1607                .stop_with(&reactor.inner.ring, || {
1608                    Err(io::Error::from_raw_os_error(errno))
1609                });
1610            reactor
1611                .inner
1612                .notify_read
1613                .stop_with(&reactor.inner.ring, || panic!("cleanup was not idempotent"));
1614            assert!(!reactor.apply_changes(reactor.inner.ring.submission()));
1615            assert!(reactor.inner.ring.submission().is_empty());
1616            complete_retained_notifier(reactor);
1617        }
1618    }
1619
1620    /// STATEMENT: When the driver fails, the notifier read is retained and handlers are
1621    /// still cleaned up and released.
1622    ///
1623    /// HOW:
1624    /// - Replace the ring with a disabled one, register a handler with nothing in flight.
1625    /// - Run the driver and check it fails with `EBADFD`.
1626    /// - Check `cleanup` was called, the handler was dropped and the notifier is retained.
1627    /// - Enable the ring and complete the retained notifier read.
1628    #[test]
1629    fn notifier_driver_error() {
1630        let Ok(mut reactor) = Reactor::new(8) else {
1631            return;
1632        };
1633        // A disabled ring rejects submission with EBADFD.
1634        let inner = Rc::get_mut(&mut reactor.inner).unwrap();
1635        inner.ring = IoUring::builder().setup_r_disabled().build(8).unwrap();
1636        reactor.fd = inner.ring.as_raw_fd();
1637        let events = Rc::new(Events::default());
1638        reactor.register(|_| {
1639            Box::new(Tracked {
1640                events: events.clone(),
1641                in_flight: 0,
1642            })
1643        });
1644        let rt = Runtime::new(ntex_rt::Driver::handle(&reactor));
1645        let err = ntex_rt::Driver::run(&reactor, &rt).unwrap_err();
1646        assert_eq!(err.raw_os_error(), Some(libc::EBADFD));
1647        // handlers are released on the error path too
1648        assert!(events.cleanup.get());
1649        assert_eq!(Rc::strong_count(&events), 1);
1650        assert_eq!(
1651            reactor.inner.notify_read.state.get(),
1652            NotifierState::Retained
1653        );
1654        drop(rt);
1655
1656        reactor
1657            .inner
1658            .ring
1659            .submitter()
1660            .register_enable_rings()
1661            .unwrap();
1662        complete_retained_notifier(reactor);
1663    }
1664
1665    /// STATEMENT: When a handler panics during dispatch, the notifier read is cancelled before
1666    /// the panic leaves the driver.
1667    ///
1668    /// HOW:
1669    /// - Register a handler that submits a `Nop` and panics on its second completion.
1670    /// - Run the driver; expect a panic and the notifier stopped with no read in the kernel.
1671    /// - Expect the notifier completion to be `ECANCELED`, and no read in the ring's `fdinfo`
1672    ///   after the reactor is dropped.
1673    #[test]
1674    fn notifier_handler_panic() {
1675        struct Panicking {
1676            api: ReactorApi,
1677            seen: bool,
1678        }
1679
1680        impl Handler for Panicking {
1681            fn completed(&mut self, _: usize, _: u32, _: io::Result<usize>) {
1682                assert!(!self.seen, "unwind with the rearmed notifier in flight");
1683                self.seen = true;
1684                // SAFETY: `Nop` entries reference no memory or descriptors.
1685                unsafe {
1686                    self.api.submit(0, |en| {
1687                        Nop::new(en);
1688                    });
1689                }
1690            }
1691            fn canceled(&mut self, _: usize) {}
1692            fn tick(&mut self) {}
1693            fn cleanup(&mut self) {}
1694        }
1695
1696        let Some(reactor) = sync_cancel_reactor() else {
1697            return;
1698        };
1699        let duplicate =
1700            // SAFETY: `dup` returned a fresh descriptor that nothing else owns.
1701            unsafe { OwnedFd::from_raw_fd(syscall!(libc::dup(reactor.as_raw_fd())).unwrap()) };
1702        let notify = reactor.notifier.handle();
1703        reactor.register(|api| {
1704            // SAFETY: `Nop` entries reference no memory or descriptors.
1705            unsafe {
1706                api.submit(0, |en| {
1707                    Nop::new(en);
1708                });
1709            }
1710            Box::new(Panicking { api, seen: false })
1711        });
1712        let rt = Runtime::new(ntex_rt::Driver::handle(&reactor));
1713        assert!(
1714            catch_unwind(AssertUnwindSafe(|| {
1715                rt.block_on(pending::<()>(), &reactor);
1716            }))
1717            .is_err()
1718        );
1719        assert_eq!(
1720            reactor.inner.notify_read.state.get(),
1721            NotifierState::Stopped
1722        );
1723        assert_notifier_canceled(&reactor);
1724        drop(rt);
1725        // SAFETY: The test is the only consumer of the completion queue.
1726        let mut cq = unsafe { reactor.inner.ring.completion_shared() };
1727        cq.sync();
1728        let entry = cq.next().unwrap();
1729        assert_eq!(entry.user_data(), Reactor::NOTIFY);
1730        assert_eq!(entry.result(), -libc::ECANCELED);
1731        drop(cq);
1732        drop(reactor);
1733        let info = std::fs::read_to_string(format!("/proc/self/fdinfo/{}", duplicate.as_raw_fd()))
1734            .unwrap();
1735        assert!(!info.contains("op=22,"), "{info}");
1736        drop(notify);
1737        drop(duplicate);
1738    }
1739
1740    /// STATEMENT: The notifier read re-arms after each wake, so repeated wakes from another
1741    /// thread all reach the runtime.
1742    ///
1743    /// HOW:
1744    /// - Wake the runtime three times from another thread, 50 ms apart.
1745    /// - Expect the blocked future to see all three wakes and finish.
1746    #[test]
1747    fn notifier_rearms() {
1748        use std::sync::{Mutex, atomic::AtomicUsize, atomic::Ordering};
1749        use std::{future::poll_fn, task::Poll, task::Waker, time::Duration};
1750
1751        let Ok(reactor) = Reactor::new(8) else {
1752            return;
1753        };
1754        let rt = Runtime::new(ntex_rt::Driver::handle(&reactor));
1755        let cnt = Arc::new(AtomicUsize::new(0));
1756        let waker = Arc::new(Mutex::new(None::<Waker>));
1757
1758        let (cnt2, waker2) = (cnt.clone(), waker.clone());
1759        let th = std::thread::spawn(move || {
1760            for i in 1..=3 {
1761                // the driver blocks on the ring before each wake
1762                std::thread::sleep(Duration::from_millis(50));
1763                cnt2.store(i, Ordering::Release);
1764                if let Some(w) = waker2.lock().unwrap().take() {
1765                    w.wake();
1766                }
1767            }
1768        });
1769
1770        let mut seen = 0;
1771        rt.block_on(
1772            poll_fn(|cx| {
1773                *waker.lock().unwrap() = Some(cx.waker().clone());
1774                let n = cnt.load(Ordering::Acquire);
1775                if n > seen {
1776                    seen = n;
1777                }
1778                if seen == 3 { Poll::Ready(()) } else { Poll::Pending }
1779            }),
1780            &reactor,
1781        );
1782        th.join().unwrap();
1783    }
1784}