1 /* -*- Mode: C; c-basic-offset:8 ; indent-tabs-mode:t -*- */
3 * Linux usbfs backend for libusb
4 * Copyright © 2007-2009 Daniel Drake <dsd@gentoo.org>
5 * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
6 * Copyright © 2013 Nathan Hjelm <hjelmn@mac.com>
7 * Copyright © 2012-2013 Hans de Goede <hdegoede@redhat.com>
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
35 #include <sys/ioctl.h>
38 #include <sys/types.h>
39 #include <sys/utsname.h>
43 #include "linux_usbfs.h"
46 * opening a usbfs node causes the device to be resumed, so we attempt to
47 * avoid this during enumeration.
49 * sysfs allows us to read the kernel's in-memory copies of device descriptors
50 * and so forth, avoiding the need to open the device:
51 * - The binary "descriptors" file contains all config descriptors since
52 * 2.6.26, commit 217a9081d8e69026186067711131b77f0ce219ed
53 * - The binary "descriptors" file was added in 2.6.23, commit
54 * 69d42a78f935d19384d1f6e4f94b65bb162b36df, but it only contains the
55 * active config descriptors
56 * - The "busnum" file was added in 2.6.22, commit
57 * 83f7d958eab2fbc6b159ee92bf1493924e1d0f72
58 * - The "devnum" file has been present since pre-2.6.18
59 * - the "bConfigurationValue" file has been present since pre-2.6.18
61 * If we have bConfigurationValue, busnum, and devnum, then we can determine
62 * the active configuration without having to open the usbfs node in RDWR mode.
63 * The busnum file is important as that is the only way we can relate sysfs
64 * devices to usbfs nodes.
66 * If we also have all descriptors, we can obtain the device descriptor and
67 * configuration without touching usbfs at all.
70 /* endianness for multi-byte fields:
72 * Descriptors exposed by usbfs have the multi-byte fields in the device
73 * descriptor as host endian. Multi-byte fields in the other descriptors are
74 * bus-endian. The kernel documentation says otherwise, but it is wrong.
76 * In sysfs all descriptors are bus-endian.
79 static const char *usbfs_path = NULL;
81 /* use usbdev*.* device names in /dev instead of the usbfs bus directories */
82 static int usbdev_names = 0;
84 /* Linux 2.6.23 adds support for O_CLOEXEC when opening files, which marks the
85 * close-on-exec flag in the underlying file descriptor. */
86 static int supports_flag_cloexec = -1;
88 /* Linux 2.6.32 adds support for a bulk continuation URB flag. this basically
89 * allows us to mark URBs as being part of a specific logical transfer when
90 * we submit them to the kernel. then, on any error except a cancellation, all
91 * URBs within that transfer will be cancelled and no more URBs will be
92 * accepted for the transfer, meaning that no more data can creep in.
94 * The BULK_CONTINUATION flag must be set on all URBs within a bulk transfer
95 * (in either direction) except the first.
96 * For IN transfers, we must also set SHORT_NOT_OK on all URBs except the
97 * last; it means that the kernel should treat a short reply as an error.
98 * For OUT transfers, SHORT_NOT_OK must not be set. it isn't needed (OUT
99 * transfers can't be short unless there's already some sort of error), and
100 * setting this flag is disallowed (a kernel with USB debugging enabled will
103 static int supports_flag_bulk_continuation = -1;
105 /* Linux 2.6.31 fixes support for the zero length packet URB flag. This
106 * allows us to mark URBs that should be followed by a zero length data
107 * packet, which can be required by device- or class-specific protocols.
109 static int supports_flag_zero_packet = -1;
111 /* clock ID for monotonic clock, as not all clock sources are available on all
112 * systems. appropriate choice made at initialization time. */
113 static clockid_t monotonic_clkid = -1;
115 /* Linux 2.6.22 (commit 83f7d958eab2fbc6b159ee92bf1493924e1d0f72) adds a busnum
116 * to sysfs, so we can relate devices. This also implies that we can read
117 * the active configuration through bConfigurationValue */
118 static int sysfs_can_relate_devices = -1;
120 /* Linux 2.6.26 (commit 217a9081d8e69026186067711131b77f0ce219ed) adds all
121 * config descriptors (rather then just the active config) to the sysfs
122 * descriptors file, so from then on we can use them. */
123 static int sysfs_has_descriptors = -1;
125 /* how many times have we initted (and not exited) ? */
126 static int init_count = 0;
128 /* Serialize hotplug start/stop */
129 static usbi_mutex_static_t linux_hotplug_startstop_lock = USBI_MUTEX_INITIALIZER;
130 /* Serialize scan-devices, event-thread, and poll */
131 usbi_mutex_static_t linux_hotplug_lock = USBI_MUTEX_INITIALIZER;
133 static int linux_start_event_monitor(void);
134 static int linux_stop_event_monitor(void);
135 static int linux_scan_devices(struct libusb_context *ctx);
136 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname);
137 static int detach_kernel_driver_and_claim(struct libusb_device_handle *, int);
139 #if !defined(USE_UDEV)
140 static int linux_default_scan_devices (struct libusb_context *ctx);
143 struct linux_device_priv {
145 unsigned char *descriptors;
147 int active_config; /* cache val for !sysfs_can_relate_devices */
150 struct linux_device_handle_priv {
158 /* submission failed after the first URB, so await cancellation/completion
159 * of all the others */
162 /* cancelled by user or timeout */
165 /* completed multi-URB transfer in non-final URB */
168 /* one or more urbs encountered a low-level error */
172 struct linux_transfer_priv {
174 struct usbfs_urb *urbs;
175 struct usbfs_urb **iso_urbs;
178 enum reap_action reap_action;
181 enum libusb_transfer_status reap_status;
183 /* next iso packet in user-supplied transfer to be populated */
184 int iso_packet_offset;
187 static int _open(const char *path, int flags)
189 #if defined(O_CLOEXEC)
190 if (supports_flag_cloexec)
191 return open(path, flags | O_CLOEXEC);
194 return open(path, flags);
197 static int _get_usbfs_fd(struct libusb_device *dev, mode_t mode, int silent)
199 struct libusb_context *ctx = DEVICE_CTX(dev);
205 snprintf(path, PATH_MAX, "%s/usbdev%d.%d",
206 usbfs_path, dev->bus_number, dev->device_address);
208 snprintf(path, PATH_MAX, "%s/%03d/%03d",
209 usbfs_path, dev->bus_number, dev->device_address);
211 fd = _open(path, mode);
213 return fd; /* Success */
215 if (errno == ENOENT) {
217 usbi_err(ctx, "File doesn't exist, wait %d ms and try again", delay/1000);
219 /* Wait 10ms for USB device path creation.*/
220 nanosleep(&(struct timespec){delay / 1000000, (delay * 1000) % 1000000000UL}, NULL);
222 fd = _open(path, mode);
224 return fd; /* Success */
228 usbi_err(ctx, "libusb couldn't open USB device %s: %s",
229 path, strerror(errno));
230 if (errno == EACCES && mode == O_RDWR)
231 usbi_err(ctx, "libusb requires write access to USB "
236 return LIBUSB_ERROR_ACCESS;
238 return LIBUSB_ERROR_NO_DEVICE;
239 return LIBUSB_ERROR_IO;
242 static struct linux_device_priv *_device_priv(struct libusb_device *dev)
244 return (struct linux_device_priv *) dev->os_priv;
247 static struct linux_device_handle_priv *_device_handle_priv(
248 struct libusb_device_handle *handle)
250 return (struct linux_device_handle_priv *) handle->os_priv;
253 /* check dirent for a /dev/usbdev%d.%d name
254 * optionally return bus/device on success */
255 static int _is_usbdev_entry(struct dirent *entry, int *bus_p, int *dev_p)
259 if (sscanf(entry->d_name, "usbdev%d.%d", &busnum, &devnum) != 2)
262 usbi_dbg("found: %s", entry->d_name);
270 static int check_usb_vfs(const char *dirname)
273 struct dirent *entry;
276 dir = opendir(dirname);
280 while ((entry = readdir(dir)) != NULL) {
281 if (entry->d_name[0] == '.')
284 /* We assume if we find any files that it must be the right place */
293 static const char *find_usbfs_path(void)
295 const char *path = "/dev/bus/usb";
296 const char *ret = NULL;
298 if (check_usb_vfs(path)) {
301 path = "/proc/bus/usb";
302 if (check_usb_vfs(path))
306 /* look for /dev/usbdev*.* if the normal places fail */
308 struct dirent *entry;
314 while ((entry = readdir(dir)) != NULL) {
315 if (_is_usbdev_entry(entry, NULL, NULL)) {
316 /* found one; that's enough */
326 /* On udev based systems without any usb-devices /dev/bus/usb will not
327 * exist. So if we've not found anything and we're using udev for hotplug
328 * simply assume /dev/bus/usb rather then making libusb_init fail. */
329 #if defined(USE_UDEV)
331 ret = "/dev/bus/usb";
335 usbi_dbg("found usbfs at %s", ret);
340 /* the monotonic clock is not usable on all systems (e.g. embedded ones often
341 * seem to lack it). fall back to REALTIME if we have to. */
342 static clockid_t find_monotonic_clock(void)
344 #ifdef CLOCK_MONOTONIC
348 /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
349 * because it's not available through timerfd */
350 r = clock_gettime(CLOCK_MONOTONIC, &ts);
352 return CLOCK_MONOTONIC;
353 usbi_dbg("monotonic clock doesn't work, errno %d", errno);
356 return CLOCK_REALTIME;
359 static int kernel_version_ge(int major, int minor, int sublevel)
362 int atoms, kmajor, kminor, ksublevel;
366 atoms = sscanf(uts.release, "%d.%d.%d", &kmajor, &kminor, &ksublevel);
375 /* kmajor == major */
377 return 0 == minor && 0 == sublevel;
383 /* kminor == minor */
385 return 0 == sublevel;
387 return ksublevel >= sublevel;
390 static int op_init(struct libusb_context *ctx)
395 usbfs_path = find_usbfs_path();
397 usbi_err(ctx, "could not find usbfs");
398 return LIBUSB_ERROR_OTHER;
401 if (monotonic_clkid == -1)
402 monotonic_clkid = find_monotonic_clock();
404 if (supports_flag_cloexec == -1) {
405 /* O_CLOEXEC flag available from Linux 2.6.23 */
406 supports_flag_cloexec = kernel_version_ge(2,6,23);
407 if (supports_flag_cloexec == -1) {
408 usbi_err(ctx, "error checking for O_CLOEXEC support");
409 return LIBUSB_ERROR_OTHER;
413 if (supports_flag_bulk_continuation == -1) {
414 /* bulk continuation URB flag available from Linux 2.6.32 */
415 supports_flag_bulk_continuation = kernel_version_ge(2,6,32);
416 if (supports_flag_bulk_continuation == -1) {
417 usbi_err(ctx, "error checking for bulk continuation support");
418 return LIBUSB_ERROR_OTHER;
422 if (supports_flag_bulk_continuation)
423 usbi_dbg("bulk continuation flag supported");
425 if (-1 == supports_flag_zero_packet) {
426 /* zero length packet URB flag fixed since Linux 2.6.31 */
427 supports_flag_zero_packet = kernel_version_ge(2,6,31);
428 if (-1 == supports_flag_zero_packet) {
429 usbi_err(ctx, "error checking for zero length packet support");
430 return LIBUSB_ERROR_OTHER;
434 if (supports_flag_zero_packet)
435 usbi_dbg("zero length packet flag supported");
437 if (-1 == sysfs_has_descriptors) {
438 /* sysfs descriptors has all descriptors since Linux 2.6.26 */
439 sysfs_has_descriptors = kernel_version_ge(2,6,26);
440 if (-1 == sysfs_has_descriptors) {
441 usbi_err(ctx, "error checking for sysfs descriptors");
442 return LIBUSB_ERROR_OTHER;
446 if (-1 == sysfs_can_relate_devices) {
447 /* sysfs has busnum since Linux 2.6.22 */
448 sysfs_can_relate_devices = kernel_version_ge(2,6,22);
449 if (-1 == sysfs_can_relate_devices) {
450 usbi_err(ctx, "error checking for sysfs busnum");
451 return LIBUSB_ERROR_OTHER;
455 if (sysfs_can_relate_devices || sysfs_has_descriptors) {
456 r = stat(SYSFS_DEVICE_PATH, &statbuf);
457 if (r != 0 || !S_ISDIR(statbuf.st_mode)) {
458 usbi_warn(ctx, "sysfs not mounted");
459 sysfs_can_relate_devices = 0;
460 sysfs_has_descriptors = 0;
464 if (sysfs_can_relate_devices)
465 usbi_dbg("sysfs can relate devices");
467 if (sysfs_has_descriptors)
468 usbi_dbg("sysfs has complete descriptors");
470 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
472 if (init_count == 0) {
473 /* start up hotplug event handler */
474 r = linux_start_event_monitor();
476 if (r == LIBUSB_SUCCESS) {
477 r = linux_scan_devices(ctx);
478 if (r == LIBUSB_SUCCESS)
480 else if (init_count == 0)
481 linux_stop_event_monitor();
483 usbi_err(ctx, "error starting hotplug event monitor");
484 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
489 static void op_exit(struct libusb_context *ctx)
492 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
493 assert(init_count != 0);
495 /* tear down event handler */
496 (void)linux_stop_event_monitor();
498 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
501 static int linux_start_event_monitor(void)
503 #if defined(USE_UDEV)
504 return linux_udev_start_event_monitor();
506 return linux_netlink_start_event_monitor();
510 static int linux_stop_event_monitor(void)
512 #if defined(USE_UDEV)
513 return linux_udev_stop_event_monitor();
515 return linux_netlink_stop_event_monitor();
519 static int linux_scan_devices(struct libusb_context *ctx)
523 usbi_mutex_static_lock(&linux_hotplug_lock);
525 #if defined(USE_UDEV)
526 ret = linux_udev_scan_devices(ctx);
528 ret = linux_default_scan_devices(ctx);
531 usbi_mutex_static_unlock(&linux_hotplug_lock);
536 static void op_hotplug_poll(void)
538 #if defined(USE_UDEV)
539 linux_udev_hotplug_poll();
541 linux_netlink_hotplug_poll();
545 static int _open_sysfs_attr(struct libusb_device *dev, const char *attr)
547 struct linux_device_priv *priv = _device_priv(dev);
548 char filename[PATH_MAX];
551 snprintf(filename, PATH_MAX, "%s/%s/%s",
552 SYSFS_DEVICE_PATH, priv->sysfs_dir, attr);
553 fd = _open(filename, O_RDONLY);
555 usbi_err(DEVICE_CTX(dev),
556 "open %s failed ret=%d errno=%d", filename, fd, errno);
557 return LIBUSB_ERROR_IO;
563 /* Note only suitable for attributes which always read >= 0, < 0 is error */
564 static int __read_sysfs_attr(struct libusb_context *ctx,
565 const char *devname, const char *attr)
567 char filename[PATH_MAX];
571 snprintf(filename, PATH_MAX, "%s/%s/%s", SYSFS_DEVICE_PATH,
573 fd = _open(filename, O_RDONLY);
575 if (errno == ENOENT) {
576 /* File doesn't exist. Assume the device has been
577 disconnected (see trac ticket #70). */
578 return LIBUSB_ERROR_NO_DEVICE;
580 usbi_err(ctx, "open %s failed errno=%d", filename, errno);
581 return LIBUSB_ERROR_IO;
586 usbi_err(ctx, "fdopen %s failed errno=%d", filename, errno);
588 return LIBUSB_ERROR_OTHER;
591 r = fscanf(f, "%d", &value);
594 usbi_err(ctx, "fscanf %s returned %d, errno=%d", attr, r, errno);
595 return LIBUSB_ERROR_NO_DEVICE; /* For unplug race (trac #70) */
598 usbi_err(ctx, "%s contains a negative value", filename);
599 return LIBUSB_ERROR_IO;
605 static int op_get_device_descriptor(struct libusb_device *dev,
606 unsigned char *buffer, int *host_endian)
608 struct linux_device_priv *priv = _device_priv(dev);
610 *host_endian = sysfs_has_descriptors ? 0 : 1;
611 memcpy(buffer, priv->descriptors, DEVICE_DESC_LENGTH);
616 /* read the bConfigurationValue for a device */
617 static int sysfs_get_active_config(struct libusb_device *dev, int *config)
620 char tmp[5] = {0, 0, 0, 0, 0};
625 fd = _open_sysfs_attr(dev, "bConfigurationValue");
629 r = read(fd, tmp, sizeof(tmp));
632 usbi_err(DEVICE_CTX(dev),
633 "read bConfigurationValue failed ret=%d errno=%d", r, errno);
634 return LIBUSB_ERROR_IO;
636 usbi_dbg("device unconfigured");
641 if (tmp[sizeof(tmp) - 1] != 0) {
642 usbi_err(DEVICE_CTX(dev), "not null-terminated?");
643 return LIBUSB_ERROR_IO;
644 } else if (tmp[0] == 0) {
645 usbi_err(DEVICE_CTX(dev), "no configuration value?");
646 return LIBUSB_ERROR_IO;
649 num = strtol(tmp, &endptr, 10);
651 usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp);
652 return LIBUSB_ERROR_IO;
659 int linux_get_device_address (struct libusb_context *ctx, int detached,
660 uint8_t *busnum, uint8_t *devaddr,const char *dev_node,
661 const char *sys_name)
665 usbi_dbg("getting address for device: %s detached: %d", sys_name, detached);
666 /* can't use sysfs to read the bus and device number if the
667 * device has been detached */
668 if (!sysfs_can_relate_devices || detached || NULL == sys_name) {
669 if (NULL == dev_node) {
670 return LIBUSB_ERROR_OTHER;
673 /* will this work with all supported kernel versions? */
674 if (!strncmp(dev_node, "/dev/bus/usb", 12)) {
675 sscanf (dev_node, "/dev/bus/usb/%hhu/%hhu", busnum, devaddr);
676 } else if (!strncmp(dev_node, "/proc/bus/usb", 13)) {
677 sscanf (dev_node, "/proc/bus/usb/%hhu/%hhu", busnum, devaddr);
680 return LIBUSB_SUCCESS;
683 usbi_dbg("scan %s", sys_name);
685 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "busnum");
688 if (sysfs_attr > 255)
689 return LIBUSB_ERROR_INVALID_PARAM;
690 *busnum = (uint8_t) sysfs_attr;
692 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "devnum");
695 if (sysfs_attr > 255)
696 return LIBUSB_ERROR_INVALID_PARAM;
698 *devaddr = (uint8_t) sysfs_attr;
700 usbi_dbg("bus=%d dev=%d", *busnum, *devaddr);
702 return LIBUSB_SUCCESS;
705 /* Return offset of the next descriptor with the given type */
706 static int seek_to_next_descriptor(struct libusb_context *ctx,
707 uint8_t descriptor_type, unsigned char *buffer, int size)
709 struct usb_descriptor_header header;
712 for (i = 0; size >= 0; i += header.bLength, size -= header.bLength) {
714 return LIBUSB_ERROR_NOT_FOUND;
717 usbi_err(ctx, "short descriptor read %d/2", size);
718 return LIBUSB_ERROR_IO;
720 usbi_parse_descriptor(buffer + i, "bb", &header, 0);
722 if (i && header.bDescriptorType == descriptor_type)
725 usbi_err(ctx, "bLength overflow by %d bytes", -size);
726 return LIBUSB_ERROR_IO;
729 /* Return offset to next config */
730 static int seek_to_next_config(struct libusb_context *ctx,
731 unsigned char *buffer, int size)
733 struct libusb_config_descriptor config;
736 return LIBUSB_ERROR_NOT_FOUND;
738 if (size < LIBUSB_DT_CONFIG_SIZE) {
739 usbi_err(ctx, "short descriptor read %d/%d",
740 size, LIBUSB_DT_CONFIG_SIZE);
741 return LIBUSB_ERROR_IO;
744 usbi_parse_descriptor(buffer, "bbwbbbbb", &config, 0);
745 if (config.bDescriptorType != LIBUSB_DT_CONFIG) {
746 usbi_err(ctx, "descriptor is not a config desc (type 0x%02x)",
747 config.bDescriptorType);
748 return LIBUSB_ERROR_IO;
752 * In usbfs the config descriptors are config.wTotalLength bytes apart,
753 * with any short reads from the device appearing as holes in the file.
755 * In sysfs wTotalLength is ignored, instead the kernel returns a
756 * config descriptor with verified bLength fields, with descriptors
757 * with an invalid bLength removed.
759 if (sysfs_has_descriptors) {
760 int next = seek_to_next_descriptor(ctx, LIBUSB_DT_CONFIG,
762 if (next == LIBUSB_ERROR_NOT_FOUND)
767 if (next != config.wTotalLength)
768 usbi_warn(ctx, "config length mismatch wTotalLength "
769 "%d real %d", config.wTotalLength, next);
772 if (config.wTotalLength < LIBUSB_DT_CONFIG_SIZE) {
773 usbi_err(ctx, "invalid wTotalLength %d",
774 config.wTotalLength);
775 return LIBUSB_ERROR_IO;
776 } else if (config.wTotalLength > size) {
777 usbi_warn(ctx, "short descriptor read %d/%d",
778 size, config.wTotalLength);
781 return config.wTotalLength;
785 static int op_get_config_descriptor_by_value(struct libusb_device *dev,
786 uint8_t value, unsigned char **buffer, int *host_endian)
788 struct libusb_context *ctx = DEVICE_CTX(dev);
789 struct linux_device_priv *priv = _device_priv(dev);
790 unsigned char *descriptors = priv->descriptors;
791 int size = priv->descriptors_len;
792 struct libusb_config_descriptor *config;
795 /* Unlike the device desc. config descs. are always in raw format */
798 /* Skip device header */
799 descriptors += DEVICE_DESC_LENGTH;
800 size -= DEVICE_DESC_LENGTH;
802 /* Seek till the config is found, or till "EOF" */
804 int next = seek_to_next_config(ctx, descriptors, size);
807 config = (struct libusb_config_descriptor *)descriptors;
808 if (config->bConfigurationValue == value) {
809 *buffer = descriptors;
817 static int op_get_active_config_descriptor(struct libusb_device *dev,
818 unsigned char *buffer, size_t len, int *host_endian)
821 unsigned char *config_desc;
823 if (sysfs_can_relate_devices) {
824 r = sysfs_get_active_config(dev, &config);
828 /* Use cached bConfigurationValue */
829 struct linux_device_priv *priv = _device_priv(dev);
830 config = priv->active_config;
833 return LIBUSB_ERROR_NOT_FOUND;
835 r = op_get_config_descriptor_by_value(dev, config, &config_desc,
840 len = MIN(len, (size_t)r);
841 memcpy(buffer, config_desc, len);
845 static int op_get_config_descriptor(struct libusb_device *dev,
846 uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
848 struct linux_device_priv *priv = _device_priv(dev);
849 unsigned char *descriptors = priv->descriptors;
850 int i, r, size = priv->descriptors_len;
852 /* Unlike the device desc. config descs. are always in raw format */
855 /* Skip device header */
856 descriptors += DEVICE_DESC_LENGTH;
857 size -= DEVICE_DESC_LENGTH;
859 /* Seek till the config is found, or till "EOF" */
861 r = seek_to_next_config(DEVICE_CTX(dev), descriptors, size);
864 if (i == config_index)
870 len = MIN(len, (size_t)r);
871 memcpy(buffer, descriptors, len);
875 /* send a control message to retrieve active configuration */
876 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
878 struct linux_device_priv *priv = _device_priv(dev);
879 unsigned char active_config = 0;
882 struct usbfs_ctrltransfer ctrl = {
883 .bmRequestType = LIBUSB_ENDPOINT_IN,
884 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
889 .data = &active_config
892 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
895 return LIBUSB_ERROR_NO_DEVICE;
897 /* we hit this error path frequently with buggy devices :( */
898 usbi_warn(DEVICE_CTX(dev),
899 "get_configuration failed ret=%d errno=%d", r, errno);
900 priv->active_config = -1;
902 if (active_config > 0) {
903 priv->active_config = active_config;
905 /* some buggy devices have a configuration 0, but we're
906 * reaching into the corner of a corner case here, so let's
907 * not support buggy devices in these circumstances.
908 * stick to the specs: a configuration value of 0 means
910 usbi_warn(DEVICE_CTX(dev),
911 "active cfg 0? assuming unconfigured device");
912 priv->active_config = -1;
916 return LIBUSB_SUCCESS;
919 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
920 uint8_t devaddr, const char *sysfs_dir)
922 struct linux_device_priv *priv = _device_priv(dev);
923 struct libusb_context *ctx = DEVICE_CTX(dev);
924 int descriptors_size = 512; /* Begin with a 1024 byte alloc */
928 dev->bus_number = busnum;
929 dev->device_address = devaddr;
932 priv->sysfs_dir = strdup(sysfs_dir);
933 if (!priv->sysfs_dir)
934 return LIBUSB_ERROR_NO_MEM;
936 /* Note speed can contain 1.5, in this case __read_sysfs_attr
937 will stop parsing at the '.' and return 1 */
938 speed = __read_sysfs_attr(DEVICE_CTX(dev), sysfs_dir, "speed");
941 case 1: dev->speed = LIBUSB_SPEED_LOW; break;
942 case 12: dev->speed = LIBUSB_SPEED_FULL; break;
943 case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
944 case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
946 usbi_warn(DEVICE_CTX(dev), "Unknown device speed: %d Mbps", speed);
951 /* cache descriptors in memory */
952 if (sysfs_has_descriptors)
953 fd = _open_sysfs_attr(dev, "descriptors");
955 fd = _get_usbfs_fd(dev, O_RDONLY, 0);
960 descriptors_size *= 2;
961 priv->descriptors = usbi_reallocf(priv->descriptors,
963 if (!priv->descriptors) {
965 return LIBUSB_ERROR_NO_MEM;
967 /* usbfs has holes in the file */
968 if (!sysfs_has_descriptors) {
969 memset(priv->descriptors + priv->descriptors_len,
970 0, descriptors_size - priv->descriptors_len);
972 r = read(fd, priv->descriptors + priv->descriptors_len,
973 descriptors_size - priv->descriptors_len);
975 usbi_err(ctx, "read descriptor failed ret=%d errno=%d",
978 return LIBUSB_ERROR_IO;
980 priv->descriptors_len += r;
981 } while (priv->descriptors_len == descriptors_size);
985 if (priv->descriptors_len < DEVICE_DESC_LENGTH) {
986 usbi_err(ctx, "short descriptor read (%d)",
987 priv->descriptors_len);
988 return LIBUSB_ERROR_IO;
991 if (sysfs_can_relate_devices)
992 return LIBUSB_SUCCESS;
994 /* cache active config */
995 fd = _get_usbfs_fd(dev, O_RDWR, 1);
997 /* cannot send a control message to determine the active
998 * config. just assume the first one is active. */
999 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
1000 "active configuration descriptor");
1001 if (priv->descriptors_len >=
1002 (DEVICE_DESC_LENGTH + LIBUSB_DT_CONFIG_SIZE)) {
1003 struct libusb_config_descriptor config;
1004 usbi_parse_descriptor(
1005 priv->descriptors + DEVICE_DESC_LENGTH,
1006 "bbwbbbbb", &config, 0);
1007 priv->active_config = config.bConfigurationValue;
1009 priv->active_config = -1; /* No config dt */
1011 return LIBUSB_SUCCESS;
1014 r = usbfs_get_active_config(dev, fd);
1020 static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir)
1022 struct libusb_context *ctx = DEVICE_CTX(dev);
1023 struct libusb_device *it;
1024 char *parent_sysfs_dir, *tmp;
1025 int ret, add_parent = 1;
1027 /* XXX -- can we figure out the topology when using usbfs? */
1028 if (NULL == sysfs_dir || 0 == strncmp(sysfs_dir, "usb", 3)) {
1029 /* either using usbfs or finding the parent of a root hub */
1030 return LIBUSB_SUCCESS;
1033 parent_sysfs_dir = strdup(sysfs_dir);
1034 if (NULL == parent_sysfs_dir) {
1035 return LIBUSB_ERROR_NO_MEM;
1037 if (NULL != (tmp = strrchr(parent_sysfs_dir, '.')) ||
1038 NULL != (tmp = strrchr(parent_sysfs_dir, '-'))) {
1039 dev->port_number = atoi(tmp + 1);
1042 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
1044 free (parent_sysfs_dir);
1045 return LIBUSB_SUCCESS;
1048 /* is the parent a root hub? */
1049 if (NULL == strchr(parent_sysfs_dir, '-')) {
1050 tmp = parent_sysfs_dir;
1051 ret = asprintf (&parent_sysfs_dir, "usb%s", tmp);
1054 return LIBUSB_ERROR_NO_MEM;
1059 /* find the parent in the context */
1060 usbi_mutex_lock(&ctx->usb_devs_lock);
1061 list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device) {
1062 struct linux_device_priv *priv = _device_priv(it);
1063 if (priv->sysfs_dir) {
1064 if (0 == strcmp (priv->sysfs_dir, parent_sysfs_dir)) {
1065 dev->parent_dev = libusb_ref_device(it);
1070 usbi_mutex_unlock(&ctx->usb_devs_lock);
1072 if (!dev->parent_dev && add_parent) {
1073 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1075 sysfs_scan_device(ctx, parent_sysfs_dir);
1080 usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev, sysfs_dir,
1081 dev->parent_dev, parent_sysfs_dir, dev->port_number);
1083 free (parent_sysfs_dir);
1085 return LIBUSB_SUCCESS;
1088 int linux_enumerate_device(struct libusb_context *ctx,
1089 uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1091 unsigned long session_id;
1092 struct libusb_device *dev;
1095 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1096 * will be reused. instead we should add a simple sysfs attribute with
1098 session_id = busnum << 8 | devaddr;
1099 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
1102 dev = usbi_get_device_by_session_id(ctx, session_id);
1104 /* device already exists in the context */
1105 usbi_dbg("session_id %ld already exists", session_id);
1106 libusb_unref_device(dev);
1107 return LIBUSB_SUCCESS;
1110 usbi_dbg("allocating new device for %d/%d (session %ld)",
1111 busnum, devaddr, session_id);
1112 dev = usbi_alloc_device(ctx, session_id);
1114 return LIBUSB_ERROR_NO_MEM;
1116 r = initialize_device(dev, busnum, devaddr, sysfs_dir);
1119 r = usbi_sanitize_device(dev);
1123 r = linux_get_parent_info(dev, sysfs_dir);
1128 libusb_unref_device(dev);
1130 usbi_connect_device(dev);
1135 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1137 struct libusb_context *ctx;
1139 usbi_mutex_static_lock(&active_contexts_lock);
1140 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1141 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1143 usbi_mutex_static_unlock(&active_contexts_lock);
1146 void linux_device_disconnected(uint8_t busnum, uint8_t devaddr)
1148 struct libusb_context *ctx;
1149 struct libusb_device *dev;
1150 unsigned long session_id = busnum << 8 | devaddr;
1152 usbi_mutex_static_lock(&active_contexts_lock);
1153 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1154 dev = usbi_get_device_by_session_id (ctx, session_id);
1156 usbi_disconnect_device (dev);
1157 libusb_unref_device(dev);
1159 usbi_dbg("device not found for session %x", session_id);
1162 usbi_mutex_static_unlock(&active_contexts_lock);
1165 #if !defined(USE_UDEV)
1166 /* open a bus directory and adds all discovered devices to the context */
1167 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1170 char dirpath[PATH_MAX];
1171 struct dirent *entry;
1172 int r = LIBUSB_ERROR_IO;
1174 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1175 usbi_dbg("%s", dirpath);
1176 dir = opendir(dirpath);
1178 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1179 /* FIXME: should handle valid race conditions like hub unplugged
1180 * during directory iteration - this is not an error */
1184 while ((entry = readdir(dir))) {
1187 if (entry->d_name[0] == '.')
1190 devaddr = atoi(entry->d_name);
1192 usbi_dbg("unknown dir entry %s", entry->d_name);
1196 if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1197 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1208 static int usbfs_get_device_list(struct libusb_context *ctx)
1210 struct dirent *entry;
1211 DIR *buses = opendir(usbfs_path);
1215 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1216 return LIBUSB_ERROR_IO;
1219 while ((entry = readdir(buses))) {
1222 if (entry->d_name[0] == '.')
1227 if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1230 r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
1232 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1236 busnum = atoi(entry->d_name);
1238 usbi_dbg("unknown dir entry %s", entry->d_name);
1242 r = usbfs_scan_busdir(ctx, busnum);
1254 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
1256 uint8_t busnum, devaddr;
1259 ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname);
1260 if (LIBUSB_SUCCESS != ret) {
1264 return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff,
1268 #if !defined(USE_UDEV)
1269 static int sysfs_get_device_list(struct libusb_context *ctx)
1271 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1272 struct dirent *entry;
1273 int r = LIBUSB_ERROR_IO;
1276 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1280 while ((entry = readdir(devices))) {
1281 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1282 || strchr(entry->d_name, ':'))
1285 if (sysfs_scan_device(ctx, entry->d_name)) {
1286 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1297 static int linux_default_scan_devices (struct libusb_context *ctx)
1299 /* we can retrieve device list and descriptors from sysfs or usbfs.
1300 * sysfs is preferable, because if we use usbfs we end up resuming
1301 * any autosuspended USB devices. however, sysfs is not available
1302 * everywhere, so we need a usbfs fallback too.
1304 * as described in the "sysfs vs usbfs" comment at the top of this
1305 * file, sometimes we have sysfs but not enough information to
1306 * relate sysfs devices to usbfs nodes. op_init() determines the
1307 * adequacy of sysfs and sets sysfs_can_relate_devices.
1309 if (sysfs_can_relate_devices != 0)
1310 return sysfs_get_device_list(ctx);
1312 return usbfs_get_device_list(ctx);
1316 static int op_open(struct libusb_device_handle *handle)
1318 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1321 hpriv->fd = _get_usbfs_fd(handle->dev, O_RDWR, 0);
1322 if (hpriv->fd < 0) {
1323 if (hpriv->fd == LIBUSB_ERROR_NO_DEVICE) {
1324 /* device will still be marked as attached if hotplug monitor thread
1325 * hasn't processed remove event yet */
1326 usbi_mutex_static_lock(&linux_hotplug_lock);
1327 if (handle->dev->attached) {
1328 usbi_dbg("open failed with no device, but device still attached");
1329 linux_device_disconnected(handle->dev->bus_number,
1330 handle->dev->device_address);
1332 usbi_mutex_static_unlock(&linux_hotplug_lock);
1337 r = ioctl(hpriv->fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1339 if (errno == ENOTTY)
1340 usbi_dbg("getcap not available");
1342 usbi_err(HANDLE_CTX(handle), "getcap failed (%d)", errno);
1344 if (supports_flag_zero_packet)
1345 hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1346 if (supports_flag_bulk_continuation)
1347 hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1350 r = usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1357 static void op_close(struct libusb_device_handle *dev_handle)
1359 struct linux_device_handle_priv *hpriv = _device_handle_priv(dev_handle);
1360 /* fd may have already been removed by POLLERR condition in op_handle_events() */
1361 if (!hpriv->fd_removed)
1362 usbi_remove_pollfd(HANDLE_CTX(dev_handle), hpriv->fd);
1366 static int op_get_configuration(struct libusb_device_handle *handle,
1371 if (sysfs_can_relate_devices) {
1372 r = sysfs_get_active_config(handle->dev, config);
1374 r = usbfs_get_active_config(handle->dev,
1375 _device_handle_priv(handle)->fd);
1376 if (r == LIBUSB_SUCCESS)
1377 *config = _device_priv(handle->dev)->active_config;
1382 if (*config == -1) {
1383 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1390 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1392 struct linux_device_priv *priv = _device_priv(handle->dev);
1393 int fd = _device_handle_priv(handle)->fd;
1394 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1396 if (errno == EINVAL)
1397 return LIBUSB_ERROR_NOT_FOUND;
1398 else if (errno == EBUSY)
1399 return LIBUSB_ERROR_BUSY;
1400 else if (errno == ENODEV)
1401 return LIBUSB_ERROR_NO_DEVICE;
1403 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1404 return LIBUSB_ERROR_OTHER;
1407 /* update our cached active config descriptor */
1408 priv->active_config = config;
1410 return LIBUSB_SUCCESS;
1413 static int claim_interface(struct libusb_device_handle *handle, int iface)
1415 int fd = _device_handle_priv(handle)->fd;
1416 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1418 if (errno == ENOENT)
1419 return LIBUSB_ERROR_NOT_FOUND;
1420 else if (errno == EBUSY)
1421 return LIBUSB_ERROR_BUSY;
1422 else if (errno == ENODEV)
1423 return LIBUSB_ERROR_NO_DEVICE;
1425 usbi_err(HANDLE_CTX(handle),
1426 "claim interface failed, error %d errno %d", r, errno);
1427 return LIBUSB_ERROR_OTHER;
1432 static int release_interface(struct libusb_device_handle *handle, int iface)
1434 int fd = _device_handle_priv(handle)->fd;
1435 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1437 if (errno == ENODEV)
1438 return LIBUSB_ERROR_NO_DEVICE;
1440 usbi_err(HANDLE_CTX(handle),
1441 "release interface failed, error %d errno %d", r, errno);
1442 return LIBUSB_ERROR_OTHER;
1447 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1450 int fd = _device_handle_priv(handle)->fd;
1451 struct usbfs_setinterface setintf;
1454 setintf.interface = iface;
1455 setintf.altsetting = altsetting;
1456 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1458 if (errno == EINVAL)
1459 return LIBUSB_ERROR_NOT_FOUND;
1460 else if (errno == ENODEV)
1461 return LIBUSB_ERROR_NO_DEVICE;
1463 usbi_err(HANDLE_CTX(handle),
1464 "setintf failed error %d errno %d", r, errno);
1465 return LIBUSB_ERROR_OTHER;
1471 static int op_clear_halt(struct libusb_device_handle *handle,
1472 unsigned char endpoint)
1474 int fd = _device_handle_priv(handle)->fd;
1475 unsigned int _endpoint = endpoint;
1476 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1478 if (errno == ENOENT)
1479 return LIBUSB_ERROR_NOT_FOUND;
1480 else if (errno == ENODEV)
1481 return LIBUSB_ERROR_NO_DEVICE;
1483 usbi_err(HANDLE_CTX(handle),
1484 "clear_halt failed error %d errno %d", r, errno);
1485 return LIBUSB_ERROR_OTHER;
1491 static int op_reset_device(struct libusb_device_handle *handle)
1493 int fd = _device_handle_priv(handle)->fd;
1496 /* Doing a device reset will cause the usbfs driver to get unbound
1497 from any interfaces it is bound to. By voluntarily unbinding
1498 the usbfs driver ourself, we stop the kernel from rebinding
1499 the interface after reset (which would end up with the interface
1500 getting bound to the in kernel driver if any). */
1501 for (i = 0; i < USB_MAXINTERFACES; i++) {
1502 if (handle->claimed_interfaces & (1L << i)) {
1503 release_interface(handle, i);
1507 usbi_mutex_lock(&handle->lock);
1508 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1510 if (errno == ENODEV) {
1511 ret = LIBUSB_ERROR_NOT_FOUND;
1515 usbi_err(HANDLE_CTX(handle),
1516 "reset failed error %d errno %d", r, errno);
1517 ret = LIBUSB_ERROR_OTHER;
1521 /* And re-claim any interfaces which were claimed before the reset */
1522 for (i = 0; i < USB_MAXINTERFACES; i++) {
1523 if (handle->claimed_interfaces & (1L << i)) {
1525 * A driver may have completed modprobing during
1526 * IOCTL_USBFS_RESET, and bound itself as soon as
1527 * IOCTL_USBFS_RESET released the device lock
1529 r = detach_kernel_driver_and_claim(handle, i);
1531 usbi_warn(HANDLE_CTX(handle),
1532 "failed to re-claim interface %d after reset: %s",
1533 i, libusb_error_name(r));
1534 handle->claimed_interfaces &= ~(1L << i);
1535 ret = LIBUSB_ERROR_NOT_FOUND;
1540 usbi_mutex_unlock(&handle->lock);
1544 static int do_streams_ioctl(struct libusb_device_handle *handle, long req,
1545 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1547 int r, fd = _device_handle_priv(handle)->fd;
1548 struct usbfs_streams *streams;
1550 if (num_endpoints > 30) /* Max 15 in + 15 out eps */
1551 return LIBUSB_ERROR_INVALID_PARAM;
1553 streams = malloc(sizeof(struct usbfs_streams) + num_endpoints);
1555 return LIBUSB_ERROR_NO_MEM;
1557 streams->num_streams = num_streams;
1558 streams->num_eps = num_endpoints;
1559 memcpy(streams->eps, endpoints, num_endpoints);
1561 r = ioctl(fd, req, streams);
1566 if (errno == ENOTTY)
1567 return LIBUSB_ERROR_NOT_SUPPORTED;
1568 else if (errno == EINVAL)
1569 return LIBUSB_ERROR_INVALID_PARAM;
1570 else if (errno == ENODEV)
1571 return LIBUSB_ERROR_NO_DEVICE;
1573 usbi_err(HANDLE_CTX(handle),
1574 "streams-ioctl failed error %d errno %d", r, errno);
1575 return LIBUSB_ERROR_OTHER;
1580 static int op_alloc_streams(struct libusb_device_handle *handle,
1581 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1583 return do_streams_ioctl(handle, IOCTL_USBFS_ALLOC_STREAMS,
1584 num_streams, endpoints, num_endpoints);
1587 static int op_free_streams(struct libusb_device_handle *handle,
1588 unsigned char *endpoints, int num_endpoints)
1590 return do_streams_ioctl(handle, IOCTL_USBFS_FREE_STREAMS, 0,
1591 endpoints, num_endpoints);
1594 static unsigned char *op_dev_mem_alloc(struct libusb_device_handle *handle,
1597 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1598 unsigned char *buffer = (unsigned char *)mmap(NULL, len,
1599 PROT_READ | PROT_WRITE, MAP_SHARED, hpriv->fd, 0);
1600 if (buffer == MAP_FAILED) {
1601 usbi_err(HANDLE_CTX(handle), "alloc dev mem failed errno %d",
1608 static int op_dev_mem_free(struct libusb_device_handle *handle,
1609 unsigned char *buffer, size_t len)
1611 if (munmap(buffer, len) != 0) {
1612 usbi_err(HANDLE_CTX(handle), "free dev mem failed errno %d",
1614 return LIBUSB_ERROR_OTHER;
1616 return LIBUSB_SUCCESS;
1620 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1623 int fd = _device_handle_priv(handle)->fd;
1624 struct usbfs_getdriver getdrv;
1627 getdrv.interface = interface;
1628 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1630 if (errno == ENODATA)
1632 else if (errno == ENODEV)
1633 return LIBUSB_ERROR_NO_DEVICE;
1635 usbi_err(HANDLE_CTX(handle),
1636 "get driver failed error %d errno %d", r, errno);
1637 return LIBUSB_ERROR_OTHER;
1640 return (strcmp(getdrv.driver, "usbfs") == 0) ? 0 : 1;
1643 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1646 int fd = _device_handle_priv(handle)->fd;
1647 struct usbfs_ioctl command;
1648 struct usbfs_getdriver getdrv;
1651 command.ifno = interface;
1652 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1653 command.data = NULL;
1655 getdrv.interface = interface;
1656 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1657 if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1658 return LIBUSB_ERROR_NOT_FOUND;
1660 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1662 if (errno == ENODATA)
1663 return LIBUSB_ERROR_NOT_FOUND;
1664 else if (errno == EINVAL)
1665 return LIBUSB_ERROR_INVALID_PARAM;
1666 else if (errno == ENODEV)
1667 return LIBUSB_ERROR_NO_DEVICE;
1669 usbi_err(HANDLE_CTX(handle),
1670 "detach failed error %d errno %d", r, errno);
1671 return LIBUSB_ERROR_OTHER;
1677 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1680 int fd = _device_handle_priv(handle)->fd;
1681 struct usbfs_ioctl command;
1684 command.ifno = interface;
1685 command.ioctl_code = IOCTL_USBFS_CONNECT;
1686 command.data = NULL;
1688 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1690 if (errno == ENODATA)
1691 return LIBUSB_ERROR_NOT_FOUND;
1692 else if (errno == EINVAL)
1693 return LIBUSB_ERROR_INVALID_PARAM;
1694 else if (errno == ENODEV)
1695 return LIBUSB_ERROR_NO_DEVICE;
1696 else if (errno == EBUSY)
1697 return LIBUSB_ERROR_BUSY;
1699 usbi_err(HANDLE_CTX(handle),
1700 "attach failed error %d errno %d", r, errno);
1701 return LIBUSB_ERROR_OTHER;
1702 } else if (r == 0) {
1703 return LIBUSB_ERROR_NOT_FOUND;
1709 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle,
1712 struct usbfs_disconnect_claim dc;
1713 int r, fd = _device_handle_priv(handle)->fd;
1715 dc.interface = interface;
1716 strcpy(dc.driver, "usbfs");
1717 dc.flags = USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER;
1718 r = ioctl(fd, IOCTL_USBFS_DISCONNECT_CLAIM, &dc);
1719 if (r == 0 || (r != 0 && errno != ENOTTY)) {
1725 return LIBUSB_ERROR_BUSY;
1727 return LIBUSB_ERROR_INVALID_PARAM;
1729 return LIBUSB_ERROR_NO_DEVICE;
1731 usbi_err(HANDLE_CTX(handle),
1732 "disconnect-and-claim failed errno %d", errno);
1733 return LIBUSB_ERROR_OTHER;
1736 /* Fallback code for kernels which don't support the
1737 disconnect-and-claim ioctl */
1738 r = op_detach_kernel_driver(handle, interface);
1739 if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND)
1742 return claim_interface(handle, interface);
1745 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1747 if (handle->auto_detach_kernel_driver)
1748 return detach_kernel_driver_and_claim(handle, iface);
1750 return claim_interface(handle, iface);
1753 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1757 r = release_interface(handle, iface);
1761 if (handle->auto_detach_kernel_driver)
1762 op_attach_kernel_driver(handle, iface);
1767 static void op_destroy_device(struct libusb_device *dev)
1769 struct linux_device_priv *priv = _device_priv(dev);
1770 if (priv->descriptors)
1771 free(priv->descriptors);
1772 if (priv->sysfs_dir)
1773 free(priv->sysfs_dir);
1776 /* URBs are discarded in reverse order of submission to avoid races. */
1777 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1779 struct libusb_transfer *transfer =
1780 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1781 struct linux_transfer_priv *tpriv =
1782 usbi_transfer_get_os_priv(itransfer);
1783 struct linux_device_handle_priv *dpriv =
1784 _device_handle_priv(transfer->dev_handle);
1786 struct usbfs_urb *urb;
1788 for (i = last_plus_one - 1; i >= first; i--) {
1789 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
1790 urb = tpriv->iso_urbs[i];
1792 urb = &tpriv->urbs[i];
1794 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
1797 if (EINVAL == errno) {
1798 usbi_dbg("URB not found --> assuming ready to be reaped");
1799 if (i == (last_plus_one - 1))
1800 ret = LIBUSB_ERROR_NOT_FOUND;
1801 } else if (ENODEV == errno) {
1802 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1803 ret = LIBUSB_ERROR_NO_DEVICE;
1805 usbi_warn(TRANSFER_CTX(transfer),
1806 "unrecognised discard errno %d", errno);
1807 ret = LIBUSB_ERROR_OTHER;
1813 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1816 for (i = 0; i < tpriv->num_urbs; i++) {
1817 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1823 free(tpriv->iso_urbs);
1824 tpriv->iso_urbs = NULL;
1827 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1829 struct libusb_transfer *transfer =
1830 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1831 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1832 struct linux_device_handle_priv *dpriv =
1833 _device_handle_priv(transfer->dev_handle);
1834 struct usbfs_urb *urbs;
1835 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1836 == LIBUSB_ENDPOINT_OUT;
1837 int bulk_buffer_len, use_bulk_continuation;
1841 if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1842 !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
1843 return LIBUSB_ERROR_NOT_SUPPORTED;
1846 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1847 * around this by splitting large transfers into 16k blocks, and then
1848 * submit all urbs at once. it would be simpler to submit one urb at
1849 * a time, but there is a big performance gain doing it this way.
1851 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1852 * using arbritary large transfers can still be a bad idea though, as
1853 * the kernel needs to allocate physical contiguous memory for this,
1854 * which may fail for large buffers.
1856 * The kernel solves this problem by splitting the transfer into
1857 * blocks itself when the host-controller is scatter-gather capable
1858 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1860 * Last, there is the issue of short-transfers when splitting, for
1861 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1862 * is needed, but this is not always available.
1864 if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1865 /* Good! Just submit everything in one go */
1866 bulk_buffer_len = transfer->length ? transfer->length : 1;
1867 use_bulk_continuation = 0;
1868 } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1869 /* Split the transfers and use bulk-continuation to
1870 avoid issues with short-transfers */
1871 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1872 use_bulk_continuation = 1;
1873 } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1874 /* Don't split, assume the kernel can alloc the buffer
1875 (otherwise the submit will fail with -ENOMEM) */
1876 bulk_buffer_len = transfer->length ? transfer->length : 1;
1877 use_bulk_continuation = 0;
1879 /* Bad, splitting without bulk-continuation, short transfers
1880 which end before the last urb will not work reliable! */
1881 /* Note we don't warn here as this is "normal" on kernels <
1882 2.6.32 and not a problem for most applications */
1883 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1884 use_bulk_continuation = 0;
1887 int num_urbs = transfer->length / bulk_buffer_len;
1888 int last_urb_partial = 0;
1890 if (transfer->length == 0) {
1892 } else if ((transfer->length % bulk_buffer_len) > 0) {
1893 last_urb_partial = 1;
1896 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
1898 urbs = calloc(num_urbs, sizeof(struct usbfs_urb));
1900 return LIBUSB_ERROR_NO_MEM;
1902 tpriv->num_urbs = num_urbs;
1903 tpriv->num_retired = 0;
1904 tpriv->reap_action = NORMAL;
1905 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1907 for (i = 0; i < num_urbs; i++) {
1908 struct usbfs_urb *urb = &urbs[i];
1909 urb->usercontext = itransfer;
1910 switch (transfer->type) {
1911 case LIBUSB_TRANSFER_TYPE_BULK:
1912 urb->type = USBFS_URB_TYPE_BULK;
1915 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1916 urb->type = USBFS_URB_TYPE_BULK;
1917 urb->stream_id = itransfer->stream_id;
1919 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1920 urb->type = USBFS_URB_TYPE_INTERRUPT;
1923 urb->endpoint = transfer->endpoint;
1924 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
1925 /* don't set the short not ok flag for the last URB */
1926 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
1927 urb->flags = USBFS_URB_SHORT_NOT_OK;
1928 if (i == num_urbs - 1 && last_urb_partial)
1929 urb->buffer_length = transfer->length % bulk_buffer_len;
1930 else if (transfer->length == 0)
1931 urb->buffer_length = 0;
1933 urb->buffer_length = bulk_buffer_len;
1935 if (i > 0 && use_bulk_continuation)
1936 urb->flags |= USBFS_URB_BULK_CONTINUATION;
1938 /* we have already checked that the flag is supported */
1939 if (is_out && i == num_urbs - 1 &&
1940 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
1941 urb->flags |= USBFS_URB_ZERO_PACKET;
1943 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1945 if (errno == ENODEV) {
1946 r = LIBUSB_ERROR_NO_DEVICE;
1948 usbi_err(TRANSFER_CTX(transfer),
1949 "submiturb failed error %d errno=%d", r, errno);
1950 r = LIBUSB_ERROR_IO;
1953 /* if the first URB submission fails, we can simply free up and
1954 * return failure immediately. */
1956 usbi_dbg("first URB failed, easy peasy");
1962 /* if it's not the first URB that failed, the situation is a bit
1963 * tricky. we may need to discard all previous URBs. there are
1965 * - discarding is asynchronous - discarded urbs will be reaped
1966 * later. the user must not have freed the transfer when the
1967 * discarded URBs are reaped, otherwise libusb will be using
1969 * - the earlier URBs may have completed successfully and we do
1970 * not want to throw away any data.
1971 * - this URB failing may be no error; EREMOTEIO means that
1972 * this transfer simply didn't need all the URBs we submitted
1973 * so, we report that the transfer was submitted successfully and
1974 * in case of error we discard all previous URBs. later when
1975 * the final reap completes we can report error to the user,
1976 * or success if an earlier URB was completed successfully.
1978 tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
1980 /* The URBs we haven't submitted yet we count as already
1982 tpriv->num_retired += num_urbs - i;
1984 /* If we completed short then don't try to discard. */
1985 if (COMPLETED_EARLY == tpriv->reap_action)
1988 discard_urbs(itransfer, 0, i);
1990 usbi_dbg("reporting successful submission but waiting for %d "
1991 "discards before reporting error", i);
1999 static int submit_iso_transfer(struct usbi_transfer *itransfer)
2001 struct libusb_transfer *transfer =
2002 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2003 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2004 struct linux_device_handle_priv *dpriv =
2005 _device_handle_priv(transfer->dev_handle);
2006 struct usbfs_urb **urbs;
2008 int num_packets = transfer->num_iso_packets;
2010 int this_urb_len = 0;
2012 int packet_offset = 0;
2013 unsigned int packet_len;
2014 unsigned char *urb_buffer = transfer->buffer;
2016 /* usbfs places arbitrary limits on iso URBs. this limit has changed
2017 * at least three times, and it's difficult to accurately detect which
2018 * limit this running kernel might impose. so we attempt to submit
2019 * whatever the user has provided. if the kernel rejects the request
2020 * due to its size, we return an error indicating such to the user.
2023 /* calculate how many URBs we need */
2024 for (i = 0; i < num_packets; i++) {
2025 unsigned int space_remaining = MAX_ISO_BUFFER_LENGTH - this_urb_len;
2026 packet_len = transfer->iso_packet_desc[i].length;
2028 if (packet_len > space_remaining) {
2030 this_urb_len = packet_len;
2031 /* check that we can actually support this packet length */
2032 if (this_urb_len > MAX_ISO_BUFFER_LENGTH)
2033 return LIBUSB_ERROR_INVALID_PARAM;
2035 this_urb_len += packet_len;
2038 usbi_dbg("need %d %dk URBs for transfer", num_urbs, MAX_ISO_BUFFER_LENGTH / 1024);
2040 urbs = calloc(num_urbs, sizeof(*urbs));
2042 return LIBUSB_ERROR_NO_MEM;
2044 tpriv->iso_urbs = urbs;
2045 tpriv->num_urbs = num_urbs;
2046 tpriv->num_retired = 0;
2047 tpriv->reap_action = NORMAL;
2048 tpriv->iso_packet_offset = 0;
2050 /* allocate + initialize each URB with the correct number of packets */
2051 for (i = 0; i < num_urbs; i++) {
2052 struct usbfs_urb *urb;
2053 unsigned int space_remaining_in_urb = MAX_ISO_BUFFER_LENGTH;
2054 int urb_packet_offset = 0;
2055 unsigned char *urb_buffer_orig = urb_buffer;
2059 /* swallow up all the packets we can fit into this URB */
2060 while (packet_offset < transfer->num_iso_packets) {
2061 packet_len = transfer->iso_packet_desc[packet_offset].length;
2062 if (packet_len <= space_remaining_in_urb) {
2064 urb_packet_offset++;
2066 space_remaining_in_urb -= packet_len;
2067 urb_buffer += packet_len;
2069 /* it can't fit, save it for the next URB */
2074 alloc_size = sizeof(*urb)
2075 + (urb_packet_offset * sizeof(struct usbfs_iso_packet_desc));
2076 urb = calloc(1, alloc_size);
2078 free_iso_urbs(tpriv);
2079 return LIBUSB_ERROR_NO_MEM;
2083 /* populate packet lengths */
2084 for (j = 0, k = packet_offset - urb_packet_offset;
2085 k < packet_offset; k++, j++) {
2086 packet_len = transfer->iso_packet_desc[k].length;
2087 urb->iso_frame_desc[j].length = packet_len;
2090 urb->usercontext = itransfer;
2091 urb->type = USBFS_URB_TYPE_ISO;
2092 /* FIXME: interface for non-ASAP data? */
2093 urb->flags = USBFS_URB_ISO_ASAP;
2094 urb->endpoint = transfer->endpoint;
2095 urb->number_of_packets = urb_packet_offset;
2096 urb->buffer = urb_buffer_orig;
2100 for (i = 0; i < num_urbs; i++) {
2101 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
2103 if (errno == ENODEV) {
2104 r = LIBUSB_ERROR_NO_DEVICE;
2105 } else if (errno == EINVAL) {
2106 usbi_warn(TRANSFER_CTX(transfer),
2107 "submiturb failed, transfer too large");
2108 r = LIBUSB_ERROR_INVALID_PARAM;
2110 usbi_err(TRANSFER_CTX(transfer),
2111 "submiturb failed error %d errno=%d", r, errno);
2112 r = LIBUSB_ERROR_IO;
2115 /* if the first URB submission fails, we can simply free up and
2116 * return failure immediately. */
2118 usbi_dbg("first URB failed, easy peasy");
2119 free_iso_urbs(tpriv);
2123 /* if it's not the first URB that failed, the situation is a bit
2124 * tricky. we must discard all previous URBs. there are
2126 * - discarding is asynchronous - discarded urbs will be reaped
2127 * later. the user must not have freed the transfer when the
2128 * discarded URBs are reaped, otherwise libusb will be using
2130 * - the earlier URBs may have completed successfully and we do
2131 * not want to throw away any data.
2132 * so, in this case we discard all the previous URBs BUT we report
2133 * that the transfer was submitted successfully. then later when
2134 * the final discard completes we can report error to the user.
2136 tpriv->reap_action = SUBMIT_FAILED;
2138 /* The URBs we haven't submitted yet we count as already
2140 tpriv->num_retired = num_urbs - i;
2141 discard_urbs(itransfer, 0, i);
2143 usbi_dbg("reporting successful submission but waiting for %d "
2144 "discards before reporting error", i);
2152 static int submit_control_transfer(struct usbi_transfer *itransfer)
2154 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2155 struct libusb_transfer *transfer =
2156 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2157 struct linux_device_handle_priv *dpriv =
2158 _device_handle_priv(transfer->dev_handle);
2159 struct usbfs_urb *urb;
2162 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
2163 return LIBUSB_ERROR_INVALID_PARAM;
2165 urb = calloc(1, sizeof(struct usbfs_urb));
2167 return LIBUSB_ERROR_NO_MEM;
2169 tpriv->num_urbs = 1;
2170 tpriv->reap_action = NORMAL;
2172 urb->usercontext = itransfer;
2173 urb->type = USBFS_URB_TYPE_CONTROL;
2174 urb->endpoint = transfer->endpoint;
2175 urb->buffer = transfer->buffer;
2176 urb->buffer_length = transfer->length;
2178 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2182 if (errno == ENODEV)
2183 return LIBUSB_ERROR_NO_DEVICE;
2185 usbi_err(TRANSFER_CTX(transfer),
2186 "submiturb failed error %d errno=%d", r, errno);
2187 return LIBUSB_ERROR_IO;
2192 static int op_submit_transfer(struct usbi_transfer *itransfer)
2194 struct libusb_transfer *transfer =
2195 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2197 switch (transfer->type) {
2198 case LIBUSB_TRANSFER_TYPE_CONTROL:
2199 return submit_control_transfer(itransfer);
2200 case LIBUSB_TRANSFER_TYPE_BULK:
2201 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2202 return submit_bulk_transfer(itransfer);
2203 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2204 return submit_bulk_transfer(itransfer);
2205 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2206 return submit_iso_transfer(itransfer);
2208 usbi_err(TRANSFER_CTX(transfer),
2209 "unknown endpoint type %d", transfer->type);
2210 return LIBUSB_ERROR_INVALID_PARAM;
2214 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2216 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2217 struct libusb_transfer *transfer =
2218 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2222 return LIBUSB_ERROR_NOT_FOUND;
2224 r = discard_urbs(itransfer, 0, tpriv->num_urbs);
2228 switch (transfer->type) {
2229 case LIBUSB_TRANSFER_TYPE_BULK:
2230 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2231 if (tpriv->reap_action == ERROR)
2233 /* else, fall through */
2235 tpriv->reap_action = CANCELLED;
2241 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2243 struct libusb_transfer *transfer =
2244 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2245 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2247 /* urbs can be freed also in submit_transfer so lock mutex first */
2248 switch (transfer->type) {
2249 case LIBUSB_TRANSFER_TYPE_CONTROL:
2250 case LIBUSB_TRANSFER_TYPE_BULK:
2251 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2252 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2258 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2259 if (tpriv->iso_urbs) {
2260 free_iso_urbs(tpriv);
2261 tpriv->iso_urbs = NULL;
2265 usbi_err(TRANSFER_CTX(transfer),
2266 "unknown endpoint type %d", transfer->type);
2270 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2271 struct usbfs_urb *urb)
2273 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2274 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2275 int urb_idx = urb - tpriv->urbs;
2277 usbi_mutex_lock(&itransfer->lock);
2278 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2279 urb_idx + 1, tpriv->num_urbs);
2281 tpriv->num_retired++;
2283 if (tpriv->reap_action != NORMAL) {
2284 /* cancelled, submit_fail, or completed early */
2285 usbi_dbg("abnormal reap: urb status %d", urb->status);
2287 /* even though we're in the process of cancelling, it's possible that
2288 * we may receive some data in these URBs that we don't want to lose.
2290 * 1. while the kernel is cancelling all the packets that make up an
2291 * URB, a few of them might complete. so we get back a successful
2292 * cancellation *and* some data.
2293 * 2. we receive a short URB which marks the early completion condition,
2294 * so we start cancelling the remaining URBs. however, we're too
2295 * slow and another URB completes (or at least completes partially).
2296 * (this can't happen since we always use BULK_CONTINUATION.)
2298 * When this happens, our objectives are not to lose any "surplus" data,
2299 * and also to stick it at the end of the previously-received data
2300 * (closing any holes), so that libusb reports the total amount of
2301 * transferred data and presents it in a contiguous chunk.
2303 if (urb->actual_length > 0) {
2304 unsigned char *target = transfer->buffer + itransfer->transferred;
2305 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2306 if (urb->buffer != target) {
2307 usbi_dbg("moving surplus data from offset %d to offset %d",
2308 (unsigned char *) urb->buffer - transfer->buffer,
2309 target - transfer->buffer);
2310 memmove(target, urb->buffer, urb->actual_length);
2312 itransfer->transferred += urb->actual_length;
2315 if (tpriv->num_retired == tpriv->num_urbs) {
2316 usbi_dbg("abnormal reap: last URB handled, reporting");
2317 if (tpriv->reap_action != COMPLETED_EARLY &&
2318 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2319 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2325 itransfer->transferred += urb->actual_length;
2327 /* Many of these errors can occur on *any* urb of a multi-urb
2328 * transfer. When they do, we tear down the rest of the transfer.
2330 switch (urb->status) {
2333 case -EREMOTEIO: /* short transfer */
2335 case -ENOENT: /* cancelled */
2340 usbi_dbg("device removed");
2341 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2342 goto cancel_remaining;
2344 usbi_dbg("detected endpoint stall");
2345 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2346 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2347 goto cancel_remaining;
2349 /* overflow can only ever occur in the last urb */
2350 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2351 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2352 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2359 usbi_dbg("low level error %d", urb->status);
2360 tpriv->reap_action = ERROR;
2361 goto cancel_remaining;
2363 usbi_warn(ITRANSFER_CTX(itransfer),
2364 "unrecognised urb status %d", urb->status);
2365 tpriv->reap_action = ERROR;
2366 goto cancel_remaining;
2369 /* if we're the last urb or we got less data than requested then we're
2371 if (urb_idx == tpriv->num_urbs - 1) {
2372 usbi_dbg("last URB in transfer --> complete!");
2374 } else if (urb->actual_length < urb->buffer_length) {
2375 usbi_dbg("short transfer %d/%d --> complete!",
2376 urb->actual_length, urb->buffer_length);
2377 if (tpriv->reap_action == NORMAL)
2378 tpriv->reap_action = COMPLETED_EARLY;
2383 if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2384 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2386 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2389 /* cancel remaining urbs and wait for their completion before
2390 * reporting results */
2391 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2394 usbi_mutex_unlock(&itransfer->lock);
2400 usbi_mutex_unlock(&itransfer->lock);
2401 return CANCELLED == tpriv->reap_action ?
2402 usbi_handle_transfer_cancellation(itransfer) :
2403 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2406 static int handle_iso_completion(struct usbi_transfer *itransfer,
2407 struct usbfs_urb *urb)
2409 struct libusb_transfer *transfer =
2410 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2411 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2412 int num_urbs = tpriv->num_urbs;
2415 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2417 usbi_mutex_lock(&itransfer->lock);
2418 for (i = 0; i < num_urbs; i++) {
2419 if (urb == tpriv->iso_urbs[i]) {
2425 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2426 usbi_mutex_unlock(&itransfer->lock);
2427 return LIBUSB_ERROR_NOT_FOUND;
2430 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2433 /* copy isochronous results back in */
2435 for (i = 0; i < urb->number_of_packets; i++) {
2436 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2437 struct libusb_iso_packet_descriptor *lib_desc =
2438 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2439 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2440 switch (urb_desc->status) {
2443 case -ENOENT: /* cancelled */
2448 usbi_dbg("device removed");
2449 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2452 usbi_dbg("detected endpoint stall");
2453 lib_desc->status = LIBUSB_TRANSFER_STALL;
2456 usbi_dbg("overflow error");
2457 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2465 usbi_dbg("low-level USB error %d", urb_desc->status);
2466 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2469 usbi_warn(TRANSFER_CTX(transfer),
2470 "unrecognised urb status %d", urb_desc->status);
2471 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2474 lib_desc->actual_length = urb_desc->actual_length;
2477 tpriv->num_retired++;
2479 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2480 usbi_dbg("CANCEL: urb status %d", urb->status);
2482 if (tpriv->num_retired == num_urbs) {
2483 usbi_dbg("CANCEL: last URB handled, reporting");
2484 free_iso_urbs(tpriv);
2485 if (tpriv->reap_action == CANCELLED) {
2486 usbi_mutex_unlock(&itransfer->lock);
2487 return usbi_handle_transfer_cancellation(itransfer);
2489 usbi_mutex_unlock(&itransfer->lock);
2490 return usbi_handle_transfer_completion(itransfer,
2491 LIBUSB_TRANSFER_ERROR);
2497 switch (urb->status) {
2500 case -ENOENT: /* cancelled */
2504 usbi_dbg("device removed");
2505 status = LIBUSB_TRANSFER_NO_DEVICE;
2508 usbi_warn(TRANSFER_CTX(transfer),
2509 "unrecognised urb status %d", urb->status);
2510 status = LIBUSB_TRANSFER_ERROR;
2514 /* if we're the last urb then we're done */
2515 if (urb_idx == num_urbs) {
2516 usbi_dbg("last URB in transfer --> complete!");
2517 free_iso_urbs(tpriv);
2518 usbi_mutex_unlock(&itransfer->lock);
2519 return usbi_handle_transfer_completion(itransfer, status);
2523 usbi_mutex_unlock(&itransfer->lock);
2527 static int handle_control_completion(struct usbi_transfer *itransfer,
2528 struct usbfs_urb *urb)
2530 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2533 usbi_mutex_lock(&itransfer->lock);
2534 usbi_dbg("handling completion status %d", urb->status);
2536 itransfer->transferred += urb->actual_length;
2538 if (tpriv->reap_action == CANCELLED) {
2539 if (urb->status != 0 && urb->status != -ENOENT)
2540 usbi_warn(ITRANSFER_CTX(itransfer),
2541 "cancel: unrecognised urb status %d", urb->status);
2544 usbi_mutex_unlock(&itransfer->lock);
2545 return usbi_handle_transfer_cancellation(itransfer);
2548 switch (urb->status) {
2550 status = LIBUSB_TRANSFER_COMPLETED;
2552 case -ENOENT: /* cancelled */
2553 status = LIBUSB_TRANSFER_CANCELLED;
2557 usbi_dbg("device removed");
2558 status = LIBUSB_TRANSFER_NO_DEVICE;
2561 usbi_dbg("unsupported control request");
2562 status = LIBUSB_TRANSFER_STALL;
2565 usbi_dbg("control overflow error");
2566 status = LIBUSB_TRANSFER_OVERFLOW;
2573 usbi_dbg("low-level bus error occurred");
2574 status = LIBUSB_TRANSFER_ERROR;
2577 usbi_warn(ITRANSFER_CTX(itransfer),
2578 "unrecognised urb status %d", urb->status);
2579 status = LIBUSB_TRANSFER_ERROR;
2585 usbi_mutex_unlock(&itransfer->lock);
2586 return usbi_handle_transfer_completion(itransfer, status);
2589 static int reap_for_handle(struct libusb_device_handle *handle)
2591 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2593 struct usbfs_urb *urb;
2594 struct usbi_transfer *itransfer;
2595 struct libusb_transfer *transfer;
2597 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2598 if (r == -1 && errno == EAGAIN)
2601 if (errno == ENODEV)
2602 return LIBUSB_ERROR_NO_DEVICE;
2604 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2606 return LIBUSB_ERROR_IO;
2609 itransfer = urb->usercontext;
2610 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2612 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2613 urb->actual_length);
2615 switch (transfer->type) {
2616 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2617 return handle_iso_completion(itransfer, urb);
2618 case LIBUSB_TRANSFER_TYPE_BULK:
2619 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2620 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2621 return handle_bulk_completion(itransfer, urb);
2622 case LIBUSB_TRANSFER_TYPE_CONTROL:
2623 return handle_control_completion(itransfer, urb);
2625 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2627 return LIBUSB_ERROR_OTHER;
2631 static int op_handle_events(struct libusb_context *ctx,
2632 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2637 usbi_mutex_lock(&ctx->open_devs_lock);
2638 for (i = 0; i < nfds && num_ready > 0; i++) {
2639 struct pollfd *pollfd = &fds[i];
2640 struct libusb_device_handle *handle;
2641 struct linux_device_handle_priv *hpriv = NULL;
2643 if (!pollfd->revents)
2647 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2648 hpriv = _device_handle_priv(handle);
2649 if (hpriv->fd == pollfd->fd)
2653 if (!hpriv || hpriv->fd != pollfd->fd) {
2654 usbi_err(ctx, "cannot find handle for fd %d",
2659 if (pollfd->revents & POLLERR) {
2660 /* remove the fd from the pollfd set so that it doesn't continuously
2661 * trigger an event, and flag that it has been removed so op_close()
2662 * doesn't try to remove it a second time */
2663 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2664 hpriv->fd_removed = 1;
2666 /* device will still be marked as attached if hotplug monitor thread
2667 * hasn't processed remove event yet */
2668 usbi_mutex_static_lock(&linux_hotplug_lock);
2669 if (handle->dev->attached)
2670 linux_device_disconnected(handle->dev->bus_number,
2671 handle->dev->device_address);
2672 usbi_mutex_static_unlock(&linux_hotplug_lock);
2674 if (hpriv->caps & USBFS_CAP_REAP_AFTER_DISCONNECT) {
2676 r = reap_for_handle(handle);
2680 usbi_handle_disconnect(handle);
2685 r = reap_for_handle(handle);
2687 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2695 usbi_mutex_unlock(&ctx->open_devs_lock);
2699 static int op_clock_gettime(int clk_id, struct timespec *tp)
2702 case USBI_CLOCK_MONOTONIC:
2703 return clock_gettime(monotonic_clkid, tp);
2704 case USBI_CLOCK_REALTIME:
2705 return clock_gettime(CLOCK_REALTIME, tp);
2707 return LIBUSB_ERROR_INVALID_PARAM;
2711 #ifdef USBI_TIMERFD_AVAILABLE
2712 static clockid_t op_get_timerfd_clockid(void)
2714 return monotonic_clkid;
2719 const struct usbi_os_backend usbi_backend = {
2720 .name = "Linux usbfs",
2721 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2724 .get_device_list = NULL,
2725 .hotplug_poll = op_hotplug_poll,
2726 .get_device_descriptor = op_get_device_descriptor,
2727 .get_active_config_descriptor = op_get_active_config_descriptor,
2728 .get_config_descriptor = op_get_config_descriptor,
2729 .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2733 .get_configuration = op_get_configuration,
2734 .set_configuration = op_set_configuration,
2735 .claim_interface = op_claim_interface,
2736 .release_interface = op_release_interface,
2738 .set_interface_altsetting = op_set_interface,
2739 .clear_halt = op_clear_halt,
2740 .reset_device = op_reset_device,
2742 .alloc_streams = op_alloc_streams,
2743 .free_streams = op_free_streams,
2745 .dev_mem_alloc = op_dev_mem_alloc,
2746 .dev_mem_free = op_dev_mem_free,
2748 .kernel_driver_active = op_kernel_driver_active,
2749 .detach_kernel_driver = op_detach_kernel_driver,
2750 .attach_kernel_driver = op_attach_kernel_driver,
2752 .destroy_device = op_destroy_device,
2754 .submit_transfer = op_submit_transfer,
2755 .cancel_transfer = op_cancel_transfer,
2756 .clear_transfer_priv = op_clear_transfer_priv,
2758 .handle_events = op_handle_events,
2760 .clock_gettime = op_clock_gettime,
2762 #ifdef USBI_TIMERFD_AVAILABLE
2763 .get_timerfd_clockid = op_get_timerfd_clockid,
2766 .device_priv_size = sizeof(struct linux_device_priv),
2767 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2768 .transfer_priv_size = sizeof(struct linux_transfer_priv),