From 93eca3e79d7aa9f93b44af5ac48eff834cfbcfc2 Mon Sep 17 00:00:00 2001 From: Ramakrishna Chilaka <49393831+RamakrishnaChilaka@users.noreply.github.com> Date: Sun, 29 Nov 2026 08:09:40 +0530 Subject: [PATCH] perf(io-core): make progress and backpressure state checks lock-free (#9724) --- crates/io-core/src/backpressure.rs | 51 ++++++++++++++++++++++++------ crates/io-core/src/io_profile.rs | 29 ++++++++++------- crates/io-core/src/pool.rs | 2 +- crates/io-core/src/progress.rs | 27 ++++++++-------- 4 files changed, 72 insertions(+), 37 deletions(-) diff --git a/crates/io-core/src/backpressure.rs b/crates/io-core/src/backpressure.rs index 896d01ed6d..60569df344 100644 --- a/crates/io-core/src/backpressure.rs +++ b/crates/io-core/src/backpressure.rs @@ -17,7 +17,7 @@ //! This module provides backpressure mechanisms to prevent system overload //! and maintain stability under high load conditions. -use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, AtomicUsize, Ordering}; use std::time::{Duration, Instant}; /// Backpressure configuration. @@ -109,18 +109,42 @@ impl BackpressureState { BackpressureState::Critical => "critical", } } + + #[inline] + const fn to_u8(self) -> u8 { + match self { + BackpressureState::Normal => 0, + BackpressureState::Warning => 1, + BackpressureState::Critical => 2, + } + } + + #[inline] + const fn from_u8(val: u8) -> Self { + match val { + 1 => BackpressureState::Warning, + 2 => BackpressureState::Critical, + _ => BackpressureState::Normal, + } + } } /// Backpressure monitor. pub struct BackpressureMonitor { /// Configuration. config: BackpressureConfig, + /// Precomputed high threshold. + high_threshold: usize, + /// Precomputed low threshold. + low_threshold: usize, /// Current concurrent operations. current: AtomicUsize, /// Total operations processed. total_processed: AtomicU64, /// Total operations rejected. total_rejected: AtomicU64, + /// Atomic state representation for lock-free reads and no-op transitions. + state_code: AtomicU8, /// Current state. state: std::sync::Mutex, /// Last state change time. @@ -132,11 +156,16 @@ pub struct BackpressureMonitor { impl BackpressureMonitor { /// Create a new backpressure monitor. pub fn new(config: BackpressureConfig) -> Self { + let high_threshold = config.high_threshold(); + let low_threshold = config.low_threshold(); Self { config, + high_threshold, + low_threshold, current: AtomicUsize::new(0), total_processed: AtomicU64::new(0), total_rejected: AtomicU64::new(0), + state_code: AtomicU8::new(BackpressureState::Normal.to_u8()), state: std::sync::Mutex::new(BackpressureState::Normal), last_state_change: std::sync::Mutex::new(None), active: AtomicBool::new(false), @@ -160,11 +189,7 @@ impl BackpressureMonitor { /// Get current state. pub fn state(&self) -> BackpressureState { - if let Ok(state) = self.state.lock() { - *state - } else { - BackpressureState::Normal - } + BackpressureState::from_u8(self.state_code.load(Ordering::Acquire)) } /// Check if backpressure is active. @@ -182,7 +207,8 @@ impl BackpressureMonitor { return true; } - let high_threshold = self.config.high_threshold(); + let high_threshold = self.high_threshold; + let low_threshold = self.low_threshold; // Use a CAS loop to ensure we never exceed `max_concurrent` under contention. loop { @@ -207,7 +233,7 @@ impl BackpressureMonitor { if current >= high_threshold { self.set_state(BackpressureState::Critical); self.active.store(true, Ordering::Relaxed); - } else if current >= self.config.low_threshold() { + } else if current >= low_threshold { self.set_state(BackpressureState::Warning); } @@ -235,7 +261,7 @@ impl BackpressureMonitor { 0 } }; - let low_threshold = self.config.low_threshold(); + let low_threshold = self.low_threshold; // Update state if needed if prev <= low_threshold + 1 { @@ -246,10 +272,15 @@ impl BackpressureMonitor { /// Set the state. fn set_state(&self, new_state: BackpressureState) { + let new_code = new_state.to_u8(); + if self.state_code.load(Ordering::Relaxed) == new_code { + return; + } if let Ok(mut state) = self.state.lock() && *state != new_state { *state = new_state; + self.state_code.store(new_code, Ordering::Release); if let Ok(mut last) = self.last_state_change.lock() { *last = Some(Instant::now()); } @@ -281,7 +312,7 @@ impl BackpressureMonitor { } let current = self.current.load(Ordering::Relaxed); - if current < self.config.high_threshold() { + if current < self.high_threshold { return false; } diff --git a/crates/io-core/src/io_profile.rs b/crates/io-core/src/io_profile.rs index 46b894c490..2a75f7bdfa 100644 --- a/crates/io-core/src/io_profile.rs +++ b/crates/io-core/src/io_profile.rs @@ -40,12 +40,17 @@ impl FromStr for StorageMedia { type Err = (); fn from_str(value: &str) -> Result { - match value.trim().to_ascii_lowercase().as_str() { - "nvme" => Ok(Self::Nvme), - "ssd" => Ok(Self::Ssd), - "hdd" => Ok(Self::Hdd), - "unknown" => Ok(Self::Unknown), - _ => Err(()), + let trimmed = value.trim(); + if trimmed.eq_ignore_ascii_case("nvme") { + Ok(Self::Nvme) + } else if trimmed.eq_ignore_ascii_case("ssd") { + Ok(Self::Ssd) + } else if trimmed.eq_ignore_ascii_case("hdd") { + Ok(Self::Hdd) + } else if trimmed.eq_ignore_ascii_case("unknown") { + Ok(Self::Unknown) + } else { + Err(()) } } } @@ -157,23 +162,23 @@ impl IoPatternDetector { } pub fn current_pattern(&self) -> AccessPattern { - if self.history.len() < 2 { + let mut iter = self.history.iter().copied(); + let Some((mut prev_offset, mut prev_len)) = iter.next() else { return AccessPattern::Unknown; - } + }; - let history = self.history.iter().copied().collect::>(); let mut sequential = 0usize; let mut random = 0usize; - for window in history.windows(2) { - let (prev_offset, prev_len) = window[0]; - let (curr_offset, _) = window[1]; + for (curr_offset, curr_len) in iter { let prev_end = prev_offset.saturating_add(prev_len); if curr_offset.abs_diff(prev_end) <= self.sequential_step_tolerance_bytes { sequential += 1; } else { random += 1; } + prev_offset = curr_offset; + prev_len = curr_len; } match (sequential, random) { diff --git a/crates/io-core/src/pool.rs b/crates/io-core/src/pool.rs index f68a56ef39..3544042210 100644 --- a/crates/io-core/src/pool.rs +++ b/crates/io-core/src/pool.rs @@ -293,7 +293,7 @@ impl PoolTier { max_buffers, semaphore: Arc::new(Semaphore::new(max_buffers)), name, - available_buffers: Mutex::new(Vec::new()), + available_buffers: Mutex::new(Vec::with_capacity(max_buffers)), metrics, acquire_metrics_lock: Mutex::new(()), tier_total_acquires: AtomicU64::new(0), diff --git a/crates/io-core/src/progress.rs b/crates/io-core/src/progress.rs index 44e4460dd5..59ad9d4bdd 100644 --- a/crates/io-core/src/progress.rs +++ b/crates/io-core/src/progress.rs @@ -28,8 +28,8 @@ pub struct OperationProgress { pub total_size: Option, /// Bytes processed. bytes_processed: AtomicU64, - /// Last update time. - last_update: std::sync::Mutex, + /// Last update timestamp as elapsed nanoseconds since `start_time`. + last_update_nanos: AtomicU64, /// Stale timeout. stale_timeout: Duration, /// Start time for transfer rate calculation. @@ -42,26 +42,28 @@ impl OperationProgress { Self { total_size, bytes_processed: AtomicU64::new(0), - last_update: std::sync::Mutex::new(Instant::now()), + last_update_nanos: AtomicU64::new(0), stale_timeout, start_time: Instant::now(), } } + #[inline] + fn record_update_time(&self) { + let elapsed_nanos = self.start_time.elapsed().as_nanos().min(u128::from(u64::MAX)) as u64; + self.last_update_nanos.store(elapsed_nanos, Ordering::Relaxed); + } + /// Update progress. pub fn update(&self, bytes: u64) { self.bytes_processed.store(bytes, Ordering::Relaxed); - if let Ok(mut last) = self.last_update.lock() { - *last = Instant::now(); - } + self.record_update_time(); } /// Add to progress. pub fn add(&self, bytes: u64) { self.bytes_processed.fetch_add(bytes, Ordering::Relaxed); - if let Ok(mut last) = self.last_update.lock() { - *last = Instant::now(); - } + self.record_update_time(); } /// Get current progress. @@ -71,11 +73,8 @@ impl OperationProgress { /// Check if progress is stale. pub fn is_stale(&self) -> bool { - if let Ok(last) = self.last_update.lock() { - last.elapsed() > self.stale_timeout - } else { - false - } + let last_nanos = self.last_update_nanos.load(Ordering::Relaxed); + self.start_time.elapsed().saturating_sub(Duration::from_nanos(last_nanos)) > self.stale_timeout } /// Get progress percentage.