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>
42 * opening a usbfs node causes the device to be resumed, so we attempt to
43 * avoid this during enumeration.
45 * sysfs allows us to read the kernel's in-memory copies of device descriptors
46 * and so forth, avoiding the need to open the device:
47 * - The binary "descriptors" file contains all config descriptors since
48 * 2.6.26, commit 217a9081d8e69026186067711131b77f0ce219ed
49 * - The binary "descriptors" file was added in 2.6.23, commit
50 * 69d42a78f935d19384d1f6e4f94b65bb162b36df, but it only contains the
51 * active config descriptors
52 * - The "busnum" file was added in 2.6.22, commit
53 * 83f7d958eab2fbc6b159ee92bf1493924e1d0f72
54 * - The "devnum" file has been present since pre-2.6.18
55 * - the "bConfigurationValue" file has been present since pre-2.6.18
57 * If we have bConfigurationValue, busnum, and devnum, then we can determine
58 * the active configuration without having to open the usbfs node in RDWR mode.
59 * The busnum file is important as that is the only way we can relate sysfs
60 * devices to usbfs nodes.
62 * If we also have all descriptors, we can obtain the device descriptor and
63 * configuration without touching usbfs at all.
66 /* endianness for multi-byte fields:
68 * Descriptors exposed by usbfs have the multi-byte fields in the device
69 * descriptor as host endian. Multi-byte fields in the other descriptors are
70 * bus-endian. The kernel documentation says otherwise, but it is wrong.
72 * In sysfs all descriptors are bus-endian.
75 #define USBDEV_PATH "/dev"
76 #define USB_DEVTMPFS_PATH "/dev/bus/usb"
78 /* use usbdev*.* device names in /dev instead of the usbfs bus directories */
79 static int usbdev_names = 0;
81 /* Linux has changed the maximum length of an individual isochronous packet
82 * over time. Initially this limit was 1,023 bytes, but Linux 2.6.18
83 * (commit 3612242e527eb47ee4756b5350f8bdf791aa5ede) increased this value to
84 * 8,192 bytes to support higher bandwidth devices. Linux 3.10
85 * (commit e2e2f0ea1c935edcf53feb4c4c8fdb4f86d57dd9) further increased this
86 * value to 49,152 bytes to support super speed devices. Linux 5.2
87 * (commit 8a1dbc8d91d3d1602282c7e6b4222c7759c916fa) even further increased
88 * this value to 98,304 bytes to support super speed plus devices.
90 static unsigned int max_iso_packet_len = 0;
92 /* is sysfs available (mounted) ? */
93 static int sysfs_available = -1;
95 /* how many times have we initted (and not exited) ? */
96 static int init_count = 0;
99 /* have no authority to operate usb device directly */
100 static int weak_authority = 0;
103 /* Serialize hotplug start/stop */
104 static usbi_mutex_static_t linux_hotplug_startstop_lock = USBI_MUTEX_INITIALIZER;
105 /* Serialize scan-devices, event-thread, and poll */
106 usbi_mutex_static_t linux_hotplug_lock = USBI_MUTEX_INITIALIZER;
108 static int linux_scan_devices(struct libusb_context *ctx);
109 static int detach_kernel_driver_and_claim(struct libusb_device_handle *, uint8_t);
111 #if !defined(HAVE_LIBUDEV)
112 static int linux_default_scan_devices(struct libusb_context *ctx);
115 struct kernel_version {
121 struct config_descriptor {
122 struct usbi_configuration_descriptor *desc;
126 struct linux_device_priv {
129 size_t descriptors_len;
130 struct config_descriptor *config_descriptors;
131 uint8_t active_config; /* cache val for !sysfs_available */
134 struct linux_device_handle_priv {
143 /* submission failed after the first URB, so await cancellation/completion
144 * of all the others */
147 /* cancelled by user or timeout */
150 /* completed multi-URB transfer in non-final URB */
153 /* one or more urbs encountered a low-level error */
157 struct linux_transfer_priv {
159 struct usbfs_urb *urbs;
160 struct usbfs_urb **iso_urbs;
163 enum reap_action reap_action;
166 enum libusb_transfer_status reap_status;
168 /* next iso packet in user-supplied transfer to be populated */
169 int iso_packet_offset;
172 static int get_usbfs_fd(struct libusb_device *dev, mode_t mode, int silent)
174 struct libusb_context *ctx = DEVICE_CTX(dev);
179 sprintf(path, USBDEV_PATH "/usbdev%u.%u",
180 dev->bus_number, dev->device_address);
182 sprintf(path, USB_DEVTMPFS_PATH "/%03u/%03u",
183 dev->bus_number, dev->device_address);
185 fd = open(path, mode | O_CLOEXEC);
187 return fd; /* Success */
189 if (errno == ENOENT) {
190 const long delay_ms = 10L;
191 const struct timespec delay_ts = { 0L, delay_ms * 1000L * 1000L };
194 usbi_err(ctx, "File doesn't exist, wait %ld ms and try again", delay_ms);
196 /* Wait 10ms for USB device path creation.*/
197 nanosleep(&delay_ts, NULL);
199 fd = open(path, mode | O_CLOEXEC);
201 return fd; /* Success */
205 usbi_err(ctx, "libusb couldn't open USB device %s, errno=%d", path, errno);
206 if (errno == EACCES && mode == O_RDWR)
207 usbi_err(ctx, "libusb requires write access to USB device nodes");
211 return LIBUSB_ERROR_ACCESS;
213 return LIBUSB_ERROR_NO_DEVICE;
214 return LIBUSB_ERROR_IO;
217 /* check dirent for a /dev/usbdev%d.%d name
218 * optionally return bus/device on success */
219 static int is_usbdev_entry(const char *name, uint8_t *bus_p, uint8_t *dev_p)
223 if (sscanf(name, "usbdev%d.%d", &busnum, &devnum) != 2)
225 if (busnum < 0 || busnum > UINT8_MAX || devnum < 0 || devnum > UINT8_MAX) {
226 usbi_dbg("invalid usbdev format '%s'", name);
230 usbi_dbg("found: %s", name);
232 *bus_p = (uint8_t)busnum;
234 *dev_p = (uint8_t)devnum;
238 static const char *find_usbfs_path(void)
242 struct dirent *entry;
244 path = USB_DEVTMPFS_PATH;
247 while ((entry = readdir(dir))) {
248 if (entry->d_name[0] == '.')
251 /* We assume if we find any files that it must be the right place */
261 /* look for /dev/usbdev*.* if the normal place fails */
265 while ((entry = readdir(dir))) {
266 if (entry->d_name[0] == '.')
269 if (is_usbdev_entry(entry->d_name, NULL, NULL)) {
270 /* found one; that's enough */
283 /* On udev based systems without any usb-devices /dev/bus/usb will not
284 * exist. So if we've not found anything and we're using udev for hotplug
285 * simply assume /dev/bus/usb rather then making libusb_init fail.
286 * Make the same assumption for Android where SELinux policies might block us
287 * from reading /dev on newer devices. */
288 #if defined(HAVE_LIBUDEV) || defined(__ANDROID__)
289 return USB_DEVTMPFS_PATH;
295 static int get_kernel_version(struct libusb_context *ctx,
296 struct kernel_version *ver)
301 if (uname(&uts) < 0) {
302 usbi_err(ctx, "uname failed, errno=%d", errno);
306 atoms = sscanf(uts.release, "%d.%d.%d", &ver->major, &ver->minor, &ver->sublevel);
308 usbi_err(ctx, "failed to parse uname release '%s'", uts.release);
315 usbi_dbg("reported kernel version is %s", uts.release);
320 static int kernel_version_ge(const struct kernel_version *ver,
321 int major, int minor, int sublevel)
323 if (ver->major > major)
325 else if (ver->major < major)
328 /* kmajor == major */
329 if (ver->minor > minor)
331 else if (ver->minor < minor)
334 /* kminor == minor */
335 if (ver->sublevel == -1)
336 return sublevel == 0;
338 return ver->sublevel >= sublevel;
341 static int op_init(struct libusb_context *ctx)
343 struct kernel_version kversion;
344 const char *usbfs_path;
347 if (get_kernel_version(ctx, &kversion) < 0)
348 return LIBUSB_ERROR_OTHER;
350 if (!kernel_version_ge(&kversion, 2, 6, 32)) {
351 usbi_err(ctx, "kernel version is too old (reported as %d.%d.%d)",
352 kversion.major, kversion.minor,
353 kversion.sublevel != -1 ? kversion.sublevel : 0);
354 return LIBUSB_ERROR_NOT_SUPPORTED;
357 usbfs_path = find_usbfs_path();
359 usbi_err(ctx, "could not find usbfs");
360 return LIBUSB_ERROR_OTHER;
363 usbi_dbg("found usbfs at %s", usbfs_path);
365 if (!max_iso_packet_len) {
366 if (kernel_version_ge(&kversion, 5, 2, 0))
367 max_iso_packet_len = 98304;
368 else if (kernel_version_ge(&kversion, 3, 10, 0))
369 max_iso_packet_len = 49152;
371 max_iso_packet_len = 8192;
374 usbi_dbg("max iso packet length is (likely) %u bytes", max_iso_packet_len);
376 if (sysfs_available == -1) {
377 struct statfs statfsbuf;
379 r = statfs(SYSFS_MOUNT_PATH, &statfsbuf);
380 if (r == 0 && statfsbuf.f_type == SYSFS_MAGIC) {
381 usbi_dbg("sysfs is available");
384 usbi_warn(ctx, "sysfs not mounted");
390 if (weak_authority) {
391 return LIBUSB_SUCCESS;
395 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
397 if (init_count == 0) {
398 /* start up hotplug event handler */
399 r = linux_start_event_monitor();
401 if (r == LIBUSB_SUCCESS) {
402 r = linux_scan_devices(ctx);
403 if (r == LIBUSB_SUCCESS)
405 else if (init_count == 0)
406 linux_stop_event_monitor();
408 usbi_err(ctx, "error starting hotplug event monitor");
410 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
415 static void op_exit(struct libusb_context *ctx)
420 if (weak_authority) {
425 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
426 assert(init_count != 0);
428 /* tear down event handler */
429 linux_stop_event_monitor();
431 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
434 static int op_set_option(struct libusb_context *ctx, enum libusb_option option, va_list ap)
440 if (option == LIBUSB_OPTION_WEAK_AUTHORITY) {
441 usbi_dbg("set libusb has weak authority");
443 return LIBUSB_SUCCESS;
449 return LIBUSB_ERROR_NOT_SUPPORTED;
452 static int linux_scan_devices(struct libusb_context *ctx)
456 usbi_mutex_static_lock(&linux_hotplug_lock);
458 #if defined(HAVE_LIBUDEV)
459 ret = linux_udev_scan_devices(ctx);
461 ret = linux_default_scan_devices(ctx);
464 usbi_mutex_static_unlock(&linux_hotplug_lock);
469 static void op_hotplug_poll(void)
471 linux_hotplug_poll();
474 static int open_sysfs_attr(struct libusb_context *ctx,
475 const char *sysfs_dir, const char *attr)
480 snprintf(filename, sizeof(filename), SYSFS_DEVICE_PATH "/%s/%s", sysfs_dir, attr);
481 fd = open(filename, O_RDONLY | O_CLOEXEC);
483 if (errno == ENOENT) {
484 /* File doesn't exist. Assume the device has been
485 disconnected (see trac ticket #70). */
486 return LIBUSB_ERROR_NO_DEVICE;
488 usbi_err(ctx, "open %s failed, errno=%d", filename, errno);
489 return LIBUSB_ERROR_IO;
495 /* Note only suitable for attributes which always read >= 0, < 0 is error */
496 static int read_sysfs_attr(struct libusb_context *ctx,
497 const char *sysfs_dir, const char *attr, int max_value, int *value_p)
499 char buf[20], *endptr;
504 fd = open_sysfs_attr(ctx, sysfs_dir, attr);
508 r = read(fd, buf, sizeof(buf));
513 return LIBUSB_ERROR_NO_DEVICE;
514 usbi_err(ctx, "attribute %s read failed, errno=%zd", attr, r);
515 return LIBUSB_ERROR_IO;
520 /* Certain attributes (e.g. bConfigurationValue) are not
521 * populated if the device is not configured. */
526 /* The kernel does *not* NULL-terminate the string, but every attribute
527 * should be terminated with a newline character. */
528 if (!isdigit(buf[0])) {
529 usbi_err(ctx, "attribute %s doesn't have numeric value?", attr);
530 return LIBUSB_ERROR_IO;
531 } else if (buf[r - 1] != '\n') {
532 usbi_err(ctx, "attribute %s doesn't end with newline?", attr);
533 return LIBUSB_ERROR_IO;
538 value = strtol(buf, &endptr, 10);
539 if (value < 0 || value > (long)max_value || errno) {
540 usbi_err(ctx, "attribute %s contains an invalid value: '%s'", attr, buf);
541 return LIBUSB_ERROR_INVALID_PARAM;
542 } else if (*endptr != '\0') {
543 /* Consider the value to be valid if the remainder is a '.'
544 * character followed by numbers. This occurs, for example,
545 * when reading the "speed" attribute for a low-speed device
547 if (*endptr == '.' && isdigit(*(endptr + 1))) {
549 while (isdigit(*endptr))
552 if (*endptr != '\0') {
553 usbi_err(ctx, "attribute %s contains an invalid value: '%s'", attr, buf);
554 return LIBUSB_ERROR_INVALID_PARAM;
558 *value_p = (int)value;
562 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
564 uint8_t busnum, devaddr;
567 ret = linux_get_device_address(ctx, 0, &busnum, &devaddr, NULL, devname, -1);
568 if (ret != LIBUSB_SUCCESS)
571 return linux_enumerate_device(ctx, busnum, devaddr, devname);
574 /* read the bConfigurationValue for a device */
575 static int sysfs_get_active_config(struct libusb_device *dev, uint8_t *config)
577 struct linux_device_priv *priv = usbi_get_device_priv(dev);
580 ret = read_sysfs_attr(DEVICE_CTX(dev), priv->sysfs_dir, "bConfigurationValue",
586 tmp = 0; /* unconfigured */
588 *config = (uint8_t)tmp;
593 int linux_get_device_address(struct libusb_context *ctx, int detached,
594 uint8_t *busnum, uint8_t *devaddr, const char *dev_node,
595 const char *sys_name, int fd)
600 usbi_dbg("getting address for device: %s detached: %d", sys_name, detached);
601 /* can't use sysfs to read the bus and device number if the
602 * device has been detached */
603 if (!sysfs_available || detached || !sys_name) {
604 if (!dev_node && fd >= 0) {
605 char *fd_path = alloca(PATH_MAX);
608 /* try to retrieve the device node from fd */
609 sprintf(proc_path, "/proc/self/fd/%d", fd);
610 r = readlink(proc_path, fd_path, PATH_MAX - 1);
618 return LIBUSB_ERROR_OTHER;
620 /* will this work with all supported kernel versions? */
621 if (!strncmp(dev_node, "/dev/bus/usb", 12))
622 sscanf(dev_node, "/dev/bus/usb/%hhu/%hhu", busnum, devaddr);
624 return LIBUSB_ERROR_OTHER;
626 return LIBUSB_SUCCESS;
629 usbi_dbg("scan %s", sys_name);
631 r = read_sysfs_attr(ctx, sys_name, "busnum", UINT8_MAX, &sysfs_val);
634 *busnum = (uint8_t)sysfs_val;
636 r = read_sysfs_attr(ctx, sys_name, "devnum", UINT8_MAX, &sysfs_val);
639 *devaddr = (uint8_t)sysfs_val;
641 usbi_dbg("bus=%u dev=%u", *busnum, *devaddr);
643 return LIBUSB_SUCCESS;
646 /* Return offset of the next config descriptor */
647 static int seek_to_next_config(struct libusb_context *ctx,
648 uint8_t *buffer, size_t len)
650 struct usbi_descriptor_header *header;
653 /* Start seeking past the config descriptor */
654 offset = LIBUSB_DT_CONFIG_SIZE;
655 buffer += LIBUSB_DT_CONFIG_SIZE;
656 len -= LIBUSB_DT_CONFIG_SIZE;
660 usbi_err(ctx, "short descriptor read %zu/2", len);
661 return LIBUSB_ERROR_IO;
664 header = (struct usbi_descriptor_header *)buffer;
665 if (header->bDescriptorType == LIBUSB_DT_CONFIG)
668 if (len < header->bLength) {
669 usbi_err(ctx, "bLength overflow by %zu bytes",
670 (size_t)header->bLength - len);
671 return LIBUSB_ERROR_IO;
674 offset += header->bLength;
675 buffer += header->bLength;
676 len -= header->bLength;
679 usbi_err(ctx, "config descriptor not found");
680 return LIBUSB_ERROR_IO;
683 static int parse_config_descriptors(struct libusb_device *dev)
685 struct libusb_context *ctx = DEVICE_CTX(dev);
686 struct linux_device_priv *priv = usbi_get_device_priv(dev);
687 struct usbi_device_descriptor *device_desc;
688 uint8_t idx, num_configs;
692 device_desc = priv->descriptors;
693 num_configs = device_desc->bNumConfigurations;
695 if (num_configs == 0)
696 return 0; /* no configurations? */
698 priv->config_descriptors = malloc(num_configs * sizeof(priv->config_descriptors[0]));
699 if (!priv->config_descriptors)
700 return LIBUSB_ERROR_NO_MEM;
702 buffer = (uint8_t *)priv->descriptors + LIBUSB_DT_DEVICE_SIZE;
703 remaining = priv->descriptors_len - LIBUSB_DT_DEVICE_SIZE;
705 for (idx = 0; idx < num_configs; idx++) {
706 struct usbi_configuration_descriptor *config_desc;
709 if (remaining < LIBUSB_DT_CONFIG_SIZE) {
710 usbi_err(ctx, "short descriptor read %zu/%d",
711 remaining, LIBUSB_DT_CONFIG_SIZE);
712 return LIBUSB_ERROR_IO;
715 config_desc = (struct usbi_configuration_descriptor *)buffer;
716 if (config_desc->bDescriptorType != LIBUSB_DT_CONFIG) {
717 usbi_err(ctx, "descriptor is not a config desc (type 0x%02x)",
718 config_desc->bDescriptorType);
719 return LIBUSB_ERROR_IO;
720 } else if (config_desc->bLength < LIBUSB_DT_CONFIG_SIZE) {
721 usbi_err(ctx, "invalid descriptor bLength %u",
722 config_desc->bLength);
723 return LIBUSB_ERROR_IO;
726 config_len = libusb_le16_to_cpu(config_desc->wTotalLength);
727 if (config_len < LIBUSB_DT_CONFIG_SIZE) {
728 usbi_err(ctx, "invalid wTotalLength %u", config_len);
729 return LIBUSB_ERROR_IO;
732 if (priv->sysfs_dir) {
734 * In sysfs wTotalLength is ignored, instead the kernel returns a
735 * config descriptor with verified bLength fields, with descriptors
736 * with an invalid bLength removed.
738 uint16_t sysfs_config_len;
741 if (num_configs > 1 && idx < num_configs - 1) {
742 offset = seek_to_next_config(ctx, buffer, remaining);
745 sysfs_config_len = (uint16_t)offset;
747 sysfs_config_len = (uint16_t)remaining;
750 if (config_len != sysfs_config_len) {
751 usbi_warn(ctx, "config length mismatch wTotalLength %u real %u",
752 config_len, sysfs_config_len);
753 config_len = sysfs_config_len;
757 * In usbfs the config descriptors are wTotalLength bytes apart,
758 * with any short reads from the device appearing as holes in the file.
760 if (config_len > remaining) {
761 usbi_warn(ctx, "short descriptor read %zu/%u", remaining, config_len);
762 config_len = (uint16_t)remaining;
766 priv->config_descriptors[idx].desc = config_desc;
767 priv->config_descriptors[idx].actual_len = config_len;
769 buffer += config_len;
770 remaining -= config_len;
773 return LIBUSB_SUCCESS;
776 static int op_get_config_descriptor_by_value(struct libusb_device *dev,
777 uint8_t value, void **buffer)
779 struct linux_device_priv *priv = usbi_get_device_priv(dev);
780 struct config_descriptor *config;
783 for (idx = 0; idx < dev->device_descriptor.bNumConfigurations; idx++) {
784 config = &priv->config_descriptors[idx];
785 if (config->desc->bConfigurationValue == value) {
786 *buffer = config->desc;
787 return (int)config->actual_len;
791 return LIBUSB_ERROR_NOT_FOUND;
794 static int op_get_active_config_descriptor(struct libusb_device *dev,
795 void *buffer, size_t len)
797 struct linux_device_priv *priv = usbi_get_device_priv(dev);
799 uint8_t active_config;
802 if (priv->sysfs_dir) {
803 r = sysfs_get_active_config(dev, &active_config);
807 /* Use cached bConfigurationValue */
808 active_config = priv->active_config;
811 if (active_config == 0) {
812 usbi_err(DEVICE_CTX(dev), "device unconfigured");
813 return LIBUSB_ERROR_NOT_FOUND;
816 r = op_get_config_descriptor_by_value(dev, active_config, &config_desc);
820 len = MIN(len, (size_t)r);
821 memcpy(buffer, config_desc, len);
825 static int op_get_config_descriptor(struct libusb_device *dev,
826 uint8_t config_index, void *buffer, size_t len)
828 struct linux_device_priv *priv = usbi_get_device_priv(dev);
829 struct config_descriptor *config;
831 if (config_index >= dev->device_descriptor.bNumConfigurations)
832 return LIBUSB_ERROR_NOT_FOUND;
834 config = &priv->config_descriptors[config_index];
835 len = MIN(len, config->actual_len);
836 memcpy(buffer, config->desc, len);
840 /* send a control message to retrieve active configuration */
841 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
843 struct linux_device_priv *priv = usbi_get_device_priv(dev);
844 uint8_t active_config = 0;
847 struct usbfs_ctrltransfer ctrl = {
848 .bmRequestType = LIBUSB_ENDPOINT_IN,
849 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
854 .data = &active_config
857 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
860 return LIBUSB_ERROR_NO_DEVICE;
862 /* we hit this error path frequently with buggy devices :( */
863 usbi_warn(DEVICE_CTX(dev), "get configuration failed, errno=%d", errno);
864 } else if (active_config == 0) {
865 /* some buggy devices have a configuration 0, but we're
866 * reaching into the corner of a corner case here, so let's
867 * not support buggy devices in these circumstances.
868 * stick to the specs: a configuration value of 0 means
870 usbi_warn(DEVICE_CTX(dev), "active cfg 0? assuming unconfigured device");
873 priv->active_config = active_config;
875 return LIBUSB_SUCCESS;
878 static enum libusb_speed usbfs_get_speed(struct libusb_context *ctx, int fd)
882 r = ioctl(fd, IOCTL_USBFS_GET_SPEED, NULL);
884 case USBFS_SPEED_UNKNOWN: return LIBUSB_SPEED_UNKNOWN;
885 case USBFS_SPEED_LOW: return LIBUSB_SPEED_LOW;
886 case USBFS_SPEED_FULL: return LIBUSB_SPEED_FULL;
887 case USBFS_SPEED_HIGH: return LIBUSB_SPEED_HIGH;
888 case USBFS_SPEED_WIRELESS: return LIBUSB_SPEED_HIGH;
889 case USBFS_SPEED_SUPER: return LIBUSB_SPEED_SUPER;
890 case USBFS_SPEED_SUPER_PLUS: return LIBUSB_SPEED_SUPER_PLUS;
892 usbi_warn(ctx, "Error getting device speed: %d", r);
895 return LIBUSB_SPEED_UNKNOWN;
898 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
899 uint8_t devaddr, const char *sysfs_dir, int wrapped_fd)
901 struct linux_device_priv *priv = usbi_get_device_priv(dev);
902 struct libusb_context *ctx = DEVICE_CTX(dev);
907 dev->bus_number = busnum;
908 dev->device_address = devaddr;
911 priv->sysfs_dir = strdup(sysfs_dir);
912 if (!priv->sysfs_dir)
913 return LIBUSB_ERROR_NO_MEM;
915 /* Note speed can contain 1.5, in this case read_sysfs_attr()
916 will stop parsing at the '.' and return 1 */
917 if (read_sysfs_attr(ctx, sysfs_dir, "speed", INT_MAX, &speed) == 0) {
919 case 1: dev->speed = LIBUSB_SPEED_LOW; break;
920 case 12: dev->speed = LIBUSB_SPEED_FULL; break;
921 case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
922 case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
923 case 10000: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
925 usbi_warn(ctx, "unknown device speed: %d Mbps", speed);
928 } else if (wrapped_fd >= 0) {
929 dev->speed = usbfs_get_speed(ctx, wrapped_fd);
932 /* cache descriptors in memory */
934 fd = open_sysfs_attr(ctx, sysfs_dir, "descriptors");
935 } else if (wrapped_fd < 0) {
936 fd = get_usbfs_fd(dev, O_RDONLY, 0);
939 r = lseek(fd, 0, SEEK_SET);
941 usbi_err(ctx, "lseek failed, errno=%d", errno);
942 return LIBUSB_ERROR_IO;
950 const size_t desc_read_length = 256;
953 alloc_len += desc_read_length;
954 priv->descriptors = usbi_reallocf(priv->descriptors, alloc_len);
955 if (!priv->descriptors) {
956 if (fd != wrapped_fd)
958 return LIBUSB_ERROR_NO_MEM;
960 read_ptr = (uint8_t *)priv->descriptors + priv->descriptors_len;
961 /* usbfs has holes in the file */
963 memset(read_ptr, 0, desc_read_length);
964 nb = read(fd, read_ptr, desc_read_length);
966 usbi_err(ctx, "read descriptor failed, errno=%d", errno);
967 if (fd != wrapped_fd)
969 return LIBUSB_ERROR_IO;
971 priv->descriptors_len += (size_t)nb;
972 } while (priv->descriptors_len == alloc_len);
974 if (fd != wrapped_fd)
977 if (priv->descriptors_len < LIBUSB_DT_DEVICE_SIZE) {
978 usbi_err(ctx, "short descriptor read (%zu)", priv->descriptors_len);
979 return LIBUSB_ERROR_IO;
982 r = parse_config_descriptors(dev);
986 memcpy(&dev->device_descriptor, priv->descriptors, LIBUSB_DT_DEVICE_SIZE);
989 /* sysfs descriptors are in bus-endian format */
990 usbi_localize_device_descriptor(&dev->device_descriptor);
991 return LIBUSB_SUCCESS;
994 /* cache active config */
996 fd = get_usbfs_fd(dev, O_RDWR, 1);
1000 /* cannot send a control message to determine the active
1001 * config. just assume the first one is active. */
1002 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
1003 "active configuration descriptor");
1004 if (priv->config_descriptors)
1005 priv->active_config = priv->config_descriptors[0].desc->bConfigurationValue;
1007 priv->active_config = 0; /* No config dt */
1009 return LIBUSB_SUCCESS;
1012 r = usbfs_get_active_config(dev, fd);
1013 if (fd != wrapped_fd)
1019 static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir)
1021 struct libusb_context *ctx = DEVICE_CTX(dev);
1022 struct libusb_device *it;
1023 char *parent_sysfs_dir, *tmp;
1024 int ret, add_parent = 1;
1026 /* XXX -- can we figure out the topology when using usbfs? */
1027 if (!sysfs_dir || !strncmp(sysfs_dir, "usb", 3)) {
1028 /* either using usbfs or finding the parent of a root hub */
1029 return LIBUSB_SUCCESS;
1032 parent_sysfs_dir = strdup(sysfs_dir);
1033 if (!parent_sysfs_dir)
1034 return LIBUSB_ERROR_NO_MEM;
1036 if ((tmp = strrchr(parent_sysfs_dir, '.')) ||
1037 (tmp = strrchr(parent_sysfs_dir, '-'))) {
1038 dev->port_number = atoi(tmp + 1);
1041 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
1043 free(parent_sysfs_dir);
1044 return LIBUSB_SUCCESS;
1047 /* is the parent a root hub? */
1048 if (!strchr(parent_sysfs_dir, '-')) {
1049 tmp = parent_sysfs_dir;
1050 ret = asprintf(&parent_sysfs_dir, "usb%s", tmp);
1053 return LIBUSB_ERROR_NO_MEM;
1057 /* find the parent in the context */
1058 usbi_mutex_lock(&ctx->usb_devs_lock);
1059 for_each_device(ctx, it) {
1060 struct linux_device_priv *priv = usbi_get_device_priv(it);
1062 if (priv->sysfs_dir) {
1063 if (!strcmp(priv->sysfs_dir, parent_sysfs_dir)) {
1064 dev->parent_dev = libusb_ref_device(it);
1069 usbi_mutex_unlock(&ctx->usb_devs_lock);
1071 if (!dev->parent_dev && add_parent) {
1072 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1074 sysfs_scan_device(ctx, parent_sysfs_dir);
1079 usbi_dbg("dev %p (%s) has parent %p (%s) port %u", dev, sysfs_dir,
1080 dev->parent_dev, parent_sysfs_dir, dev->port_number);
1082 free(parent_sysfs_dir);
1084 return LIBUSB_SUCCESS;
1087 int linux_enumerate_device(struct libusb_context *ctx,
1088 uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1090 unsigned long session_id;
1091 struct libusb_device *dev;
1094 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1095 * will be reused. instead we should add a simple sysfs attribute with
1097 session_id = busnum << 8 | devaddr;
1098 usbi_dbg("busnum %u devaddr %u session_id %lu", busnum, devaddr, session_id);
1100 dev = usbi_get_device_by_session_id(ctx, session_id);
1102 /* device already exists in the context */
1103 usbi_dbg("session_id %lu already exists", session_id);
1104 libusb_unref_device(dev);
1105 return LIBUSB_SUCCESS;
1108 usbi_dbg("allocating new device for %u/%u (session %lu)",
1109 busnum, devaddr, session_id);
1110 dev = usbi_alloc_device(ctx, session_id);
1112 return LIBUSB_ERROR_NO_MEM;
1114 r = initialize_device(dev, busnum, devaddr, sysfs_dir, -1);
1117 r = usbi_sanitize_device(dev);
1121 r = linux_get_parent_info(dev, sysfs_dir);
1126 libusb_unref_device(dev);
1128 usbi_connect_device(dev);
1133 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1135 struct libusb_context *ctx;
1137 usbi_mutex_static_lock(&active_contexts_lock);
1138 for_each_context(ctx) {
1139 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1141 usbi_mutex_static_unlock(&active_contexts_lock);
1144 void linux_device_disconnected(uint8_t busnum, uint8_t devaddr)
1146 struct libusb_context *ctx;
1147 struct libusb_device *dev;
1148 unsigned long session_id = busnum << 8 | devaddr;
1150 usbi_mutex_static_lock(&active_contexts_lock);
1151 for_each_context(ctx) {
1152 dev = usbi_get_device_by_session_id(ctx, session_id);
1154 usbi_disconnect_device(dev);
1155 libusb_unref_device(dev);
1157 usbi_dbg("device not found for session %lx", session_id);
1160 usbi_mutex_static_unlock(&active_contexts_lock);
1163 #if !defined(HAVE_LIBUDEV)
1164 static int parse_u8(const char *str, uint8_t *val_p)
1170 num = strtol(str, &endptr, 10);
1171 if (num < 0 || num > UINT8_MAX || errno)
1173 if (endptr == str || *endptr != '\0')
1176 *val_p = (uint8_t)num;
1180 /* open a bus directory and adds all discovered devices to the context */
1181 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1185 struct dirent *entry;
1186 int r = LIBUSB_ERROR_IO;
1188 sprintf(dirpath, USB_DEVTMPFS_PATH "/%03u", busnum);
1189 usbi_dbg("%s", dirpath);
1190 dir = opendir(dirpath);
1192 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1193 /* FIXME: should handle valid race conditions like hub unplugged
1194 * during directory iteration - this is not an error */
1198 while ((entry = readdir(dir))) {
1201 if (entry->d_name[0] == '.')
1204 if (!parse_u8(entry->d_name, &devaddr)) {
1205 usbi_dbg("unknown dir entry %s", entry->d_name);
1209 if (linux_enumerate_device(ctx, busnum, devaddr, NULL)) {
1210 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1221 static int usbfs_get_device_list(struct libusb_context *ctx)
1223 struct dirent *entry;
1225 uint8_t busnum, devaddr;
1229 buses = opendir(USBDEV_PATH);
1231 buses = opendir(USB_DEVTMPFS_PATH);
1234 usbi_err(ctx, "opendir buses failed, errno=%d", errno);
1235 return LIBUSB_ERROR_IO;
1238 while ((entry = readdir(buses))) {
1239 if (entry->d_name[0] == '.')
1243 if (!is_usbdev_entry(entry->d_name, &busnum, &devaddr))
1246 r = linux_enumerate_device(ctx, busnum, devaddr, NULL);
1248 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1252 if (!parse_u8(entry->d_name, &busnum)) {
1253 usbi_dbg("unknown dir entry %s", entry->d_name);
1257 r = usbfs_scan_busdir(ctx, busnum);
1268 static int sysfs_get_device_list(struct libusb_context *ctx)
1270 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1271 struct dirent *entry;
1272 int num_devices = 0;
1273 int num_enumerated = 0;
1276 usbi_err(ctx, "opendir devices failed, errno=%d", errno);
1277 return LIBUSB_ERROR_IO;
1280 while ((entry = readdir(devices))) {
1281 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1282 || strchr(entry->d_name, ':'))
1287 if (sysfs_scan_device(ctx, entry->d_name)) {
1288 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1297 /* successful if at least one device was enumerated or no devices were found */
1298 if (num_enumerated || !num_devices)
1299 return LIBUSB_SUCCESS;
1301 return LIBUSB_ERROR_IO;
1304 static int linux_default_scan_devices(struct libusb_context *ctx)
1306 /* we can retrieve device list and descriptors from sysfs or usbfs.
1307 * sysfs is preferable, because if we use usbfs we end up resuming
1308 * any autosuspended USB devices. however, sysfs is not available
1309 * everywhere, so we need a usbfs fallback too.
1311 if (sysfs_available)
1312 return sysfs_get_device_list(ctx);
1314 return usbfs_get_device_list(ctx);
1318 static int initialize_handle(struct libusb_device_handle *handle, int fd)
1320 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1325 r = ioctl(fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1327 if (errno == ENOTTY)
1328 usbi_dbg("getcap not available");
1330 usbi_err(HANDLE_CTX(handle), "getcap failed, errno=%d", errno);
1331 hpriv->caps = USBFS_CAP_BULK_CONTINUATION;
1334 return usbi_add_event_source(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1337 static int op_wrap_sys_device(struct libusb_context *ctx,
1338 struct libusb_device_handle *handle, intptr_t sys_dev)
1340 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1341 int fd = (int)sys_dev;
1342 uint8_t busnum, devaddr;
1343 struct usbfs_connectinfo ci;
1344 struct libusb_device *dev;
1347 r = linux_get_device_address(ctx, 1, &busnum, &devaddr, NULL, NULL, fd);
1349 r = ioctl(fd, IOCTL_USBFS_CONNECTINFO, &ci);
1351 usbi_err(ctx, "connectinfo failed, errno=%d", errno);
1352 return LIBUSB_ERROR_IO;
1354 /* There is no ioctl to get the bus number. We choose 0 here
1355 * as linux starts numbering buses from 1. */
1357 devaddr = ci.devnum;
1360 /* Session id is unused as we do not add the device to the list of
1361 * connected devices. */
1362 usbi_dbg("allocating new device for fd %d", fd);
1363 dev = usbi_alloc_device(ctx, 0);
1365 return LIBUSB_ERROR_NO_MEM;
1367 r = initialize_device(dev, busnum, devaddr, NULL, fd);
1370 r = usbi_sanitize_device(dev);
1373 /* Consider the device as connected, but do not add it to the managed
1375 usbi_atomic_store(&dev->attached, 1);
1378 r = initialize_handle(handle, fd);
1383 libusb_unref_device(dev);
1387 static int op_open(struct libusb_device_handle *handle)
1391 fd = get_usbfs_fd(handle->dev, O_RDWR, 0);
1393 if (fd == LIBUSB_ERROR_NO_DEVICE) {
1394 /* device will still be marked as attached if hotplug monitor thread
1395 * hasn't processed remove event yet */
1396 usbi_mutex_static_lock(&linux_hotplug_lock);
1397 if (usbi_atomic_load(&handle->dev->attached)) {
1398 usbi_dbg("open failed with no device, but device still attached");
1399 linux_device_disconnected(handle->dev->bus_number,
1400 handle->dev->device_address);
1402 usbi_mutex_static_unlock(&linux_hotplug_lock);
1407 r = initialize_handle(handle, fd);
1414 static void op_close(struct libusb_device_handle *dev_handle)
1416 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(dev_handle);
1418 /* fd may have already been removed by POLLERR condition in op_handle_events() */
1419 if (!hpriv->fd_removed)
1420 usbi_remove_event_source(HANDLE_CTX(dev_handle), hpriv->fd);
1421 if (!hpriv->fd_keep)
1425 static int op_get_configuration(struct libusb_device_handle *handle,
1428 struct linux_device_priv *priv = usbi_get_device_priv(handle->dev);
1431 if (priv->sysfs_dir) {
1432 r = sysfs_get_active_config(handle->dev, config);
1434 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1436 r = usbfs_get_active_config(handle->dev, hpriv->fd);
1437 if (r == LIBUSB_SUCCESS)
1438 *config = priv->active_config;
1444 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1449 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1451 struct linux_device_priv *priv = usbi_get_device_priv(handle->dev);
1452 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1454 int r = ioctl(fd, IOCTL_USBFS_SETCONFIGURATION, &config);
1457 if (errno == EINVAL)
1458 return LIBUSB_ERROR_NOT_FOUND;
1459 else if (errno == EBUSY)
1460 return LIBUSB_ERROR_BUSY;
1461 else if (errno == ENODEV)
1462 return LIBUSB_ERROR_NO_DEVICE;
1464 usbi_err(HANDLE_CTX(handle), "set configuration failed, errno=%d", errno);
1465 return LIBUSB_ERROR_OTHER;
1471 /* update our cached active config descriptor */
1472 priv->active_config = (uint8_t)config;
1474 return LIBUSB_SUCCESS;
1477 static int claim_interface(struct libusb_device_handle *handle, unsigned int iface)
1479 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1481 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTERFACE, &iface);
1484 if (errno == ENOENT)
1485 return LIBUSB_ERROR_NOT_FOUND;
1486 else if (errno == EBUSY)
1487 return LIBUSB_ERROR_BUSY;
1488 else if (errno == ENODEV)
1489 return LIBUSB_ERROR_NO_DEVICE;
1491 usbi_err(HANDLE_CTX(handle), "claim interface failed, errno=%d", errno);
1492 return LIBUSB_ERROR_OTHER;
1497 static int release_interface(struct libusb_device_handle *handle, unsigned int iface)
1499 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1501 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTERFACE, &iface);
1504 if (errno == ENODEV)
1505 return LIBUSB_ERROR_NO_DEVICE;
1507 usbi_err(HANDLE_CTX(handle), "release interface failed, errno=%d", errno);
1508 return LIBUSB_ERROR_OTHER;
1513 static int op_set_interface(struct libusb_device_handle *handle, uint8_t interface,
1516 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1518 struct usbfs_setinterface setintf;
1521 setintf.interface = interface;
1522 setintf.altsetting = altsetting;
1523 r = ioctl(fd, IOCTL_USBFS_SETINTERFACE, &setintf);
1525 if (errno == EINVAL)
1526 return LIBUSB_ERROR_NOT_FOUND;
1527 else if (errno == ENODEV)
1528 return LIBUSB_ERROR_NO_DEVICE;
1530 usbi_err(HANDLE_CTX(handle), "set interface failed, errno=%d", errno);
1531 return LIBUSB_ERROR_OTHER;
1537 static int op_clear_halt(struct libusb_device_handle *handle,
1538 unsigned char endpoint)
1540 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1542 unsigned int _endpoint = endpoint;
1543 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1546 if (errno == ENOENT)
1547 return LIBUSB_ERROR_NOT_FOUND;
1548 else if (errno == ENODEV)
1549 return LIBUSB_ERROR_NO_DEVICE;
1551 usbi_err(HANDLE_CTX(handle), "clear halt failed, errno=%d", errno);
1552 return LIBUSB_ERROR_OTHER;
1558 static int op_reset_device(struct libusb_device_handle *handle)
1560 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1565 /* Doing a device reset will cause the usbfs driver to get unbound
1566 * from any interfaces it is bound to. By voluntarily unbinding
1567 * the usbfs driver ourself, we stop the kernel from rebinding
1568 * the interface after reset (which would end up with the interface
1569 * getting bound to the in kernel driver if any). */
1570 for (i = 0; i < USB_MAXINTERFACES; i++) {
1571 if (handle->claimed_interfaces & (1UL << i))
1572 release_interface(handle, i);
1575 usbi_mutex_lock(&handle->lock);
1576 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1578 if (errno == ENODEV) {
1579 ret = LIBUSB_ERROR_NOT_FOUND;
1583 usbi_err(HANDLE_CTX(handle), "reset failed, errno=%d", errno);
1584 ret = LIBUSB_ERROR_OTHER;
1588 /* And re-claim any interfaces which were claimed before the reset */
1589 for (i = 0; i < USB_MAXINTERFACES; i++) {
1590 if (!(handle->claimed_interfaces & (1UL << i)))
1593 * A driver may have completed modprobing during
1594 * IOCTL_USBFS_RESET, and bound itself as soon as
1595 * IOCTL_USBFS_RESET released the device lock
1597 r = detach_kernel_driver_and_claim(handle, i);
1599 usbi_warn(HANDLE_CTX(handle), "failed to re-claim interface %u after reset: %s",
1600 i, libusb_error_name(r));
1601 handle->claimed_interfaces &= ~(1UL << i);
1602 ret = LIBUSB_ERROR_NOT_FOUND;
1606 usbi_mutex_unlock(&handle->lock);
1610 static int do_streams_ioctl(struct libusb_device_handle *handle, long req,
1611 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1613 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1614 int r, fd = hpriv->fd;
1615 struct usbfs_streams *streams;
1617 if (num_endpoints > 30) /* Max 15 in + 15 out eps */
1618 return LIBUSB_ERROR_INVALID_PARAM;
1620 streams = malloc(sizeof(*streams) + num_endpoints);
1622 return LIBUSB_ERROR_NO_MEM;
1624 streams->num_streams = num_streams;
1625 streams->num_eps = num_endpoints;
1626 memcpy(streams->eps, endpoints, num_endpoints);
1628 r = ioctl(fd, req, streams);
1633 if (errno == ENOTTY)
1634 return LIBUSB_ERROR_NOT_SUPPORTED;
1635 else if (errno == EINVAL)
1636 return LIBUSB_ERROR_INVALID_PARAM;
1637 else if (errno == ENODEV)
1638 return LIBUSB_ERROR_NO_DEVICE;
1640 usbi_err(HANDLE_CTX(handle), "streams-ioctl failed, errno=%d", errno);
1641 return LIBUSB_ERROR_OTHER;
1646 static int op_alloc_streams(struct libusb_device_handle *handle,
1647 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1649 return do_streams_ioctl(handle, IOCTL_USBFS_ALLOC_STREAMS,
1650 num_streams, endpoints, num_endpoints);
1653 static int op_free_streams(struct libusb_device_handle *handle,
1654 unsigned char *endpoints, int num_endpoints)
1656 return do_streams_ioctl(handle, IOCTL_USBFS_FREE_STREAMS, 0,
1657 endpoints, num_endpoints);
1660 static void *op_dev_mem_alloc(struct libusb_device_handle *handle, size_t len)
1662 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1665 buffer = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, hpriv->fd, 0);
1666 if (buffer == MAP_FAILED) {
1667 usbi_err(HANDLE_CTX(handle), "alloc dev mem failed, errno=%d", errno);
1673 static int op_dev_mem_free(struct libusb_device_handle *handle, void *buffer,
1676 if (munmap(buffer, len) != 0) {
1677 usbi_err(HANDLE_CTX(handle), "free dev mem failed, errno=%d", errno);
1678 return LIBUSB_ERROR_OTHER;
1680 return LIBUSB_SUCCESS;
1684 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1687 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1689 struct usbfs_getdriver getdrv;
1692 getdrv.interface = interface;
1693 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1695 if (errno == ENODATA)
1697 else if (errno == ENODEV)
1698 return LIBUSB_ERROR_NO_DEVICE;
1700 usbi_err(HANDLE_CTX(handle), "get driver failed, errno=%d", errno);
1701 return LIBUSB_ERROR_OTHER;
1704 return strcmp(getdrv.driver, "usbfs") != 0;
1707 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1710 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1712 struct usbfs_ioctl command;
1713 struct usbfs_getdriver getdrv;
1716 command.ifno = interface;
1717 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1718 command.data = NULL;
1720 getdrv.interface = interface;
1721 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1722 if (r == 0 && !strcmp(getdrv.driver, "usbfs"))
1723 return LIBUSB_ERROR_NOT_FOUND;
1725 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1727 if (errno == ENODATA)
1728 return LIBUSB_ERROR_NOT_FOUND;
1729 else if (errno == EINVAL)
1730 return LIBUSB_ERROR_INVALID_PARAM;
1731 else if (errno == ENODEV)
1732 return LIBUSB_ERROR_NO_DEVICE;
1734 usbi_err(HANDLE_CTX(handle), "detach failed, errno=%d", errno);
1735 return LIBUSB_ERROR_OTHER;
1741 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1744 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1746 struct usbfs_ioctl command;
1749 command.ifno = interface;
1750 command.ioctl_code = IOCTL_USBFS_CONNECT;
1751 command.data = NULL;
1753 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1755 if (errno == ENODATA)
1756 return LIBUSB_ERROR_NOT_FOUND;
1757 else if (errno == EINVAL)
1758 return LIBUSB_ERROR_INVALID_PARAM;
1759 else if (errno == ENODEV)
1760 return LIBUSB_ERROR_NO_DEVICE;
1761 else if (errno == EBUSY)
1762 return LIBUSB_ERROR_BUSY;
1764 usbi_err(HANDLE_CTX(handle), "attach failed, errno=%d", errno);
1765 return LIBUSB_ERROR_OTHER;
1766 } else if (r == 0) {
1767 return LIBUSB_ERROR_NOT_FOUND;
1773 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle,
1776 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1777 struct usbfs_disconnect_claim dc;
1778 int r, fd = hpriv->fd;
1780 dc.interface = interface;
1781 strcpy(dc.driver, "usbfs");
1782 dc.flags = USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER;
1783 r = ioctl(fd, IOCTL_USBFS_DISCONNECT_CLAIM, &dc);
1790 return LIBUSB_ERROR_BUSY;
1792 return LIBUSB_ERROR_INVALID_PARAM;
1794 return LIBUSB_ERROR_NO_DEVICE;
1796 usbi_err(HANDLE_CTX(handle), "disconnect-and-claim failed, errno=%d", errno);
1797 return LIBUSB_ERROR_OTHER;
1800 /* Fallback code for kernels which don't support the
1801 disconnect-and-claim ioctl */
1802 r = op_detach_kernel_driver(handle, interface);
1803 if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND)
1806 return claim_interface(handle, interface);
1809 static int op_claim_interface(struct libusb_device_handle *handle, uint8_t interface)
1811 if (handle->auto_detach_kernel_driver)
1812 return detach_kernel_driver_and_claim(handle, interface);
1814 return claim_interface(handle, interface);
1817 static int op_release_interface(struct libusb_device_handle *handle, uint8_t interface)
1821 r = release_interface(handle, interface);
1825 if (handle->auto_detach_kernel_driver)
1826 op_attach_kernel_driver(handle, interface);
1831 static void op_destroy_device(struct libusb_device *dev)
1833 struct linux_device_priv *priv = usbi_get_device_priv(dev);
1835 free(priv->config_descriptors);
1836 free(priv->descriptors);
1837 free(priv->sysfs_dir);
1840 /* URBs are discarded in reverse order of submission to avoid races. */
1841 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1843 struct libusb_transfer *transfer =
1844 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1845 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
1846 struct linux_device_handle_priv *hpriv =
1847 usbi_get_device_handle_priv(transfer->dev_handle);
1849 struct usbfs_urb *urb;
1851 for (i = last_plus_one - 1; i >= first; i--) {
1852 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS)
1853 urb = tpriv->iso_urbs[i];
1855 urb = &tpriv->urbs[i];
1857 if (ioctl(hpriv->fd, IOCTL_USBFS_DISCARDURB, urb) == 0)
1860 if (errno == EINVAL) {
1861 usbi_dbg("URB not found --> assuming ready to be reaped");
1862 if (i == (last_plus_one - 1))
1863 ret = LIBUSB_ERROR_NOT_FOUND;
1864 } else if (errno == ENODEV) {
1865 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1866 ret = LIBUSB_ERROR_NO_DEVICE;
1868 usbi_warn(TRANSFER_CTX(transfer), "unrecognised discard errno %d", errno);
1869 ret = LIBUSB_ERROR_OTHER;
1875 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1879 for (i = 0; i < tpriv->num_urbs; i++) {
1880 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1887 free(tpriv->iso_urbs);
1888 tpriv->iso_urbs = NULL;
1891 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1893 struct libusb_transfer *transfer =
1894 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1895 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
1896 struct linux_device_handle_priv *hpriv =
1897 usbi_get_device_handle_priv(transfer->dev_handle);
1898 struct usbfs_urb *urbs;
1899 int is_out = IS_XFEROUT(transfer);
1900 int bulk_buffer_len, use_bulk_continuation;
1902 int last_urb_partial = 0;
1907 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1908 * around this by splitting large transfers into 16k blocks, and then
1909 * submit all urbs at once. it would be simpler to submit one urb at
1910 * a time, but there is a big performance gain doing it this way.
1912 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1913 * using arbitrary large transfers can still be a bad idea though, as
1914 * the kernel needs to allocate physical contiguous memory for this,
1915 * which may fail for large buffers.
1917 * The kernel solves this problem by splitting the transfer into
1918 * blocks itself when the host-controller is scatter-gather capable
1919 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1921 * Last, there is the issue of short-transfers when splitting, for
1922 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1923 * is needed, but this is not always available.
1925 if (hpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1926 /* Good! Just submit everything in one go */
1927 bulk_buffer_len = transfer->length ? transfer->length : 1;
1928 use_bulk_continuation = 0;
1929 } else if (hpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1930 /* Split the transfers and use bulk-continuation to
1931 avoid issues with short-transfers */
1932 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1933 use_bulk_continuation = 1;
1934 } else if (hpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1935 /* Don't split, assume the kernel can alloc the buffer
1936 (otherwise the submit will fail with -ENOMEM) */
1937 bulk_buffer_len = transfer->length ? transfer->length : 1;
1938 use_bulk_continuation = 0;
1940 /* Bad, splitting without bulk-continuation, short transfers
1941 which end before the last urb will not work reliable! */
1942 /* Note we don't warn here as this is "normal" on kernels <
1943 2.6.32 and not a problem for most applications */
1944 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1945 use_bulk_continuation = 0;
1948 num_urbs = transfer->length / bulk_buffer_len;
1950 if (transfer->length == 0) {
1952 } else if ((transfer->length % bulk_buffer_len) > 0) {
1953 last_urb_partial = 1;
1956 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs, transfer->length);
1957 urbs = calloc(num_urbs, sizeof(*urbs));
1959 return LIBUSB_ERROR_NO_MEM;
1961 tpriv->num_urbs = num_urbs;
1962 tpriv->num_retired = 0;
1963 tpriv->reap_action = NORMAL;
1964 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1966 for (i = 0; i < num_urbs; i++) {
1967 struct usbfs_urb *urb = &urbs[i];
1969 urb->usercontext = itransfer;
1970 switch (transfer->type) {
1971 case LIBUSB_TRANSFER_TYPE_BULK:
1972 urb->type = USBFS_URB_TYPE_BULK;
1975 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1976 urb->type = USBFS_URB_TYPE_BULK;
1977 urb->stream_id = itransfer->stream_id;
1979 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1980 urb->type = USBFS_URB_TYPE_INTERRUPT;
1983 urb->endpoint = transfer->endpoint;
1984 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
1986 /* don't set the short not ok flag for the last URB */
1987 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
1988 urb->flags = USBFS_URB_SHORT_NOT_OK;
1990 if (i == num_urbs - 1 && last_urb_partial)
1991 urb->buffer_length = transfer->length % bulk_buffer_len;
1992 else if (transfer->length == 0)
1993 urb->buffer_length = 0;
1995 urb->buffer_length = bulk_buffer_len;
1997 if (i > 0 && use_bulk_continuation)
1998 urb->flags |= USBFS_URB_BULK_CONTINUATION;
2000 /* we have already checked that the flag is supported */
2001 if (is_out && i == num_urbs - 1 &&
2002 (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET))
2003 urb->flags |= USBFS_URB_ZERO_PACKET;
2005 r = ioctl(hpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2009 if (errno == ENODEV) {
2010 r = LIBUSB_ERROR_NO_DEVICE;
2011 } else if (errno == ENOMEM) {
2012 r = LIBUSB_ERROR_NO_MEM;
2014 usbi_err(TRANSFER_CTX(transfer), "submiturb failed, errno=%d", errno);
2015 r = LIBUSB_ERROR_IO;
2018 /* if the first URB submission fails, we can simply free up and
2019 * return failure immediately. */
2021 usbi_dbg("first URB failed, easy peasy");
2027 /* if it's not the first URB that failed, the situation is a bit
2028 * tricky. we may need to discard all previous URBs. there are
2030 * - discarding is asynchronous - discarded urbs will be reaped
2031 * later. the user must not have freed the transfer when the
2032 * discarded URBs are reaped, otherwise libusb will be using
2034 * - the earlier URBs may have completed successfully and we do
2035 * not want to throw away any data.
2036 * - this URB failing may be no error; EREMOTEIO means that
2037 * this transfer simply didn't need all the URBs we submitted
2038 * so, we report that the transfer was submitted successfully and
2039 * in case of error we discard all previous URBs. later when
2040 * the final reap completes we can report error to the user,
2041 * or success if an earlier URB was completed successfully.
2043 tpriv->reap_action = errno == EREMOTEIO ? COMPLETED_EARLY : SUBMIT_FAILED;
2045 /* The URBs we haven't submitted yet we count as already
2047 tpriv->num_retired += num_urbs - i;
2049 /* If we completed short then don't try to discard. */
2050 if (tpriv->reap_action == COMPLETED_EARLY)
2053 discard_urbs(itransfer, 0, i);
2055 usbi_dbg("reporting successful submission but waiting for %d "
2056 "discards before reporting error", i);
2063 static int submit_iso_transfer(struct usbi_transfer *itransfer)
2065 struct libusb_transfer *transfer =
2066 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2067 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2068 struct linux_device_handle_priv *hpriv =
2069 usbi_get_device_handle_priv(transfer->dev_handle);
2070 struct usbfs_urb **urbs;
2071 int num_packets = transfer->num_iso_packets;
2072 int num_packets_remaining;
2075 unsigned int packet_len;
2076 unsigned int total_len = 0;
2077 unsigned char *urb_buffer = transfer->buffer;
2079 if (num_packets < 1)
2080 return LIBUSB_ERROR_INVALID_PARAM;
2082 /* usbfs places arbitrary limits on iso URBs. this limit has changed
2083 * at least three times, but we attempt to detect this limit during
2084 * init and check it here. if the kernel rejects the request due to
2085 * its size, we return an error indicating such to the user.
2087 for (i = 0; i < num_packets; i++) {
2088 packet_len = transfer->iso_packet_desc[i].length;
2090 if (packet_len > max_iso_packet_len) {
2091 usbi_warn(TRANSFER_CTX(transfer),
2092 "iso packet length of %u bytes exceeds maximum of %u bytes",
2093 packet_len, max_iso_packet_len);
2094 return LIBUSB_ERROR_INVALID_PARAM;
2097 total_len += packet_len;
2100 if (transfer->length < (int)total_len)
2101 return LIBUSB_ERROR_INVALID_PARAM;
2103 /* usbfs limits the number of iso packets per URB */
2104 num_urbs = (num_packets + (MAX_ISO_PACKETS_PER_URB - 1)) / MAX_ISO_PACKETS_PER_URB;
2106 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs, transfer->length);
2108 urbs = calloc(num_urbs, sizeof(*urbs));
2110 return LIBUSB_ERROR_NO_MEM;
2112 tpriv->iso_urbs = urbs;
2113 tpriv->num_urbs = num_urbs;
2114 tpriv->num_retired = 0;
2115 tpriv->reap_action = NORMAL;
2116 tpriv->iso_packet_offset = 0;
2118 /* allocate + initialize each URB with the correct number of packets */
2119 num_packets_remaining = num_packets;
2120 for (i = 0, j = 0; i < num_urbs; i++) {
2121 int num_packets_in_urb = MIN(num_packets_remaining, MAX_ISO_PACKETS_PER_URB);
2122 struct usbfs_urb *urb;
2126 alloc_size = sizeof(*urb)
2127 + (num_packets_in_urb * sizeof(struct usbfs_iso_packet_desc));
2128 urb = calloc(1, alloc_size);
2130 free_iso_urbs(tpriv);
2131 return LIBUSB_ERROR_NO_MEM;
2135 /* populate packet lengths */
2136 for (k = 0; k < num_packets_in_urb; j++, k++) {
2137 packet_len = transfer->iso_packet_desc[j].length;
2138 urb->buffer_length += packet_len;
2139 urb->iso_frame_desc[k].length = packet_len;
2142 urb->usercontext = itransfer;
2143 urb->type = USBFS_URB_TYPE_ISO;
2144 /* FIXME: interface for non-ASAP data? */
2145 urb->flags = USBFS_URB_ISO_ASAP;
2146 urb->endpoint = transfer->endpoint;
2147 urb->number_of_packets = num_packets_in_urb;
2148 urb->buffer = urb_buffer;
2150 urb_buffer += urb->buffer_length;
2151 num_packets_remaining -= num_packets_in_urb;
2155 for (i = 0; i < num_urbs; i++) {
2156 int r = ioctl(hpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
2161 if (errno == ENODEV) {
2162 r = LIBUSB_ERROR_NO_DEVICE;
2163 } else if (errno == EINVAL) {
2164 usbi_warn(TRANSFER_CTX(transfer), "submiturb failed, transfer too large");
2165 r = LIBUSB_ERROR_INVALID_PARAM;
2166 } else if (errno == EMSGSIZE) {
2167 usbi_warn(TRANSFER_CTX(transfer), "submiturb failed, iso packet length too large");
2168 r = LIBUSB_ERROR_INVALID_PARAM;
2170 usbi_err(TRANSFER_CTX(transfer), "submiturb failed, errno=%d", errno);
2171 r = LIBUSB_ERROR_IO;
2174 /* if the first URB submission fails, we can simply free up and
2175 * return failure immediately. */
2177 usbi_dbg("first URB failed, easy peasy");
2178 free_iso_urbs(tpriv);
2182 /* if it's not the first URB that failed, the situation is a bit
2183 * tricky. we must discard all previous URBs. there are
2185 * - discarding is asynchronous - discarded urbs will be reaped
2186 * later. the user must not have freed the transfer when the
2187 * discarded URBs are reaped, otherwise libusb will be using
2189 * - the earlier URBs may have completed successfully and we do
2190 * not want to throw away any data.
2191 * so, in this case we discard all the previous URBs BUT we report
2192 * that the transfer was submitted successfully. then later when
2193 * the final discard completes we can report error to the user.
2195 tpriv->reap_action = SUBMIT_FAILED;
2197 /* The URBs we haven't submitted yet we count as already
2199 tpriv->num_retired = num_urbs - i;
2200 discard_urbs(itransfer, 0, i);
2202 usbi_dbg("reporting successful submission but waiting for %d "
2203 "discards before reporting error", i);
2210 static int submit_control_transfer(struct usbi_transfer *itransfer)
2212 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2213 struct libusb_transfer *transfer =
2214 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2215 struct linux_device_handle_priv *hpriv =
2216 usbi_get_device_handle_priv(transfer->dev_handle);
2217 struct usbfs_urb *urb;
2220 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
2221 return LIBUSB_ERROR_INVALID_PARAM;
2223 urb = calloc(1, sizeof(*urb));
2225 return LIBUSB_ERROR_NO_MEM;
2227 tpriv->num_urbs = 1;
2228 tpriv->reap_action = NORMAL;
2230 urb->usercontext = itransfer;
2231 urb->type = USBFS_URB_TYPE_CONTROL;
2232 urb->endpoint = transfer->endpoint;
2233 urb->buffer = transfer->buffer;
2234 urb->buffer_length = transfer->length;
2236 r = ioctl(hpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2240 if (errno == ENODEV)
2241 return LIBUSB_ERROR_NO_DEVICE;
2243 usbi_err(TRANSFER_CTX(transfer), "submiturb failed, errno=%d", errno);
2244 return LIBUSB_ERROR_IO;
2249 static int op_submit_transfer(struct usbi_transfer *itransfer)
2251 struct libusb_transfer *transfer =
2252 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2254 switch (transfer->type) {
2255 case LIBUSB_TRANSFER_TYPE_CONTROL:
2256 return submit_control_transfer(itransfer);
2257 case LIBUSB_TRANSFER_TYPE_BULK:
2258 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2259 return submit_bulk_transfer(itransfer);
2260 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2261 return submit_bulk_transfer(itransfer);
2262 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2263 return submit_iso_transfer(itransfer);
2265 usbi_err(TRANSFER_CTX(transfer), "unknown transfer type %u", transfer->type);
2266 return LIBUSB_ERROR_INVALID_PARAM;
2270 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2272 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2273 struct libusb_transfer *transfer =
2274 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2278 return LIBUSB_ERROR_NOT_FOUND;
2280 r = discard_urbs(itransfer, 0, tpriv->num_urbs);
2284 switch (transfer->type) {
2285 case LIBUSB_TRANSFER_TYPE_BULK:
2286 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2287 if (tpriv->reap_action == ERROR)
2289 /* else, fall through */
2291 tpriv->reap_action = CANCELLED;
2297 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2299 struct libusb_transfer *transfer =
2300 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2301 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2303 switch (transfer->type) {
2304 case LIBUSB_TRANSFER_TYPE_CONTROL:
2305 case LIBUSB_TRANSFER_TYPE_BULK:
2306 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2307 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2313 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2314 if (tpriv->iso_urbs) {
2315 free_iso_urbs(tpriv);
2316 tpriv->iso_urbs = NULL;
2320 usbi_err(TRANSFER_CTX(transfer), "unknown transfer type %u", transfer->type);
2324 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2325 struct usbfs_urb *urb)
2327 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2328 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2329 int urb_idx = urb - tpriv->urbs;
2331 usbi_mutex_lock(&itransfer->lock);
2332 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2333 urb_idx + 1, tpriv->num_urbs);
2335 tpriv->num_retired++;
2337 if (tpriv->reap_action != NORMAL) {
2338 /* cancelled, submit_fail, or completed early */
2339 usbi_dbg("abnormal reap: urb status %d", urb->status);
2341 /* even though we're in the process of cancelling, it's possible that
2342 * we may receive some data in these URBs that we don't want to lose.
2344 * 1. while the kernel is cancelling all the packets that make up an
2345 * URB, a few of them might complete. so we get back a successful
2346 * cancellation *and* some data.
2347 * 2. we receive a short URB which marks the early completion condition,
2348 * so we start cancelling the remaining URBs. however, we're too
2349 * slow and another URB completes (or at least completes partially).
2350 * (this can't happen since we always use BULK_CONTINUATION.)
2352 * When this happens, our objectives are not to lose any "surplus" data,
2353 * and also to stick it at the end of the previously-received data
2354 * (closing any holes), so that libusb reports the total amount of
2355 * transferred data and presents it in a contiguous chunk.
2357 if (urb->actual_length > 0) {
2358 unsigned char *target = transfer->buffer + itransfer->transferred;
2360 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2361 if (urb->buffer != target) {
2362 usbi_dbg("moving surplus data from offset %zu to offset %zu",
2363 (unsigned char *)urb->buffer - transfer->buffer,
2364 target - transfer->buffer);
2365 memmove(target, urb->buffer, urb->actual_length);
2367 itransfer->transferred += urb->actual_length;
2370 if (tpriv->num_retired == tpriv->num_urbs) {
2371 usbi_dbg("abnormal reap: last URB handled, reporting");
2372 if (tpriv->reap_action != COMPLETED_EARLY &&
2373 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2374 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2380 itransfer->transferred += urb->actual_length;
2382 /* Many of these errors can occur on *any* urb of a multi-urb
2383 * transfer. When they do, we tear down the rest of the transfer.
2385 switch (urb->status) {
2388 case -EREMOTEIO: /* short transfer */
2390 case -ENOENT: /* cancelled */
2395 usbi_dbg("device removed");
2396 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2397 goto cancel_remaining;
2399 usbi_dbg("detected endpoint stall");
2400 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2401 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2402 goto cancel_remaining;
2404 /* overflow can only ever occur in the last urb */
2405 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2406 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2407 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2414 usbi_dbg("low-level bus error %d", urb->status);
2415 tpriv->reap_action = ERROR;
2416 goto cancel_remaining;
2418 usbi_warn(ITRANSFER_CTX(itransfer), "unrecognised urb status %d", urb->status);
2419 tpriv->reap_action = ERROR;
2420 goto cancel_remaining;
2423 /* if we've reaped all urbs or we got less data than requested then we're
2425 if (tpriv->num_retired == tpriv->num_urbs) {
2426 usbi_dbg("all URBs in transfer reaped --> complete!");
2428 } else if (urb->actual_length < urb->buffer_length) {
2429 usbi_dbg("short transfer %d/%d --> complete!",
2430 urb->actual_length, urb->buffer_length);
2431 if (tpriv->reap_action == NORMAL)
2432 tpriv->reap_action = COMPLETED_EARLY;
2438 if (tpriv->reap_action == ERROR && tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2439 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2441 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2444 /* cancel remaining urbs and wait for their completion before
2445 * reporting results */
2446 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2449 usbi_mutex_unlock(&itransfer->lock);
2455 usbi_mutex_unlock(&itransfer->lock);
2456 return tpriv->reap_action == CANCELLED ?
2457 usbi_handle_transfer_cancellation(itransfer) :
2458 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2461 static int handle_iso_completion(struct usbi_transfer *itransfer,
2462 struct usbfs_urb *urb)
2464 struct libusb_transfer *transfer =
2465 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2466 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2467 int num_urbs = tpriv->num_urbs;
2470 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2472 usbi_mutex_lock(&itransfer->lock);
2473 for (i = 0; i < num_urbs; i++) {
2474 if (urb == tpriv->iso_urbs[i]) {
2480 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2481 usbi_mutex_unlock(&itransfer->lock);
2482 return LIBUSB_ERROR_NOT_FOUND;
2485 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2488 /* copy isochronous results back in */
2490 for (i = 0; i < urb->number_of_packets; i++) {
2491 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2492 struct libusb_iso_packet_descriptor *lib_desc =
2493 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2495 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2496 switch (urb_desc->status) {
2499 case -ENOENT: /* cancelled */
2504 usbi_dbg("packet %d - device removed", i);
2505 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2508 usbi_dbg("packet %d - detected endpoint stall", i);
2509 lib_desc->status = LIBUSB_TRANSFER_STALL;
2512 usbi_dbg("packet %d - overflow error", i);
2513 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2521 usbi_dbg("packet %d - low-level USB error %d", i, urb_desc->status);
2522 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2525 usbi_warn(TRANSFER_CTX(transfer), "packet %d - unrecognised urb status %d",
2526 i, urb_desc->status);
2527 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2530 lib_desc->actual_length = urb_desc->actual_length;
2533 tpriv->num_retired++;
2535 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2536 usbi_dbg("CANCEL: urb status %d", urb->status);
2538 if (tpriv->num_retired == num_urbs) {
2539 usbi_dbg("CANCEL: last URB handled, reporting");
2540 free_iso_urbs(tpriv);
2541 if (tpriv->reap_action == CANCELLED) {
2542 usbi_mutex_unlock(&itransfer->lock);
2543 return usbi_handle_transfer_cancellation(itransfer);
2545 usbi_mutex_unlock(&itransfer->lock);
2546 return usbi_handle_transfer_completion(itransfer, LIBUSB_TRANSFER_ERROR);
2552 switch (urb->status) {
2555 case -ENOENT: /* cancelled */
2559 usbi_dbg("device removed");
2560 status = LIBUSB_TRANSFER_NO_DEVICE;
2563 usbi_warn(TRANSFER_CTX(transfer), "unrecognised urb status %d", urb->status);
2564 status = LIBUSB_TRANSFER_ERROR;
2568 /* if we've reaped all urbs then we're done */
2569 if (tpriv->num_retired == num_urbs) {
2570 usbi_dbg("all URBs in transfer reaped --> complete!");
2571 free_iso_urbs(tpriv);
2572 usbi_mutex_unlock(&itransfer->lock);
2573 return usbi_handle_transfer_completion(itransfer, status);
2577 usbi_mutex_unlock(&itransfer->lock);
2581 static int handle_control_completion(struct usbi_transfer *itransfer,
2582 struct usbfs_urb *urb)
2584 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2587 usbi_mutex_lock(&itransfer->lock);
2588 usbi_dbg("handling completion status %d", urb->status);
2590 itransfer->transferred += urb->actual_length;
2592 if (tpriv->reap_action == CANCELLED) {
2593 if (urb->status && urb->status != -ENOENT)
2594 usbi_warn(ITRANSFER_CTX(itransfer), "cancel: unrecognised urb status %d",
2598 usbi_mutex_unlock(&itransfer->lock);
2599 return usbi_handle_transfer_cancellation(itransfer);
2602 switch (urb->status) {
2604 status = LIBUSB_TRANSFER_COMPLETED;
2606 case -ENOENT: /* cancelled */
2607 status = LIBUSB_TRANSFER_CANCELLED;
2611 usbi_dbg("device removed");
2612 status = LIBUSB_TRANSFER_NO_DEVICE;
2615 usbi_dbg("unsupported control request");
2616 status = LIBUSB_TRANSFER_STALL;
2619 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2620 status = LIBUSB_TRANSFER_OVERFLOW;
2627 usbi_dbg("low-level bus error %d", urb->status);
2628 status = LIBUSB_TRANSFER_ERROR;
2631 usbi_warn(ITRANSFER_CTX(itransfer), "unrecognised urb status %d", urb->status);
2632 status = LIBUSB_TRANSFER_ERROR;
2638 usbi_mutex_unlock(&itransfer->lock);
2639 return usbi_handle_transfer_completion(itransfer, status);
2642 static int reap_for_handle(struct libusb_device_handle *handle)
2644 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
2646 struct usbfs_urb *urb = NULL;
2647 struct usbi_transfer *itransfer;
2648 struct libusb_transfer *transfer;
2650 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2652 if (errno == EAGAIN)
2654 if (errno == ENODEV)
2655 return LIBUSB_ERROR_NO_DEVICE;
2657 usbi_err(HANDLE_CTX(handle), "reap failed, errno=%d", errno);
2658 return LIBUSB_ERROR_IO;
2661 itransfer = urb->usercontext;
2662 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2664 usbi_dbg("urb type=%u status=%d transferred=%d", urb->type, urb->status, urb->actual_length);
2666 switch (transfer->type) {
2667 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2668 return handle_iso_completion(itransfer, urb);
2669 case LIBUSB_TRANSFER_TYPE_BULK:
2670 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2671 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2672 return handle_bulk_completion(itransfer, urb);
2673 case LIBUSB_TRANSFER_TYPE_CONTROL:
2674 return handle_control_completion(itransfer, urb);
2676 usbi_err(HANDLE_CTX(handle), "unrecognised transfer type %u", transfer->type);
2677 return LIBUSB_ERROR_OTHER;
2681 static int op_handle_events(struct libusb_context *ctx,
2682 void *event_data, unsigned int count, unsigned int num_ready)
2684 struct pollfd *fds = event_data;
2688 usbi_mutex_lock(&ctx->open_devs_lock);
2689 for (n = 0; n < count && num_ready > 0; n++) {
2690 struct pollfd *pollfd = &fds[n];
2691 struct libusb_device_handle *handle;
2692 struct linux_device_handle_priv *hpriv = NULL;
2695 if (!pollfd->revents)
2699 for_each_open_device(ctx, handle) {
2700 hpriv = usbi_get_device_handle_priv(handle);
2701 if (hpriv->fd == pollfd->fd)
2705 if (!hpriv || hpriv->fd != pollfd->fd) {
2706 usbi_err(ctx, "cannot find handle for fd %d",
2711 if (pollfd->revents & POLLERR) {
2712 /* remove the fd from the pollfd set so that it doesn't continuously
2713 * trigger an event, and flag that it has been removed so op_close()
2714 * doesn't try to remove it a second time */
2715 usbi_remove_event_source(HANDLE_CTX(handle), hpriv->fd);
2716 hpriv->fd_removed = 1;
2718 /* device will still be marked as attached if hotplug monitor thread
2719 * hasn't processed remove event yet */
2720 usbi_mutex_static_lock(&linux_hotplug_lock);
2721 if (usbi_atomic_load(&handle->dev->attached))
2722 linux_device_disconnected(handle->dev->bus_number,
2723 handle->dev->device_address);
2724 usbi_mutex_static_unlock(&linux_hotplug_lock);
2726 if (hpriv->caps & USBFS_CAP_REAP_AFTER_DISCONNECT) {
2728 r = reap_for_handle(handle);
2732 usbi_handle_disconnect(handle);
2738 r = reap_for_handle(handle);
2739 } while (r == 0 && ++reap_count <= 25);
2741 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2749 usbi_mutex_unlock(&ctx->open_devs_lock);
2753 const struct usbi_os_backend usbi_backend = {
2754 .name = "Linux usbfs",
2755 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2758 .set_option = op_set_option,
2759 .hotplug_poll = op_hotplug_poll,
2760 .get_active_config_descriptor = op_get_active_config_descriptor,
2761 .get_config_descriptor = op_get_config_descriptor,
2762 .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2764 .wrap_sys_device = op_wrap_sys_device,
2767 .get_configuration = op_get_configuration,
2768 .set_configuration = op_set_configuration,
2769 .claim_interface = op_claim_interface,
2770 .release_interface = op_release_interface,
2772 .set_interface_altsetting = op_set_interface,
2773 .clear_halt = op_clear_halt,
2774 .reset_device = op_reset_device,
2776 .alloc_streams = op_alloc_streams,
2777 .free_streams = op_free_streams,
2779 .dev_mem_alloc = op_dev_mem_alloc,
2780 .dev_mem_free = op_dev_mem_free,
2782 .kernel_driver_active = op_kernel_driver_active,
2783 .detach_kernel_driver = op_detach_kernel_driver,
2784 .attach_kernel_driver = op_attach_kernel_driver,
2786 .destroy_device = op_destroy_device,
2788 .submit_transfer = op_submit_transfer,
2789 .cancel_transfer = op_cancel_transfer,
2790 .clear_transfer_priv = op_clear_transfer_priv,
2792 .handle_events = op_handle_events,
2794 .device_priv_size = sizeof(struct linux_device_priv),
2795 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2796 .transfer_priv_size = sizeof(struct linux_transfer_priv),