Skip to content

windows: bound hub descriptor requests with a timeout - #1882

Merged
sonatique merged 12 commits into
libusb:masterfrom
sonatique:windows-hub-ioctl-timeout
Aug 4, 2026
Merged

sonatique merged 12 commits into
libusb:masterfrom
sonatique:windows-hub-ioctl-timeout

Conversation

@sonatique

@sonatique sonatique commented Jul 16, 2026 •

Copy link
Copy Markdown
Member

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

@sonatique
sonatique requested review from Youw and mcuee July 16, 2026 15:05

@Youw Youw left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 OVERLAPPED plus 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 /WX settings;
  • 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).

Comment thread libusb/os/windows_winusb.c Resolved
Comment thread libusb/os/windows_winusb.c Resolved
Comment thread libusb/os/windows_winusb.c Resolved
@sonatique

Copy link
Copy Markdown
Member Author

@Youw : pushed 3 new commit addressing your comments.
The #1136 evidence prompted extending coverage to init_root_hub() (beyond what Codex literally asked at P3)
Codex asked for "skip or throttle" (P1): this is the throttle variant.

@mcuee

mcuee commented Jul 17, 2026

Copy link
Copy Markdown
Member

I like this idea even though I may not be qualified to review the code changes.

@mcuee mcuee added the windows label Jul 17, 2026

@Youw Youw left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Comment thread libusb/os/windows_winusb.c Resolved
@mcuee

mcuee commented Jul 23, 2026

Copy link
Copy Markdown
Member

I do not have the right device to trigger the issue mentioned in PR #1741. But at least there is no issue.

 libusb_pr1882  $Env:LIBUSB_DEBUG=3
 libusb_pr1882  .\build\v145\x64\Release-Hotplug-MT\listdevs.exe -v
libusb: info [winusbx_init] WinUSB DLL available (with isoch support)
libusb: info [windows_init] UsbDk backend is not available
24ae:4057 (bus 3, device 13) path: 2.3.2.3
    manufacturer = SEMICO
    product = USB Keyboard
7768:642c (bus 3, device 11) path: 2.3.2.1
    manufacturer = Dongle
    product = Inphic IN9 SLE
    serial_number = 20240401
1a2c:7fff (bus 3, device 12) path: 2.3.2.2
    manufacturer =
    product = 2.4G Wireless Device
    serial_number = 8545124150344637
047f:c056 (bus 1, device 3) path: 6
    manufacturer = Plantronics
    product = Plantronics Blackwire 3220 Series
    serial_number = BB305534D79EBD418B6757528EAC0C19
413c:b06e (bus 3, device 7) path: 2.5libusb: warning [winusb_get_device_string] could not retrieve language IDs for 'USB\VID_413C&PID_B06E\2110': [31] A device attached to the system is not functioning.
libusb: warning [winusb_get_device_string] could not retrieve language IDs for 'USB\VID_413C&PID_B06E\2110': [31] A device attached to the system is not functioning.

413c:b06f (bus 3, device 10) path: 2.3.5libusb: warning [winusb_get_device_string] could not retrieve language IDs for 'USB\VID_413C&PID_B06F\0123456789ABCDEF': [31] A device attached to the system is not functioning.
libusb: warning [winusb_get_device_string] could not retrieve language IDs for 'USB\VID_413C&PID_B06F\0123456789ABCDEF': [31] A device attached to the system is not functioning.

1bcf:2bb4 (bus 1, device 1) path: 3
    manufacturer = CN03N9728LU00548DCG8A00
    product = Integrated_Webcam_FHD
    serial_number = 01.00.00
0bda:402e (bus 3, device 9) path: 2.3.4
    manufacturer = Generic
    product = USB Audio
    serial_number = 200901010001
0424:2740 (bus 3, device 14) path: 2.3.2.5
    manufacturer = Microchip Tech
    product = Hub Controller
8087:0033 (bus 1, device 2) path: 10
0b95:772b (bus 1, device 5) path: 7.1
    manufacturer = ASIX Elec. Corp.
    product = AX88772C
    serial_number = C1B13D
0bda:8153 (bus 3, device 3) path: 4.4
    manufacturer = Realtek
    product = USB 10/100/1000 LAN
    serial_number = 111000001
16c0:05dc (bus 1, device 6) path: 7.4
    manufacturer = www.fischl.de
    product = USBasp
    serial_number = 0001
0bda:0413 (bus 3, device 2) path: 4.3libusb: warning [winusb_get_device_string] could not retrieve language IDs for 'USB\VID_0BDA&PID_0413\9&18D5C933&0&3': [31] A device attached to the system is not functioning.
libusb: warning [winusb_get_device_string] could not retrieve language IDs for 'USB\VID_0BDA&PID_0413\9&18D5C933&0&3': [31] A device attached to the system is not functioning.

0bda:0487 (bus 3, device 1) path: 4
    manufacturer = Dell Inc.
    product = Dell dock
05e3:0608 (bus 1, device 4) path: 7
    product = USB2.0 Hub
8086:15f0 (bus 3, device 0)
0bda:5487 (bus 3, device 4) path: 2
    manufacturer = Dell Inc.
    product = Dell dock
8086:7ec0 (bus 2, device 0)
0424:2744 (bus 3, device 8) path: 2.3.2
    manufacturer = Microchip Tech
    product = USB2744
8086:7e7d (bus 1, device 0)
0bda:5413 (bus 3, device 6) path: 2.3
    manufacturer = Dell Inc.
    product = Dell dock
0424:5744 (bus 3, device 5) path: 4.3.2libusb: warning [winusb_get_device_string] could not retrieve language IDs for 'USB\VID_0424&PID_5744\A&3AD159B5&0&2': [31] A device attached to the system is not functioning.
libusb: warning [winusb_get_device_string] could not retrieve language IDs for 'USB\VID_0424&PID_5744\A&3AD159B5&0&2': [31] A device attached to the system is not functioning.

@sonatique
sonatique force-pushed the windows-hub-ioctl-timeout branch from 2591c3a to 3cf9bac Compare July 29, 2026 08:54
@sonatique
sonatique requested a review from Youw July 29, 2026 09:16

@Youw Youw left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Related to #1136 and #1741.

Generated by Codex (GPT-5.6 Sol).

Comment thread libusb/os/windows_winusb.c Resolved
Comment thread libusb/os/windows_winusb.c Resolved
sonatique added a commit that referenced this pull request Aug 1, 2026
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.
sonatique added a commit that referenced this pull request Aug 1, 2026
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
@sonatique

sonatique commented Aug 1, 2026 •

Copy link
Copy Markdown
Member Author

@Youw

Codex reviewed current head [3cf9bac]

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.
Backoff list: hub_timeout_backoff_active() now prunes every expired entry it traverses, not just a matching one.

Please re-review

@Youw

Youw commented Aug 1, 2026

Copy link
Copy Markdown
Member

@sonatique this PR is for sonatique:windows-hub-ioctl-timeout, but the two commits with fixes you've mentioned are pushed to libusb:windows-hub-ioctl-timeout.

To make this work you need either create a PR into libsub:master from libusb:windows-hub-ioctl-timeout or push the fixes to sonatique:windows-hub-ioctl-timeout.

@sonatique
sonatique force-pushed the windows-hub-ioctl-timeout branch from 3cf9bac to a288bdb Compare August 2, 2026 05:58
@sonatique

Copy link
Copy Markdown
Member Author

@Youw :

@sonatique this PR is for sonatique:windows-hub-ioctl-timeout, but the two commits with fixes you've mentioned are pushed to libusb:windows-hub-ioctl-timeout.

Sorry: I pushed to the wrong repos. Corrected now, thanks.

Comment thread libusb/os/windows_winusb.c Resolved

@Youw Youw left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Related to #1136 and #1741.

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.
@sonatique
sonatique force-pushed the windows-hub-ioctl-timeout branch from a288bdb to de056b1 Compare August 2, 2026 22:19
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
@sonatique
sonatique requested a review from Youw August 2, 2026 22:20
@sonatique

Copy link
Copy Markdown
Member Author

@slouken any chance you could test this code? Thank you very much in advance.

@sonatique

Copy link
Copy Markdown
Member Author

@Youw : I addressed your last comment. Please re-review at your convenience.
I'll obviously squash some commits before merging the PR (those who corrects things previously introduced in the same PR).

@Youw Youw left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Comment thread libusb/os/windows_winusb.c Resolved
@sonatique

Copy link
Copy Markdown
Member Author

@Youw : thanks again for this finding. Last commit addresses it. Please re-review, thanks you.

@sonatique
sonatique requested a review from Youw August 3, 2026 15:46
@Youw

Youw commented Aug 3, 2026

Copy link
Copy Markdown
Member

I see last commit in this branch is 17 hours ago, are you shure you pushed to the right branch (or pushed at all)?

saschazepter pushed a commit to saschazepter/libusb that referenced this pull request Aug 3, 2026
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 Youw left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 Youw left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

@sonatique

Copy link
Copy Markdown
Member Author

Thank you for the approval @Youw !

@mcuee @Youw : shall we wait for @slouken to test it with his hardware before merging?

@mcuee

mcuee commented Aug 4, 2026

Copy link
Copy Markdown
Member

Thank you for the approval @Youw !

@mcuee @Youw : shall we wait for @slouken to test it with his hardware before merging?

I think it is okay to merge first.

@sonatique
sonatique merged commit d7213e9 into libusb:master Aug 4, 2026
43 checks passed
sonatique added a commit that referenced this pull request Aug 4, 2026
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.
sonatique added a commit that referenced this pull request Aug 4, 2026
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.
sonatique added a commit that referenced this pull request Aug 4, 2026
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Libusb deadlocks with the Nacon wired controller

3 participants