darwin_cancel_transfer() routes bulk, interrupt and isochronous
transfers to darwin_abort_transfers(), which already knows how to abort
a single bulk stream with AbortStreamsPipe(). LIBUSB_TRANSFER_TYPE_BULK_STREAM
was missing from the switch, so libusb_cancel_transfer() returned
LIBUSB_ERROR_INVALID_PARAM for every stream transfer.
USB Attached SCSI uses the command tag as the bulk stream id, so a
redirection host cancels stream transfers constantly. When the cancel is
not applied the transfer stays in flight on the host controller and the
guest's command never completes, which surfaces as a 30 second SCSI
timeout and a device reset in the guest.
A caller that cancels its transfers and waits for them to complete, as
usbredirhost does when it releases a device, waits forever while a
stream transfer is pending, and USB Attached SCSI keeps one pending on
its status pipe.
Assisted-by: OpenCode:deepseek-v4.1-flash
Assisted-by: Claude:claude-fable-5-2
We need to maintain the invariant that `device` is never an invalid
pointer because another thread might be concurrently accessing it. We
want that thread to error from an outdated `device` rather than crash
on a NULL pointer.
When a device is disconnected or otherwise `dpriv->device` is invalid,
`GetConfigurationDescriptorPtr` will return `kIOReturnNoDevice` and
`IOUSBConfigurationDescriptorPtr` will not be set. This means that we
have an uninitialized pointer that is read from which is... very bad.
Similar to the previous commit with device capture counts, we also need to
take account of multiple contexts calling open/close on a device and make
sure the open_count is immune to data races.
When one process has two contexts to libusb, it may trigger a reenumeration
while the other context accesses `*dpriv->device`. Adding a mutex to access
`device` can be costly because it is used in every function. Instead, we
maintain an invariant: the `darwin_cached_device` must be valid at all
times. In particular, this means the fields `device` and `service` must not
be stale or we will have a use after free triggerable through a race
condition.
Previously, in `darwin_devices_detached` during reenumeration, it was
possible for `old_device->device` to be freed. We now defer this free to
`darwin_get_cached_device` after a new `device` is written. Note that the
order is important because we do not have locks, so we must free the old
device after writing the new one. The same point applies to `service` which
we take care to free after the new `service` is written.
A caveat here is that even if we do not crash it is still possible for one
context to be using an outdated `device` and `service` leading to an error
return. This should be acceptable because it would be a similar situation
to the device being detached during an API call.
If two threads try to capture at the same time, the result can be
inconsistent. For example, a process can have two different contexts to
libusb and both call `libusb_reset_device`.
The cleanup function darwin_cleanup_devices was intented to be called only once
at program exit. When the initialization/finalization code was changed to
destroy the cached device list on last exit this function should have been
modified to require a lock on darwin_cached_devices_lock. This commit updates
cleanup to protect the cached device list with the cached devices mutex and
updates darwin_init to print out an error and return if a reference leak is
detected.
Also using this opportunity to correct the naming of the mutex. Changed
darwin_cached_devices_lock to darwin_cached_devices_mutex. Also cleaning the
initialization code up a bit. Removing the context pointer from the hotplug
thread as it is not used for anything but logging.
Fixes#1124
Signed-off-by: Nathan Hjelm <[email protected]>
Historically Mac OS X always cleared the data toggle on the host side. For
consistency, libusb has been calling ClearPipeStallBothEnds to also clear the
device side toggle. Newer versions of the IOUSBLib do not clear the host side
toggle so there is no need to make this call. Additionally, some buggy devices
may fail to correctly implement clearing the data toggle.
Signed-off-by: Nathan Hjelm <[email protected]>
[Tormod: Return result from AbortPipe]
Signed-off-by: Tormod Volden <[email protected]>
The darwin event thread (in contrast to other OS implementations) tries
to log to the context that created it. However, this context is only
guaranteed to be valid until the thread has started. It may be that
another context is the last one to be destroyed, causing the event
thread to log using an already destroyed context.
Fix this by only passing on ctx where it is acceptable.
Fixes#1108
On non-macOS platforms, ResetDevice() does nothing so we use the "old" way of
calling re-enumerate. If the device is captured, we have to re-enumerate, then
re-capture, re-authorize, and finally restore the state.
Some functions were returning e.g. -ENOMEM and the caller would check
for negative return values. However, on Haiku, contrary to modern
standards, these macros are negative, so this logic would fail. In any
case, change the function to return -1 instead. For good measure also
set errno to the appropriate value, although it is not used in the
current code.
This was discovered on Haiku builds because the value for ENOMEM is
INT_MIN which cannot be negated without overflow.
Signed-off-by: Tormod Volden <[email protected]>
Since libusb_set_option() is variadic, there is no symbol
for it with @ appended in the DLL, and the automatic
generation of libusb-1.0.def misses it.
Signed-off-by: Tormod Volden <[email protected]>
This results in very long timeouts.
This PR uses clock_gettime(CLOCK_MONOTONIC, ...) to calculate the elapsed time
Closes#1035
Signed-off-by: Nathan Hjelm <[email protected]>
In some versions of macOS a pipe stall returned when setting the alternate interface
causes the interface to become unusable. To handle this case the backend was always
re-claiming the interface before clearing the pipe stall. In macOS Monterey
unconditionally re-claiming the interface leads to an error due to the process already
having exclusive access. To resolve this issue we attempt to clear the halt and only
re-claim the interface if clearing the pipe stall returns kIOUSBUnknownPipeErr. Tested
with 12.0.1 and 10.13 and get the expected results in both cases with a custom USB
device that has this behavior.
Fixes#1011Closes#1031
Signed-off-by: Nathan Hjelm <[email protected]>
If the value is always the same we retain binary compatibility.
References #935
Signed-off-by: Tormod Volden <[email protected]>
Signed-off-by: Nathan Hjelm <[email protected]>
Commit 32a2206942 reordered and
refactored libusb_init. This resulted in moving code outside the
default ctx lock that was unrelated to it. But this resulted in
broken error path cleanup logic that leaves the default ctx as
locked, half initialized and freed in case a libusb_set_option or
the usbi_io_init call fails.
Undo part of the previous reordering to unlock and clear the default
ctx in all error paths in libusb_init.
Closes#995
Signed-off-by: Nathan Hjelm <[email protected]>
After commit f7084fe the if clause would always be true, so remove it.
Thanks to "xloem" for reporting.
References #942
Signed-off-by: Tormod Volden <[email protected]>
Some of the changes in commit 9c28ad2 rely on all transfers having (or
appearing to have) asynchronous completion.
However, the libusb0.sys backend of libusbk.dll performs all control
transfers synchronously and ignores any "overlapped" structure handed to
it. Our asynchronous handling will in this case be pending and
eventually time out although the USB request itself was successful.
Therefore restore the possibility of synchronous completion of control
transfers, by forcing the completion handling on a successful return
from request submission. This brings the code closer to how it was
established in commit ce95f65.
Fixes#94
Tested-by: Xiaofan Chen <[email protected]>
Signed-off-by: Tormod Volden <[email protected]>
The default timeouts of 5 seconds used by WinUSB are cleared in
configure_endpoints(). This was not called if not at least one extra
endpoint apart from endpoint 0 existed, so that in those cases the
default timeout of 5 seconds remained in place.
Fix this by calling configure_endpoints, even if no interface specific
endpoints were found, so that it can configure endpoint 0.
Closes#963
Signed-off-by: Julian Scheel <[email protected]>
[Tormod: Refactored to reduce duplicated code]
Signed-off-by: Tormod Volden <[email protected]>
The NZXT Kraken Z73 device has been reported to brokenly have two
identical device interface GUIDs registered. Accept such cases by
treating the ERROR_MORE_DATA return value as success and processing the
first returned GUID as if it would be the only one.
If one day we see legitimate cases of multiple GUIDs we will need to
deal with them properly.
References jdkvision/libusb#1
Closes#1010
Signed-off-by: Tormod Volden <[email protected]>
kUSBReEnumerateCaptureDeviceMask was introduced in the 10.10 SDK, so
compiling on 10.9 and earlier will fail with:
os/darwin_usb.c: In function 'darwin_reenumerate_device':
os/darwin_usb.c:1749:18: error: 'kUSBReEnumerateCaptureDeviceMask' undeclared (first use in this function); did you mean 'USBReEnumerateOptions'?
options |= kUSBReEnumerateCaptureDeviceMask;
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
USBReEnumerateOptions
os/darwin_usb.c:1749:18: note: each undeclared identifier is reported only once for each function it appears in
Downstream report: https://trac.macports.org/ticket/63668Closes#1023
The default options configured with libusb_set_option(NULL, ...)
were only applied when the default context was created, and were
ignored when calling libusb_init() with a non-null context pointer.
Make sure the default options will be applied to all new contexts. This
is important when using LIBUSB_OPTION_NO_DEVICE_DISCOVERY which must
be respected during the context initialization in order to work.
Closes#942
[Tormod: amend comments]
Signed-off-by: Tormod Volden <[email protected]>
Other code checks this field for being NULL or not, so NULLing it upon
last release seems the right thing to do. I noticed this during code
review, I never actually reproduced any problem.
Closes#981
The standard procedure to define ssize_t on Windows is to wrap it around
a check for the _SSIZE_T_DEFINED macro.
If not done, it makes it impossible to use the libusb.h header along
with other headers (from other libraries) that also attempt to define
ssize_t.
Closes#1007
Signed-off-by: Paul Cercueil <[email protected]>
This only fixes issue (A):
libusb: error [composite_copy_transfer_data] program assertion failed - no function to copy transfer data
References #966Closes#967
The kIOMasterPortDefault constant has been replaced by kIOMainPortDefault. Both
are synonmys for 0. To avoid extra checks on the target macOS release just go
ahead and use 0.
Signed-off-by: Nathan Hjelm <[email protected]>
With macOS Monterey Apple started using a new error code to indicate a pipe
stall. This new error code needs to be handled both in translation to libusb
error codes and when handling errors setting the alt setting.
References #1011
Signed-off-by: Nathan Hjelm <[email protected]>
If the backend init fails, the control goes to err_io_exit which tries
to clean up hotplug related lists that aren't initialized. Moving
hotplug_init before makes sure the lists are valid so if backend init
fails they get cleaned up without errors.
Closes#989