From 5212222ca5e49a773ca2da32079a87ed87ddb2dc Mon Sep 17 00:00:00 2001 From: overtrue Date: Sun, 25 Oct 2026 18:17:52 +0800 Subject: [PATCH 1/2] fix: retain caller resources until native read completion --- README.md | 2 + src/driver.rs | 193 ++++++++++++-------- src/driver_fault_recovery_tests.rs | 1 + src/driver_submit_result_tests.rs | 1 + src/lib.rs | 4 +- tests/completion_owner.rs | 279 +++++++++++++++++++++++++++++ 6 files changed, 405 insertions(+), 75 deletions(-) create mode 100644 tests/completion_owner.rs diff --git a/README.md b/README.md index 9aea67a..b3c6324 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,8 @@ assert_eq!(snapshot.delivered + snapshot.orphan_reclaimed, snapshot.submitted); - `shutdown_async()` — with the default-off `tokio-runtime` feature, transfer consuming cleanup to Tokio's blocking pool at method call time. See [shutdown ownership and runtime boundaries](docs/shutdown.md). - `shard_iowq_setup()` — inspect each shard's best-effort startup registration request and result. Success returns the *previous* kernel limits; see [io-wq startup reporting](docs/iowq-startup.md). +Use `OwnedUringDriver` when a read must retain a resource lease through native completion. Its `read_at_with_owner`, `read_at_direct_with_owner`, and `read_current_with_owner` methods move the owner through the existing queue and pending table without boxing or spawning a task. `Owner` must be `Send + Unpin + 'static`, and its destructor must not panic or block. Dropping a submitted handle or its runtime does not release the owner; final completion does. An unresolved bounded shutdown retains it with the leaked native operation. Returned bytes do not retain it. Existing `UringDriver` and `ReadHandle` are aliases for the unit-owner types, so existing constructors and `ReadRequest` literals remain unchanged. + ### Shard selection Round-robin binds each read to the next shard, even if that shard is busy or diff --git a/src/driver.rs b/src/driver.rs index d700cb0..fb47cea 100644 --- a/src/driver.rs +++ b/src/driver.rs @@ -772,7 +772,7 @@ pub struct StatsSnapshot { pub submit_errors: u64, } -enum Msg { +enum Msg { Read { id: u64, #[cfg(feature = "diagnostics")] @@ -786,6 +786,7 @@ enum Msg { /// (rustfs/backlog#1060/#1102). If the driver rejects the op (shutting /// down) the permit is dropped with the message — released immediately. permit: ReadPermits, + owner: Option, /// Block size the read must be aligned to. `1` means a normal buffered /// read; `> 1` means the file was opened `O_DIRECT` and the driver must /// read the block-aligned superset range into a block-aligned buffer @@ -833,7 +834,7 @@ enum Msg { /// `buf[pad .. pad + region_len]` (both block-aligned) and hands the caller /// only `buf[pad + head .. pad + head + want]` — alignment padding never /// escapes. -struct Pending { +struct Pending { #[cfg(feature = "diagnostics")] timing: Option>, buf: Vec, @@ -845,6 +846,7 @@ struct Pending { /// Bytes already read into the read region (`buf[pad..]`). nread: usize, _permit: ReadPermits, + _owner: Option, /// Offset inside `buf` where the block-aligned read region starts. pad: usize, /// Bytes of the read region that precede the caller's logical range. @@ -864,7 +866,7 @@ struct Pending { cancel_requested: bool, } -impl Pending { +impl Pending { /// Build the read SQE for the not-yet-read remainder /// `[pad + nread, pad + region_len)` at file offset `offset + nread`. This is /// the single place a read SQE is constructed: the initial submit calls it @@ -888,7 +890,7 @@ impl Pending { } /// Where a [`ReadHandle`] is in its lifecycle (rustfs/backlog#1102). -enum HandleState { +enum HandleState { /// Nothing was ever handed to the driver (a rejected parameter, or the /// driver was already gone). The result is already sitting in `rx`, and /// there is no buffer, permit, or SQE to reclaim. @@ -899,6 +901,7 @@ enum HandleState { WaitingPermit { acquire: AcquireFut, file: Arc, + owner: Option, offset: u64, len: usize, align: usize, @@ -927,19 +930,23 @@ enum HandleState { /// (the common case, unchanged from the blocking implementation). Only when the /// semaphore is saturated does the handle acquire the permit and submit on its /// first poll, so `submit` never blocks a runtime worker. +pub type ReadHandle = OwnedReadHandle<()>; + +/// A read handle carrying a caller-supplied completion owner. +/// The owner is not part of the returned buffer and is released at final completion. #[must_use = "a read handle must be awaited or explicitly dropped"] -pub struct ReadHandle { +pub struct OwnedReadHandle { id: u64, #[cfg(feature = "diagnostics")] timing: Option>, rx: oneshot::Receiver>>, - tx: mpsc::Sender, + tx: mpsc::Sender>, finished: bool, cancel_on_drop: bool, - state: HandleState, + state: HandleState, } -impl ReadHandle { +impl OwnedReadHandle { /// Keep the driver's buffer until the normal CQE even when this handle is /// dropped. /// @@ -956,7 +963,7 @@ impl ReadHandle { } } -impl Future for ReadHandle { +impl Future for OwnedReadHandle { type Output = io::Result>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { @@ -975,6 +982,7 @@ impl Future for ReadHandle { if let Some(res) = acquired { let Ok(permit) = res else { // The semaphore was closed: the driver is gone. + this.state = HandleState::Inert; this.finished = true; return Poll::Ready(Err(io::Error::other("uring driver shut down"))); }; @@ -987,6 +995,7 @@ impl Future for ReadHandle { }; let HandleState::WaitingPermit { file, + owner, offset, len, align, @@ -1012,6 +1021,7 @@ impl Future for ReadHandle { len, done, permit, + owner, align, }) .is_err() @@ -1043,7 +1053,7 @@ impl Future for ReadHandle { } } -impl Drop for ReadHandle { +impl Drop for OwnedReadHandle { fn drop(&mut self) { // The buffer is deliberately NOT touched here: the driver owns it // until the CQE. All we may do is ask the kernel to hurry up. A handle @@ -1079,8 +1089,8 @@ impl Drop for ReadHandle { /// dropped, and its bounded drain is what shutdown joins on. A `ReadHandle` /// carries the `tx` and `wake` of the shard that accepted it, so a cancel or a /// deferred submission always routes back to that same shard. -struct Shard { - tx: mpsc::Sender, +struct Shard { + tx: mpsc::Sender>, handle: Option>, stats: Arc, iowq_setup: IoWqSetup, @@ -1093,7 +1103,7 @@ struct Shard { wake_efd: Arc, } -impl Shard { +impl Shard { /// Ask the shard's thread to drain and exit, then join it. Idempotent: the /// `JoinHandle` is taken, so a later `Drop` is a no-op. fn join(&mut self) { @@ -1105,7 +1115,7 @@ impl Shard { } } -impl Drop for Shard { +impl Drop for Shard { fn drop(&mut self) { self.join(); } @@ -1118,7 +1128,12 @@ impl Drop for Shard { /// that can be awaited or dropped without freeing memory still visible to the /// kernel. Construct it through [`UringDriver::probe_and_start`] so restricted /// environments can fall back to a blocking backend before serving traffic. -pub struct UringDriver { +pub type UringDriver = OwnedUringDriver<()>; + +/// A read driver that retains caller-supplied owners through native completion. +/// Owners move through the existing queue and pending table without boxing or +/// spawning a task. Use an owner that does not panic or block in its destructor. +pub struct OwnedUringDriver { limits: ReadLimits, shard_policy: ShardPolicy, byte_admission: Option>, @@ -1128,7 +1143,7 @@ pub struct UringDriver { /// bandwidth (~5 GB/s measured, rustfs/backlog#1145). Sharding lifts that /// ceiling roughly linearly while keeping the ring set per-disk, so a stalled /// disk still cannot starve another disk's rings (rustfs/backlog#1055). - shards: Vec, + shards: Vec>, next_id: AtomicU64, /// Round-robin cursor for shard selection. Relaxed: it only has to spread /// ops, never to order them. @@ -1149,7 +1164,7 @@ pub struct ReadRequest { pub len: usize, } -impl UringDriver { +impl OwnedUringDriver { /// Create the ring AND verify a real `IORING_OP_READ` round-trip on a /// temp file before accepting work. `io_uring_setup` succeeding is not /// enough: gVisor/seccomp environments can create a ring whose ops then @@ -1284,7 +1299,7 @@ impl UringDriver { start: usize, charge: u32, capacity_aware: bool, - ) -> (&Shard, Result) { + ) -> (&Shard, Result) { let first = &self.shards[start]; let bytes = self.byte_admission.as_ref().map(|admission| &admission.bytes); if !capacity_aware { @@ -1331,12 +1346,12 @@ impl UringDriver { /// memcpy across driver threads; correctness does not depend on the choice, /// because the handle remembers which shard took the op. #[cfg(feature = "fault-injection")] - fn shard(&self) -> &Shard { + fn shard(&self) -> &Shard { let n = self.shards.len(); &self.shards[self.rr.fetch_add(1, Ordering::Relaxed) % n] } - fn start_shard(entries: u32, probe: bool, byte_admission: Option>) -> Result { + fn start_shard(entries: u32, probe: bool, byte_admission: Option>) -> Result, ProbeFailure> { let mut ring = IoUring::new(entries).map_err(ProbeFailure::Setup)?; // Require the NODROP feature (kernel >= 5.5). Without it, CQ overflow // silently drops CQEs, stranding pending entries forever and hanging @@ -1419,8 +1434,8 @@ impl UringDriver { /// The offset must be at most `i64::MAX`; `u64::MAX` is reserved for /// [`Self::read_current`] and is returned as an asynchronous /// `io::ErrorKind::InvalidInput` result rather than panicking. - pub fn read_at(&self, file: Arc, offset: u64, len: usize) -> ReadHandle { - self.submit(file, offset, len, 1, false, true) + pub fn read_at(&self, file: Arc, offset: u64, len: usize) -> OwnedReadHandle { + self.submit((file, None), offset, len, 1, false, true) } /// Create handles in input order for up to [`MAX_BATCH_READS`] buffered positioned reads. @@ -1437,14 +1452,14 @@ impl UringDriver { /// More than [`MAX_BATCH_READS`] requests returns `InvalidInput` before any /// submission. Individual invalid requests return errors from their handles, /// exactly like [`Self::read_at`]; they do not reject other batch members. - pub fn read_at_batch(&self, requests: Vec) -> io::Result> { + pub fn read_at_batch(&self, requests: Vec) -> io::Result>> { if requests.len() > MAX_BATCH_READS { return Err(io::Error::new(io::ErrorKind::InvalidInput, "read batch exceeds MAX_BATCH_READS")); } let mut handles = Vec::with_capacity(requests.len()); let mut wakes: Vec> = Vec::with_capacity(requests.len()); for ReadRequest { file, offset, len } in requests { - let handle = self.submit(file, offset, len, 1, false, false); + let handle = self.submit((file, None), offset, len, 1, false, false); if let HandleState::Submitted { wake } = &handle.state && !wakes.iter().any(|queued| Arc::ptr_eq(queued, wake)) { @@ -1462,8 +1477,8 @@ impl UringDriver { } /// Read at the file's current position (read(2) semantics) — pipes. - pub fn read_current(&self, file: Arc, len: usize) -> ReadHandle { - self.submit(file, CURRENT_POSITION, len, 1, true, true) + pub fn read_current(&self, file: Arc, len: usize) -> OwnedReadHandle { + self.submit((file, None), CURRENT_POSITION, len, 1, true, true) } /// Positioned read from a file opened with `O_DIRECT` (rustfs/backlog#1102). @@ -1481,19 +1496,44 @@ impl UringDriver { /// the awaited result as `io::ErrorKind::InvalidInput`. /// A non-aligned short read that does not cover the requested range succeeds /// only when metadata confirms EOF; a failed metadata lookup returns an error. - pub fn read_at_direct(&self, file: Arc, offset: u64, len: usize, align: usize) -> ReadHandle { - self.submit(file, offset, len, align, false, true) + pub fn read_at_direct(&self, file: Arc, offset: u64, len: usize, align: usize) -> OwnedReadHandle { + self.submit((file, None), offset, len, align, false, true) } - fn submit( + /// Buffered positioned read retaining `owner` until its final native completion. + /// Dropping the handle abandons only the result. An unsubmitted or rejected + /// read releases its owner normally; an unresolved shutdown retains it with + /// the leaked pending operation. The returned bytes never retain the owner. + pub fn read_at_with_owner(&self, file: Arc, offset: u64, len: usize, owner: O) -> OwnedReadHandle { + self.submit((file, Some(owner)), offset, len, 1, false, true) + } + + /// Stream read with the same completion ownership as [`Self::read_at_with_owner`]. + pub fn read_current_with_owner(&self, file: Arc, len: usize, owner: O) -> OwnedReadHandle { + self.submit((file, Some(owner)), CURRENT_POSITION, len, 1, true, true) + } + + /// Direct positioned read with the same completion ownership as [`Self::read_at_with_owner`]. + pub fn read_at_direct_with_owner( &self, file: Arc, offset: u64, len: usize, align: usize, + owner: O, + ) -> OwnedReadHandle { + self.submit((file, Some(owner)), offset, len, align, false, true) + } + + fn submit( + &self, + (file, owner): (Arc, Option), + offset: u64, + len: usize, + align: usize, allow_current_position: bool, notify_now: bool, - ) -> ReadHandle { + ) -> OwnedReadHandle { let id = self.next_id.fetch_add(1, Ordering::Relaxed); assert_eq!(id & CANCEL_BIT, 0, "op id overflowed into the cancel bit"); let (done, rx) = oneshot::channel(); @@ -1515,7 +1555,7 @@ impl UringDriver { io::ErrorKind::InvalidInput, "offset u64::MAX is reserved for read_current", ))); - return ReadHandle { + return OwnedReadHandle { id, #[cfg(feature = "diagnostics")] timing, @@ -1539,7 +1579,7 @@ impl UringDriver { io::ErrorKind::InvalidInput, "offset exceeds i64::MAX (kernel loff_t is signed)", ))); - return ReadHandle { + return OwnedReadHandle { id, #[cfg(feature = "diagnostics")] timing, @@ -1562,7 +1602,7 @@ impl UringDriver { io::ErrorKind::InvalidInput, "read length exceeds MAX_RW_COUNT or configured logical read limit; caller must chunk", ))); - return ReadHandle { + return OwnedReadHandle { id, #[cfg(feature = "diagnostics")] timing, @@ -1601,7 +1641,7 @@ impl UringDriver { io::ErrorKind::InvalidInput, "alignment must be a power of two, and the block-aligned range must fit MAX_RW_COUNT and end within i64::MAX", ))); - return ReadHandle { + return OwnedReadHandle { id, #[cfg(feature = "diagnostics")] timing, @@ -1616,7 +1656,7 @@ impl UringDriver { if self.limits.max_in_flight_bytes.is_some_and(|max| allocation_bytes > max) { let _ = done.send(Err(io::Error::new(io::ErrorKind::InvalidInput, "aligned allocation exceeds byte budget"))); - return ReadHandle { + return OwnedReadHandle { id, #[cfg(feature = "diagnostics")] timing, @@ -1672,6 +1712,7 @@ impl UringDriver { len, done, permit, + owner, align, }) { // Driver gone: the op never reached it. Surface an explicit @@ -1682,7 +1723,7 @@ impl UringDriver { if let Msg::Read { done, .. } = msg { let _ = done.send(Err(io::Error::other("uring driver shut down"))); } - return ReadHandle { + return OwnedReadHandle { id, #[cfg(feature = "diagnostics")] timing, @@ -1697,7 +1738,7 @@ impl UringDriver { if notify_now { shard.wake_efd.signal(); } - ReadHandle { + OwnedReadHandle { id, #[cfg(feature = "diagnostics")] timing, @@ -1713,7 +1754,7 @@ impl UringDriver { // Saturated: `entries` ops are already in flight. Do NOT block the // calling (runtime worker) thread — hand the acquire future to the // handle, which awaits it on its first poll and submits then. - Err(TryAcquireError::NoPermits) => ReadHandle { + Err(TryAcquireError::NoPermits) => OwnedReadHandle { id, #[cfg(feature = "diagnostics")] timing, @@ -1731,6 +1772,7 @@ impl UringDriver { .and_then(|admission| admission.shared_reservation.clone()), ), file, + owner, offset, len, align, @@ -1741,7 +1783,7 @@ impl UringDriver { // The driver has exited and closed the semaphore. Err(TryAcquireError::Closed) => { let _ = done.send(Err(io::Error::other("uring driver shut down"))); - ReadHandle { + OwnedReadHandle { id, #[cfg(feature = "diagnostics")] timing, @@ -1816,29 +1858,6 @@ impl UringDriver { shard.wake_efd.signal(); } - /// Close admission and ask every shard to cancel/drain, without joining - /// driver threads or waiting for pending reads to complete. - /// - /// Count and byte waiters are woken with an admission error. An already - /// kernel-submitted operation still owns its buffer until its read CQE, or retains - /// it through the leak-over-UAF escape path. Concurrent and repeated calls - /// are safe; every call closes all admission before returning. - pub fn request_shutdown(&self) { - if let Some(admission) = &self.byte_admission { - admission.close(); - } - // Also close count-only admission when byte limits are disabled. Do not - // use a once flag: a concurrent caller must not return before this work - // is complete merely because another caller started the request. - for shard in &self.shards { - shard.sem.close(); - } - for shard in &self.shards { - let _ = shard.tx.send(Msg::Shutdown); - shard.wake_efd.signal(); - } - } - /// Advisory query: whether every driver thread's join handle reports /// finished (or has already been joined). This does not join threads or /// imply a clean drain; use [`Self::shutdown`] to join and inspect its stats. @@ -1909,7 +1928,32 @@ impl UringDriver { } } -impl Drop for UringDriver { +impl OwnedUringDriver { + /// Close admission and ask every shard to cancel/drain, without joining + /// driver threads or waiting for pending reads to complete. + /// + /// Count and byte waiters are woken with an admission error. An already + /// kernel-submitted operation still owns its buffer until its read CQE, or retains + /// it through the leak-over-UAF escape path. Concurrent and repeated calls + /// are safe; every call closes all admission before returning. + pub fn request_shutdown(&self) { + if let Some(admission) = &self.byte_admission { + admission.close(); + } + // Also close count-only admission when byte limits are disabled. Do not + // use a once flag: a concurrent caller must not return before this work + // is complete merely because another caller started the request. + for shard in &self.shards { + shard.sem.close(); + } + for shard in &self.shards { + let _ = shard.tx.send(Msg::Shutdown); + shard.wake_efd.signal(); + } + } +} + +impl Drop for OwnedUringDriver { fn drop(&mut self) { // Ask every shard to stop before joining any of them, so their bounded // drains overlap. Dropping the `Vec` would instead run each @@ -2091,13 +2135,13 @@ fn drain_probe_cqe(ring: &mut IoUring) -> io::Result { /// destructors during an unwind: it aborts the process first, leaving the /// ring mapped and the buffers allocated (leak over UAF). A storage read path /// silently corrupting memory is worse than a crash. -struct DriverState { +struct DriverState { ring: IoUring, - pending: HashMap, + pending: HashMap>, backlog: VecDeque, } -impl Drop for DriverState { +impl Drop for DriverState { fn drop(&mut self) { if std::thread::panicking() { // Abort BEFORE any field destructor runs: the ring stays mapped @@ -2118,7 +2162,7 @@ impl Drop for DriverState { /// Finish a non-aligned O_DIRECT short read only after confirming the file tail. /// Keeping the metadata result explicit lets tests inject errors without closing /// a live fd or changing process-wide environment state (rustfs/backlog#2647). -fn finish_direct_short_read(p: &mut Pending, file_len: io::Result) -> io::Result> { +fn finish_direct_short_read(p: &mut Pending, file_len: io::Result) -> io::Result> { let file_len = file_len?; if p.offset + (p.nread as u64) < file_len { return Err(io::Error::other("io_uring O_DIRECT: non-block-aligned short read before EOF")); @@ -2135,7 +2179,7 @@ fn finish_direct_short_read(p: &mut Pending, file_len: io::Result) -> io::R /// corruption. Only bytes the kernel actually wrote are exposed: `avail` is /// clamped to `nread`, so the zero-filled remainder of the buffer stays hidden /// (content hygiene, C12 / rustfs/backlog#1062). -fn deliver(p: &mut Pending) -> Vec { +fn deliver(p: &mut Pending) -> Vec { if p.done.as_ref().is_none_or(oneshot::Sender::is_closed) { // Only called after the terminal read CQE. Keep the allocation in the // entry for normal reclamation, avoiding an orphan's O_DIRECT memmove. @@ -2164,7 +2208,7 @@ enum ReapStep { /// Decide what follows a READ completion, never an AsyncCancel completion. /// Cancellation only suppresses continuation: an already-complete successful /// read still wins the race, and streams keep their read(2) short-read result. -fn reap_read(p: &mut Pending, id: u64, res: i32, shutting_down: bool) -> ReapStep { +fn reap_read(p: &mut Pending, id: u64, res: i32, shutting_down: bool) -> ReapStep { let stop_continuation = p.cancel_requested || shutting_down; if res < 0 { let err = -res; @@ -2253,8 +2297,8 @@ mod fault_recovery_tests; /// transient; any other errno is counted and, after a bounded run, transitions /// the shard to shutdown so callers fall back to the std backend. /// Returns the accepted SQE count, or zero when idle or submission failed. -fn submit_ring( - state: &mut DriverState, +fn submit_ring( + state: &mut DriverState, stats: &DriverStats, consecutive_submit_errors: &mut u32, submit_error_logged: &mut bool, @@ -2333,9 +2377,9 @@ fn update_cq_overflow(stats: &DriverStats, previous: &mut u32, observed: u32) -> observed != 0 } -fn drive( +fn drive( ring: IoUring, - rx: mpsc::Receiver, + rx: mpsc::Receiver>, stats: Arc, sem: Arc, cq_efd: EventFd, @@ -2425,6 +2469,7 @@ fn drive( len, done, permit, + owner, align, } => { if shutting_down { @@ -2488,6 +2533,7 @@ fn drive( // Released exactly when this entry is removed at the // final CQE — never at future drop (backlog#1060). _permit: permit, + _owner: owner, pad, head, want: len, @@ -3129,6 +3175,7 @@ mod cancellation_efficiency_tests { done: Some(done), offset: 0, nread: 0, + _owner: None, _permit: ReadPermits { _count: Arc::clone(&sem).try_acquire_owned().expect("fixture permit"), _bytes: None, diff --git a/src/driver_fault_recovery_tests.rs b/src/driver_fault_recovery_tests.rs index d5d3ee5..8470ef6 100644 --- a/src/driver_fault_recovery_tests.rs +++ b/src/driver_fault_recovery_tests.rs @@ -46,6 +46,7 @@ fn direct_prefix() -> (Pending, oneshot::Receiver>>) { done: Some(done), offset: 4096, nread: 5, + _owner: None, _permit: ReadPermits { _count: Arc::new(Semaphore::new(1)).try_acquire_owned().unwrap(), _bytes: None, diff --git a/src/driver_submit_result_tests.rs b/src/driver_submit_result_tests.rs index 6f580ab..6cc23be 100644 --- a/src/driver_submit_result_tests.rs +++ b/src/driver_submit_result_tests.rs @@ -46,6 +46,7 @@ fn pending_read(file: Arc, count: &Arc, bytes: &Arc) done: None, offset: 0, nread: 0, + _owner: None, _permit: ReadPermits { _count: Arc::clone(count).try_acquire_owned().unwrap(), _bytes: Some(Arc::clone(bytes).try_acquire_many_owned(16).unwrap()), diff --git a/src/lib.rs b/src/lib.rs index ca47b5b..ae077a0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -56,6 +56,6 @@ pub use diagnostics::{DIAGNOSTICS_SAMPLE_INTERVAL, DiagnosticsSnapshot, LatencyH #[cfg(target_os = "linux")] pub use driver::{ - IoWqRegistration, IoWqSetup, MAX_BATCH_READS, ProbeFailure, ReadHandle, ReadLimits, ReadRequest, ShardPolicy, - SharedReadBudget, StatsSnapshot, UringDriver, + IoWqRegistration, IoWqSetup, MAX_BATCH_READS, OwnedReadHandle, OwnedUringDriver, ProbeFailure, ReadHandle, ReadLimits, + ReadRequest, ShardPolicy, SharedReadBudget, StatsSnapshot, UringDriver, }; diff --git a/tests/completion_owner.rs b/tests/completion_owner.rs new file mode 100644 index 0000000..4bd20dd --- /dev/null +++ b/tests/completion_owner.rs @@ -0,0 +1,279 @@ +// Copyright 2024 RustFS Team +// SPDX-License-Identifier: Apache-2.0 + +//! Native completion ownership must outlive the caller's future. +#![cfg(target_os = "linux")] + +use std::fs::File; +use std::future::Future; +use std::io::Write; +use std::os::fd::FromRawFd; +use std::os::unix::fs::OpenOptionsExt; +use std::pin::Pin; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::task::{Context, Poll, Waker}; +use std::time::{Duration, Instant}; + +use rustfs_uring::OwnedUringDriver; + +struct Owner(Arc); + +impl Drop for Owner { + fn drop(&mut self) { + self.0.fetch_add(1, Ordering::SeqCst); + } +} + +fn driver() -> Option> { + match OwnedUringDriver::probe_and_start(2) { + Ok(driver) => Some(driver), + Err(error) => { + assert!(error.is_expected_restriction(), "unexpected probe failure: {error}"); + eprintln!("SKIP completion owner: restricted io_uring ({error})"); + None + } + } +} + +fn owner() -> (Owner, Arc) { + let drops = Arc::new(AtomicUsize::new(0)); + (Owner(Arc::clone(&drops)), drops) +} + +fn poll_once(future: &mut F) -> Poll { + Pin::new(future).poll(&mut Context::from_waker(Waker::noop())) +} + +fn pipe() -> (Arc, File) { + let mut fds = [-1; 2]; + // SAFETY: pipe2 initializes both descriptors on success; each is owned once. + assert_eq!(unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) }, 0); + // SAFETY: each successful pipe descriptor is transferred to one File. + unsafe { (Arc::new(File::from_raw_fd(fds[0])), File::from_raw_fd(fds[1])) } +} + +fn wait_until(mut condition: impl FnMut() -> bool) { + let deadline = Instant::now() + Duration::from_secs(5); + while !condition() { + assert!(Instant::now() < deadline, "native completion deadline"); + std::thread::yield_now(); + } +} + +#[test] +fn submitted_owner_survives_caller_drop() { + let Some(driver) = driver() else { return }; + let (reader, mut writer) = pipe(); + let drops = Arc::new(AtomicUsize::new(0)); + let owner = Owner(Arc::clone(&drops)); + let future = driver.read_current_with_owner(reader, 4, owner).without_cancel_on_drop(); + wait_until(|| driver.stats().in_flight == 1); + drop(future); + let premature_release = drops.load(Ordering::SeqCst); + assert_eq!(driver.stats().in_flight, 1, "pipe has no data or EOF"); + writer.write_all(b"done").expect("complete native pipe read"); + wait_until(|| driver.stats().in_flight == 0); + assert_eq!(driver.shutdown().orphan_reclaimed, 1); + assert_eq!(drops.load(Ordering::SeqCst), 1, "release after completion"); + assert_eq!(premature_release, 0, "caller drop must not release a pending read owner"); +} + +#[test] +fn native_owner_survives_request_runtime_shutdown() { + let Some(driver) = driver() else { return }; + let (reader, mut writer) = pipe(); + let (owner, drops) = owner(); + let runtime = tokio::runtime::Builder::new_current_thread() + .build() + .expect("request runtime"); + let future = driver.read_current_with_owner(reader, 4, owner).without_cancel_on_drop(); + let task = runtime.spawn(future); + runtime.block_on(tokio::task::yield_now()); + wait_until(|| driver.stats().in_flight == 1); + drop(runtime); + assert!(task.is_finished(), "runtime shutdown drops the requesting task"); + assert_eq!(drops.load(Ordering::SeqCst), 0); + writer + .write_all(b"done") + .expect("complete native read after runtime shutdown"); + wait_until(|| driver.stats().in_flight == 0); + assert_eq!(driver.shutdown().orphan_reclaimed, 1); + assert_eq!(drops.load(Ordering::SeqCst), 1); +} + +#[test] +fn default_drop_cancellation_reclaims_owner_with_native_read() { + let Some(driver) = driver() else { return }; + let (reader, _writer) = pipe(); + let (owner, drops) = owner(); + let handle = driver.read_current_with_owner(reader, 4, owner); + wait_until(|| driver.stats().in_flight == 1); + assert_eq!(drops.load(Ordering::SeqCst), 0); + drop(handle); + wait_until(|| driver.stats().in_flight == 0); + assert_eq!(driver.shutdown().orphan_reclaimed, 1); + assert_eq!(drops.load(Ordering::SeqCst), 1); +} + +#[test] +fn unsubmitted_owner_releases_when_waiter_is_dropped() { + let Some(driver) = driver() else { return }; + let (reader, _writer) = pipe(); + let busy = [ + driver.read_current(Arc::clone(&reader), 4), + driver.read_current(Arc::clone(&reader), 4), + ]; + wait_until(|| driver.stats().in_flight == 2); + let (owner, drops) = owner(); + let waiting = driver.read_current_with_owner(reader, 4, owner); + assert_eq!(drops.load(Ordering::SeqCst), 0); + drop(waiting); + assert_eq!(drops.load(Ordering::SeqCst), 1); + drop(busy); + let stats = driver.shutdown(); + assert_eq!(stats.submitted, 2, "unpolled waiter never submitted"); + assert_eq!(stats.in_flight, 0); +} + +#[test] +fn deferred_owner_moves_to_native_completion_after_admission() { + let Some(driver) = driver() else { return }; + let (busy_reader, _busy_writer) = pipe(); + let first = driver.read_current(Arc::clone(&busy_reader), 4); + let second = driver.read_current(busy_reader, 4); + wait_until(|| driver.stats().in_flight == 2); + let (reader, mut writer) = pipe(); + let (owner, drops) = owner(); + let mut waiting = driver.read_current_with_owner(reader, 4, owner).without_cancel_on_drop(); + assert!(poll_once(&mut waiting).is_pending()); + assert_eq!(drops.load(Ordering::SeqCst), 0); + drop(first); + wait_until(|| { + assert!(poll_once(&mut waiting).is_pending()); + driver.stats().submitted == 3 + }); + drop(waiting); + assert_eq!(drops.load(Ordering::SeqCst), 0, "admitted owner moved off caller"); + writer.write_all(b"done").expect("complete admitted read"); + wait_until(|| drops.load(Ordering::SeqCst) == 1); + drop(second); + assert_eq!(driver.shutdown().in_flight, 0); +} + +#[test] +fn closed_admission_releases_owner_even_if_finished_handle_is_retained() { + let Some(driver) = driver() else { return }; + let (reader, _writer) = pipe(); + let busy = [ + driver.read_current(Arc::clone(&reader), 4), + driver.read_current(Arc::clone(&reader), 4), + ]; + wait_until(|| driver.stats().in_flight == 2); + let (owner, drops) = owner(); + let mut waiting = driver.read_current_with_owner(reader, 4, owner); + assert!(poll_once(&mut waiting).is_pending()); + driver.request_shutdown(); + assert!(matches!(poll_once(&mut waiting), Poll::Ready(Err(_)))); + assert_eq!(drops.load(Ordering::SeqCst), 1, "finished waiter must release its owner"); + drop(busy); + assert_eq!(driver.shutdown().in_flight, 0); + drop(waiting); + assert_eq!(drops.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn rejected_and_empty_reads_release_owners_at_their_completion_boundary() { + let Some(driver) = driver() else { return }; + let file = Arc::new(File::open("/dev/null").expect("fixture")); + for (offset, len, align) in [(u64::MAX, 4, 1), (0, 4, 3)] { + let (owner, drops) = owner(); + let mut handle = driver.read_at_direct_with_owner(Arc::clone(&file), offset, len, align, owner); + let Poll::Ready(result) = poll_once(&mut handle) else { panic!("unsubmitted read must be ready") }; + assert_eq!(result.expect_err("invalid parameters").kind(), std::io::ErrorKind::InvalidInput); + assert_eq!(drops.load(Ordering::SeqCst), 1, "rejected owner releases immediately"); + } + assert_eq!(driver.stats().submitted, 0); + // Zero-length reads follow the normal submission path in the existing API. + let (owner, drops) = owner(); + let empty = driver.read_at_with_owner(file, 0, 0, owner); + let result = tokio::time::timeout(Duration::from_secs(5), empty) + .await + .expect("empty read deadline") + .expect("empty read result"); + assert!(result.is_empty()); + wait_until(|| drops.load(Ordering::SeqCst) == 1); + assert_eq!(driver.shutdown().submitted, 1); +} + +#[tokio::test] +async fn buffered_and_direct_results_do_not_retain_completion_owners() { + let Some(driver) = driver() else { return }; + let path = std::env::temp_dir().join(format!("uring-completion-owner-{}", std::process::id())); + let content: Vec<_> = (0..8192).map(|index| (index % 251) as u8).collect(); + std::fs::write(&path, &content).expect("write fixture"); + for (direct, length) in [(false, 4097), (true, 4097), (false, 16384), (true, 16384)] { + let file = Arc::new( + std::fs::OpenOptions::new() + .read(true) + .custom_flags(if direct { libc::O_DIRECT } else { 0 }) + .open(&path) + .expect("open actual read mode"), + ); + let (owner, drops) = owner(); + let handle = if direct { + driver.read_at_direct_with_owner(file, 17, length, 4096, owner) + } else { + driver.read_at_with_owner(file, 17, length, owner) + }; + let result = tokio::time::timeout(Duration::from_secs(5), handle) + .await + .expect("read deadline") + .expect("native read"); + assert_eq!(result, content[17..(17 + length).min(content.len())]); + wait_until(|| drops.load(Ordering::SeqCst) == 1); + assert_eq!( + result.len(), + length.min(content.len() - 17), + "retained bytes do not retain the native owner" + ); + } + assert_eq!(driver.shutdown().delivered, 4); + std::fs::remove_file(path).expect("remove fixture"); +} + +#[cfg(feature = "fault-injection")] +#[test] +fn unresolved_native_completion_keeps_owner_on_bounded_shutdown() { + const CHILD: &str = "RUSTFS_URING_OWNER_DRAIN_CHILD"; + if std::env::var_os(CHILD).is_none() { + let Some(probe) = driver() else { return }; + assert_eq!(probe.shutdown().in_flight, 0); + let output = std::process::Command::new(std::env::current_exe().expect("test binary")) + .args([ + "--exact", + "unresolved_native_completion_keeps_owner_on_bounded_shutdown", + "--nocapture", + ]) + .env(CHILD, "1") + .env("RUSTFS_URING_FAULT_STUCK_DRAIN", "1") + .env("RUSTFS_URING_FAULT_DRAIN_TIMEOUT_MS", "50") + .output() + .expect("bounded-drain subprocess"); + assert!(output.status.success(), "child failed: {}", String::from_utf8_lossy(&output.stderr)); + assert!( + !String::from_utf8_lossy(&output.stderr).contains("SKIP "), + "child must execute native path" + ); + return; + } + let Some(driver) = driver() else { panic!("child must run real io_uring") }; + let (reader, _writer) = pipe(); + let (owner, drops) = owner(); + let handle = driver.read_current_with_owner(reader, 4, owner); + wait_until(|| driver.stats().in_flight == 1); + drop(handle); + let stats = driver.shutdown(); + assert_eq!(stats.in_flight, 1, "fault seam withholds the native completion"); + assert_eq!(drops.load(Ordering::SeqCst), 0, "unresolved I/O must retain its owner"); +} From eb8fc160e71d804427de1e905f5c226d580f71bf Mon Sep 17 00:00:00 2001 From: overtrue Date: Sun, 25 Oct 2026 18:38:27 +0800 Subject: [PATCH 2/2] fix: use the supported atomic update API --- src/driver.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/driver.rs b/src/driver.rs index fb47cea..3d69bd9 100644 --- a/src/driver.rs +++ b/src/driver.rs @@ -580,7 +580,7 @@ impl SharedReadBudget { } self.inner .available - .fetch_update(Ordering::AcqRel, Ordering::Acquire, |available| available.checked_sub(bytes)) + .try_update(Ordering::AcqRel, Ordering::Acquire, |available| available.checked_sub(bytes)) .map_err(|_| io::Error::new(io::ErrorKind::WouldBlock, "shared read budget has insufficient unreserved capacity"))?; Ok(Arc::new(SharedReadReservation { pool: Arc::clone(&self.inner),