From 9e07d77e6f54089a83283fd81948bfcfd8d78dd4 Mon Sep 17 00:00:00 2001 From: quaternion Date: Tue, 24 Nov 2026 00:35:40 -0500 Subject: [PATCH 1/2] fix(hle): serialize device callbacks across delivery threads Registration and poll threads both called deliver directly, so an initial enumeration callback and a hotplug could run at the same time; GameInput guarantees one callback at a time in order. Events now go through one queue in Hub state, with a single thread draining it; callbacks that enqueue more events join the same loop instead of nesting. Add a regression that holds a registration callback open while another thread polls and checks peak concurrency is one. --- crates/victory-hle/src/modules/gameinput.rs | 106 +++++++++++++++++++- 1 file changed, 102 insertions(+), 4 deletions(-) diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index a411bd0f4a..59b8814e32 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -325,6 +325,10 @@ struct State { pending: Vec, /// Device callbacks running now: token and thread. running: Vec<(u64, ThreadId)>, + /// Events waiting for the single delivery loop. + queue: VecDeque, + /// One thread drains `queue`; other producers only append. + delivering: bool, } pub struct Hub { @@ -369,6 +373,8 @@ impl Hub { callbacks: Vec::new(), pending: Vec::new(), running: Vec::new(), + queue: VecDeque::new(), + delivering: false, }), returned: Condvar::new(), })); @@ -410,12 +416,32 @@ impl Hub { self.deliver(events); } - /// Runs callbacks, never under our lock: they call back into us. One - /// unregistered since the event was taken does not run, and - /// `UnregisterCallback` waits for one that runs. + /// Runs callbacks one at a time, in the order they were queued, never + /// under our lock: they call back into us. A callback delivered from a + /// callback joins the same queue instead of nesting. One unregistered + /// since the event was queued does not run, and `UnregisterCallback` + /// waits for one that runs. fn deliver(&self, events: Vec) { + { + let mut state = self.state(); + state.queue.extend(events); + if state.delivering { + return; + } + state.delivering = true; + } let me = std::thread::current().id(); - for e in events { + loop { + let e = { + let mut state = self.state(); + match state.queue.pop_front() { + Some(e) => e, + None => { + state.delivering = false; + return; + } + } + }; let r = e.registration; { let mut state = self.state(); @@ -1586,6 +1612,78 @@ mod tests { leave.join().unwrap(); } + #[test] + fn callbacks_from_registration_and_poll_are_serialized() { + use std::sync::atomic::AtomicBool; + static ACTIVE: AtomicU32 = AtomicU32::new(0); + static PEAK: AtomicU32 = AtomicU32::new(0); + static CALLS: AtomicU32 = AtomicU32::new(0); + static RELEASE: AtomicBool = AtomicBool::new(false); + extern "system" fn tracked( + _: u64, + _: *mut c_void, + _: *const Device, + _: u64, + _: u32, + _: u32, + ) { + let active = ACTIVE.fetch_add(1, Ordering::SeqCst) + 1; + PEAK.fetch_max(active, Ordering::SeqCst); + CALLS.fetch_add(1, Ordering::SeqCst); + while !RELEASE.load(Ordering::SeqCst) { + std::thread::sleep(Duration::from_millis(1)); + } + ACTIVE.fetch_sub(1, Ordering::SeqCst); + } + let (hub, host) = fake(); + type Register = extern "system" fn( + This, + *const Device, + u32, + u32, + u32, + *mut c_void, + Option, + *mut u64, + ) -> HRESULT; + let register = slot::(&hub.object, 0x48); + ACTIVE.store(0, Ordering::SeqCst); + PEAK.store(0, Ordering::SeqCst); + CALLS.store(0, Ordering::SeqCst); + RELEASE.store(false, Ordering::SeqCst); + // Blocking enumeration delivers its first callback on the registering + // thread, which stays inside it while the poll thread runs. + let registrar = std::thread::spawn(move || { + let mut token = 0; + register( + &hub.object, + std::ptr::null(), + GAMEPAD_KIND, + 1, + 2, + std::ptr::null_mut(), + Some(tracked), + &mut token, + ) + }); + let deadline = Instant::now() + Duration::from_secs(2); + while ACTIVE.load(Ordering::SeqCst) == 0 && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(1)); + } + assert_ne!(ACTIVE.load(Ordering::SeqCst), 0, "registration delivered a callback"); + let poller = std::thread::spawn(move || { + host.lock().unwrap().pads[1] = Some(PadState::default()); + hub.poll(); + }); + std::thread::sleep(Duration::from_millis(50)); + assert_eq!(ACTIVE.load(Ordering::SeqCst), 1, "only one callback runs"); + RELEASE.store(true, Ordering::SeqCst); + assert_eq!(registrar.join().unwrap(), S_OK); + poller.join().unwrap(); + assert_eq!(PEAK.load(Ordering::SeqCst), 1); + assert!(CALLS.load(Ordering::SeqCst) >= 2, "initial and hotplug both ran"); + } + #[test] fn devices_are_found_by_id_and_rumble_reaches_the_host() { let (hub, host) = fake(); From 7da55befe68142103d81110c5eaab47a8f4d6b43 Mon Sep 17 00:00:00 2001 From: quaternion Date: Tue, 24 Nov 2026 09:09:35 -0500 Subject: [PATCH 2/2] fix(hle): preserve blocking GameInput enumeration Run blocking enumeration on the caller when another delivery is active. Hold hotplug events for that registration until enumeration ends, and track inline callbacks for unregistration. --- crates/victory-hle/src/modules/gameinput.rs | 367 +++++++++++++------- 1 file changed, 247 insertions(+), 120 deletions(-) diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index 59b8814e32..477f402076 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -311,6 +311,11 @@ struct Event { previous: u32, } +struct Enumeration { + registration: Registration, + hotplug: Vec, +} + #[derive(Default)] struct Slot { connected: bool, @@ -321,13 +326,16 @@ struct Slot { struct State { slots: [Slot; DEVICES], callbacks: Vec, + /// Blocking enumerations running outside the queue. Polls record their + /// hotplug events here but cannot deliver them until enumeration ends. + enumerating: Vec, /// Asynchronous enumerations, delivered by the next poll. pending: Vec, /// Device callbacks running now: token and thread. running: Vec<(u64, ThreadId)>, /// Events waiting for the single delivery loop. queue: VecDeque, - /// One thread drains `queue`; other producers only append. + /// One thread drains `queue`; other producers only append to it. delivering: bool, } @@ -371,6 +379,7 @@ impl Hub { state: Mutex::new(State { slots: Default::default(), callbacks: Vec::new(), + enumerating: Vec::new(), pending: Vec::new(), running: Vec::new(), queue: VecDeque::new(), @@ -405,32 +414,26 @@ impl Hub { lock(&self.state) } - /// Reads the host once; device callbacks run on the calling thread. + /// Reads the host once and queues its device callbacks. fn poll(&self) { let (pads, keys) = { let mut source = lock(&self.source); let pads: [_; PADS] = std::array::from_fn(|slot| source.pad(slot)); (pads, source.keys()) }; - let events = self.state().poll(&self.devices, pads, keys); - self.deliver(events); - } - - /// Runs callbacks one at a time, in the order they were queued, never - /// under our lock: they call back into us. A callback delivered from a - /// callback joins the same queue instead of nesting. One unregistered - /// since the event was queued does not run, and `UnregisterCallback` - /// waits for one that runs. - fn deliver(&self, events: Vec) { - { + let drain = { let mut state = self.state(); + let events = state.poll(&self.devices, pads, keys); state.queue.extend(events); - if state.delivering { - return; - } - state.delivering = true; + state.claim_delivery() + }; + if drain { + self.drain(); } - let me = std::thread::current().id(); + } + + /// The owner of the delivery turn runs queued callbacks in order. + fn drain(&self) { loop { let e = { let mut state = self.state(); @@ -442,28 +445,40 @@ impl Hub { } } }; - let r = e.registration; - { - let mut state = self.state(); - if !state.callbacks.iter().any(|c| c.token == r.token) { - continue; - } - state.running.push((r.token, me)); - } - (r.callback)( - r.token, - r.context as *mut c_void, - &self.devices[e.device], - e.timestamp, - e.current, - e.previous, - ); + self.invoke(e); + } + } + + /// Call without the state lock, but check and mark the callback running + /// under the same lock so unregistration cannot race with its start. + fn invoke(&self, e: Event) { + let r = e.registration; + let me = std::thread::current().id(); + { let mut state = self.state(); - if let Some(i) = state.running.iter().position(|&x| x == (r.token, me)) { - state.running.swap_remove(i); + if !state.callbacks.iter().any(|c| c.token == r.token) + && !state + .enumerating + .iter() + .any(|c| c.registration.token == r.token) + { + return; } - self.returned.notify_all(); + state.running.push((r.token, me)); } + (r.callback)( + r.token, + r.context as *mut c_void, + &self.devices[e.device], + e.timestamp, + e.current, + e.previous, + ); + let mut state = self.state(); + if let Some(i) = state.running.iter().position(|&x| x == (r.token, me)) { + state.running.swap_remove(i); + } + self.returned.notify_all(); } fn index(&self, device: *const Device) -> Option { @@ -472,6 +487,15 @@ impl Hub { } impl State { + /// Claim the turn while still holding the lock used to queue the events. + fn claim_delivery(&mut self) -> bool { + if self.delivering || self.queue.is_empty() { + return false; + } + self.delivering = true; + true + } + fn poll( &mut self, devices: &[Device; DEVICES], @@ -526,12 +550,14 @@ impl State { } else { (STATUS_CONNECTED, 0) }; - events.extend( - self.callbacks - .iter() - .filter(|r| r.matches(devices, index) && r.status & STATUS_CONNECTED != 0) - .map(|r| r.event(index, now, current, previous)), - ); + let event = |r: &Registration| { + (r.matches(devices, index) && r.status & STATUS_CONNECTED != 0) + .then(|| r.event(index, now, current, previous)) + }; + events.extend(self.callbacks.iter().filter_map(event)); + for enumeration in &mut self.enumerating { + enumeration.hotplug.extend(event(&enumeration.registration)); + } } } } @@ -779,32 +805,65 @@ extern "system" fn register_device( context: context as usize, callback, }; - let mut found = Vec::new(); - { + let (inline, mut drain) = { let mut state = hub.state(); - if enumeration != 0 && status & STATUS_CONNECTED != 0 { + let found: Vec<_> = if enumeration != 0 && status & STATUS_CONNECTED != 0 { let now = now(); - found = (0..DEVICES) + (0..DEVICES) .filter(|&i| state.slots[i].connected && registration.matches(&hub.devices, i)) .map(|i| registration.event(i, now, STATUS_CONNECTED, 0)) - .collect(); - } + .collect() + } else { + Vec::new() + }; tracing::info!( kind = format_args!("{kind:#x}"), enumeration, devices = found.len(), "input device callback" ); - state.callbacks.push(registration); - if enumeration == ASYNC_ENUMERATION { - state.pending.append(&mut found); + if !out.is_null() { + // SAFETY: checked non-null. Publish the token before any callback can run. + unsafe { out.write(registration.token) }; + } + if enumeration != ASYNC_ENUMERATION && !found.is_empty() && state.delivering { + // The current deliverer can be waiting on a lock held by this caller. + // Enumerate inline and hold back this registration's hotplug events. + state.enumerating.push(Enumeration { + registration, + hotplug: Vec::new(), + }); + (found, false) + } else { + state.callbacks.push(registration); + if enumeration == ASYNC_ENUMERATION { + state.pending.extend(found); + } else { + state.queue.extend(found); + } + (Vec::new(), state.claim_delivery()) + } + }; + if !inline.is_empty() { + for event in inline { + hub.invoke(event); + } + let mut state = hub.state(); + // The callback can stop itself, so only publish a registration that remains active. + if let Some(i) = state + .enumerating + .iter() + .position(|c| c.registration.token == registration.token) + { + let enumeration = state.enumerating.remove(i); + state.callbacks.push(enumeration.registration); + state.queue.extend(enumeration.hotplug); + drain = state.claim_delivery(); } } - if !out.is_null() { - // SAFETY: checked non-null. - unsafe { out.write(registration.token) }; + if drain { + hub.drain(); } - hub.deliver(found); S_OK } /// Guide button and keyboard layout callbacks: neither ever changes here. @@ -821,6 +880,7 @@ extern "system" fn register_other( fn forget(this: This, token: u64) { let mut state = hub(this).state(); state.callbacks.retain(|r| r.token != token); + state.enumerating.retain(|c| c.registration.token != token); state.pending.retain(|e| e.registration.token != token); } extern "system" fn stop_callback(this: This, token: u64) { @@ -1380,6 +1440,60 @@ mod tests { token } + const CALLBACK_WAIT: Duration = Duration::from_secs(5); + + fn register_observer(hub: &Hub, enumeration: u32, observer: &C) { + extern "system" fn observe( + _: u64, + context: *mut c_void, + device: *const Device, + _: u64, + current: u32, + _: u32, + ) { + // SAFETY: the test keeps the observer alive until all polls finish. + let (observer, index) = unsafe { (&*context.cast::(), (*device).index) }; + observer(index, current); + } + assert_eq!( + register_device( + &hub.object, + std::ptr::null(), + GAMEPAD_KIND, + STATUS_CONNECTED, + enumeration, + (observer as *const C).cast_mut().cast(), + Some(observe::), + std::ptr::null_mut(), + ), + S_OK + ); + } + + fn with_active_poll(test: impl FnOnce(&'static Hub, &Mutex)) { + use std::sync::mpsc::channel; + + let (hub, host) = fake(); + let (entered, inside) = channel(); + let (release, wait) = channel(); + let wait = Mutex::new(wait); + let slow = |index, current| { + if index == 0 && current == STATUS_CONNECTED { + let _ = entered.send(()); + let _ = wait.lock().unwrap().recv_timeout(2 * CALLBACK_WAIT); + } + }; + register_observer(hub, 0, &slow); + host.lock().unwrap().pads[0] = Some(PadState::default()); + std::thread::scope(|scope| { + let release = release; + scope.spawn(move || hub.poll()); + inside.recv_timeout(CALLBACK_WAIT).unwrap(); + test(hub, &host); + release.send(()).unwrap(); + }); + } + fn result(hr: HRESULT, out: *const c_void) -> Result<*const Reading, HRESULT> { if hr == S_OK { Ok(out.cast()) @@ -1614,74 +1728,87 @@ mod tests { #[test] fn callbacks_from_registration_and_poll_are_serialized() { - use std::sync::atomic::AtomicBool; - static ACTIVE: AtomicU32 = AtomicU32::new(0); - static PEAK: AtomicU32 = AtomicU32::new(0); - static CALLS: AtomicU32 = AtomicU32::new(0); - static RELEASE: AtomicBool = AtomicBool::new(false); - extern "system" fn tracked( - _: u64, - _: *mut c_void, - _: *const Device, - _: u64, - _: u32, - _: u32, - ) { - let active = ACTIVE.fetch_add(1, Ordering::SeqCst) + 1; - PEAK.fetch_max(active, Ordering::SeqCst); - CALLS.fetch_add(1, Ordering::SeqCst); - while !RELEASE.load(Ordering::SeqCst) { - std::thread::sleep(Duration::from_millis(1)); - } - ACTIVE.fetch_sub(1, Ordering::SeqCst); - } + use std::sync::mpsc::channel; + let (hub, host) = fake(); - type Register = extern "system" fn( - This, - *const Device, - u32, - u32, - u32, - *mut c_void, - Option, - *mut u64, - ) -> HRESULT; - let register = slot::(&hub.object, 0x48); - ACTIVE.store(0, Ordering::SeqCst); - PEAK.store(0, Ordering::SeqCst); - CALLS.store(0, Ordering::SeqCst); - RELEASE.store(false, Ordering::SeqCst); - // Blocking enumeration delivers its first callback on the registering - // thread, which stays inside it while the poll thread runs. - let registrar = std::thread::spawn(move || { - let mut token = 0; - register( - &hub.object, - std::ptr::null(), - GAMEPAD_KIND, - 1, - 2, - std::ptr::null_mut(), - Some(tracked), - &mut token, - ) - }); - let deadline = Instant::now() + Duration::from_secs(2); - while ACTIVE.load(Ordering::SeqCst) == 0 && Instant::now() < deadline { - std::thread::sleep(Duration::from_millis(1)); - } - assert_ne!(ACTIVE.load(Ordering::SeqCst), 0, "registration delivered a callback"); - let poller = std::thread::spawn(move || { + let (entered, inside) = channel(); + let (release, wait) = channel(); + let wait = Mutex::new(wait); + let log = Mutex::new(Vec::new()); + let observe = |index, current| { + log.lock().unwrap().push((index, current)); + if index == FALLBACK && current == STATUS_CONNECTED { + let _ = entered.send(()); + let _ = wait.lock().unwrap().recv_timeout(CALLBACK_WAIT); + } + }; + std::thread::scope(|scope| { + let release = release; + scope.spawn(|| register_observer(hub, 2, &observe)); + inside.recv_timeout(CALLBACK_WAIT).unwrap(); host.lock().unwrap().pads[1] = Some(PadState::default()); hub.poll(); + assert_eq!(*log.lock().unwrap(), [(FALLBACK, STATUS_CONNECTED)]); + release.send(()).unwrap(); }); - std::thread::sleep(Duration::from_millis(50)); - assert_eq!(ACTIVE.load(Ordering::SeqCst), 1, "only one callback runs"); - RELEASE.store(true, Ordering::SeqCst); - assert_eq!(registrar.join().unwrap(), S_OK); - poller.join().unwrap(); - assert_eq!(PEAK.load(Ordering::SeqCst), 1); - assert!(CALLS.load(Ordering::SeqCst) >= 2, "initial and hotplug both ran"); + assert_eq!( + *log.lock().unwrap(), + [(FALLBACK, STATUS_CONNECTED), (1, STATUS_CONNECTED), (FALLBACK, 0)] + ); + } + + #[test] + fn blocking_enumeration_finishes_on_registering_thread_while_poll_delivers() { + use std::sync::mpsc::channel; + + let finished = Mutex::new(None); + let observe = |_, _| *finished.lock().unwrap() = Some(std::thread::current().id()); + with_active_poll(|hub, _| { + let (returned, result) = channel(); + std::thread::scope(|scope| { + let observe = &observe; + let finished = &finished; + scope.spawn(move || { + register_observer(hub, 2, observe); + let _ = returned.send((std::thread::current().id(), *finished.lock().unwrap())); + }); + let (caller, callback) = result.recv_timeout(CALLBACK_WAIT).unwrap(); + assert_eq!(callback, Some(caller), "callback must finish before return"); + }); + }); + } + + #[test] + fn blocking_enumeration_reports_devices_connected_during_its_callback() { + use std::sync::mpsc::channel; + + let (entered, inside) = channel(); + let (release, wait) = channel(); + let wait = Mutex::new(wait); + let log = Mutex::new(Vec::new()); + let observe = |index, current| { + log.lock().unwrap().push((index, current)); + if index == 0 { + let _ = entered.send(()); + let _ = wait.lock().unwrap().recv_timeout(CALLBACK_WAIT); + } + }; + with_active_poll(|hub, host| { + std::thread::scope(|scope| { + let observe = &observe; + let release = release; + scope.spawn(move || register_observer(hub, 2, observe)); + inside.recv_timeout(CALLBACK_WAIT).unwrap(); + host.lock().unwrap().pads[1] = Some(PadState::default()); + hub.poll(); + assert_eq!(*log.lock().unwrap(), [(0, STATUS_CONNECTED)]); + release.send(()).unwrap(); + }); + }); + assert_eq!( + *log.lock().unwrap(), + [(0, STATUS_CONNECTED), (1, STATUS_CONNECTED)] + ); } #[test]