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>
8 * Copyright © 2020 Chris Dickens <christopher.a.dickens@gmail.com>
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 #include "linux_usbfs.h"
35 #include <sys/ioctl.h>
37 #include <sys/utsname.h>
41 * opening a usbfs node causes the device to be resumed, so we attempt to
42 * avoid this during enumeration.
44 * sysfs allows us to read the kernel's in-memory copies of device descriptors
45 * and so forth, avoiding the need to open the device:
46 * - The binary "descriptors" file contains all config descriptors since
47 * 2.6.26, commit 217a9081d8e69026186067711131b77f0ce219ed
48 * - The binary "descriptors" file was added in 2.6.23, commit
49 * 69d42a78f935d19384d1f6e4f94b65bb162b36df, but it only contains the
50 * active config descriptors
51 * - The "busnum" file was added in 2.6.22, commit
52 * 83f7d958eab2fbc6b159ee92bf1493924e1d0f72
53 * - The "devnum" file has been present since pre-2.6.18
54 * - the "bConfigurationValue" file has been present since pre-2.6.18
56 * If we have bConfigurationValue, busnum, and devnum, then we can determine
57 * the active configuration without having to open the usbfs node in RDWR mode.
58 * The busnum file is important as that is the only way we can relate sysfs
59 * devices to usbfs nodes.
61 * If we also have all descriptors, we can obtain the device descriptor and
62 * configuration without touching usbfs at all.
65 /* endianness for multi-byte fields:
67 * Descriptors exposed by usbfs have the multi-byte fields in the device
68 * descriptor as host endian. Multi-byte fields in the other descriptors are
69 * bus-endian. The kernel documentation says otherwise, but it is wrong.
71 * In sysfs all descriptors are bus-endian.
74 #define USBDEV_PATH "/dev"
75 #define USB_DEVTMPFS_PATH "/dev/bus/usb"
77 /* use usbdev*.* device names in /dev instead of the usbfs bus directories */
78 static int usbdev_names = 0;
80 /* Linux has changed the maximum length of an individual isochronous packet
81 * over time. Initially this limit was 1,023 bytes, but Linux 2.6.18
82 * (commit 3612242e527eb47ee4756b5350f8bdf791aa5ede) increased this value to
83 * 8,192 bytes to support higher bandwidth devices. Linux 3.10
84 * (commit e2e2f0ea1c935edcf53feb4c4c8fdb4f86d57dd9) further increased this
85 * value to 49,152 bytes to support super speed devices. Linux 5.2
86 * (commit 8a1dbc8d91d3d1602282c7e6b4222c7759c916fa) even further increased
87 * this value to 98,304 bytes to support super speed plus devices.
89 static unsigned int max_iso_packet_len = 0;
91 /* is sysfs available (mounted) ? */
92 static int sysfs_available = -1;
94 /* how many times have we initted (and not exited) ? */
95 static int init_count = 0;
97 /* Serialize hotplug start/stop */
98 static usbi_mutex_static_t linux_hotplug_startstop_lock = USBI_MUTEX_INITIALIZER;
99 /* Serialize scan-devices, event-thread, and poll */
100 usbi_mutex_static_t linux_hotplug_lock = USBI_MUTEX_INITIALIZER;
102 static int linux_scan_devices(struct libusb_context *ctx);
103 static int detach_kernel_driver_and_claim(struct libusb_device_handle *, uint8_t);
105 #if !defined(HAVE_LIBUDEV)
106 static int linux_default_scan_devices(struct libusb_context *ctx);
109 struct kernel_version {
115 struct config_descriptor {
116 struct usbi_configuration_descriptor *desc;
120 struct linux_device_priv {
123 size_t descriptors_len;
124 struct config_descriptor *config_descriptors;
125 uint8_t active_config; /* cache val for !sysfs_available */
128 struct linux_device_handle_priv {
137 /* submission failed after the first URB, so await cancellation/completion
138 * of all the others */
141 /* cancelled by user or timeout */
144 /* completed multi-URB transfer in non-final URB */
147 /* one or more urbs encountered a low-level error */
151 struct linux_transfer_priv {
153 struct usbfs_urb *urbs;
154 struct usbfs_urb **iso_urbs;
157 enum reap_action reap_action;
160 enum libusb_transfer_status reap_status;
162 /* next iso packet in user-supplied transfer to be populated */
163 int iso_packet_offset;
166 static int get_usbfs_fd(struct libusb_device *dev, mode_t mode, int silent)
168 struct libusb_context *ctx = DEVICE_CTX(dev);
173 sprintf(path, USBDEV_PATH "/usbdev%u.%u",
174 dev->bus_number, dev->device_address);
176 sprintf(path, USB_DEVTMPFS_PATH "/%03u/%03u",
177 dev->bus_number, dev->device_address);
179 fd = open(path, mode | O_CLOEXEC);
181 return fd; /* Success */
183 if (errno == ENOENT) {
184 const long delay_ms = 10L;
185 const struct timespec delay_ts = { 0L, delay_ms * 1000L * 1000L };
188 usbi_err(ctx, "File doesn't exist, wait %ld ms and try again", delay_ms);
190 /* Wait 10ms for USB device path creation.*/
191 nanosleep(&delay_ts, NULL);
193 fd = open(path, mode | O_CLOEXEC);
195 return fd; /* Success */
199 usbi_err(ctx, "libusb couldn't open USB device %s, errno=%d", path, errno);
200 if (errno == EACCES && mode == O_RDWR)
201 usbi_err(ctx, "libusb requires write access to USB device nodes");
205 return LIBUSB_ERROR_ACCESS;
207 return LIBUSB_ERROR_NO_DEVICE;
208 return LIBUSB_ERROR_IO;
211 /* check dirent for a /dev/usbdev%d.%d name
212 * optionally return bus/device on success */
213 static int is_usbdev_entry(const char *name, uint8_t *bus_p, uint8_t *dev_p)
217 if (sscanf(name, "usbdev%d.%d", &busnum, &devnum) != 2)
219 if (busnum < 0 || busnum > UINT8_MAX || devnum < 0 || devnum > UINT8_MAX) {
220 usbi_dbg("invalid usbdev format '%s'", name);
224 usbi_dbg("found: %s", name);
226 *bus_p = (uint8_t)busnum;
228 *dev_p = (uint8_t)devnum;
232 static const char *find_usbfs_path(void)
236 struct dirent *entry;
238 path = USB_DEVTMPFS_PATH;
241 while ((entry = readdir(dir))) {
242 if (entry->d_name[0] == '.')
245 /* We assume if we find any files that it must be the right place */
255 /* look for /dev/usbdev*.* if the normal place fails */
259 while ((entry = readdir(dir))) {
260 if (entry->d_name[0] == '.')
263 if (is_usbdev_entry(entry->d_name, NULL, NULL)) {
264 /* found one; that's enough */
277 /* On udev based systems without any usb-devices /dev/bus/usb will not
278 * exist. So if we've not found anything and we're using udev for hotplug
279 * simply assume /dev/bus/usb rather then making libusb_init fail.
280 * Make the same assumption for Android where SELinux policies might block us
281 * from reading /dev on newer devices. */
282 #if defined(HAVE_LIBUDEV) || defined(__ANDROID__)
283 return USB_DEVTMPFS_PATH;
289 static int get_kernel_version(struct libusb_context *ctx,
290 struct kernel_version *ver)
295 if (uname(&uts) < 0) {
296 usbi_err(ctx, "uname failed, errno=%d", errno);
300 atoms = sscanf(uts.release, "%d.%d.%d", &ver->major, &ver->minor, &ver->sublevel);
302 usbi_err(ctx, "failed to parse uname release '%s'", uts.release);
309 usbi_dbg("reported kernel version is %s", uts.release);
314 static int kernel_version_ge(const struct kernel_version *ver,
315 int major, int minor, int sublevel)
317 if (ver->major > major)
319 else if (ver->major < major)
322 /* kmajor == major */
323 if (ver->minor > minor)
325 else if (ver->minor < minor)
328 /* kminor == minor */
329 if (ver->sublevel == -1)
330 return sublevel == 0;
332 return ver->sublevel >= sublevel;
335 static int op_init(struct libusb_context *ctx)
337 struct kernel_version kversion;
338 const char *usbfs_path;
341 if (get_kernel_version(ctx, &kversion) < 0)
342 return LIBUSB_ERROR_OTHER;
344 if (!kernel_version_ge(&kversion, 2, 6, 32)) {
345 usbi_err(ctx, "kernel version is too old (reported as %d.%d.%d)",
346 kversion.major, kversion.minor,
347 kversion.sublevel != -1 ? kversion.sublevel : 0);
348 return LIBUSB_ERROR_NOT_SUPPORTED;
351 usbfs_path = find_usbfs_path();
353 usbi_err(ctx, "could not find usbfs");
354 return LIBUSB_ERROR_OTHER;
357 usbi_dbg("found usbfs at %s", usbfs_path);
359 if (!max_iso_packet_len) {
360 if (kernel_version_ge(&kversion, 5, 2, 0))
361 max_iso_packet_len = 98304;
362 else if (kernel_version_ge(&kversion, 3, 10, 0))
363 max_iso_packet_len = 49152;
365 max_iso_packet_len = 8192;
368 usbi_dbg("max iso packet length is (likely) %u bytes", max_iso_packet_len);
370 if (sysfs_available == -1) {
371 struct statfs statfsbuf;
373 r = statfs(SYSFS_MOUNT_PATH, &statfsbuf);
374 if (r == 0 && statfsbuf.f_type == SYSFS_MAGIC) {
375 usbi_dbg("sysfs is available");
378 usbi_warn(ctx, "sysfs not mounted");
383 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
385 if (init_count == 0) {
386 /* start up hotplug event handler */
387 r = linux_start_event_monitor();
389 if (r == LIBUSB_SUCCESS) {
390 r = linux_scan_devices(ctx);
391 if (r == LIBUSB_SUCCESS)
393 else if (init_count == 0)
394 linux_stop_event_monitor();
396 usbi_err(ctx, "error starting hotplug event monitor");
398 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
403 static void op_exit(struct libusb_context *ctx)
406 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
407 assert(init_count != 0);
409 /* tear down event handler */
410 linux_stop_event_monitor();
412 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
415 static int linux_scan_devices(struct libusb_context *ctx)
419 usbi_mutex_static_lock(&linux_hotplug_lock);
421 #if defined(HAVE_LIBUDEV)
422 ret = linux_udev_scan_devices(ctx);
424 ret = linux_default_scan_devices(ctx);
427 usbi_mutex_static_unlock(&linux_hotplug_lock);
432 static void op_hotplug_poll(void)
434 linux_hotplug_poll();
437 static int open_sysfs_attr(struct libusb_context *ctx,
438 const char *sysfs_dir, const char *attr)
443 snprintf(filename, sizeof(filename), SYSFS_DEVICE_PATH "/%s/%s", sysfs_dir, attr);
444 fd = open(filename, O_RDONLY | O_CLOEXEC);
446 if (errno == ENOENT) {
447 /* File doesn't exist. Assume the device has been
448 disconnected (see trac ticket #70). */
449 return LIBUSB_ERROR_NO_DEVICE;
451 usbi_err(ctx, "open %s failed, errno=%d", filename, errno);
452 return LIBUSB_ERROR_IO;
458 /* Note only suitable for attributes which always read >= 0, < 0 is error */
459 static int read_sysfs_attr(struct libusb_context *ctx,
460 const char *sysfs_dir, const char *attr, int max_value, int *value_p)
462 char buf[20], *endptr;
467 fd = open_sysfs_attr(ctx, sysfs_dir, attr);
471 r = read(fd, buf, sizeof(buf));
476 return LIBUSB_ERROR_NO_DEVICE;
477 usbi_err(ctx, "attribute %s read failed, errno=%zd", attr, r);
478 return LIBUSB_ERROR_IO;
483 /* Certain attributes (e.g. bConfigurationValue) are not
484 * populated if the device is not configured. */
489 /* The kernel does *not* NULL-terminate the string, but every attribute
490 * should be terminated with a newline character. */
491 if (!isdigit(buf[0])) {
492 usbi_err(ctx, "attribute %s doesn't have numeric value?", attr);
493 return LIBUSB_ERROR_IO;
494 } else if (buf[r - 1] != '\n') {
495 usbi_err(ctx, "attribute %s doesn't end with newline?", attr);
496 return LIBUSB_ERROR_IO;
501 value = strtol(buf, &endptr, 10);
502 if (value < 0 || value > (long)max_value || errno) {
503 usbi_err(ctx, "attribute %s contains an invalid value: '%s'", attr, buf);
504 return LIBUSB_ERROR_INVALID_PARAM;
505 } else if (*endptr != '\0') {
506 /* Consider the value to be valid if the remainder is a '.'
507 * character followed by numbers. This occurs, for example,
508 * when reading the "speed" attribute for a low-speed device
510 if (*endptr == '.' && isdigit(*(endptr + 1))) {
512 while (isdigit(*endptr))
515 if (*endptr != '\0') {
516 usbi_err(ctx, "attribute %s contains an invalid value: '%s'", attr, buf);
517 return LIBUSB_ERROR_INVALID_PARAM;
521 *value_p = (int)value;
525 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
527 uint8_t busnum, devaddr;
530 ret = linux_get_device_address(ctx, 0, &busnum, &devaddr, NULL, devname, -1);
531 if (ret != LIBUSB_SUCCESS)
534 return linux_enumerate_device(ctx, busnum, devaddr, devname);
537 /* read the bConfigurationValue for a device */
538 static int sysfs_get_active_config(struct libusb_device *dev, uint8_t *config)
540 struct linux_device_priv *priv = usbi_get_device_priv(dev);
543 ret = read_sysfs_attr(DEVICE_CTX(dev), priv->sysfs_dir, "bConfigurationValue",
549 tmp = 0; /* unconfigured */
551 *config = (uint8_t)tmp;
556 int linux_get_device_address(struct libusb_context *ctx, int detached,
557 uint8_t *busnum, uint8_t *devaddr, const char *dev_node,
558 const char *sys_name, int fd)
563 usbi_dbg("getting address for device: %s detached: %d", sys_name, detached);
564 /* can't use sysfs to read the bus and device number if the
565 * device has been detached */
566 if (!sysfs_available || detached || !sys_name) {
567 if (!dev_node && fd >= 0) {
568 char *fd_path = alloca(PATH_MAX);
571 /* try to retrieve the device node from fd */
572 sprintf(proc_path, "/proc/self/fd/%d", fd);
573 r = readlink(proc_path, fd_path, PATH_MAX - 1);
581 return LIBUSB_ERROR_OTHER;
583 /* will this work with all supported kernel versions? */
584 if (!strncmp(dev_node, "/dev/bus/usb", 12))
585 sscanf(dev_node, "/dev/bus/usb/%hhu/%hhu", busnum, devaddr);
587 return LIBUSB_ERROR_OTHER;
589 return LIBUSB_SUCCESS;
592 usbi_dbg("scan %s", sys_name);
594 r = read_sysfs_attr(ctx, sys_name, "busnum", UINT8_MAX, &sysfs_val);
597 *busnum = (uint8_t)sysfs_val;
599 r = read_sysfs_attr(ctx, sys_name, "devnum", UINT8_MAX, &sysfs_val);
602 *devaddr = (uint8_t)sysfs_val;
604 usbi_dbg("bus=%u dev=%u", *busnum, *devaddr);
606 return LIBUSB_SUCCESS;
609 /* Return offset of the next config descriptor */
610 static int seek_to_next_config(struct libusb_context *ctx,
611 uint8_t *buffer, size_t len)
613 struct usbi_descriptor_header *header;
618 usbi_err(ctx, "short descriptor read %zu/2", len);
619 return LIBUSB_ERROR_IO;
622 header = (struct usbi_descriptor_header *)buffer;
623 if (header->bDescriptorType == LIBUSB_DT_CONFIG)
626 if (len < header->bLength) {
627 usbi_err(ctx, "bLength overflow by %zu bytes",
628 (size_t)header->bLength - len);
629 return LIBUSB_ERROR_IO;
632 offset += header->bLength;
633 buffer += header->bLength;
634 len -= header->bLength;
637 usbi_err(ctx, "config descriptor not found");
638 return LIBUSB_ERROR_IO;
641 static int parse_config_descriptors(struct libusb_device *dev)
643 struct libusb_context *ctx = DEVICE_CTX(dev);
644 struct linux_device_priv *priv = usbi_get_device_priv(dev);
645 struct usbi_device_descriptor *device_desc;
646 uint8_t idx, num_configs;
650 device_desc = (struct usbi_device_descriptor *)priv->descriptors;
651 num_configs = device_desc->bNumConfigurations;
653 if (num_configs == 0)
654 return 0; /* no configurations? */
656 priv->config_descriptors = malloc(num_configs * sizeof(priv->config_descriptors[0]));
657 if (!priv->config_descriptors)
658 return LIBUSB_ERROR_NO_MEM;
660 buffer = priv->descriptors + LIBUSB_DT_DEVICE_SIZE;
661 remaining = priv->descriptors_len - LIBUSB_DT_DEVICE_SIZE;
663 for (idx = 0; idx < num_configs; idx++) {
664 struct usbi_configuration_descriptor *config_desc;
667 if (remaining < LIBUSB_DT_CONFIG_SIZE) {
668 usbi_err(ctx, "short descriptor read %zu/%d",
669 remaining, LIBUSB_DT_CONFIG_SIZE);
670 return LIBUSB_ERROR_IO;
673 config_desc = (struct usbi_configuration_descriptor *)buffer;
674 if (config_desc->bDescriptorType != LIBUSB_DT_CONFIG) {
675 usbi_err(ctx, "descriptor is not a config desc (type 0x%02x)",
676 config_desc->bDescriptorType);
677 return LIBUSB_ERROR_IO;
678 } else if (config_desc->bLength < LIBUSB_DT_CONFIG_SIZE) {
679 usbi_err(ctx, "invalid descriptor bLength %u",
680 config_desc->bLength);
681 return LIBUSB_ERROR_IO;
684 config_len = libusb_le16_to_cpu(config_desc->wTotalLength);
685 if (config_len < LIBUSB_DT_CONFIG_SIZE) {
686 usbi_err(ctx, "invalid wTotalLength %u", config_len);
687 return LIBUSB_ERROR_IO;
690 if (priv->sysfs_dir) {
692 * In sysfs wTotalLength is ignored, instead the kernel returns a
693 * config descriptor with verified bLength fields, with descriptors
694 * with an invalid bLength removed.
696 uint16_t sysfs_config_len;
699 if (num_configs > 1 && idx < num_configs - 1) {
700 offset = seek_to_next_config(ctx, buffer + LIBUSB_DT_CONFIG_SIZE,
701 remaining - LIBUSB_DT_CONFIG_SIZE);
704 sysfs_config_len = (uint16_t)offset;
706 sysfs_config_len = (uint16_t)remaining;
709 if (config_len != sysfs_config_len) {
710 usbi_warn(ctx, "config length mismatch wTotalLength %u real %u",
711 config_len, sysfs_config_len);
712 config_len = sysfs_config_len;
716 * In usbfs the config descriptors are wTotalLength bytes apart,
717 * with any short reads from the device appearing as holes in the file.
719 if (config_len > remaining) {
720 usbi_warn(ctx, "short descriptor read %zu/%u", remaining, config_len);
721 config_len = (uint16_t)remaining;
725 priv->config_descriptors[idx].desc = config_desc;
726 priv->config_descriptors[idx].actual_len = config_len;
728 buffer += config_len;
729 remaining -= config_len;
732 return LIBUSB_SUCCESS;
735 static int op_get_config_descriptor_by_value(struct libusb_device *dev,
736 uint8_t value, void **buffer)
738 struct linux_device_priv *priv = usbi_get_device_priv(dev);
739 struct config_descriptor *config;
742 for (idx = 0; idx < dev->device_descriptor.bNumConfigurations; idx++) {
743 config = &priv->config_descriptors[idx];
744 if (config->desc->bConfigurationValue == value) {
745 *buffer = config->desc;
746 return (int)config->actual_len;
750 return LIBUSB_ERROR_NOT_FOUND;
753 static int op_get_active_config_descriptor(struct libusb_device *dev,
754 void *buffer, size_t len)
756 struct linux_device_priv *priv = usbi_get_device_priv(dev);
758 uint8_t active_config;
761 if (priv->sysfs_dir) {
762 r = sysfs_get_active_config(dev, &active_config);
766 /* Use cached bConfigurationValue */
767 active_config = priv->active_config;
770 if (active_config == 0) {
771 usbi_err(DEVICE_CTX(dev), "device unconfigured");
772 return LIBUSB_ERROR_NOT_FOUND;
775 r = op_get_config_descriptor_by_value(dev, active_config, &config_desc);
779 len = MIN(len, (size_t)r);
780 memcpy(buffer, config_desc, len);
784 static int op_get_config_descriptor(struct libusb_device *dev,
785 uint8_t config_index, void *buffer, size_t len)
787 struct linux_device_priv *priv = usbi_get_device_priv(dev);
788 struct config_descriptor *config;
790 if (config_index >= dev->device_descriptor.bNumConfigurations)
791 return LIBUSB_ERROR_NOT_FOUND;
793 config = &priv->config_descriptors[config_index];
794 len = MIN(len, config->actual_len);
795 memcpy(buffer, config->desc, len);
799 /* send a control message to retrieve active configuration */
800 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
802 struct linux_device_priv *priv = usbi_get_device_priv(dev);
803 uint8_t active_config = 0;
806 struct usbfs_ctrltransfer ctrl = {
807 .bmRequestType = LIBUSB_ENDPOINT_IN,
808 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
813 .data = &active_config
816 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
819 return LIBUSB_ERROR_NO_DEVICE;
821 /* we hit this error path frequently with buggy devices :( */
822 usbi_warn(DEVICE_CTX(dev), "get configuration failed, errno=%d", errno);
823 } else if (active_config == 0) {
824 /* some buggy devices have a configuration 0, but we're
825 * reaching into the corner of a corner case here, so let's
826 * not support buggy devices in these circumstances.
827 * stick to the specs: a configuration value of 0 means
829 usbi_warn(DEVICE_CTX(dev), "active cfg 0? assuming unconfigured device");
832 priv->active_config = active_config;
834 return LIBUSB_SUCCESS;
837 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
838 uint8_t devaddr, const char *sysfs_dir, int wrapped_fd)
840 struct linux_device_priv *priv = usbi_get_device_priv(dev);
841 struct libusb_context *ctx = DEVICE_CTX(dev);
846 dev->bus_number = busnum;
847 dev->device_address = devaddr;
850 priv->sysfs_dir = strdup(sysfs_dir);
851 if (!priv->sysfs_dir)
852 return LIBUSB_ERROR_NO_MEM;
854 /* Note speed can contain 1.5, in this case read_sysfs_attr()
855 will stop parsing at the '.' and return 1 */
856 if (read_sysfs_attr(ctx, sysfs_dir, "speed", INT_MAX, &speed) == 0) {
858 case 1: dev->speed = LIBUSB_SPEED_LOW; break;
859 case 12: dev->speed = LIBUSB_SPEED_FULL; break;
860 case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
861 case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
862 case 10000: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
864 usbi_warn(ctx, "unknown device speed: %d Mbps", speed);
869 /* cache descriptors in memory */
871 fd = open_sysfs_attr(ctx, sysfs_dir, "descriptors");
872 } else if (wrapped_fd < 0) {
873 fd = get_usbfs_fd(dev, O_RDONLY, 0);
876 r = lseek(fd, 0, SEEK_SET);
878 usbi_err(ctx, "lseek failed, errno=%d", errno);
879 return LIBUSB_ERROR_IO;
888 priv->descriptors = usbi_reallocf(priv->descriptors, alloc_len);
889 if (!priv->descriptors) {
890 if (fd != wrapped_fd)
892 return LIBUSB_ERROR_NO_MEM;
894 /* usbfs has holes in the file */
896 memset(priv->descriptors + priv->descriptors_len,
897 0, alloc_len - priv->descriptors_len);
898 nb = read(fd, priv->descriptors + priv->descriptors_len,
899 alloc_len - priv->descriptors_len);
901 usbi_err(ctx, "read descriptor failed, errno=%d", errno);
902 if (fd != wrapped_fd)
904 return LIBUSB_ERROR_IO;
906 priv->descriptors_len += (size_t)nb;
907 } while (priv->descriptors_len == alloc_len);
909 if (fd != wrapped_fd)
912 if (priv->descriptors_len < LIBUSB_DT_DEVICE_SIZE) {
913 usbi_err(ctx, "short descriptor read (%zu)", priv->descriptors_len);
914 return LIBUSB_ERROR_IO;
917 r = parse_config_descriptors(dev);
921 memcpy(&dev->device_descriptor, priv->descriptors, LIBUSB_DT_DEVICE_SIZE);
924 /* sysfs descriptors are in bus-endian format */
925 usbi_localize_device_descriptor(&dev->device_descriptor);
926 return LIBUSB_SUCCESS;
929 /* cache active config */
931 fd = get_usbfs_fd(dev, O_RDWR, 1);
935 /* cannot send a control message to determine the active
936 * config. just assume the first one is active. */
937 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
938 "active configuration descriptor");
939 if (priv->config_descriptors)
940 priv->active_config = priv->config_descriptors[0].desc->bConfigurationValue;
942 priv->active_config = 0; /* No config dt */
944 return LIBUSB_SUCCESS;
947 r = usbfs_get_active_config(dev, fd);
948 if (fd != wrapped_fd)
954 static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir)
956 struct libusb_context *ctx = DEVICE_CTX(dev);
957 struct libusb_device *it;
958 char *parent_sysfs_dir, *tmp;
959 int ret, add_parent = 1;
961 /* XXX -- can we figure out the topology when using usbfs? */
962 if (!sysfs_dir || !strncmp(sysfs_dir, "usb", 3)) {
963 /* either using usbfs or finding the parent of a root hub */
964 return LIBUSB_SUCCESS;
967 parent_sysfs_dir = strdup(sysfs_dir);
968 if (!parent_sysfs_dir)
969 return LIBUSB_ERROR_NO_MEM;
971 if ((tmp = strrchr(parent_sysfs_dir, '.')) ||
972 (tmp = strrchr(parent_sysfs_dir, '-'))) {
973 dev->port_number = atoi(tmp + 1);
976 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
978 free(parent_sysfs_dir);
979 return LIBUSB_SUCCESS;
982 /* is the parent a root hub? */
983 if (!strchr(parent_sysfs_dir, '-')) {
984 tmp = parent_sysfs_dir;
985 ret = asprintf(&parent_sysfs_dir, "usb%s", tmp);
988 return LIBUSB_ERROR_NO_MEM;
992 /* find the parent in the context */
993 usbi_mutex_lock(&ctx->usb_devs_lock);
994 list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device) {
995 struct linux_device_priv *priv = usbi_get_device_priv(it);
997 if (priv->sysfs_dir) {
998 if (!strcmp(priv->sysfs_dir, parent_sysfs_dir)) {
999 dev->parent_dev = libusb_ref_device(it);
1004 usbi_mutex_unlock(&ctx->usb_devs_lock);
1006 if (!dev->parent_dev && add_parent) {
1007 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1009 sysfs_scan_device(ctx, parent_sysfs_dir);
1014 usbi_dbg("dev %p (%s) has parent %p (%s) port %u", dev, sysfs_dir,
1015 dev->parent_dev, parent_sysfs_dir, dev->port_number);
1017 free(parent_sysfs_dir);
1019 return LIBUSB_SUCCESS;
1022 int linux_enumerate_device(struct libusb_context *ctx,
1023 uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1025 unsigned long session_id;
1026 struct libusb_device *dev;
1029 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1030 * will be reused. instead we should add a simple sysfs attribute with
1032 session_id = busnum << 8 | devaddr;
1033 usbi_dbg("busnum %u devaddr %u session_id %lu", busnum, devaddr, session_id);
1035 dev = usbi_get_device_by_session_id(ctx, session_id);
1037 /* device already exists in the context */
1038 usbi_dbg("session_id %lu already exists", session_id);
1039 libusb_unref_device(dev);
1040 return LIBUSB_SUCCESS;
1043 usbi_dbg("allocating new device for %u/%u (session %lu)",
1044 busnum, devaddr, session_id);
1045 dev = usbi_alloc_device(ctx, session_id);
1047 return LIBUSB_ERROR_NO_MEM;
1049 r = initialize_device(dev, busnum, devaddr, sysfs_dir, -1);
1052 r = usbi_sanitize_device(dev);
1056 r = linux_get_parent_info(dev, sysfs_dir);
1061 libusb_unref_device(dev);
1063 usbi_connect_device(dev);
1068 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1070 struct libusb_context *ctx;
1072 usbi_mutex_static_lock(&active_contexts_lock);
1073 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1074 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1076 usbi_mutex_static_unlock(&active_contexts_lock);
1079 void linux_device_disconnected(uint8_t busnum, uint8_t devaddr)
1081 struct libusb_context *ctx;
1082 struct libusb_device *dev;
1083 unsigned long session_id = busnum << 8 | devaddr;
1085 usbi_mutex_static_lock(&active_contexts_lock);
1086 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1087 dev = usbi_get_device_by_session_id(ctx, session_id);
1089 usbi_disconnect_device(dev);
1090 libusb_unref_device(dev);
1092 usbi_dbg("device not found for session %lx", session_id);
1095 usbi_mutex_static_unlock(&active_contexts_lock);
1098 #if !defined(HAVE_LIBUDEV)
1099 static int parse_u8(const char *str, uint8_t *val_p)
1105 num = strtol(str, &endptr, 10);
1106 if (num < 0 || num > UINT8_MAX || errno)
1108 if (endptr == str || *endptr != '\0')
1111 *val_p = (uint8_t)num;
1115 /* open a bus directory and adds all discovered devices to the context */
1116 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1120 struct dirent *entry;
1121 int r = LIBUSB_ERROR_IO;
1123 sprintf(dirpath, USB_DEVTMPFS_PATH "/%03u", busnum);
1124 usbi_dbg("%s", dirpath);
1125 dir = opendir(dirpath);
1127 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1128 /* FIXME: should handle valid race conditions like hub unplugged
1129 * during directory iteration - this is not an error */
1133 while ((entry = readdir(dir))) {
1136 if (entry->d_name[0] == '.')
1139 if (!parse_u8(entry->d_name, &devaddr)) {
1140 usbi_dbg("unknown dir entry %s", entry->d_name);
1144 if (linux_enumerate_device(ctx, busnum, devaddr, NULL)) {
1145 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1156 static int usbfs_get_device_list(struct libusb_context *ctx)
1158 struct dirent *entry;
1160 uint8_t busnum, devaddr;
1164 buses = opendir(USBDEV_PATH);
1166 buses = opendir(USB_DEVTMPFS_PATH);
1169 usbi_err(ctx, "opendir buses failed, errno=%d", errno);
1170 return LIBUSB_ERROR_IO;
1173 while ((entry = readdir(buses))) {
1174 if (entry->d_name[0] == '.')
1178 if (!is_usbdev_entry(entry->d_name, &busnum, &devaddr))
1181 r = linux_enumerate_device(ctx, busnum, devaddr, NULL);
1183 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1187 if (!parse_u8(entry->d_name, &busnum)) {
1188 usbi_dbg("unknown dir entry %s", entry->d_name);
1192 r = usbfs_scan_busdir(ctx, busnum);
1203 static int sysfs_get_device_list(struct libusb_context *ctx)
1205 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1206 struct dirent *entry;
1207 int num_devices = 0;
1208 int num_enumerated = 0;
1211 usbi_err(ctx, "opendir devices failed, errno=%d", errno);
1212 return LIBUSB_ERROR_IO;
1215 while ((entry = readdir(devices))) {
1216 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1217 || strchr(entry->d_name, ':'))
1222 if (sysfs_scan_device(ctx, entry->d_name)) {
1223 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1232 /* successful if at least one device was enumerated or no devices were found */
1233 if (num_enumerated || !num_devices)
1234 return LIBUSB_SUCCESS;
1236 return LIBUSB_ERROR_IO;
1239 static int linux_default_scan_devices(struct libusb_context *ctx)
1241 /* we can retrieve device list and descriptors from sysfs or usbfs.
1242 * sysfs is preferable, because if we use usbfs we end up resuming
1243 * any autosuspended USB devices. however, sysfs is not available
1244 * everywhere, so we need a usbfs fallback too.
1246 if (sysfs_available)
1247 return sysfs_get_device_list(ctx);
1249 return usbfs_get_device_list(ctx);
1253 static int initialize_handle(struct libusb_device_handle *handle, int fd)
1255 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1260 r = ioctl(fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1262 if (errno == ENOTTY)
1263 usbi_dbg("getcap not available");
1265 usbi_err(HANDLE_CTX(handle), "getcap failed, errno=%d", errno);
1266 hpriv->caps = USBFS_CAP_BULK_CONTINUATION;
1269 return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1272 static int op_wrap_sys_device(struct libusb_context *ctx,
1273 struct libusb_device_handle *handle, intptr_t sys_dev)
1275 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1276 int fd = (int)sys_dev;
1277 uint8_t busnum, devaddr;
1278 struct usbfs_connectinfo ci;
1279 struct libusb_device *dev;
1282 r = linux_get_device_address(ctx, 1, &busnum, &devaddr, NULL, NULL, fd);
1284 r = ioctl(fd, IOCTL_USBFS_CONNECTINFO, &ci);
1286 usbi_err(ctx, "connectinfo failed, errno=%d", errno);
1287 return LIBUSB_ERROR_IO;
1289 /* There is no ioctl to get the bus number. We choose 0 here
1290 * as linux starts numbering buses from 1. */
1292 devaddr = ci.devnum;
1295 /* Session id is unused as we do not add the device to the list of
1296 * connected devices. */
1297 usbi_dbg("allocating new device for fd %d", fd);
1298 dev = usbi_alloc_device(ctx, 0);
1300 return LIBUSB_ERROR_NO_MEM;
1302 r = initialize_device(dev, busnum, devaddr, NULL, fd);
1305 r = usbi_sanitize_device(dev);
1308 /* Consider the device as connected, but do not add it to the managed
1313 r = initialize_handle(handle, fd);
1318 libusb_unref_device(dev);
1322 static int op_open(struct libusb_device_handle *handle)
1326 fd = get_usbfs_fd(handle->dev, O_RDWR, 0);
1328 if (fd == LIBUSB_ERROR_NO_DEVICE) {
1329 /* device will still be marked as attached if hotplug monitor thread
1330 * hasn't processed remove event yet */
1331 usbi_mutex_static_lock(&linux_hotplug_lock);
1332 if (handle->dev->attached) {
1333 usbi_dbg("open failed with no device, but device still attached");
1334 linux_device_disconnected(handle->dev->bus_number,
1335 handle->dev->device_address);
1337 usbi_mutex_static_unlock(&linux_hotplug_lock);
1342 r = initialize_handle(handle, fd);
1349 static void op_close(struct libusb_device_handle *dev_handle)
1351 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(dev_handle);
1353 /* fd may have already been removed by POLLERR condition in op_handle_events() */
1354 if (!hpriv->fd_removed)
1355 usbi_remove_pollfd(HANDLE_CTX(dev_handle), hpriv->fd);
1356 if (!hpriv->fd_keep)
1360 static int op_get_configuration(struct libusb_device_handle *handle,
1363 struct linux_device_priv *priv = usbi_get_device_priv(handle->dev);
1366 if (priv->sysfs_dir) {
1367 r = sysfs_get_active_config(handle->dev, config);
1369 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1371 r = usbfs_get_active_config(handle->dev, hpriv->fd);
1372 if (r == LIBUSB_SUCCESS)
1373 *config = priv->active_config;
1379 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1384 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1386 struct linux_device_priv *priv = usbi_get_device_priv(handle->dev);
1387 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1389 int r = ioctl(fd, IOCTL_USBFS_SETCONFIGURATION, &config);
1392 if (errno == EINVAL)
1393 return LIBUSB_ERROR_NOT_FOUND;
1394 else if (errno == EBUSY)
1395 return LIBUSB_ERROR_BUSY;
1396 else if (errno == ENODEV)
1397 return LIBUSB_ERROR_NO_DEVICE;
1399 usbi_err(HANDLE_CTX(handle), "set configuration failed, errno=%d", errno);
1400 return LIBUSB_ERROR_OTHER;
1406 /* update our cached active config descriptor */
1407 priv->active_config = (uint8_t)config;
1409 return LIBUSB_SUCCESS;
1412 static int claim_interface(struct libusb_device_handle *handle, unsigned int iface)
1414 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1416 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTERFACE, &iface);
1419 if (errno == ENOENT)
1420 return LIBUSB_ERROR_NOT_FOUND;
1421 else if (errno == EBUSY)
1422 return LIBUSB_ERROR_BUSY;
1423 else if (errno == ENODEV)
1424 return LIBUSB_ERROR_NO_DEVICE;
1426 usbi_err(HANDLE_CTX(handle), "claim interface failed, errno=%d", errno);
1427 return LIBUSB_ERROR_OTHER;
1432 static int release_interface(struct libusb_device_handle *handle, unsigned int iface)
1434 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1436 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTERFACE, &iface);
1439 if (errno == ENODEV)
1440 return LIBUSB_ERROR_NO_DEVICE;
1442 usbi_err(HANDLE_CTX(handle), "release interface failed, errno=%d", errno);
1443 return LIBUSB_ERROR_OTHER;
1448 static int op_set_interface(struct libusb_device_handle *handle, uint8_t interface,
1451 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1453 struct usbfs_setinterface setintf;
1456 setintf.interface = interface;
1457 setintf.altsetting = altsetting;
1458 r = ioctl(fd, IOCTL_USBFS_SETINTERFACE, &setintf);
1460 if (errno == EINVAL)
1461 return LIBUSB_ERROR_NOT_FOUND;
1462 else if (errno == ENODEV)
1463 return LIBUSB_ERROR_NO_DEVICE;
1465 usbi_err(HANDLE_CTX(handle), "set interface failed, errno=%d", errno);
1466 return LIBUSB_ERROR_OTHER;
1472 static int op_clear_halt(struct libusb_device_handle *handle,
1473 unsigned char endpoint)
1475 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1477 unsigned int _endpoint = endpoint;
1478 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1481 if (errno == ENOENT)
1482 return LIBUSB_ERROR_NOT_FOUND;
1483 else if (errno == ENODEV)
1484 return LIBUSB_ERROR_NO_DEVICE;
1486 usbi_err(HANDLE_CTX(handle), "clear halt failed, errno=%d", errno);
1487 return LIBUSB_ERROR_OTHER;
1493 static int op_reset_device(struct libusb_device_handle *handle)
1495 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1500 /* Doing a device reset will cause the usbfs driver to get unbound
1501 * from any interfaces it is bound to. By voluntarily unbinding
1502 * the usbfs driver ourself, we stop the kernel from rebinding
1503 * the interface after reset (which would end up with the interface
1504 * getting bound to the in kernel driver if any). */
1505 for (i = 0; i < USB_MAXINTERFACES; i++) {
1506 if (handle->claimed_interfaces & (1UL << i))
1507 release_interface(handle, i);
1510 usbi_mutex_lock(&handle->lock);
1511 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1513 if (errno == ENODEV) {
1514 ret = LIBUSB_ERROR_NOT_FOUND;
1518 usbi_err(HANDLE_CTX(handle), "reset failed, errno=%d", errno);
1519 ret = LIBUSB_ERROR_OTHER;
1523 /* And re-claim any interfaces which were claimed before the reset */
1524 for (i = 0; i < USB_MAXINTERFACES; i++) {
1525 if (!(handle->claimed_interfaces & (1UL << i)))
1528 * A driver may have completed modprobing during
1529 * IOCTL_USBFS_RESET, and bound itself as soon as
1530 * IOCTL_USBFS_RESET released the device lock
1532 r = detach_kernel_driver_and_claim(handle, i);
1534 usbi_warn(HANDLE_CTX(handle), "failed to re-claim interface %u after reset: %s",
1535 i, libusb_error_name(r));
1536 handle->claimed_interfaces &= ~(1UL << i);
1537 ret = LIBUSB_ERROR_NOT_FOUND;
1541 usbi_mutex_unlock(&handle->lock);
1545 static int do_streams_ioctl(struct libusb_device_handle *handle, long req,
1546 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1548 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1549 int r, fd = hpriv->fd;
1550 struct usbfs_streams *streams;
1552 if (num_endpoints > 30) /* Max 15 in + 15 out eps */
1553 return LIBUSB_ERROR_INVALID_PARAM;
1555 streams = malloc(sizeof(*streams) + num_endpoints);
1557 return LIBUSB_ERROR_NO_MEM;
1559 streams->num_streams = num_streams;
1560 streams->num_eps = num_endpoints;
1561 memcpy(streams->eps, endpoints, num_endpoints);
1563 r = ioctl(fd, req, streams);
1568 if (errno == ENOTTY)
1569 return LIBUSB_ERROR_NOT_SUPPORTED;
1570 else if (errno == EINVAL)
1571 return LIBUSB_ERROR_INVALID_PARAM;
1572 else if (errno == ENODEV)
1573 return LIBUSB_ERROR_NO_DEVICE;
1575 usbi_err(HANDLE_CTX(handle), "streams-ioctl failed, errno=%d", errno);
1576 return LIBUSB_ERROR_OTHER;
1581 static int op_alloc_streams(struct libusb_device_handle *handle,
1582 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1584 return do_streams_ioctl(handle, IOCTL_USBFS_ALLOC_STREAMS,
1585 num_streams, endpoints, num_endpoints);
1588 static int op_free_streams(struct libusb_device_handle *handle,
1589 unsigned char *endpoints, int num_endpoints)
1591 return do_streams_ioctl(handle, IOCTL_USBFS_FREE_STREAMS, 0,
1592 endpoints, num_endpoints);
1595 static void *op_dev_mem_alloc(struct libusb_device_handle *handle, size_t len)
1597 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1600 buffer = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, hpriv->fd, 0);
1601 if (buffer == MAP_FAILED) {
1602 usbi_err(HANDLE_CTX(handle), "alloc dev mem failed, errno=%d", errno);
1608 static int op_dev_mem_free(struct libusb_device_handle *handle, void *buffer,
1611 if (munmap(buffer, len) != 0) {
1612 usbi_err(HANDLE_CTX(handle), "free dev mem failed, errno=%d", errno);
1613 return LIBUSB_ERROR_OTHER;
1615 return LIBUSB_SUCCESS;
1619 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1622 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
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), "get driver failed, errno=%d", errno);
1636 return LIBUSB_ERROR_OTHER;
1639 return strcmp(getdrv.driver, "usbfs") != 0;
1642 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1645 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
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"))
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), "detach failed, errno=%d", errno);
1670 return LIBUSB_ERROR_OTHER;
1676 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1679 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
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), "attach failed, errno=%d", errno);
1700 return LIBUSB_ERROR_OTHER;
1701 } else if (r == 0) {
1702 return LIBUSB_ERROR_NOT_FOUND;
1708 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle,
1711 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1712 struct usbfs_disconnect_claim dc;
1713 int r, fd = hpriv->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);
1725 return LIBUSB_ERROR_BUSY;
1727 return LIBUSB_ERROR_INVALID_PARAM;
1729 return LIBUSB_ERROR_NO_DEVICE;
1731 usbi_err(HANDLE_CTX(handle), "disconnect-and-claim failed, errno=%d", errno);
1732 return LIBUSB_ERROR_OTHER;
1735 /* Fallback code for kernels which don't support the
1736 disconnect-and-claim ioctl */
1737 r = op_detach_kernel_driver(handle, interface);
1738 if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND)
1741 return claim_interface(handle, interface);
1744 static int op_claim_interface(struct libusb_device_handle *handle, uint8_t interface)
1746 if (handle->auto_detach_kernel_driver)
1747 return detach_kernel_driver_and_claim(handle, interface);
1749 return claim_interface(handle, interface);
1752 static int op_release_interface(struct libusb_device_handle *handle, uint8_t interface)
1756 r = release_interface(handle, interface);
1760 if (handle->auto_detach_kernel_driver)
1761 op_attach_kernel_driver(handle, interface);
1766 static void op_destroy_device(struct libusb_device *dev)
1768 struct linux_device_priv *priv = usbi_get_device_priv(dev);
1770 free(priv->config_descriptors);
1771 free(priv->descriptors);
1772 free(priv->sysfs_dir);
1775 /* URBs are discarded in reverse order of submission to avoid races. */
1776 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1778 struct libusb_transfer *transfer =
1779 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1780 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
1781 struct linux_device_handle_priv *hpriv =
1782 usbi_get_device_handle_priv(transfer->dev_handle);
1784 struct usbfs_urb *urb;
1786 for (i = last_plus_one - 1; i >= first; i--) {
1787 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS)
1788 urb = tpriv->iso_urbs[i];
1790 urb = &tpriv->urbs[i];
1792 if (ioctl(hpriv->fd, IOCTL_USBFS_DISCARDURB, urb) == 0)
1795 if (errno == EINVAL) {
1796 usbi_dbg("URB not found --> assuming ready to be reaped");
1797 if (i == (last_plus_one - 1))
1798 ret = LIBUSB_ERROR_NOT_FOUND;
1799 } else if (errno == ENODEV) {
1800 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1801 ret = LIBUSB_ERROR_NO_DEVICE;
1803 usbi_warn(TRANSFER_CTX(transfer), "unrecognised discard errno %d", errno);
1804 ret = LIBUSB_ERROR_OTHER;
1810 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1814 for (i = 0; i < tpriv->num_urbs; i++) {
1815 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1822 free(tpriv->iso_urbs);
1823 tpriv->iso_urbs = NULL;
1826 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1828 struct libusb_transfer *transfer =
1829 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1830 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
1831 struct linux_device_handle_priv *hpriv =
1832 usbi_get_device_handle_priv(transfer->dev_handle);
1833 struct usbfs_urb *urbs;
1834 int is_out = IS_XFEROUT(transfer);
1835 int bulk_buffer_len, use_bulk_continuation;
1837 int last_urb_partial = 0;
1842 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1843 * around this by splitting large transfers into 16k blocks, and then
1844 * submit all urbs at once. it would be simpler to submit one urb at
1845 * a time, but there is a big performance gain doing it this way.
1847 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1848 * using arbritary large transfers can still be a bad idea though, as
1849 * the kernel needs to allocate physical contiguous memory for this,
1850 * which may fail for large buffers.
1852 * The kernel solves this problem by splitting the transfer into
1853 * blocks itself when the host-controller is scatter-gather capable
1854 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1856 * Last, there is the issue of short-transfers when splitting, for
1857 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1858 * is needed, but this is not always available.
1860 if (hpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1861 /* Good! Just submit everything in one go */
1862 bulk_buffer_len = transfer->length ? transfer->length : 1;
1863 use_bulk_continuation = 0;
1864 } else if (hpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1865 /* Split the transfers and use bulk-continuation to
1866 avoid issues with short-transfers */
1867 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1868 use_bulk_continuation = 1;
1869 } else if (hpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1870 /* Don't split, assume the kernel can alloc the buffer
1871 (otherwise the submit will fail with -ENOMEM) */
1872 bulk_buffer_len = transfer->length ? transfer->length : 1;
1873 use_bulk_continuation = 0;
1875 /* Bad, splitting without bulk-continuation, short transfers
1876 which end before the last urb will not work reliable! */
1877 /* Note we don't warn here as this is "normal" on kernels <
1878 2.6.32 and not a problem for most applications */
1879 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1880 use_bulk_continuation = 0;
1883 num_urbs = transfer->length / bulk_buffer_len;
1885 if (transfer->length == 0) {
1887 } else if ((transfer->length % bulk_buffer_len) > 0) {
1888 last_urb_partial = 1;
1891 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs, transfer->length);
1892 urbs = calloc(num_urbs, sizeof(*urbs));
1894 return LIBUSB_ERROR_NO_MEM;
1896 tpriv->num_urbs = num_urbs;
1897 tpriv->num_retired = 0;
1898 tpriv->reap_action = NORMAL;
1899 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1901 for (i = 0; i < num_urbs; i++) {
1902 struct usbfs_urb *urb = &urbs[i];
1904 urb->usercontext = itransfer;
1905 switch (transfer->type) {
1906 case LIBUSB_TRANSFER_TYPE_BULK:
1907 urb->type = USBFS_URB_TYPE_BULK;
1910 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1911 urb->type = USBFS_URB_TYPE_BULK;
1912 urb->stream_id = itransfer->stream_id;
1914 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1915 urb->type = USBFS_URB_TYPE_INTERRUPT;
1918 urb->endpoint = transfer->endpoint;
1919 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
1921 /* don't set the short not ok flag for the last URB */
1922 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
1923 urb->flags = USBFS_URB_SHORT_NOT_OK;
1925 if (i == num_urbs - 1 && last_urb_partial)
1926 urb->buffer_length = transfer->length % bulk_buffer_len;
1927 else if (transfer->length == 0)
1928 urb->buffer_length = 0;
1930 urb->buffer_length = bulk_buffer_len;
1932 if (i > 0 && use_bulk_continuation)
1933 urb->flags |= USBFS_URB_BULK_CONTINUATION;
1935 /* we have already checked that the flag is supported */
1936 if (is_out && i == num_urbs - 1 &&
1937 (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET))
1938 urb->flags |= USBFS_URB_ZERO_PACKET;
1940 r = ioctl(hpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1944 if (errno == ENODEV) {
1945 r = LIBUSB_ERROR_NO_DEVICE;
1946 } else if (errno == ENOMEM) {
1947 r = LIBUSB_ERROR_NO_MEM;
1949 usbi_err(TRANSFER_CTX(transfer), "submiturb failed, errno=%d", 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 = errno == EREMOTEIO ? 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 (tpriv->reap_action == COMPLETED_EARLY)
1988 discard_urbs(itransfer, 0, i);
1990 usbi_dbg("reporting successful submission but waiting for %d "
1991 "discards before reporting error", i);
1998 static int submit_iso_transfer(struct usbi_transfer *itransfer)
2000 struct libusb_transfer *transfer =
2001 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2002 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2003 struct linux_device_handle_priv *hpriv =
2004 usbi_get_device_handle_priv(transfer->dev_handle);
2005 struct usbfs_urb **urbs;
2006 int num_packets = transfer->num_iso_packets;
2007 int num_packets_remaining;
2010 unsigned int packet_len;
2011 unsigned int total_len = 0;
2012 unsigned char *urb_buffer = transfer->buffer;
2014 if (num_packets < 1)
2015 return LIBUSB_ERROR_INVALID_PARAM;
2017 /* usbfs places arbitrary limits on iso URBs. this limit has changed
2018 * at least three times, but we attempt to detect this limit during
2019 * init and check it here. if the kernel rejects the request due to
2020 * its size, we return an error indicating such to the user.
2022 for (i = 0; i < num_packets; i++) {
2023 packet_len = transfer->iso_packet_desc[i].length;
2025 if (packet_len > max_iso_packet_len) {
2026 usbi_warn(TRANSFER_CTX(transfer),
2027 "iso packet length of %u bytes exceeds maximum of %u bytes",
2028 packet_len, max_iso_packet_len);
2029 return LIBUSB_ERROR_INVALID_PARAM;
2032 total_len += packet_len;
2035 if (transfer->length < (int)total_len)
2036 return LIBUSB_ERROR_INVALID_PARAM;
2038 /* usbfs limits the number of iso packets per URB */
2039 num_urbs = (num_packets + (MAX_ISO_PACKETS_PER_URB - 1)) / MAX_ISO_PACKETS_PER_URB;
2041 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs, transfer->length);
2043 urbs = calloc(num_urbs, sizeof(*urbs));
2045 return LIBUSB_ERROR_NO_MEM;
2047 tpriv->iso_urbs = urbs;
2048 tpriv->num_urbs = num_urbs;
2049 tpriv->num_retired = 0;
2050 tpriv->reap_action = NORMAL;
2051 tpriv->iso_packet_offset = 0;
2053 /* allocate + initialize each URB with the correct number of packets */
2054 num_packets_remaining = num_packets;
2055 for (i = 0, j = 0; i < num_urbs; i++) {
2056 int num_packets_in_urb = MIN(num_packets_remaining, MAX_ISO_PACKETS_PER_URB);
2057 struct usbfs_urb *urb;
2061 alloc_size = sizeof(*urb)
2062 + (num_packets_in_urb * sizeof(struct usbfs_iso_packet_desc));
2063 urb = calloc(1, alloc_size);
2065 free_iso_urbs(tpriv);
2066 return LIBUSB_ERROR_NO_MEM;
2070 /* populate packet lengths */
2071 for (k = 0; k < num_packets_in_urb; j++, k++) {
2072 packet_len = transfer->iso_packet_desc[j].length;
2073 urb->buffer_length += packet_len;
2074 urb->iso_frame_desc[k].length = packet_len;
2077 urb->usercontext = itransfer;
2078 urb->type = USBFS_URB_TYPE_ISO;
2079 /* FIXME: interface for non-ASAP data? */
2080 urb->flags = USBFS_URB_ISO_ASAP;
2081 urb->endpoint = transfer->endpoint;
2082 urb->number_of_packets = num_packets_in_urb;
2083 urb->buffer = urb_buffer;
2085 urb_buffer += urb->buffer_length;
2086 num_packets_remaining -= num_packets_in_urb;
2090 for (i = 0; i < num_urbs; i++) {
2091 int r = ioctl(hpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
2096 if (errno == ENODEV) {
2097 r = LIBUSB_ERROR_NO_DEVICE;
2098 } else if (errno == EINVAL) {
2099 usbi_warn(TRANSFER_CTX(transfer), "submiturb failed, transfer too large");
2100 r = LIBUSB_ERROR_INVALID_PARAM;
2101 } else if (errno == EMSGSIZE) {
2102 usbi_warn(TRANSFER_CTX(transfer), "submiturb failed, iso packet length too large");
2103 r = LIBUSB_ERROR_INVALID_PARAM;
2105 usbi_err(TRANSFER_CTX(transfer), "submiturb failed, errno=%d", errno);
2106 r = LIBUSB_ERROR_IO;
2109 /* if the first URB submission fails, we can simply free up and
2110 * return failure immediately. */
2112 usbi_dbg("first URB failed, easy peasy");
2113 free_iso_urbs(tpriv);
2117 /* if it's not the first URB that failed, the situation is a bit
2118 * tricky. we must discard all previous URBs. there are
2120 * - discarding is asynchronous - discarded urbs will be reaped
2121 * later. the user must not have freed the transfer when the
2122 * discarded URBs are reaped, otherwise libusb will be using
2124 * - the earlier URBs may have completed successfully and we do
2125 * not want to throw away any data.
2126 * so, in this case we discard all the previous URBs BUT we report
2127 * that the transfer was submitted successfully. then later when
2128 * the final discard completes we can report error to the user.
2130 tpriv->reap_action = SUBMIT_FAILED;
2132 /* The URBs we haven't submitted yet we count as already
2134 tpriv->num_retired = num_urbs - i;
2135 discard_urbs(itransfer, 0, i);
2137 usbi_dbg("reporting successful submission but waiting for %d "
2138 "discards before reporting error", i);
2145 static int submit_control_transfer(struct usbi_transfer *itransfer)
2147 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2148 struct libusb_transfer *transfer =
2149 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2150 struct linux_device_handle_priv *hpriv =
2151 usbi_get_device_handle_priv(transfer->dev_handle);
2152 struct usbfs_urb *urb;
2155 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
2156 return LIBUSB_ERROR_INVALID_PARAM;
2158 urb = calloc(1, sizeof(*urb));
2160 return LIBUSB_ERROR_NO_MEM;
2162 tpriv->num_urbs = 1;
2163 tpriv->reap_action = NORMAL;
2165 urb->usercontext = itransfer;
2166 urb->type = USBFS_URB_TYPE_CONTROL;
2167 urb->endpoint = transfer->endpoint;
2168 urb->buffer = transfer->buffer;
2169 urb->buffer_length = transfer->length;
2171 r = ioctl(hpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2175 if (errno == ENODEV)
2176 return LIBUSB_ERROR_NO_DEVICE;
2178 usbi_err(TRANSFER_CTX(transfer), "submiturb failed, errno=%d", errno);
2179 return LIBUSB_ERROR_IO;
2184 static int op_submit_transfer(struct usbi_transfer *itransfer)
2186 struct libusb_transfer *transfer =
2187 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2189 switch (transfer->type) {
2190 case LIBUSB_TRANSFER_TYPE_CONTROL:
2191 return submit_control_transfer(itransfer);
2192 case LIBUSB_TRANSFER_TYPE_BULK:
2193 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2194 return submit_bulk_transfer(itransfer);
2195 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2196 return submit_bulk_transfer(itransfer);
2197 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2198 return submit_iso_transfer(itransfer);
2200 usbi_err(TRANSFER_CTX(transfer), "unknown transfer type %u", transfer->type);
2201 return LIBUSB_ERROR_INVALID_PARAM;
2205 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2207 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2208 struct libusb_transfer *transfer =
2209 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2213 return LIBUSB_ERROR_NOT_FOUND;
2215 r = discard_urbs(itransfer, 0, tpriv->num_urbs);
2219 switch (transfer->type) {
2220 case LIBUSB_TRANSFER_TYPE_BULK:
2221 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2222 if (tpriv->reap_action == ERROR)
2224 /* else, fall through */
2226 tpriv->reap_action = CANCELLED;
2232 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2234 struct libusb_transfer *transfer =
2235 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2236 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2238 switch (transfer->type) {
2239 case LIBUSB_TRANSFER_TYPE_CONTROL:
2240 case LIBUSB_TRANSFER_TYPE_BULK:
2241 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2242 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2248 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2249 if (tpriv->iso_urbs) {
2250 free_iso_urbs(tpriv);
2251 tpriv->iso_urbs = NULL;
2255 usbi_err(TRANSFER_CTX(transfer), "unknown transfer type %u", transfer->type);
2259 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2260 struct usbfs_urb *urb)
2262 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2263 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2264 int urb_idx = urb - tpriv->urbs;
2266 usbi_mutex_lock(&itransfer->lock);
2267 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2268 urb_idx + 1, tpriv->num_urbs);
2270 tpriv->num_retired++;
2272 if (tpriv->reap_action != NORMAL) {
2273 /* cancelled, submit_fail, or completed early */
2274 usbi_dbg("abnormal reap: urb status %d", urb->status);
2276 /* even though we're in the process of cancelling, it's possible that
2277 * we may receive some data in these URBs that we don't want to lose.
2279 * 1. while the kernel is cancelling all the packets that make up an
2280 * URB, a few of them might complete. so we get back a successful
2281 * cancellation *and* some data.
2282 * 2. we receive a short URB which marks the early completion condition,
2283 * so we start cancelling the remaining URBs. however, we're too
2284 * slow and another URB completes (or at least completes partially).
2285 * (this can't happen since we always use BULK_CONTINUATION.)
2287 * When this happens, our objectives are not to lose any "surplus" data,
2288 * and also to stick it at the end of the previously-received data
2289 * (closing any holes), so that libusb reports the total amount of
2290 * transferred data and presents it in a contiguous chunk.
2292 if (urb->actual_length > 0) {
2293 unsigned char *target = transfer->buffer + itransfer->transferred;
2295 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2296 if (urb->buffer != target) {
2297 usbi_dbg("moving surplus data from offset %zu to offset %zu",
2298 (unsigned char *)urb->buffer - transfer->buffer,
2299 target - transfer->buffer);
2300 memmove(target, urb->buffer, urb->actual_length);
2302 itransfer->transferred += urb->actual_length;
2305 if (tpriv->num_retired == tpriv->num_urbs) {
2306 usbi_dbg("abnormal reap: last URB handled, reporting");
2307 if (tpriv->reap_action != COMPLETED_EARLY &&
2308 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2309 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2315 itransfer->transferred += urb->actual_length;
2317 /* Many of these errors can occur on *any* urb of a multi-urb
2318 * transfer. When they do, we tear down the rest of the transfer.
2320 switch (urb->status) {
2323 case -EREMOTEIO: /* short transfer */
2325 case -ENOENT: /* cancelled */
2330 usbi_dbg("device removed");
2331 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2332 goto cancel_remaining;
2334 usbi_dbg("detected endpoint stall");
2335 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2336 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2337 goto cancel_remaining;
2339 /* overflow can only ever occur in the last urb */
2340 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2341 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2342 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2349 usbi_dbg("low-level bus error %d", urb->status);
2350 tpriv->reap_action = ERROR;
2351 goto cancel_remaining;
2353 usbi_warn(ITRANSFER_CTX(itransfer), "unrecognised urb status %d", urb->status);
2354 tpriv->reap_action = ERROR;
2355 goto cancel_remaining;
2358 /* if we've reaped all urbs or we got less data than requested then we're
2360 if (tpriv->num_retired == tpriv->num_urbs) {
2361 usbi_dbg("all URBs in transfer reaped --> complete!");
2363 } else if (urb->actual_length < urb->buffer_length) {
2364 usbi_dbg("short transfer %d/%d --> complete!",
2365 urb->actual_length, urb->buffer_length);
2366 if (tpriv->reap_action == NORMAL)
2367 tpriv->reap_action = COMPLETED_EARLY;
2373 if (tpriv->reap_action == ERROR && tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2374 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2376 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2379 /* cancel remaining urbs and wait for their completion before
2380 * reporting results */
2381 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2384 usbi_mutex_unlock(&itransfer->lock);
2390 usbi_mutex_unlock(&itransfer->lock);
2391 return tpriv->reap_action == CANCELLED ?
2392 usbi_handle_transfer_cancellation(itransfer) :
2393 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2396 static int handle_iso_completion(struct usbi_transfer *itransfer,
2397 struct usbfs_urb *urb)
2399 struct libusb_transfer *transfer =
2400 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2401 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2402 int num_urbs = tpriv->num_urbs;
2405 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2407 usbi_mutex_lock(&itransfer->lock);
2408 for (i = 0; i < num_urbs; i++) {
2409 if (urb == tpriv->iso_urbs[i]) {
2415 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2416 usbi_mutex_unlock(&itransfer->lock);
2417 return LIBUSB_ERROR_NOT_FOUND;
2420 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2423 /* copy isochronous results back in */
2425 for (i = 0; i < urb->number_of_packets; i++) {
2426 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2427 struct libusb_iso_packet_descriptor *lib_desc =
2428 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2430 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2431 switch (urb_desc->status) {
2434 case -ENOENT: /* cancelled */
2439 usbi_dbg("packet %d - device removed", i);
2440 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2443 usbi_dbg("packet %d - detected endpoint stall", i);
2444 lib_desc->status = LIBUSB_TRANSFER_STALL;
2447 usbi_dbg("packet %d - overflow error", i);
2448 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2456 usbi_dbg("packet %d - low-level USB error %d", i, urb_desc->status);
2457 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2460 usbi_warn(TRANSFER_CTX(transfer), "packet %d - unrecognised urb status %d",
2461 i, urb_desc->status);
2462 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2465 lib_desc->actual_length = urb_desc->actual_length;
2468 tpriv->num_retired++;
2470 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2471 usbi_dbg("CANCEL: urb status %d", urb->status);
2473 if (tpriv->num_retired == num_urbs) {
2474 usbi_dbg("CANCEL: last URB handled, reporting");
2475 free_iso_urbs(tpriv);
2476 if (tpriv->reap_action == CANCELLED) {
2477 usbi_mutex_unlock(&itransfer->lock);
2478 return usbi_handle_transfer_cancellation(itransfer);
2480 usbi_mutex_unlock(&itransfer->lock);
2481 return usbi_handle_transfer_completion(itransfer, LIBUSB_TRANSFER_ERROR);
2487 switch (urb->status) {
2490 case -ENOENT: /* cancelled */
2494 usbi_dbg("device removed");
2495 status = LIBUSB_TRANSFER_NO_DEVICE;
2498 usbi_warn(TRANSFER_CTX(transfer), "unrecognised urb status %d", urb->status);
2499 status = LIBUSB_TRANSFER_ERROR;
2503 /* if we've reaped all urbs then we're done */
2504 if (tpriv->num_retired == num_urbs) {
2505 usbi_dbg("all URBs in transfer reaped --> complete!");
2506 free_iso_urbs(tpriv);
2507 usbi_mutex_unlock(&itransfer->lock);
2508 return usbi_handle_transfer_completion(itransfer, status);
2512 usbi_mutex_unlock(&itransfer->lock);
2516 static int handle_control_completion(struct usbi_transfer *itransfer,
2517 struct usbfs_urb *urb)
2519 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2522 usbi_mutex_lock(&itransfer->lock);
2523 usbi_dbg("handling completion status %d", urb->status);
2525 itransfer->transferred += urb->actual_length;
2527 if (tpriv->reap_action == CANCELLED) {
2528 if (urb->status && urb->status != -ENOENT)
2529 usbi_warn(ITRANSFER_CTX(itransfer), "cancel: unrecognised urb status %d",
2533 usbi_mutex_unlock(&itransfer->lock);
2534 return usbi_handle_transfer_cancellation(itransfer);
2537 switch (urb->status) {
2539 status = LIBUSB_TRANSFER_COMPLETED;
2541 case -ENOENT: /* cancelled */
2542 status = LIBUSB_TRANSFER_CANCELLED;
2546 usbi_dbg("device removed");
2547 status = LIBUSB_TRANSFER_NO_DEVICE;
2550 usbi_dbg("unsupported control request");
2551 status = LIBUSB_TRANSFER_STALL;
2554 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2555 status = LIBUSB_TRANSFER_OVERFLOW;
2562 usbi_dbg("low-level bus error %d", urb->status);
2563 status = LIBUSB_TRANSFER_ERROR;
2566 usbi_warn(ITRANSFER_CTX(itransfer), "unrecognised urb status %d", urb->status);
2567 status = LIBUSB_TRANSFER_ERROR;
2573 usbi_mutex_unlock(&itransfer->lock);
2574 return usbi_handle_transfer_completion(itransfer, status);
2577 static int reap_for_handle(struct libusb_device_handle *handle)
2579 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
2581 struct usbfs_urb *urb = NULL;
2582 struct usbi_transfer *itransfer;
2583 struct libusb_transfer *transfer;
2585 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2587 if (errno == EAGAIN)
2589 if (errno == ENODEV)
2590 return LIBUSB_ERROR_NO_DEVICE;
2592 usbi_err(HANDLE_CTX(handle), "reap failed, errno=%d", errno);
2593 return LIBUSB_ERROR_IO;
2596 itransfer = urb->usercontext;
2597 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2599 usbi_dbg("urb type=%u status=%d transferred=%d", urb->type, urb->status, urb->actual_length);
2601 switch (transfer->type) {
2602 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2603 return handle_iso_completion(itransfer, urb);
2604 case LIBUSB_TRANSFER_TYPE_BULK:
2605 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2606 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2607 return handle_bulk_completion(itransfer, urb);
2608 case LIBUSB_TRANSFER_TYPE_CONTROL:
2609 return handle_control_completion(itransfer, urb);
2611 usbi_err(HANDLE_CTX(handle), "unrecognised transfer type %u", transfer->type);
2612 return LIBUSB_ERROR_OTHER;
2616 static int op_handle_events(struct libusb_context *ctx,
2617 struct pollfd *fds, usbi_nfds_t nfds, int num_ready)
2622 usbi_mutex_lock(&ctx->open_devs_lock);
2623 for (n = 0; n < nfds && num_ready > 0; n++) {
2624 struct pollfd *pollfd = &fds[n];
2625 struct libusb_device_handle *handle;
2626 struct linux_device_handle_priv *hpriv = NULL;
2628 if (!pollfd->revents)
2632 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2633 hpriv = usbi_get_device_handle_priv(handle);
2634 if (hpriv->fd == pollfd->fd)
2638 if (!hpriv || hpriv->fd != pollfd->fd) {
2639 usbi_err(ctx, "cannot find handle for fd %d",
2644 if (pollfd->revents & POLLERR) {
2645 /* remove the fd from the pollfd set so that it doesn't continuously
2646 * trigger an event, and flag that it has been removed so op_close()
2647 * doesn't try to remove it a second time */
2648 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2649 hpriv->fd_removed = 1;
2651 /* device will still be marked as attached if hotplug monitor thread
2652 * hasn't processed remove event yet */
2653 usbi_mutex_static_lock(&linux_hotplug_lock);
2654 if (handle->dev->attached)
2655 linux_device_disconnected(handle->dev->bus_number,
2656 handle->dev->device_address);
2657 usbi_mutex_static_unlock(&linux_hotplug_lock);
2659 if (hpriv->caps & USBFS_CAP_REAP_AFTER_DISCONNECT) {
2661 r = reap_for_handle(handle);
2665 usbi_handle_disconnect(handle);
2670 r = reap_for_handle(handle);
2672 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2680 usbi_mutex_unlock(&ctx->open_devs_lock);
2684 const struct usbi_os_backend usbi_backend = {
2685 .name = "Linux usbfs",
2686 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2689 .hotplug_poll = op_hotplug_poll,
2690 .get_active_config_descriptor = op_get_active_config_descriptor,
2691 .get_config_descriptor = op_get_config_descriptor,
2692 .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2694 .wrap_sys_device = op_wrap_sys_device,
2697 .get_configuration = op_get_configuration,
2698 .set_configuration = op_set_configuration,
2699 .claim_interface = op_claim_interface,
2700 .release_interface = op_release_interface,
2702 .set_interface_altsetting = op_set_interface,
2703 .clear_halt = op_clear_halt,
2704 .reset_device = op_reset_device,
2706 .alloc_streams = op_alloc_streams,
2707 .free_streams = op_free_streams,
2709 .dev_mem_alloc = op_dev_mem_alloc,
2710 .dev_mem_free = op_dev_mem_free,
2712 .kernel_driver_active = op_kernel_driver_active,
2713 .detach_kernel_driver = op_detach_kernel_driver,
2714 .attach_kernel_driver = op_attach_kernel_driver,
2716 .destroy_device = op_destroy_device,
2718 .submit_transfer = op_submit_transfer,
2719 .cancel_transfer = op_cancel_transfer,
2720 .clear_transfer_priv = op_clear_transfer_priv,
2722 .handle_events = op_handle_events,
2724 .device_priv_size = sizeof(struct linux_device_priv),
2725 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2726 .transfer_priv_size = sizeof(struct linux_transfer_priv),