Repository navigation
windows: bound hub descriptor requests with a timeout - #1882
Conversation
Youw
left a comment
There was a problem hiding this comment.
Codex reviewed exact head e8c712d04508d236b2437d60c19c11df8ea376bc against master (c8da8731eca73d9bb96a95bcd945a18ccf2db477), including the history in #1127 and #1741, the affected-device reports in #1136 and #1163, and Microsoft's overlapped-I/O/cancellation contracts.
The underlying problem is real and worth fixing: one hub DeviceIoControl() can block enumeration while the device-list path is serialized. The Nacon report in #1136 identifies IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX; #1163 reports the same unplug-to-unblock behavior with an 8BitDo controller. The first implementation in #1127 stopped the infinite wait for testers, but also produced 15-20 second scans and stress/stress_mt failures. #1741 retained several correctness blockers: stack-owned OVERLAPPED and caller buffers outliving asynchronous CancelIoEx(), a shared/auto-reset event race, lost completion byte counts and errors, and an unbounded string-descriptor path.
This rewrite resolves those earlier lifetime and concurrency defects well:
- each request has a private manual-reset event and heap-owned
OVERLAPPEDplus METHOD_BUFFERED data; - timed-out state remains alive until terminal completion instead of being freed after merely requesting cancellation;
- completion byte counts and
GetLastError()are propagated correctly; - configuration and string-descriptor paths are covered; and
- root-hub queries remain synchronous, with a documented five-second rationale.
Two timeout-policy blockers remain in the inline findings. The five-second limit is currently per IOCTL rather than per bad device: it can multiply across configurations within one scan, and the historically implicated node-information failure is retried from scratch on every later device-list scan. If cancellation never reaches terminal state, those retries also accumulate orphan requests and event handles.
Runtime validation is still required after those paths are corrected. CI can compile the code but cannot prove that the affected hub driver returns ERROR_IO_PENDING, that the timeout actually fires, or that enumeration and later scans remain responsive. A current-head Nacon/8BitDo debug run should demonstrate the pending -> timeout/cancel path, successful return from enumeration, bounded subsequent scans, and stable orphan/handle counts.
Verification performed by Codex:
- all 57 current GitHub Actions check-runs passed;
- a full VS2022 v143 Debug/Win32 solution build passed with the project's
/W4 /WXsettings; - direct MinGW-w64 x86_64 and i686 compilation of the changed source passed without warnings in the new code; and
- AppVeyor's legacy MSVC/MinGW/Cygwin jobs were still queued at review time, so that remaining CI gate was not treated as evidence yet.
References: #1741 lifetime review, #1741 design review, CancelIoEx, and DeviceIoControl.
Generated by Codex (GPT-5).
|
I like this idea even though I may not be qualified to review the code changes. |
Youw
left a comment
There was a problem hiding this comment.
Codex (GPT-5.6 Sol) and Claude Code (Claude Fable 5) independently reviewed exact head 2591c3a56e7c356d6062586f0d8572e8aa69097f against the PR base, then cross-checked the results against the caller and core refcount paths.
The cross-check retained one actionable P2 blocker: the new backoff early return runs before init_device() takes ownership of the caller's retained parent_dev reference. A polling application can therefore add another parent reference on every scan during the backoff window and pin the parent hub/device after disconnect. The inline finding includes the minimal fix.
The three existing review concerns are addressed by the current commits and can be resolved:
- Configuration probing stops at the first descriptor timeout, skips the V2 request on that handle, and does not multiply the timeout across all configurations.
- Repeated enumeration is throttled per device for 30 seconds, satisfying the requested skip-or-throttle behavior instead of paying the timeout on every scan.
- Root-hub handles are opened for overlapped I/O, all relevant root-hub IOCTLs use the bounded helper, timeout exits stop the port loops, and the rationale now names the historically implicated IOCTL accurately.
Fable 5 also raised two low-severity hypotheses that the combined cross-check did not retain as findings. Hub-wide throttling is not justified without hardware evidence because the IOCTL targets a specific child port and a hub-wide backoff could hide healthy siblings. The string path cannot pay two timeout waits in one call: failure of the language-ID request returns immediately before the requested-string IOCTL. Those behaviors remain suitable targets for the affected-device runtime test rather than code-review blockers.
Static verification covered the full diff, helper lifetime/cancellation, all hub-handle call sites, initialization and enumeration ownership, backend init/exit lifetime, and git diff --check. Current GitHub Actions checks and the PR AppVeyor status pass; the separate AppVeyor branch status remains failed. Hardware validation with a wedged Nacon/8BitDo-class device is still required to observe pending -> timeout/cancel behavior, bounded later scans, sibling-port behavior, and stable orphan/handle counts.
Related to #1127, #1136, #1163, and #1741.
Generated by Codex (GPT-5.6 Sol), assisted by Claude Code (Claude Fable 5).
|
I do not have the right device to trigger the issue mentioned in PR #1741. But at least there is no issue. |
2591c3a to
3cf9bac
Compare
Youw
left a comment
There was a problem hiding this comment.
Codex reviewed current head 3cf9bac against base 6bb9740 and cross-checked the result against the complete existing conversation.
All four earlier inline findings are addressed and remain resolved. Two new issues are left inline: timed-out actual string descriptor requests are not throttled after the language ID is cached, and expired backoff entries for devices that never reappear are retained until backend exit.
All current CI checks pass and git diff --check is clean. Affected-device validation with a Nacon/8BitDo-class device is still outstanding; the available runtime report covers healthy devices only.
The PR description also needs an update: it still says root-hub queries remain synchronous, whereas the later commits correctly route root-hub IOCTLs through the overlapped timeout helper.
Generated by Codex (GPT-5.6 Sol).
hub_timeout_backoff_active() only removed an expired entry when the same device was queried again, so entries for timed-out devices that never reappear accumulated until the last backend exit. Prune every expired entry seen while traversing under the lock instead. Devices that are queried again keep the same 30-second window behavior. Reported by Codex review on GitHub PR #1882.
A timed-out string descriptor request returned LIBUSB_ERROR_IO without recording any cooldown. The core caches only successful lookups and config/interface strings reach the fetch helper directly, so every later lookup against a wedged control pipe stalled for the full request timeout again and could park another orphaned request. Record an expiry time in the device private data when a string request times out and skip string requests until it passes. The cooldown is per device object rather than the enumeration backoff on purpose: a device without strings can still be enumerable and usable, so it must not disappear from the device list. A recreated device object loses the cooldown and pays at most one extra timeout on its first string lookup. Failures other than timeouts stay retryable. The request error is now captured before CloseHandle(), which may clobber it. Reported by Codex review on GitHub PR #1882.
IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION issues a control transfer on the bus and the hub driver applies no timeout to it, so a device that stops responding on its control pipe hangs enumeration forever with the device list lock held (observed with the Nacon PS4 Compact Controller). Issue the hub IOCTLs used during enumeration and string descriptor reads asynchronously against heap-owned request state and give up after 5 seconds. Since CancelIoEx() is asynchronous and METHOD_BUFFERED completion writes into the output buffer and OVERLAPPED afterwards, a timed-out request is parked on an orphan list and only freed once the kernel has finished with it. Root hub queries are answered from hub driver state and never reach a device, so init_root_hub() is intentionally left synchronous. Assisted-by: claude-code:claude-fable-5
Both inline findings addressed on the newer commits. Strings: a timed-out request now arms a per-device-object cooldown (string_backoff_expiry) checked before opening the hub. Deliberately separate from the enumeration backoff, so string trouble never hides an otherwise enumerable device from the list. Please re-review |
|
@sonatique this PR is for To make this work you need either create a PR into |
3cf9bac to
a288bdb
Compare
|
@Youw :
Sorry: I pushed to the wrong repos. Corrected now, thanks. |
Youw
left a comment
There was a problem hiding this comment.
Codex reviewed exact head a288bdb against its merge base and current master, including the complete prior discussion and the newly included fixes.
The two July 29 findings are addressed and their review threads have been resolved:
- timed-out actual string descriptor requests now arm a per-device cooldown before later hub opens; and
- backoff lookup now prunes every expired entry it traverses.
One remaining P2 concurrency issue is left inline: the new 64-bit cooldown deadline is read and written without synchronization even though these public getters may run concurrently. That can tear on Win32 and can miss the throttle the field is meant to enforce.
Repository attribution also needs cleanup before merge. The eight commits after 90b7f99 lack the required Assisted-by trailer, and the PR body credits only Claude even though several commits explicitly implement Codex review findings. The appropriate trailers should be added; review-assisted commits should include Assisted-by: Codex:GPT-5.6 Sol, and the PR description should include the same Codex attribution.
Verification at this head:
- all current GitHub Actions and AppVeyor checks pass;
- a full VS2026/v145 Debug Win32 solution build passes; and
- git diff --check is clean.
Affected-device runtime validation with a wedged Nacon/8BitDo-class device remains the important residual test because CI cannot exercise the hub driver's pending -> timeout/cancel behavior.
Generated by Codex (GPT-5.6 Sol).
The Nacon report (libusb#1136) implicates IOCTL_USB_GET_NODE_CONNECTION_ INFORMATION_EX, not the descriptor request: connection-info queries can also block when a device on the queried port wedges the hub driver. Correct the timeout rationale accordingly, and drop the assumption that root hub queries never reach a device: bound init_root_hub()'s node and per-port queries with the same helper, since a wedged device attached directly to a root hub port exposes the exact same hang. Once one request on a root hub handle has timed out, further requests would most likely each pay the full timeout as well, so the speed query loops give up on the first timeout and fall back to the pessimistic default instead of probing the remaining ports. A timeout on the initial node information query is reported as LIBUSB_ERROR_TIMEOUT so that the caller can tell it apart from an access failure. Assisted-by: claude-code:claude-fable-5
bNumConfigurations is device-supplied and not sanitized until usbi_sanitize_device() runs after descriptor caching, so a wedged control pipe combined with a bogus configuration count of up to 255 could multiply the per-request timeout into a stall of many minutes for a single enumeration pass. Give up on the device at the first request timeout instead: once one descriptor request has timed out, every further request on that control pipe would most likely pay the full timeout as well. Ordinary per-descriptor failures keep the existing skip-and-continue behavior. cache_config_descriptors() now reports the abandonment via LIBUSB_ERROR_TIMEOUT so that init_device() can also skip the V2 speed query it would otherwise issue on the same handle.
A device whose initialization fails on a hub IOCTL timeout is left with priv->initialized unset, so every subsequent libusb_get_device_list() re-attempts the initialization and pays the full timeout again. For a polling application this turns one wedged device into a persistent multi-second stall on every scan, and if cancellation of the timed-out requests never reaches a terminal state, each retry can also park another orphaned request and event handle. Record a per-device backoff (keyed by device instance ID) when initialization fails on a timeout, and skip re-initialization until it expires, 30 seconds later. The backoff is deliberately not cleared on reconnection, since a replug cannot cheaply be told apart from a still-wedged device: a replugged healthy device may thus stay invisible for up to one backoff period, which is self-healing and much cheaper than stalling every scan. A successful initialization clears the device's entry.
The GEN_PASS enumeration caller hands its retained parent_dev reference to init_device(), which either transfers it to the device at dev->parent_dev = parent_dev or must release it. The backoff early exit introduced by the previous commit runs before that transfer and returned without releasing, so every device list scan during a backoff window leaked one reference to the parent hub, pinning it after disconnect.
The early failure returns in init_device() that run before ownership of the caller's retained parent_dev reference is transferred at dev->parent_dev = parent_dev have always leaked that reference: parent not a hub, first ancestor mismatch (which also leaked the ancestor reference itself), ancestor not found, and bus number not found. These paths are rare, which is why the leaks went unnoticed, but they follow from the same ownership contract as the backoff exit fixed by the previous commit.
a288bdb to
de056b1
Compare
hub_timeout_backoff_active() only removed an expired entry when the same device was queried again, so entries for timed-out devices that never reappear accumulated until the last backend exit. Prune every expired entry seen while traversing under the lock instead. Devices that are queried again keep the same 30-second window behavior. Reported by Codex review on GitHub PR libusb#1882.
A timed-out string descriptor request returned LIBUSB_ERROR_IO without recording any cooldown. The core caches only successful lookups and config/interface strings reach the fetch helper directly, so every later lookup against a wedged control pipe stalled for the full request timeout again and could park another orphaned request. Record an expiry time in the device private data when a string request times out and skip string requests until it passes. The cooldown is per device object rather than the enumeration backoff on purpose: a device without strings can still be enumerable and usable, so it must not disappear from the device list. A recreated device object loses the cooldown and pays at most one extra timeout on its first string lookup. Failures other than timeouts stay retryable. The request error is now captured before CloseHandle(), which may clobber it. Reported by Codex review on GitHub PR libusb#1882.
reap_orphaned_requests() logged while holding orphaned_requests_lock. The static mutex is a spinlock, so a contending thread spins for the duration of the logging I/O. Count freed requests inside the critical section and log once after releasing the lock.
The string getters may run concurrently for the same device and libusb promises thread safety, but the 64-bit cooldown deadline was read and written with plain accesses. Those can tear on 32-bit builds, so a reader could see a mixed value and miss an armed cooldown, which is exactly the retry the field is meant to prevent. Access the deadline with InterlockedCompareExchange64() and InterlockedExchange64(). Reported by Codex review on GitHub PR libusb#1882
|
@slouken any chance you could test this code? Thank you very much in advance. |
|
@Youw : I addressed your last comment. Please re-review at your convenience. |
Youw
left a comment
There was a problem hiding this comment.
Codex re-reviewed current tip de056b1af69b4c069767f89925e98ab6e2339fdd.
The previous plain-access race is addressed in intent, but one blocking Win32 correctness issue remains: the 64-bit interlocked operand is not 8-byte aligned in the actual backend-private layout. Details and concrete alternatives are in the inline finding.
All current checks are green, and a local VS 2026 Win32 Debug build passed; those compile checks do not exercise the runtime alignment precondition.
Generated by Codex (GPT-5.6 Sol).
|
@Youw : thanks again for this finding. Last commit addresses it. Please re-review, thanks you. |
|
I see last commit in this branch is 17 hours ago, are you shure you pushed to the right branch (or pushed at all)? |
usbi_get_device_priv() only guarantees pointer alignment for backend private data, so on Win32 the 64-bit cooldown deadline can sit at offset 4 mod 8 and the interlocked operations on it have a misaligned operand, which Microsoft documents as unpredictable. Replace it with a 32-bit GetTickCount() deadline accessed through 32-bit interlocked operations, which only need the 4-byte alignment the layout does guarantee. The comparison is wrap-safe, 0 means unarmed (a computed 0 is nudged to 1), and an expired deadline is cleared so it cannot come back to life when the tick counter wraps after 49.7 days. Reported by Codex review on GitHub PR libusb#1882.
Youw
left a comment
There was a problem hiding this comment.
Codex re-reviewed current tip 1b1bf122fe5b6af30120e831bce70c36a77ad386 after the merge from master.
The merge introduces no PR-specific Windows changes. The existing alignment finding remains actionable despite the follow-up saying it was fixed: libusb/os/windows_common.h still declares volatile LONG64 string_backoff_expiry, and windows_winusb.c still accesses it with InterlockedCompareExchange64() and InterlockedExchange64(). A direct comparison with the previously reviewed de056b1 shows both Windows files are unchanged. The proposed 32-bit GetTickCount() deadline and 32-bit interlocked operations are not present in the live branch.
Existing finding: #1882 (comment)
git diff --check is clean and a local VS 2026 Win32 Debug build passed at this tip. GitHub CI for the merge is still running.
Generated by Codex (GPT-5.6 Sol).
usbi_get_device_priv() only guarantees pointer alignment for backend private data, so on Win32 the 64-bit cooldown deadline can sit at offset 4 mod 8 and the interlocked operations on it have a misaligned operand, which Microsoft documents as unpredictable. Replace it with a 32-bit GetTickCount() deadline accessed through 32-bit interlocked operations, which only need the 4-byte alignment the layout does guarantee. The comparison is wrap-safe, 0 means unarmed (a computed 0 is nudged to 1), and an expired deadline is cleared so it cannot come back to life when the tick counter wraps after 49.7 days. Reported by Codex review on GitHub PR libusb#1882. Assisted-by: Codex:GPT-5.6 Sol
Youw
left a comment
There was a problem hiding this comment.
Codex re-reviewed current tip 113a20ec4f6cef59a268f90426366cd4563aac49 after cherry-picking saschazepter/libusb@24b077b.
No remaining code findings were found. The cooldown deadline now uses 32-bit interlocked operations on a properly aligned LONG; the signed-delta comparison is wrap-safe for the 30-second interval, zero is handled as the unarmed sentinel, and the conditional clear cannot overwrite a concurrently re-armed deadline. This addresses both the original unsynchronized-access finding and the subsequent 64-bit alignment finding.
The cherry-picked patch matches the source commit, git diff --check is clean, and local VS 2026 Win32 Debug and x64 Debug builds passed. GitHub CI triggered by this push is still running.
Generated by Codex (GPT-5.6 Sol).
hub_timeout_backoff_active() only removed an expired entry when the same device was queried again, so entries for timed-out devices that never reappear accumulated until the last backend exit. Prune every expired entry seen while traversing under the lock instead. Devices that are queried again keep the same 30-second window behavior. Reported by Codex review on GitHub PR #1882.
A timed-out string descriptor request returned LIBUSB_ERROR_IO without recording any cooldown. The core caches only successful lookups and config/interface strings reach the fetch helper directly, so every later lookup against a wedged control pipe stalled for the full request timeout again and could park another orphaned request. Record an expiry time in the device private data when a string request times out and skip string requests until it passes. The cooldown is per device object rather than the enumeration backoff on purpose: a device without strings can still be enumerable and usable, so it must not disappear from the device list. A recreated device object loses the cooldown and pays at most one extra timeout on its first string lookup. Failures other than timeouts stay retryable. The request error is now captured before CloseHandle(), which may clobber it. Reported by Codex review on GitHub PR #1882.
The string getters may run concurrently for the same device and libusb promises thread safety, but the 64-bit cooldown deadline was read and written with plain accesses. Those can tear on 32-bit builds, so a reader could see a mixed value and miss an armed cooldown, which is exactly the retry the field is meant to prevent. Access the deadline with InterlockedCompareExchange64() and InterlockedExchange64(). Reported by Codex review on GitHub PR #1882
While reviewing #1741, I thought that we could solve pending issues better by starting from scratch based on what we learned.
Since I had not enough time available to start yet another PR, I told my conclusions and ideas to Claude AI , directing him to write coherent code.
This is the result. I reviewed it myself carefully before posting and it seems to do the job, and it really worth being considered as an alternative to #1741, as long as it actually solves the issue obviously : @slouken could please quickly test whether this code solves your issue in a desirable way? Thank you very much in advance for you help.
IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION issues a control transfer on the bus and the hub driver applies no timeout to it, so a device that stops responding on its control pipe hangs enumeration forever with the device list lock held. The Nacon PS4 Compact Controller report (#1136) additionally shows connection-info queries blocking the same way.
Issue the hub IOCTLs used during enumeration and string descriptor reads asynchronously against heap-owned request state and give up after 5 seconds. Since CancelIoEx() is asynchronous and METHOD_BUFFERED completion writes into the output buffer and OVERLAPPED afterwards, a timed-out request is parked on an orphan list and only freed once the kernel has finished with it.
Root hub queries were originally left synchronous on the assumption that they never reach a device, but the Nacon report (#1136) implicates IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX, so init_root_hub()'s node and per-port queries now go through the same bounded helper, giving up on the port loops at the first timeout. Devices whose initialization times out are retried with a 30-second backoff instead of stalling every scan, and string descriptor requests get a per-device cooldown after a timeout.
Fixes: #1136
Replaces: #1741
Assisted-by: claude-code:claude-fable-5