diff --git a/src/drivers/mod.rs b/src/drivers/mod.rs index 9146d505..716ea681 100644 --- a/src/drivers/mod.rs +++ b/src/drivers/mod.rs @@ -272,6 +272,38 @@ pub(crate) fn device_access() -> MutexGuard<'static, automation::ManualIntent> { .unwrap_or_else(|poisoned| poisoned.into_inner()) } +/// How long a background read waits for [`DEVICE_ACCESS`] before giving up. +const DEVICE_ACCESS_WAIT: std::time::Duration = std::time::Duration::from_secs(30); + +/// [`device_access`] with a bounded wait, for background work. A native call +/// stuck inside `hidapi` keeps the lock for good, and an unbounded wait would +/// pile every later poll up behind it with no word in the log. The error is +/// `WouldBlock`, so the caller treats the mouse as busy, not asleep. +fn device_access_within( + wait: std::time::Duration, +) -> Result> { + let deadline = std::time::Instant::now() + wait; + loop { + match DEVICE_ACCESS.try_lock() { + Ok(guard) => return Ok(guard), + Err(std::sync::TryLockError::Poisoned(poisoned)) => return Ok(poisoned.into_inner()), + Err(std::sync::TryLockError::WouldBlock) => {} + } + if std::time::Instant::now() >= deadline { + tracing::warn!( + wait_secs = wait.as_secs(), + "Native device access is held by another call; skipping this read" + ); + return Err(std::io::Error::new( + std::io::ErrorKind::WouldBlock, + "native device access is busy", + ) + .into()); + } + std::thread::sleep(std::time::Duration::from_millis(50)); + } +} + pub(crate) fn manual_report_access( vendor_id: u16, ) -> Result> { @@ -319,7 +351,7 @@ pub fn apply_profile(profile: &ApplicationProfile) -> Result { .next() .unwrap_or_default() .to_ascii_lowercase(); - let mut access = device_access(); + let mut access = device_access_within(DEVICE_ACCESS_WAIT)?; ensure_native_ownership()?; access.invalidate( &brand, @@ -360,7 +392,12 @@ pub(crate) fn reconcile_automatic( automation: &mut automation::NativeAutomation, desired: Option<&ApplicationProfile>, ) -> Result { - let access = device_access(); + let access = match device_access_within(DEVICE_ACCESS_WAIT) { + Ok(access) => access, + // A stuck native call holds the lock: leave the automation state + // alone and try again on the next pass. + Err(_) => return Ok(Reconciled::Deferred), + }; automation.observe_manual_intent(&access); if crate::hid::client_session_active() { return Ok(Reconciled::Deferred); @@ -421,7 +458,7 @@ fn write_settings_held( /// (e.g. asleep or disconnected). pub fn read_status(device_id: &str) -> Result> { let brand = device_id.split(':').next().unwrap_or_default(); - let _access = device_access(); + let _access = device_access_within(DEVICE_ACCESS_WAIT)?; ensure_native_ownership()?; if brand.eq_ignore_ascii_case(pulsar::BRAND) { return pulsar::read_status(); @@ -440,7 +477,7 @@ pub fn read_status(device_id: &str) -> Result> { /// local Bridge. Native-only devices use this path when WebHID cannot access /// their protected configuration interface. pub fn apply_settings(brand: &str, dpi: Option, polling_rate_hz: Option) -> Result { - let mut access = device_access(); + let mut access = device_access_within(DEVICE_ACCESS_WAIT)?; ensure_native_ownership()?; access.invalidate(brand, dpi.is_some(), polling_rate_hz.is_some())?; native_hid::apply_settings( @@ -548,6 +585,36 @@ mod tests { ) } + #[test] + fn a_bounded_wait_for_device_access_gives_up_while_it_is_held() { + let _serial = TEST_NATIVE.lock().unwrap_or_else(|e| e.into_inner()); + let wait = std::time::Duration::from_millis(120); + { + let _held = device_access(); + let error = device_access_within(wait).err().expect("the lock is held"); + let kind = error + .downcast_ref::() + .map(std::io::Error::kind); + // WouldBlock reads as busy, so the poll does not mark the mouse asleep. + assert_eq!(kind, Some(std::io::ErrorKind::WouldBlock)); + } + assert!(device_access_within(wait).is_ok()); + } + + #[test] + fn a_bounded_wait_gets_the_lock_when_it_is_released_in_time() { + let _serial = TEST_NATIVE.lock().unwrap_or_else(|e| e.into_inner()); + let (locked_tx, locked_rx) = std::sync::mpsc::channel(); + let releaser = std::thread::spawn(move || { + let _held = device_access(); + locked_tx.send(()).unwrap(); + std::thread::sleep(std::time::Duration::from_millis(100)); + }); + locked_rx.recv().unwrap(); + assert!(device_access_within(std::time::Duration::from_secs(5)).is_ok()); + releaser.join().unwrap(); + } + #[test] fn manual_settings_takeover_preserves_3200_on_automatic_exit() { let _serial = TEST_NATIVE.lock().unwrap_or_else(|e| e.into_inner()); diff --git a/src/hid.rs b/src/hid.rs index 72bd6098..49889aaa 100644 --- a/src/hid.rs +++ b/src/hid.rs @@ -2,7 +2,7 @@ use std::{ collections::{HashMap, HashSet}, ffi::CString, sync::{ - Arc, Mutex, Once, OnceLock, PoisonError, + Arc, Mutex, Once, OnceLock, PoisonError, RwLock, atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}, }, thread, @@ -1415,7 +1415,8 @@ fn inspect_candidate( let mut collections = Vec::new(); let mut paths = Vec::with_capacity(unique_paths.len()); for path in unique_paths { - let (mut path_collections, layout) = inspect_path(api, &path, infos, inspect_descriptors); + let (mut path_collections, layout, _) = + inspect_path(api, &path, infos, inspect_descriptors); collections.append(&mut path_collections); paths.push(CandidatePath { path, layout }); } @@ -1439,13 +1440,14 @@ fn inspect_candidate( /// The collections and report layout of one path, parsed from its report /// descriptor. When the descriptor is not read (`read_descriptor` false, as /// for Razer) or cannot be, each collection the platform enumerated for the -/// path stands in with its usage page and usage only. +/// path stands in with its usage page and usage only. The flag is whether the +/// descriptor was actually parsed. fn inspect_path( api: &HidApi, path: &CString, infos: &[hidapi::DeviceInfo], read_descriptor: bool, -) -> (Vec, ReportLayout) { +) -> (Vec, ReportLayout, bool) { let parsed = read_descriptor .then(|| { api.open_path(path).ok().and_then(|device| { @@ -1455,7 +1457,14 @@ fn inspect_path( }) }) .flatten(); - parsed.unwrap_or_else(|| (enumerated_collections(infos, path), ReportLayout::default())) + match parsed { + Some((collections, layout)) => (collections, layout, true), + None => ( + enumerated_collections(infos, path), + ReportLayout::default(), + false, + ), + } } fn enumerated_collections(infos: &[hidapi::DeviceInfo], path: &CString) -> Vec { @@ -1574,6 +1583,22 @@ fn report_bytes(bits: &HashMap) -> std::collections::BTreeMap, DescribedDevice>>> = Mutex::new(None); +/// Orders descriptor reads against the start of a control-panel session. +/// `describe_devices` holds it shared from the moment it decides it may open +/// a device until it has finished opening them; a new session takes it +/// exclusively while it registers itself. So a session waits for in-flight +/// descriptor reads, and a read that starts afterwards sees the session and +/// stays off the hardware, instead of the two opening the same interfaces at +/// once (which Windows answers with `Access is denied`). +static SESSION_GATE: RwLock<()> = RwLock::new(()); + +/// Forgets every cached description. A mouse that slept through a suspend +/// comes back with new paths, and a description taken before it is not +/// worth trusting. +fn forget_described() { + *DESCRIBED.lock().unwrap_or_else(PoisonError::into_inner) = None; +} + /// Every device on the bus that one of `filters` matches, described for the /// native helper. Only matching collections' devices are opened, and only to /// read their report descriptors; security keys and Logitech receiver child @@ -1583,6 +1608,7 @@ static DESCRIBED: Mutex, DescribedDevice>>> = Mutex::new( /// not been described yet is listed from enumeration alone (usage pages, no /// reports) and described properly once the session ends. pub(crate) fn describe_devices(filters: &[HidFilter]) -> Result, String> { + let _gate = SESSION_GATE.read().unwrap_or_else(PoisonError::into_inner); let api = new_api().map_err(|error| error.to_string())?; let blocked = security_key_paths(&api); let mut wanted = HashSet::new(); @@ -1617,7 +1643,10 @@ pub(crate) fn describe_devices(filters: &[HidFilter]) -> Result device.clone(), None => { let device = describe_group(&api, &group, &infos, may_open); - if may_open { + // Only a description whose descriptors were really read is + // remembered; one that fell back to enumeration (a mouse that + // was asleep, a path that was busy) is retried on the next scan. + if device.complete { cache.insert(group, device.clone()); } device @@ -1641,12 +1670,16 @@ fn describe_group( let mut seen = HashSet::new(); let mut collections = Vec::new(); let mut paths = Vec::new(); + let mut complete = open; for info in infos { let path = info.path().to_owned(); if !seen.insert(path.clone()) { continue; } - let (path_collections, layout) = inspect_path(api, &path, infos, read_descriptor); + let (path_collections, layout, parsed) = inspect_path(api, &path, infos, read_descriptor); + // A descriptor that was meant to be read and was not leaves the + // description incomplete, whatever the session state was. + complete &= parsed || !read_descriptor; collections.extend(path_collections.iter().cloned()); paths.push(DescribedPath { path: path.to_string_lossy().into_owned(), @@ -1672,7 +1705,7 @@ fn describe_group( .find_map(|info| info.serial_number().filter(|serial| !serial.is_empty())) .unwrap_or_default() .to_owned(), - complete: open, + complete, } } @@ -1867,7 +1900,7 @@ static RESUME_WATCH: Once = Once::new(); /// A thread that sleeps in short steps can only wake late if the whole machine /// was suspended, so a wall-clock jump well past the step means a resume. This /// works the same on every platform without a hidden window or suspend hook. -fn start_resume_watch() { +pub(crate) fn start_resume_watch() { RESUME_WATCH.call_once(|| { let spawned = thread::Builder::new() .name("openmouse-resume-watch".into()) @@ -1881,6 +1914,7 @@ fn start_resume_watch() { .is_ok_and(|gap| gap >= RESUME_GAP_THRESHOLD) { tracing::info!("System resume detected; HID handles will be reopened"); + forget_described(); RESUME_GENERATION.fetch_add(1, Ordering::AcqRel); } last = now; @@ -1892,6 +1926,12 @@ fn start_resume_watch() { }); } +/// Counts the resumes seen so far, for background work that has no session +/// of its own to carry the news. +pub(crate) fn resume_generation() -> u64 { + RESUME_GENERATION.load(Ordering::Acquire) +} + /// Whether the control panel currently has a HID websocket open. Bridge treats /// that as a connected client, and background device reads stay off the /// hardware meanwhile so they never interleave with the panel's traffic. @@ -1903,7 +1943,13 @@ struct ActiveSessionGuard; impl ActiveSessionGuard { fn new() -> Self { + // `device_access` covers native reads and writes; the gate covers + // descriptor reads. Both are released once the count is final, which + // is all a later reader needs to see before it stays away. Holding + // either for the whole session would stall every native call that + // should simply report the panel as the owner. let _access = crate::drivers::device_access(); + let _gate = SESSION_GATE.write().unwrap_or_else(PoisonError::into_inner); ACTIVE_SESSIONS.fetch_add(1, Ordering::AcqRel); Self } @@ -2063,6 +2109,40 @@ impl DescribedDevice { #[cfg(test)] mod tests { + #[test] + fn a_new_session_waits_for_an_in_flight_descriptor_read() { + use std::sync::atomic::AtomicBool; + let _serial = crate::drivers::TEST_NATIVE + .lock() + .unwrap_or_else(|e| e.into_inner()); + let read = super::SESSION_GATE.read().unwrap(); + let started = std::sync::Arc::new(AtomicBool::new(false)); + let registered = std::sync::Arc::new(AtomicBool::new(false)); + let session = { + let (started, registered) = (started.clone(), registered.clone()); + std::thread::spawn(move || { + started.store(true, super::Ordering::Release); + let guard = super::ActiveSessionGuard::new(); + registered.store(true, super::Ordering::Release); + guard + }) + }; + while !started.load(super::Ordering::Acquire) { + std::thread::yield_now(); + } + std::thread::sleep(std::time::Duration::from_millis(150)); + // The read is still in flight, so the session has not registered and + // a reader that checks now would still be allowed to open. + assert!(!registered.load(super::Ordering::Acquire)); + assert!(!super::client_session_active()); + drop(read); + let guard = session.join().unwrap(); + assert!(registered.load(super::Ordering::Acquire)); + assert!(super::client_session_active()); + drop(guard); + assert!(!super::client_session_active()); + } + #[test] fn a_filter_matches_a_device_by_product_and_any_collection_usage() { use super::{DescribedDevice, HidFilter}; diff --git a/src/service.rs b/src/service.rs index 0b0716b1..a526a7c9 100644 --- a/src/service.rs +++ b/src/service.rs @@ -108,6 +108,10 @@ const BATTERY_POLL_INTERVAL: Duration = Duration::from_secs(5 * 60); /// How often the HID bus is listed to see which mice are plugged in. One scan /// is about 5 ms and opens no device, so this costs well under 0.1% of a core. +/// How long one battery poll may run before it is abandoned. A poll covers +/// every remembered mouse at up to the helper's own timeout each, so this is +/// well past any healthy poll. +const BATTERY_POLL_TIMEOUT: Duration = BATTERY_POLL_INTERVAL; const DEVICE_SCAN_INTERVAL: Duration = Duration::from_secs(5); /// How often an asleep mouse is read again, so it shows as connected soon @@ -1540,6 +1544,9 @@ impl BridgeService { /// low-battery notification. Polling pauses while the control panel holds /// a HID session, so Bridge never talks to a mouse mid-session. pub fn start_battery_monitor(&self) { + // The resume watch used to start with the first panel session, so a + // Bridge nobody had opened the panel on never noticed it had slept. + crate::hid::start_resume_watch(); let service = self.clone(); tokio::spawn(async move { let mut interval = tokio::time::interval(BATTERY_POLL_INTERVAL); @@ -1562,8 +1569,13 @@ impl BridgeService { interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); let mut previous: Option> = None; let mut last_recheck = Instant::now(); + let mut resume_seen = crate::hid::resume_generation(); loop { interval.tick().await; + // After a suspend the mice re-enumerate and their readings + // are stale, so read again instead of waiting for the timer. + let resume_generation = crate::hid::resume_generation(); + let resumed = resume_generation != resume_seen; let detected = tokio::task::spawn_blocking(drivers::detect_mice) .await .unwrap_or_default(); @@ -1594,7 +1606,8 @@ impl BridgeService { if service.battery_polling.load(Ordering::Acquire) { continue; } - if scan_wants_read(previous.as_ref(), &ids, have_reading) || recheck { + if scan_wants_read(previous.as_ref(), &ids, have_reading) || recheck || resumed { + resume_seen = resume_generation; last_recheck = Instant::now(); tokio::spawn(poll_batteries(service.clone())); } @@ -1993,18 +2006,91 @@ impl Drop for PollGuard { /// One battery poll at a time: a scan-triggered poll skips when the timed one /// is already running, and the reverse. async fn poll_batteries(service: BridgeService) { - if service.battery_polling.swap(true, Ordering::AcqRel) { + let flag = Arc::clone(&service.battery_polling); + run_one_poll(&flag, BATTERY_POLL_TIMEOUT, poll_batteries_once(service)).await; +} + +/// Runs `poll` unless one is already running, for at most `limit`. A read +/// that never returns would otherwise leave the flag set for the life of the +/// process and every later poll would skip silently. Dropping the poll here +/// clears the flag through the guard, so the next one runs. +async fn run_one_poll( + flag: &Arc, + limit: Duration, + poll: impl std::future::Future, +) { + if flag.swap(true, Ordering::AcqRel) { return; } - let _guard = PollGuard(Arc::clone(&service.battery_polling)); - poll_batteries_once(service).await; + let _guard = PollGuard(Arc::clone(flag)); + if !finishes_within(limit, poll).await { + tracing::warn!( + timeout_secs = limit.as_secs(), + "The battery poll did not finish in time and was abandoned" + ); + } +} + +/// Runs `poll` for at most `limit`; false when it was abandoned. +async fn finishes_within(limit: Duration, poll: impl std::future::Future) -> bool { + tokio::time::timeout(limit, poll).await.is_ok() } async fn poll_batteries_once(service: BridgeService) { + let started = Instant::now(); + let mut recorded = 0usize; + let mut failed = 0usize; + poll_devices(&service, &mut recorded, &mut failed).await; + tracing::info!( + recorded, + failed, + elapsed_ms = started.elapsed().as_millis() as u64, + "Battery poll finished" + ); +} + +/// The blocking worker of a battery poll's discovery, and of its reads. A poll +/// that times out is dropped, but its worker keeps running on the blocking +/// pool; admitting another before it returns would add a thread per poll for +/// as long as a native call stays stuck. +static DISCOVERY_WORKER: AtomicBool = AtomicBool::new(false); +static STATUS_WORKER: AtomicBool = AtomicBool::new(false); + +/// Clears its slot when the blocking worker exits, by return or by panic. +struct WorkerSlot(&'static AtomicBool); + +impl Drop for WorkerSlot { + fn drop(&mut self) { + self.0.store(false, Ordering::Release); + } +} + +/// `spawn_blocking(work)` unless the previous worker for `slot` is still +/// running. The slot is released when the worker finishes, not when whoever +/// awaited it gave up, so a stuck native call holds at most one thread. +fn spawn_exclusive( + slot: &'static AtomicBool, + work: impl FnOnce() -> T + Send + 'static, +) -> Option> { + if slot.swap(true, Ordering::AcqRel) { + return None; + } + let held = WorkerSlot(slot); + Some(tokio::task::spawn_blocking(move || { + let _held = held; + work() + })) +} + +async fn poll_devices(service: &BridgeService, recorded: &mut usize, failed: &mut usize) { + let service = service.clone(); let profiled = profile_devices(&service.inner.read().await.config); - let discovered = tokio::task::spawn_blocking(drivers::detect_mice) - .await - .unwrap_or_default(); + let Some(discovery) = spawn_exclusive(&DISCOVERY_WORKER, drivers::detect_mice) else { + tracing::warn!("A previous device discovery is still running; skipping this battery poll"); + *failed += 1; + return; + }; + let discovered = discovery.await.unwrap_or_default(); let devices = merge_detected_mice(profiled, &discovered); { // Pruning the live readings is in-memory only, so it runs even while @@ -2018,7 +2104,13 @@ async fn poll_batteries_once(service: BridgeService) { } for (device_id, device_name) in devices { let id = device_id.clone(); - let outcome = tokio::task::spawn_blocking(move || crate::drivers::read_status(&id)).await; + let Some(read) = spawn_exclusive(&STATUS_WORKER, move || crate::drivers::read_status(&id)) + else { + tracing::warn!(%device_id, "A previous battery read is still running; skipping the rest of this poll"); + *failed += 1; + break; + }; + let outcome = read.await; match outcome { Ok(Ok(Some(status))) => { // The web panel reports batteries as `:` (the @@ -2055,6 +2147,8 @@ async fn poll_batteries_once(service: BridgeService) { }; if let Err(error) = service.record_battery(reading).await { tracing::warn!(%error, "Could not record the mouse battery"); + } else { + *recorded += 1; } } Ok(Ok(None)) => { @@ -2068,6 +2162,7 @@ async fn poll_batteries_once(service: BridgeService) { .downcast_ref::() .is_some_and(|error| error.kind() == std::io::ErrorKind::WouldBlock); if !deferred { + *failed += 1; let through = read_through(&device_id, &discovered); mark_unanswered(&service, &device_id, through.as_deref()).await; } @@ -2306,6 +2401,71 @@ mod tests { assert_eq!(snapshot.pending_native_restores, 0); } + #[tokio::test] + async fn a_second_worker_is_refused_until_the_first_one_exits() { + static SLOT: AtomicBool = AtomicBool::new(false); + let (release, hold) = std::sync::mpsc::channel::<()>(); + let first = spawn_exclusive(&SLOT, move || { + let _ = hold.recv(); + 1 + }) + .expect("the slot starts free"); + // Whoever awaited the first worker may give up; the worker still runs. + assert!(spawn_exclusive(&SLOT, || 2).is_none()); + release.send(()).unwrap(); + assert_eq!(first.await.unwrap(), 1); + assert!(!SLOT.load(Ordering::Acquire)); + assert_eq!(spawn_exclusive(&SLOT, || 3).unwrap().await.unwrap(), 3); + } + + #[tokio::test] + async fn a_panicking_worker_still_frees_its_slot() { + static SLOT: AtomicBool = AtomicBool::new(false); + let worker = spawn_exclusive(&SLOT, || -> u8 { panic!("native call failed") }).unwrap(); + assert!(worker.await.is_err()); + assert!(!SLOT.load(Ordering::Acquire)); + } + + #[tokio::test] + async fn a_poll_that_never_returns_is_abandoned_and_the_next_poll_runs() { + let flag = Arc::new(AtomicBool::new(false)); + let limit = Duration::from_millis(50); + run_one_poll(&flag, limit, std::future::pending()).await; + assert!( + !flag.load(Ordering::Acquire), + "an abandoned poll must clear the flag" + ); + + let ran = Arc::new(AtomicBool::new(false)); + let marker = Arc::clone(&ran); + run_one_poll(&flag, limit, async move { + marker.store(true, Ordering::Release); + }) + .await; + assert!(ran.load(Ordering::Acquire), "the next poll must run"); + assert!(!flag.load(Ordering::Acquire)); + } + + #[tokio::test] + async fn a_poll_is_skipped_while_another_is_running() { + let flag = Arc::new(AtomicBool::new(true)); + let ran = Arc::new(AtomicBool::new(false)); + let marker = Arc::clone(&ran); + run_one_poll(&flag, Duration::from_millis(50), async move { + marker.store(true, Ordering::Release); + }) + .await; + assert!(!ran.load(Ordering::Acquire)); + // The running poll's flag is not the skipped poll's to clear. + assert!(flag.load(Ordering::Acquire)); + } + + #[tokio::test] + async fn a_poll_inside_the_limit_reports_that_it_finished() { + assert!(finishes_within(Duration::from_secs(5), async {}).await); + assert!(!finishes_within(Duration::from_millis(30), std::future::pending()).await); + } + #[tokio::test] async fn deferred_native_pass_keeps_the_last_real_outcome() { let bridge = service(BridgeConfig::default());