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 *, int);
105 #if !defined(HAVE_LIBUDEV)
106 static int linux_default_scan_devices(struct libusb_context *ctx);
109 struct kernel_version {
115 struct linux_device_priv {
117 unsigned char *descriptors;
119 int active_config; /* cache val for !sysfs_available */
122 struct linux_device_handle_priv {
131 /* submission failed after the first URB, so await cancellation/completion
132 * of all the others */
135 /* cancelled by user or timeout */
138 /* completed multi-URB transfer in non-final URB */
141 /* one or more urbs encountered a low-level error */
145 struct linux_transfer_priv {
147 struct usbfs_urb *urbs;
148 struct usbfs_urb **iso_urbs;
151 enum reap_action reap_action;
154 enum libusb_transfer_status reap_status;
156 /* next iso packet in user-supplied transfer to be populated */
157 int iso_packet_offset;
160 static int get_usbfs_fd(struct libusb_device *dev, mode_t mode, int silent)
162 struct libusb_context *ctx = DEVICE_CTX(dev);
167 sprintf(path, USBDEV_PATH "/usbdev%u.%u",
168 dev->bus_number, dev->device_address);
170 sprintf(path, USB_DEVTMPFS_PATH "/%03u/%03u",
171 dev->bus_number, dev->device_address);
173 fd = open(path, mode | O_CLOEXEC);
175 return fd; /* Success */
177 if (errno == ENOENT) {
178 const long delay_ms = 10L;
179 const struct timespec delay_ts = { 0L, delay_ms * 1000L * 1000L };
182 usbi_err(ctx, "File doesn't exist, wait %ld ms and try again", delay_ms);
184 /* Wait 10ms for USB device path creation.*/
185 nanosleep(&delay_ts, NULL);
187 fd = open(path, mode | O_CLOEXEC);
189 return fd; /* Success */
193 usbi_err(ctx, "libusb couldn't open USB device %s, errno=%d", path, errno);
194 if (errno == EACCES && mode == O_RDWR)
195 usbi_err(ctx, "libusb requires write access to USB device nodes");
199 return LIBUSB_ERROR_ACCESS;
201 return LIBUSB_ERROR_NO_DEVICE;
202 return LIBUSB_ERROR_IO;
205 /* check dirent for a /dev/usbdev%d.%d name
206 * optionally return bus/device on success */
207 static int is_usbdev_entry(const char *name, uint8_t *bus_p, uint8_t *dev_p)
211 if (sscanf(name, "usbdev%d.%d", &busnum, &devnum) != 2)
213 if (busnum < 0 || busnum > UINT8_MAX || devnum < 0 || devnum > UINT8_MAX) {
214 usbi_dbg("invalid usbdev format '%s'", name);
218 usbi_dbg("found: %s", name);
220 *bus_p = (uint8_t)busnum;
222 *dev_p = (uint8_t)devnum;
226 static const char *find_usbfs_path(void)
230 struct dirent *entry;
232 path = USB_DEVTMPFS_PATH;
235 while ((entry = readdir(dir))) {
236 if (entry->d_name[0] == '.')
239 /* We assume if we find any files that it must be the right place */
249 /* look for /dev/usbdev*.* if the normal place fails */
253 while ((entry = readdir(dir))) {
254 if (entry->d_name[0] == '.')
257 if (is_usbdev_entry(entry->d_name, NULL, NULL)) {
258 /* found one; that's enough */
271 /* On udev based systems without any usb-devices /dev/bus/usb will not
272 * exist. So if we've not found anything and we're using udev for hotplug
273 * simply assume /dev/bus/usb rather then making libusb_init fail.
274 * Make the same assumption for Android where SELinux policies might block us
275 * from reading /dev on newer devices. */
276 #if defined(HAVE_LIBUDEV) || defined(__ANDROID__)
277 return USB_DEVTMPFS_PATH;
283 static int get_kernel_version(struct libusb_context *ctx,
284 struct kernel_version *ver)
289 if (uname(&uts) < 0) {
290 usbi_err(ctx, "uname failed, errno=%d", errno);
294 atoms = sscanf(uts.release, "%d.%d.%d", &ver->major, &ver->minor, &ver->sublevel);
296 usbi_err(ctx, "failed to parse uname release '%s'", uts.release);
303 usbi_dbg("reported kernel version is %s", uts.release);
308 static int kernel_version_ge(const struct kernel_version *ver,
309 int major, int minor, int sublevel)
311 if (ver->major > major)
313 else if (ver->major < major)
316 /* kmajor == major */
317 if (ver->minor > minor)
319 else if (ver->minor < minor)
322 /* kminor == minor */
323 if (ver->sublevel == -1)
324 return sublevel == 0;
326 return ver->sublevel >= sublevel;
329 static int op_init(struct libusb_context *ctx)
331 struct kernel_version kversion;
332 const char *usbfs_path;
335 if (get_kernel_version(ctx, &kversion) < 0)
336 return LIBUSB_ERROR_OTHER;
338 if (!kernel_version_ge(&kversion, 2, 6, 32)) {
339 usbi_err(ctx, "kernel version is too old (reported as %d.%d.%d)",
340 kversion.major, kversion.minor,
341 kversion.sublevel != -1 ? kversion.sublevel : 0);
342 return LIBUSB_ERROR_NOT_SUPPORTED;
345 usbfs_path = find_usbfs_path();
347 usbi_err(ctx, "could not find usbfs");
348 return LIBUSB_ERROR_OTHER;
351 usbi_dbg("found usbfs at %s", usbfs_path);
353 if (!max_iso_packet_len) {
354 if (kernel_version_ge(&kversion, 5, 2, 0))
355 max_iso_packet_len = 98304;
356 else if (kernel_version_ge(&kversion, 3, 10, 0))
357 max_iso_packet_len = 49152;
359 max_iso_packet_len = 8192;
362 usbi_dbg("max iso packet length is (likely) %u bytes", max_iso_packet_len);
364 if (sysfs_available == -1) {
365 struct statfs statfsbuf;
367 r = statfs(SYSFS_MOUNT_PATH, &statfsbuf);
368 if (r == 0 && statfsbuf.f_type == SYSFS_MAGIC) {
369 usbi_dbg("sysfs is available");
372 usbi_warn(ctx, "sysfs not mounted");
377 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
379 if (init_count == 0) {
380 /* start up hotplug event handler */
381 r = linux_start_event_monitor();
383 if (r == LIBUSB_SUCCESS) {
384 r = linux_scan_devices(ctx);
385 if (r == LIBUSB_SUCCESS)
387 else if (init_count == 0)
388 linux_stop_event_monitor();
390 usbi_err(ctx, "error starting hotplug event monitor");
392 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
397 static void op_exit(struct libusb_context *ctx)
400 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
401 assert(init_count != 0);
403 /* tear down event handler */
404 linux_stop_event_monitor();
406 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
409 static int linux_scan_devices(struct libusb_context *ctx)
413 usbi_mutex_static_lock(&linux_hotplug_lock);
415 #if defined(HAVE_LIBUDEV)
416 ret = linux_udev_scan_devices(ctx);
418 ret = linux_default_scan_devices(ctx);
421 usbi_mutex_static_unlock(&linux_hotplug_lock);
426 static void op_hotplug_poll(void)
428 linux_hotplug_poll();
431 static int open_sysfs_attr(struct libusb_context *ctx,
432 const char *sysfs_dir, const char *attr)
437 snprintf(filename, sizeof(filename), SYSFS_DEVICE_PATH "/%s/%s", sysfs_dir, attr);
438 fd = open(filename, O_RDONLY | O_CLOEXEC);
440 if (errno == ENOENT) {
441 /* File doesn't exist. Assume the device has been
442 disconnected (see trac ticket #70). */
443 return LIBUSB_ERROR_NO_DEVICE;
445 usbi_err(ctx, "open %s failed, errno=%d", filename, errno);
446 return LIBUSB_ERROR_IO;
452 /* Note only suitable for attributes which always read >= 0, < 0 is error */
453 static int read_sysfs_attr(struct libusb_context *ctx,
454 const char *sysfs_dir, const char *attr, int max_value, int *value_p)
456 char buf[20], *endptr;
461 fd = open_sysfs_attr(ctx, sysfs_dir, attr);
465 r = read(fd, buf, sizeof(buf));
470 return LIBUSB_ERROR_NO_DEVICE;
471 usbi_err(ctx, "attribute %s read failed, errno=%zd", attr, r);
472 return LIBUSB_ERROR_IO;
477 /* Certain attributes (e.g. bConfigurationValue) are not
478 * populated if the device is not configured. */
483 /* The kernel does *not* NULL-terminate the string, but every attribute
484 * should be terminated with a newline character. */
485 if (!isdigit(buf[0])) {
486 usbi_err(ctx, "attribute %s doesn't have numeric value?", attr);
487 return LIBUSB_ERROR_IO;
488 } else if (buf[r - 1] != '\n') {
489 usbi_err(ctx, "attribute %s doesn't end with newline?", attr);
490 return LIBUSB_ERROR_IO;
495 value = strtol(buf, &endptr, 10);
496 if (value < 0 || value > (long)max_value || errno) {
497 usbi_err(ctx, "attribute %s contains an invalid value: '%s'", attr, buf);
498 return LIBUSB_ERROR_INVALID_PARAM;
499 } else if (*endptr != '\0') {
500 /* Consider the value to be valid if the remainder is a '.'
501 * character followed by numbers. This occurs, for example,
502 * when reading the "speed" attribute for a low-speed device
504 if (*endptr == '.' && isdigit(*(endptr + 1))) {
506 while (isdigit(*endptr))
509 if (*endptr != '\0') {
510 usbi_err(ctx, "attribute %s contains an invalid value: '%s'", attr, buf);
511 return LIBUSB_ERROR_INVALID_PARAM;
515 *value_p = (int)value;
519 static int op_get_device_descriptor(struct libusb_device *dev,
520 unsigned char *buffer, int *host_endian)
522 struct linux_device_priv *priv = usbi_get_device_priv(dev);
524 *host_endian = priv->sysfs_dir != NULL;
525 memcpy(buffer, priv->descriptors, LIBUSB_DT_DEVICE_SIZE);
530 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
532 uint8_t busnum, devaddr;
535 ret = linux_get_device_address(ctx, 0, &busnum, &devaddr, NULL, devname, -1);
536 if (ret != LIBUSB_SUCCESS)
539 return linux_enumerate_device(ctx, busnum, devaddr, devname);
542 /* read the bConfigurationValue for a device */
543 static int sysfs_get_active_config(struct libusb_device *dev, int *config)
545 struct linux_device_priv *priv = usbi_get_device_priv(dev);
548 ret = read_sysfs_attr(DEVICE_CTX(dev), priv->sysfs_dir, "bConfigurationValue",
554 usbi_dbg("device unconfigured");
559 int linux_get_device_address(struct libusb_context *ctx, int detached,
560 uint8_t *busnum, uint8_t *devaddr, const char *dev_node,
561 const char *sys_name, int fd)
566 usbi_dbg("getting address for device: %s detached: %d", sys_name, detached);
567 /* can't use sysfs to read the bus and device number if the
568 * device has been detached */
569 if (!sysfs_available || detached || !sys_name) {
570 if (!dev_node && fd >= 0) {
571 char *fd_path = alloca(PATH_MAX);
574 /* try to retrieve the device node from fd */
575 sprintf(proc_path, "/proc/self/fd/%d", fd);
576 r = readlink(proc_path, fd_path, PATH_MAX - 1);
584 return LIBUSB_ERROR_OTHER;
586 /* will this work with all supported kernel versions? */
587 if (!strncmp(dev_node, "/dev/bus/usb", 12))
588 sscanf(dev_node, "/dev/bus/usb/%hhu/%hhu", busnum, devaddr);
590 return LIBUSB_ERROR_OTHER;
592 return LIBUSB_SUCCESS;
595 usbi_dbg("scan %s", sys_name);
597 r = read_sysfs_attr(ctx, sys_name, "busnum", UINT8_MAX, &sysfs_val);
600 *busnum = (uint8_t)sysfs_val;
602 r = read_sysfs_attr(ctx, sys_name, "devnum", UINT8_MAX, &sysfs_val);
605 *devaddr = (uint8_t)sysfs_val;
607 usbi_dbg("bus=%u dev=%u", *busnum, *devaddr);
609 return LIBUSB_SUCCESS;
612 /* Return offset of the next descriptor with the given type */
613 static int seek_to_next_descriptor(struct libusb_context *ctx,
614 uint8_t descriptor_type, unsigned char *buffer, int size)
616 struct usbi_descriptor_header *header;
619 for (i = 0; size >= 0; i += header->bLength, size -= header->bLength) {
621 return LIBUSB_ERROR_NOT_FOUND;
624 usbi_err(ctx, "short descriptor read %d/2", size);
625 return LIBUSB_ERROR_IO;
628 header = (struct usbi_descriptor_header *)(buffer + i);
629 if (i && header->bDescriptorType == descriptor_type)
632 usbi_err(ctx, "bLength overflow by %d bytes", -size);
633 return LIBUSB_ERROR_IO;
636 /* Return offset to next config */
637 static int seek_to_next_config(struct libusb_device *dev,
638 unsigned char *buffer, int size)
640 struct libusb_context *ctx = DEVICE_CTX(dev);
641 struct linux_device_priv *priv = usbi_get_device_priv(dev);
642 struct usbi_configuration_descriptor *config;
646 return LIBUSB_ERROR_NOT_FOUND;
648 if (size < LIBUSB_DT_CONFIG_SIZE) {
649 usbi_err(ctx, "short descriptor read %d/%d",
650 size, LIBUSB_DT_CONFIG_SIZE);
651 return LIBUSB_ERROR_IO;
654 config = (struct usbi_configuration_descriptor *)buffer;
655 if (config->bDescriptorType != LIBUSB_DT_CONFIG) {
656 usbi_err(ctx, "descriptor is not a config desc (type 0x%02x)",
657 config->bDescriptorType);
658 return LIBUSB_ERROR_IO;
661 config_len = libusb_le16_to_cpu(config->wTotalLength);
663 * In usbfs the config descriptors are wTotalLength bytes apart,
664 * with any short reads from the device appearing as holes in the file.
666 * In sysfs wTotalLength is ignored, instead the kernel returns a
667 * config descriptor with verified bLength fields, with descriptors
668 * with an invalid bLength removed.
670 if (priv->sysfs_dir) {
671 int next = seek_to_next_descriptor(ctx, LIBUSB_DT_CONFIG, buffer, size);
673 if (next == LIBUSB_ERROR_NOT_FOUND)
678 if (next != config_len)
679 usbi_warn(ctx, "config length mismatch wTotalLength %u real %d",
683 if (config_len < LIBUSB_DT_CONFIG_SIZE) {
684 usbi_err(ctx, "invalid wTotalLength %u", config_len);
685 return LIBUSB_ERROR_IO;
686 } else if (config_len > size) {
687 usbi_warn(ctx, "short descriptor read %d/%u",
696 static int op_get_config_descriptor_by_value(struct libusb_device *dev,
697 uint8_t value, unsigned char **buffer)
699 struct linux_device_priv *priv = usbi_get_device_priv(dev);
700 unsigned char *descriptors = priv->descriptors;
701 int size = priv->descriptors_len;
702 struct usbi_configuration_descriptor *config;
706 /* Skip device header */
707 descriptors += LIBUSB_DT_DEVICE_SIZE;
708 size -= LIBUSB_DT_DEVICE_SIZE;
710 /* Seek till the config is found, or till "EOF" */
712 int next = seek_to_next_config(dev, descriptors, size);
716 config = (struct usbi_configuration_descriptor *)descriptors;
717 if (config->bConfigurationValue == value) {
718 *buffer = descriptors;
726 static int op_get_active_config_descriptor(struct libusb_device *dev,
727 unsigned char *buffer, size_t len)
729 struct linux_device_priv *priv = usbi_get_device_priv(dev);
731 unsigned char *config_desc;
733 if (priv->sysfs_dir) {
734 r = sysfs_get_active_config(dev, &config);
738 /* Use cached bConfigurationValue */
739 config = priv->active_config;
742 return LIBUSB_ERROR_NOT_FOUND;
744 r = op_get_config_descriptor_by_value(dev, config, &config_desc);
748 len = MIN(len, (size_t)r);
749 memcpy(buffer, config_desc, len);
753 static int op_get_config_descriptor(struct libusb_device *dev,
754 uint8_t config_index, unsigned char *buffer, size_t len)
756 struct linux_device_priv *priv = usbi_get_device_priv(dev);
757 unsigned char *descriptors = priv->descriptors;
758 int i, r, size = priv->descriptors_len;
760 /* Skip device header */
761 descriptors += LIBUSB_DT_DEVICE_SIZE;
762 size -= LIBUSB_DT_DEVICE_SIZE;
764 /* Seek till the config is found, or till "EOF" */
766 r = seek_to_next_config(dev, descriptors, size);
769 if (i == config_index)
775 len = MIN(len, (size_t)r);
776 memcpy(buffer, descriptors, len);
780 /* send a control message to retrieve active configuration */
781 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
783 struct linux_device_priv *priv = usbi_get_device_priv(dev);
784 unsigned char active_config = 0;
787 struct usbfs_ctrltransfer ctrl = {
788 .bmRequestType = LIBUSB_ENDPOINT_IN,
789 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
794 .data = &active_config
797 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
800 return LIBUSB_ERROR_NO_DEVICE;
802 /* we hit this error path frequently with buggy devices :( */
803 usbi_warn(DEVICE_CTX(dev), "get configuration failed, errno=%d", errno);
804 priv->active_config = -1;
806 if (active_config > 0) {
807 priv->active_config = active_config;
809 /* some buggy devices have a configuration 0, but we're
810 * reaching into the corner of a corner case here, so let's
811 * not support buggy devices in these circumstances.
812 * stick to the specs: a configuration value of 0 means
814 usbi_warn(DEVICE_CTX(dev), "active cfg 0? assuming unconfigured device");
815 priv->active_config = -1;
819 return LIBUSB_SUCCESS;
822 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
823 uint8_t devaddr, const char *sysfs_dir, int wrapped_fd)
825 struct linux_device_priv *priv = usbi_get_device_priv(dev);
826 struct libusb_context *ctx = DEVICE_CTX(dev);
827 int descriptors_size = 0;
831 dev->bus_number = busnum;
832 dev->device_address = devaddr;
835 priv->sysfs_dir = strdup(sysfs_dir);
836 if (!priv->sysfs_dir)
837 return LIBUSB_ERROR_NO_MEM;
839 /* Note speed can contain 1.5, in this case read_sysfs_attr()
840 will stop parsing at the '.' and return 1 */
841 if (read_sysfs_attr(ctx, sysfs_dir, "speed", INT_MAX, &speed) == 0) {
843 case 1: dev->speed = LIBUSB_SPEED_LOW; break;
844 case 12: dev->speed = LIBUSB_SPEED_FULL; break;
845 case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
846 case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
847 case 10000: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
849 usbi_warn(ctx, "unknown device speed: %d Mbps", speed);
854 /* cache descriptors in memory */
856 fd = open_sysfs_attr(ctx, sysfs_dir, "descriptors");
857 } else if (wrapped_fd < 0) {
858 fd = get_usbfs_fd(dev, O_RDONLY, 0);
861 r = lseek(fd, 0, SEEK_SET);
863 usbi_err(ctx, "lseek failed, errno=%d", errno);
864 return LIBUSB_ERROR_IO;
871 descriptors_size += 256;
872 priv->descriptors = usbi_reallocf(priv->descriptors, descriptors_size);
873 if (!priv->descriptors) {
874 if (fd != wrapped_fd)
876 return LIBUSB_ERROR_NO_MEM;
878 /* usbfs has holes in the file */
880 memset(priv->descriptors + priv->descriptors_len,
881 0, descriptors_size - priv->descriptors_len);
883 r = read(fd, priv->descriptors + priv->descriptors_len,
884 descriptors_size - priv->descriptors_len);
886 usbi_err(ctx, "read descriptor failed, errno=%d", errno);
887 if (fd != wrapped_fd)
889 return LIBUSB_ERROR_IO;
891 priv->descriptors_len += r;
892 } while (priv->descriptors_len == descriptors_size);
894 if (fd != wrapped_fd)
897 if (priv->descriptors_len < LIBUSB_DT_DEVICE_SIZE) {
898 usbi_err(ctx, "short descriptor read (%d)", priv->descriptors_len);
899 return LIBUSB_ERROR_IO;
903 return LIBUSB_SUCCESS;
905 /* cache active config */
907 fd = get_usbfs_fd(dev, O_RDWR, 1);
911 /* cannot send a control message to determine the active
912 * config. just assume the first one is active. */
913 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
914 "active configuration descriptor");
915 if (priv->descriptors_len >= (LIBUSB_DT_DEVICE_SIZE + LIBUSB_DT_CONFIG_SIZE)) {
916 struct usbi_configuration_descriptor *config;
918 config = (struct usbi_configuration_descriptor *)(priv->descriptors + LIBUSB_DT_DEVICE_SIZE);
919 priv->active_config = config->bConfigurationValue;
921 priv->active_config = -1; /* No config dt */
924 return LIBUSB_SUCCESS;
927 r = usbfs_get_active_config(dev, fd);
928 if (fd != wrapped_fd)
934 static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir)
936 struct libusb_context *ctx = DEVICE_CTX(dev);
937 struct libusb_device *it;
938 char *parent_sysfs_dir, *tmp;
939 int ret, add_parent = 1;
941 /* XXX -- can we figure out the topology when using usbfs? */
942 if (!sysfs_dir || !strncmp(sysfs_dir, "usb", 3)) {
943 /* either using usbfs or finding the parent of a root hub */
944 return LIBUSB_SUCCESS;
947 parent_sysfs_dir = strdup(sysfs_dir);
948 if (!parent_sysfs_dir)
949 return LIBUSB_ERROR_NO_MEM;
951 if ((tmp = strrchr(parent_sysfs_dir, '.')) ||
952 (tmp = strrchr(parent_sysfs_dir, '-'))) {
953 dev->port_number = atoi(tmp + 1);
956 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
958 free(parent_sysfs_dir);
959 return LIBUSB_SUCCESS;
962 /* is the parent a root hub? */
963 if (!strchr(parent_sysfs_dir, '-')) {
964 tmp = parent_sysfs_dir;
965 ret = asprintf(&parent_sysfs_dir, "usb%s", tmp);
968 return LIBUSB_ERROR_NO_MEM;
972 /* find the parent in the context */
973 usbi_mutex_lock(&ctx->usb_devs_lock);
974 list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device) {
975 struct linux_device_priv *priv = usbi_get_device_priv(it);
977 if (priv->sysfs_dir) {
978 if (!strcmp(priv->sysfs_dir, parent_sysfs_dir)) {
979 dev->parent_dev = libusb_ref_device(it);
984 usbi_mutex_unlock(&ctx->usb_devs_lock);
986 if (!dev->parent_dev && add_parent) {
987 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
989 sysfs_scan_device(ctx, parent_sysfs_dir);
994 usbi_dbg("dev %p (%s) has parent %p (%s) port %u", dev, sysfs_dir,
995 dev->parent_dev, parent_sysfs_dir, dev->port_number);
997 free(parent_sysfs_dir);
999 return LIBUSB_SUCCESS;
1002 int linux_enumerate_device(struct libusb_context *ctx,
1003 uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1005 unsigned long session_id;
1006 struct libusb_device *dev;
1009 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1010 * will be reused. instead we should add a simple sysfs attribute with
1012 session_id = busnum << 8 | devaddr;
1013 usbi_dbg("busnum %u devaddr %u session_id %lu", busnum, devaddr, session_id);
1015 dev = usbi_get_device_by_session_id(ctx, session_id);
1017 /* device already exists in the context */
1018 usbi_dbg("session_id %lu already exists", session_id);
1019 libusb_unref_device(dev);
1020 return LIBUSB_SUCCESS;
1023 usbi_dbg("allocating new device for %u/%u (session %lu)",
1024 busnum, devaddr, session_id);
1025 dev = usbi_alloc_device(ctx, session_id);
1027 return LIBUSB_ERROR_NO_MEM;
1029 r = initialize_device(dev, busnum, devaddr, sysfs_dir, -1);
1032 r = usbi_sanitize_device(dev);
1036 r = linux_get_parent_info(dev, sysfs_dir);
1041 libusb_unref_device(dev);
1043 usbi_connect_device(dev);
1048 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1050 struct libusb_context *ctx;
1052 usbi_mutex_static_lock(&active_contexts_lock);
1053 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1054 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1056 usbi_mutex_static_unlock(&active_contexts_lock);
1059 void linux_device_disconnected(uint8_t busnum, uint8_t devaddr)
1061 struct libusb_context *ctx;
1062 struct libusb_device *dev;
1063 unsigned long session_id = busnum << 8 | devaddr;
1065 usbi_mutex_static_lock(&active_contexts_lock);
1066 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1067 dev = usbi_get_device_by_session_id (ctx, session_id);
1069 usbi_disconnect_device(dev);
1070 libusb_unref_device(dev);
1072 usbi_dbg("device not found for session %lx", session_id);
1075 usbi_mutex_static_unlock(&active_contexts_lock);
1078 #if !defined(HAVE_LIBUDEV)
1079 static int parse_u8(const char *str, uint8_t *val_p)
1085 num = strtol(str, &endptr, 10);
1086 if (num < 0 || num > UINT8_MAX || errno)
1088 if (endptr == str || *endptr != '\0')
1091 *val_p = (uint8_t)num;
1095 /* open a bus directory and adds all discovered devices to the context */
1096 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1100 struct dirent *entry;
1101 int r = LIBUSB_ERROR_IO;
1103 sprintf(dirpath, USB_DEVTMPFS_PATH "/%03u", busnum);
1104 usbi_dbg("%s", dirpath);
1105 dir = opendir(dirpath);
1107 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1108 /* FIXME: should handle valid race conditions like hub unplugged
1109 * during directory iteration - this is not an error */
1113 while ((entry = readdir(dir))) {
1116 if (entry->d_name[0] == '.')
1119 if (!parse_u8(entry->d_name, &devaddr)) {
1120 usbi_dbg("unknown dir entry %s", entry->d_name);
1124 if (linux_enumerate_device(ctx, busnum, devaddr, NULL)) {
1125 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1136 static int usbfs_get_device_list(struct libusb_context *ctx)
1138 struct dirent *entry;
1140 uint8_t busnum, devaddr;
1144 buses = opendir(USBDEV_PATH);
1146 buses = opendir(USB_DEVTMPFS_PATH);
1149 usbi_err(ctx, "opendir buses failed, errno=%d", errno);
1150 return LIBUSB_ERROR_IO;
1153 while ((entry = readdir(buses))) {
1154 if (entry->d_name[0] == '.')
1158 if (!is_usbdev_entry(entry->d_name, &busnum, &devaddr))
1161 r = linux_enumerate_device(ctx, busnum, devaddr, NULL);
1163 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1167 if (!parse_u8(entry->d_name, &busnum)) {
1168 usbi_dbg("unknown dir entry %s", entry->d_name);
1172 r = usbfs_scan_busdir(ctx, busnum);
1183 static int sysfs_get_device_list(struct libusb_context *ctx)
1185 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1186 struct dirent *entry;
1187 int num_devices = 0;
1188 int num_enumerated = 0;
1191 usbi_err(ctx, "opendir devices failed, errno=%d", errno);
1192 return LIBUSB_ERROR_IO;
1195 while ((entry = readdir(devices))) {
1196 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1197 || strchr(entry->d_name, ':'))
1202 if (sysfs_scan_device(ctx, entry->d_name)) {
1203 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1212 /* successful if at least one device was enumerated or no devices were found */
1213 if (num_enumerated || !num_devices)
1214 return LIBUSB_SUCCESS;
1216 return LIBUSB_ERROR_IO;
1219 static int linux_default_scan_devices(struct libusb_context *ctx)
1221 /* we can retrieve device list and descriptors from sysfs or usbfs.
1222 * sysfs is preferable, because if we use usbfs we end up resuming
1223 * any autosuspended USB devices. however, sysfs is not available
1224 * everywhere, so we need a usbfs fallback too.
1226 if (sysfs_available)
1227 return sysfs_get_device_list(ctx);
1229 return usbfs_get_device_list(ctx);
1233 static int initialize_handle(struct libusb_device_handle *handle, int fd)
1235 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1240 r = ioctl(fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1242 if (errno == ENOTTY)
1243 usbi_dbg("getcap not available");
1245 usbi_err(HANDLE_CTX(handle), "getcap failed, errno=%d", errno);
1246 hpriv->caps = USBFS_CAP_BULK_CONTINUATION;
1249 return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1252 static int op_wrap_sys_device(struct libusb_context *ctx,
1253 struct libusb_device_handle *handle, intptr_t sys_dev)
1255 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1256 int fd = (int)sys_dev;
1257 uint8_t busnum, devaddr;
1258 struct usbfs_connectinfo ci;
1259 struct libusb_device *dev;
1262 r = linux_get_device_address(ctx, 1, &busnum, &devaddr, NULL, NULL, fd);
1264 r = ioctl(fd, IOCTL_USBFS_CONNECTINFO, &ci);
1266 usbi_err(ctx, "connectinfo failed, errno=%d", errno);
1267 return LIBUSB_ERROR_IO;
1269 /* There is no ioctl to get the bus number. We choose 0 here
1270 * as linux starts numbering buses from 1. */
1272 devaddr = ci.devnum;
1275 /* Session id is unused as we do not add the device to the list of
1276 * connected devices. */
1277 usbi_dbg("allocating new device for fd %d", fd);
1278 dev = usbi_alloc_device(ctx, 0);
1280 return LIBUSB_ERROR_NO_MEM;
1282 r = initialize_device(dev, busnum, devaddr, NULL, fd);
1285 r = usbi_sanitize_device(dev);
1288 /* Consider the device as connected, but do not add it to the managed
1293 r = initialize_handle(handle, fd);
1298 libusb_unref_device(dev);
1302 static int op_open(struct libusb_device_handle *handle)
1306 fd = get_usbfs_fd(handle->dev, O_RDWR, 0);
1308 if (fd == LIBUSB_ERROR_NO_DEVICE) {
1309 /* device will still be marked as attached if hotplug monitor thread
1310 * hasn't processed remove event yet */
1311 usbi_mutex_static_lock(&linux_hotplug_lock);
1312 if (handle->dev->attached) {
1313 usbi_dbg("open failed with no device, but device still attached");
1314 linux_device_disconnected(handle->dev->bus_number,
1315 handle->dev->device_address);
1317 usbi_mutex_static_unlock(&linux_hotplug_lock);
1322 r = initialize_handle(handle, fd);
1329 static void op_close(struct libusb_device_handle *dev_handle)
1331 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(dev_handle);
1333 /* fd may have already been removed by POLLERR condition in op_handle_events() */
1334 if (!hpriv->fd_removed)
1335 usbi_remove_pollfd(HANDLE_CTX(dev_handle), hpriv->fd);
1336 if (!hpriv->fd_keep)
1340 static int op_get_configuration(struct libusb_device_handle *handle,
1343 struct linux_device_priv *priv = usbi_get_device_priv(handle->dev);
1346 if (priv->sysfs_dir) {
1347 r = sysfs_get_active_config(handle->dev, config);
1349 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1351 r = usbfs_get_active_config(handle->dev, hpriv->fd);
1352 if (r == LIBUSB_SUCCESS)
1353 *config = priv->active_config;
1358 if (*config == -1) {
1359 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1366 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1368 struct linux_device_priv *priv = usbi_get_device_priv(handle->dev);
1369 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1371 int r = ioctl(fd, IOCTL_USBFS_SETCONFIGURATION, &config);
1374 if (errno == EINVAL)
1375 return LIBUSB_ERROR_NOT_FOUND;
1376 else if (errno == EBUSY)
1377 return LIBUSB_ERROR_BUSY;
1378 else if (errno == ENODEV)
1379 return LIBUSB_ERROR_NO_DEVICE;
1381 usbi_err(HANDLE_CTX(handle), "set configuration failed, errno=%d", errno);
1382 return LIBUSB_ERROR_OTHER;
1385 /* update our cached active config descriptor */
1386 priv->active_config = config;
1388 return LIBUSB_SUCCESS;
1391 static int claim_interface(struct libusb_device_handle *handle, int iface)
1393 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1395 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTERFACE, &iface);
1398 if (errno == ENOENT)
1399 return LIBUSB_ERROR_NOT_FOUND;
1400 else if (errno == EBUSY)
1401 return LIBUSB_ERROR_BUSY;
1402 else if (errno == ENODEV)
1403 return LIBUSB_ERROR_NO_DEVICE;
1405 usbi_err(HANDLE_CTX(handle), "claim interface failed, errno=%d", errno);
1406 return LIBUSB_ERROR_OTHER;
1411 static int release_interface(struct libusb_device_handle *handle, int iface)
1413 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1415 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTERFACE, &iface);
1418 if (errno == ENODEV)
1419 return LIBUSB_ERROR_NO_DEVICE;
1421 usbi_err(HANDLE_CTX(handle), "release interface failed, errno=%d", errno);
1422 return LIBUSB_ERROR_OTHER;
1427 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1430 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1432 struct usbfs_setinterface setintf;
1435 setintf.interface = iface;
1436 setintf.altsetting = altsetting;
1437 r = ioctl(fd, IOCTL_USBFS_SETINTERFACE, &setintf);
1439 if (errno == EINVAL)
1440 return LIBUSB_ERROR_NOT_FOUND;
1441 else if (errno == ENODEV)
1442 return LIBUSB_ERROR_NO_DEVICE;
1444 usbi_err(HANDLE_CTX(handle), "set interface failed, errno=%d", errno);
1445 return LIBUSB_ERROR_OTHER;
1451 static int op_clear_halt(struct libusb_device_handle *handle,
1452 unsigned char endpoint)
1454 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1456 unsigned int _endpoint = endpoint;
1457 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1460 if (errno == ENOENT)
1461 return LIBUSB_ERROR_NOT_FOUND;
1462 else if (errno == ENODEV)
1463 return LIBUSB_ERROR_NO_DEVICE;
1465 usbi_err(HANDLE_CTX(handle), "clear halt failed, errno=%d", errno);
1466 return LIBUSB_ERROR_OTHER;
1472 static int op_reset_device(struct libusb_device_handle *handle)
1474 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1478 /* Doing a device reset will cause the usbfs driver to get unbound
1479 * from any interfaces it is bound to. By voluntarily unbinding
1480 * the usbfs driver ourself, we stop the kernel from rebinding
1481 * the interface after reset (which would end up with the interface
1482 * getting bound to the in kernel driver if any). */
1483 for (i = 0; i < USB_MAXINTERFACES; i++) {
1484 if (handle->claimed_interfaces & (1UL << i))
1485 release_interface(handle, i);
1488 usbi_mutex_lock(&handle->lock);
1489 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1491 if (errno == ENODEV) {
1492 ret = LIBUSB_ERROR_NOT_FOUND;
1496 usbi_err(HANDLE_CTX(handle), "reset failed, errno=%d", errno);
1497 ret = LIBUSB_ERROR_OTHER;
1501 /* And re-claim any interfaces which were claimed before the reset */
1502 for (i = 0; i < USB_MAXINTERFACES; i++) {
1503 if (!(handle->claimed_interfaces & (1UL << i)))
1506 * A driver may have completed modprobing during
1507 * IOCTL_USBFS_RESET, and bound itself as soon as
1508 * IOCTL_USBFS_RESET released the device lock
1510 r = detach_kernel_driver_and_claim(handle, i);
1512 usbi_warn(HANDLE_CTX(handle), "failed to re-claim interface %d after reset: %s",
1513 i, libusb_error_name(r));
1514 handle->claimed_interfaces &= ~(1UL << i);
1515 ret = LIBUSB_ERROR_NOT_FOUND;
1519 usbi_mutex_unlock(&handle->lock);
1523 static int do_streams_ioctl(struct libusb_device_handle *handle, long req,
1524 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1526 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1527 int r, fd = hpriv->fd;
1528 struct usbfs_streams *streams;
1530 if (num_endpoints > 30) /* Max 15 in + 15 out eps */
1531 return LIBUSB_ERROR_INVALID_PARAM;
1533 streams = malloc(sizeof(*streams) + num_endpoints);
1535 return LIBUSB_ERROR_NO_MEM;
1537 streams->num_streams = num_streams;
1538 streams->num_eps = num_endpoints;
1539 memcpy(streams->eps, endpoints, num_endpoints);
1541 r = ioctl(fd, req, streams);
1546 if (errno == ENOTTY)
1547 return LIBUSB_ERROR_NOT_SUPPORTED;
1548 else if (errno == EINVAL)
1549 return LIBUSB_ERROR_INVALID_PARAM;
1550 else if (errno == ENODEV)
1551 return LIBUSB_ERROR_NO_DEVICE;
1553 usbi_err(HANDLE_CTX(handle), "streams-ioctl failed, errno=%d", errno);
1554 return LIBUSB_ERROR_OTHER;
1559 static int op_alloc_streams(struct libusb_device_handle *handle,
1560 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1562 return do_streams_ioctl(handle, IOCTL_USBFS_ALLOC_STREAMS,
1563 num_streams, endpoints, num_endpoints);
1566 static int op_free_streams(struct libusb_device_handle *handle,
1567 unsigned char *endpoints, int num_endpoints)
1569 return do_streams_ioctl(handle, IOCTL_USBFS_FREE_STREAMS, 0,
1570 endpoints, num_endpoints);
1573 static unsigned char *op_dev_mem_alloc(struct libusb_device_handle *handle,
1576 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1577 unsigned char *buffer;
1579 buffer = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, hpriv->fd, 0);
1580 if (buffer == MAP_FAILED) {
1581 usbi_err(HANDLE_CTX(handle), "alloc dev mem failed, errno=%d", errno);
1587 static int op_dev_mem_free(struct libusb_device_handle *handle,
1588 unsigned char *buffer, size_t len)
1590 if (munmap(buffer, len) != 0) {
1591 usbi_err(HANDLE_CTX(handle), "free dev mem failed, errno=%d", errno);
1592 return LIBUSB_ERROR_OTHER;
1594 return LIBUSB_SUCCESS;
1598 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1601 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1603 struct usbfs_getdriver getdrv;
1606 getdrv.interface = interface;
1607 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1609 if (errno == ENODATA)
1611 else if (errno == ENODEV)
1612 return LIBUSB_ERROR_NO_DEVICE;
1614 usbi_err(HANDLE_CTX(handle), "get driver failed, errno=%d", errno);
1615 return LIBUSB_ERROR_OTHER;
1618 return strcmp(getdrv.driver, "usbfs") != 0;
1621 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1624 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1626 struct usbfs_ioctl command;
1627 struct usbfs_getdriver getdrv;
1630 command.ifno = interface;
1631 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1632 command.data = NULL;
1634 getdrv.interface = interface;
1635 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1636 if (r == 0 && !strcmp(getdrv.driver, "usbfs"))
1637 return LIBUSB_ERROR_NOT_FOUND;
1639 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1641 if (errno == ENODATA)
1642 return LIBUSB_ERROR_NOT_FOUND;
1643 else if (errno == EINVAL)
1644 return LIBUSB_ERROR_INVALID_PARAM;
1645 else if (errno == ENODEV)
1646 return LIBUSB_ERROR_NO_DEVICE;
1648 usbi_err(HANDLE_CTX(handle), "detach failed, errno=%d", errno);
1649 return LIBUSB_ERROR_OTHER;
1655 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1658 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1660 struct usbfs_ioctl command;
1663 command.ifno = interface;
1664 command.ioctl_code = IOCTL_USBFS_CONNECT;
1665 command.data = NULL;
1667 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1669 if (errno == ENODATA)
1670 return LIBUSB_ERROR_NOT_FOUND;
1671 else if (errno == EINVAL)
1672 return LIBUSB_ERROR_INVALID_PARAM;
1673 else if (errno == ENODEV)
1674 return LIBUSB_ERROR_NO_DEVICE;
1675 else if (errno == EBUSY)
1676 return LIBUSB_ERROR_BUSY;
1678 usbi_err(HANDLE_CTX(handle), "attach failed, errno=%d", errno);
1679 return LIBUSB_ERROR_OTHER;
1680 } else if (r == 0) {
1681 return LIBUSB_ERROR_NOT_FOUND;
1687 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle,
1690 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1691 struct usbfs_disconnect_claim dc;
1692 int r, fd = hpriv->fd;
1694 dc.interface = interface;
1695 strcpy(dc.driver, "usbfs");
1696 dc.flags = USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER;
1697 r = ioctl(fd, IOCTL_USBFS_DISCONNECT_CLAIM, &dc);
1704 return LIBUSB_ERROR_BUSY;
1706 return LIBUSB_ERROR_INVALID_PARAM;
1708 return LIBUSB_ERROR_NO_DEVICE;
1710 usbi_err(HANDLE_CTX(handle), "disconnect-and-claim failed, errno=%d", errno);
1711 return LIBUSB_ERROR_OTHER;
1714 /* Fallback code for kernels which don't support the
1715 disconnect-and-claim ioctl */
1716 r = op_detach_kernel_driver(handle, interface);
1717 if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND)
1720 return claim_interface(handle, interface);
1723 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1725 if (handle->auto_detach_kernel_driver)
1726 return detach_kernel_driver_and_claim(handle, iface);
1728 return claim_interface(handle, iface);
1731 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1735 r = release_interface(handle, iface);
1739 if (handle->auto_detach_kernel_driver)
1740 op_attach_kernel_driver(handle, iface);
1745 static void op_destroy_device(struct libusb_device *dev)
1747 struct linux_device_priv *priv = usbi_get_device_priv(dev);
1749 free(priv->descriptors);
1750 free(priv->sysfs_dir);
1753 /* URBs are discarded in reverse order of submission to avoid races. */
1754 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1756 struct libusb_transfer *transfer =
1757 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1758 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
1759 struct linux_device_handle_priv *hpriv =
1760 usbi_get_device_handle_priv(transfer->dev_handle);
1762 struct usbfs_urb *urb;
1764 for (i = last_plus_one - 1; i >= first; i--) {
1765 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS)
1766 urb = tpriv->iso_urbs[i];
1768 urb = &tpriv->urbs[i];
1770 if (ioctl(hpriv->fd, IOCTL_USBFS_DISCARDURB, urb) == 0)
1773 if (errno == EINVAL) {
1774 usbi_dbg("URB not found --> assuming ready to be reaped");
1775 if (i == (last_plus_one - 1))
1776 ret = LIBUSB_ERROR_NOT_FOUND;
1777 } else if (errno == ENODEV) {
1778 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1779 ret = LIBUSB_ERROR_NO_DEVICE;
1781 usbi_warn(TRANSFER_CTX(transfer), "unrecognised discard errno %d", errno);
1782 ret = LIBUSB_ERROR_OTHER;
1788 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1792 for (i = 0; i < tpriv->num_urbs; i++) {
1793 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1800 free(tpriv->iso_urbs);
1801 tpriv->iso_urbs = NULL;
1804 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1806 struct libusb_transfer *transfer =
1807 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1808 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
1809 struct linux_device_handle_priv *hpriv =
1810 usbi_get_device_handle_priv(transfer->dev_handle);
1811 struct usbfs_urb *urbs;
1812 int is_out = IS_XFEROUT(transfer);
1813 int bulk_buffer_len, use_bulk_continuation;
1815 int last_urb_partial = 0;
1820 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1821 * around this by splitting large transfers into 16k blocks, and then
1822 * submit all urbs at once. it would be simpler to submit one urb at
1823 * a time, but there is a big performance gain doing it this way.
1825 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1826 * using arbritary large transfers can still be a bad idea though, as
1827 * the kernel needs to allocate physical contiguous memory for this,
1828 * which may fail for large buffers.
1830 * The kernel solves this problem by splitting the transfer into
1831 * blocks itself when the host-controller is scatter-gather capable
1832 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1834 * Last, there is the issue of short-transfers when splitting, for
1835 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1836 * is needed, but this is not always available.
1838 if (hpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1839 /* Good! Just submit everything in one go */
1840 bulk_buffer_len = transfer->length ? transfer->length : 1;
1841 use_bulk_continuation = 0;
1842 } else if (hpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1843 /* Split the transfers and use bulk-continuation to
1844 avoid issues with short-transfers */
1845 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1846 use_bulk_continuation = 1;
1847 } else if (hpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1848 /* Don't split, assume the kernel can alloc the buffer
1849 (otherwise the submit will fail with -ENOMEM) */
1850 bulk_buffer_len = transfer->length ? transfer->length : 1;
1851 use_bulk_continuation = 0;
1853 /* Bad, splitting without bulk-continuation, short transfers
1854 which end before the last urb will not work reliable! */
1855 /* Note we don't warn here as this is "normal" on kernels <
1856 2.6.32 and not a problem for most applications */
1857 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1858 use_bulk_continuation = 0;
1861 num_urbs = transfer->length / bulk_buffer_len;
1863 if (transfer->length == 0) {
1865 } else if ((transfer->length % bulk_buffer_len) > 0) {
1866 last_urb_partial = 1;
1869 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs, transfer->length);
1870 urbs = calloc(num_urbs, sizeof(*urbs));
1872 return LIBUSB_ERROR_NO_MEM;
1874 tpriv->num_urbs = num_urbs;
1875 tpriv->num_retired = 0;
1876 tpriv->reap_action = NORMAL;
1877 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1879 for (i = 0; i < num_urbs; i++) {
1880 struct usbfs_urb *urb = &urbs[i];
1882 urb->usercontext = itransfer;
1883 switch (transfer->type) {
1884 case LIBUSB_TRANSFER_TYPE_BULK:
1885 urb->type = USBFS_URB_TYPE_BULK;
1888 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1889 urb->type = USBFS_URB_TYPE_BULK;
1890 urb->stream_id = itransfer->stream_id;
1892 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1893 urb->type = USBFS_URB_TYPE_INTERRUPT;
1896 urb->endpoint = transfer->endpoint;
1897 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
1899 /* don't set the short not ok flag for the last URB */
1900 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
1901 urb->flags = USBFS_URB_SHORT_NOT_OK;
1903 if (i == num_urbs - 1 && last_urb_partial)
1904 urb->buffer_length = transfer->length % bulk_buffer_len;
1905 else if (transfer->length == 0)
1906 urb->buffer_length = 0;
1908 urb->buffer_length = bulk_buffer_len;
1910 if (i > 0 && use_bulk_continuation)
1911 urb->flags |= USBFS_URB_BULK_CONTINUATION;
1913 /* we have already checked that the flag is supported */
1914 if (is_out && i == num_urbs - 1 &&
1915 (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET))
1916 urb->flags |= USBFS_URB_ZERO_PACKET;
1918 r = ioctl(hpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1922 if (errno == ENODEV) {
1923 r = LIBUSB_ERROR_NO_DEVICE;
1924 } else if (errno == ENOMEM) {
1925 r = LIBUSB_ERROR_NO_MEM;
1927 usbi_err(TRANSFER_CTX(transfer), "submiturb failed, errno=%d", errno);
1928 r = LIBUSB_ERROR_IO;
1931 /* if the first URB submission fails, we can simply free up and
1932 * return failure immediately. */
1934 usbi_dbg("first URB failed, easy peasy");
1940 /* if it's not the first URB that failed, the situation is a bit
1941 * tricky. we may need to discard all previous URBs. there are
1943 * - discarding is asynchronous - discarded urbs will be reaped
1944 * later. the user must not have freed the transfer when the
1945 * discarded URBs are reaped, otherwise libusb will be using
1947 * - the earlier URBs may have completed successfully and we do
1948 * not want to throw away any data.
1949 * - this URB failing may be no error; EREMOTEIO means that
1950 * this transfer simply didn't need all the URBs we submitted
1951 * so, we report that the transfer was submitted successfully and
1952 * in case of error we discard all previous URBs. later when
1953 * the final reap completes we can report error to the user,
1954 * or success if an earlier URB was completed successfully.
1956 tpriv->reap_action = errno == EREMOTEIO ? COMPLETED_EARLY : SUBMIT_FAILED;
1958 /* The URBs we haven't submitted yet we count as already
1960 tpriv->num_retired += num_urbs - i;
1962 /* If we completed short then don't try to discard. */
1963 if (tpriv->reap_action == COMPLETED_EARLY)
1966 discard_urbs(itransfer, 0, i);
1968 usbi_dbg("reporting successful submission but waiting for %d "
1969 "discards before reporting error", i);
1976 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1978 struct libusb_transfer *transfer =
1979 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1980 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
1981 struct linux_device_handle_priv *hpriv =
1982 usbi_get_device_handle_priv(transfer->dev_handle);
1983 struct usbfs_urb **urbs;
1984 int num_packets = transfer->num_iso_packets;
1985 int num_packets_remaining;
1988 unsigned int packet_len;
1989 unsigned int total_len = 0;
1990 unsigned char *urb_buffer = transfer->buffer;
1992 if (num_packets < 1)
1993 return LIBUSB_ERROR_INVALID_PARAM;
1995 /* usbfs places arbitrary limits on iso URBs. this limit has changed
1996 * at least three times, but we attempt to detect this limit during
1997 * init and check it here. if the kernel rejects the request due to
1998 * its size, we return an error indicating such to the user.
2000 for (i = 0; i < num_packets; i++) {
2001 packet_len = transfer->iso_packet_desc[i].length;
2003 if (packet_len > max_iso_packet_len) {
2004 usbi_warn(TRANSFER_CTX(transfer),
2005 "iso packet length of %u bytes exceeds maximum of %u bytes",
2006 packet_len, max_iso_packet_len);
2007 return LIBUSB_ERROR_INVALID_PARAM;
2010 total_len += packet_len;
2013 if (transfer->length < (int)total_len)
2014 return LIBUSB_ERROR_INVALID_PARAM;
2016 /* usbfs limits the number of iso packets per URB */
2017 num_urbs = (num_packets + (MAX_ISO_PACKETS_PER_URB - 1)) / MAX_ISO_PACKETS_PER_URB;
2019 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs, transfer->length);
2021 urbs = calloc(num_urbs, sizeof(*urbs));
2023 return LIBUSB_ERROR_NO_MEM;
2025 tpriv->iso_urbs = urbs;
2026 tpriv->num_urbs = num_urbs;
2027 tpriv->num_retired = 0;
2028 tpriv->reap_action = NORMAL;
2029 tpriv->iso_packet_offset = 0;
2031 /* allocate + initialize each URB with the correct number of packets */
2032 num_packets_remaining = num_packets;
2033 for (i = 0, j = 0; i < num_urbs; i++) {
2034 int num_packets_in_urb = MIN(num_packets_remaining, MAX_ISO_PACKETS_PER_URB);
2035 struct usbfs_urb *urb;
2039 alloc_size = sizeof(*urb)
2040 + (num_packets_in_urb * sizeof(struct usbfs_iso_packet_desc));
2041 urb = calloc(1, alloc_size);
2043 free_iso_urbs(tpriv);
2044 return LIBUSB_ERROR_NO_MEM;
2048 /* populate packet lengths */
2049 for (k = 0; k < num_packets_in_urb; j++, k++) {
2050 packet_len = transfer->iso_packet_desc[j].length;
2051 urb->buffer_length += packet_len;
2052 urb->iso_frame_desc[k].length = packet_len;
2055 urb->usercontext = itransfer;
2056 urb->type = USBFS_URB_TYPE_ISO;
2057 /* FIXME: interface for non-ASAP data? */
2058 urb->flags = USBFS_URB_ISO_ASAP;
2059 urb->endpoint = transfer->endpoint;
2060 urb->number_of_packets = num_packets_in_urb;
2061 urb->buffer = urb_buffer;
2063 urb_buffer += urb->buffer_length;
2064 num_packets_remaining -= num_packets_in_urb;
2068 for (i = 0; i < num_urbs; i++) {
2069 int r = ioctl(hpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
2074 if (errno == ENODEV) {
2075 r = LIBUSB_ERROR_NO_DEVICE;
2076 } else if (errno == EINVAL) {
2077 usbi_warn(TRANSFER_CTX(transfer), "submiturb failed, transfer too large");
2078 r = LIBUSB_ERROR_INVALID_PARAM;
2079 } else if (errno == EMSGSIZE) {
2080 usbi_warn(TRANSFER_CTX(transfer), "submiturb failed, iso packet length too large");
2081 r = LIBUSB_ERROR_INVALID_PARAM;
2083 usbi_err(TRANSFER_CTX(transfer), "submiturb failed, errno=%d", errno);
2084 r = LIBUSB_ERROR_IO;
2087 /* if the first URB submission fails, we can simply free up and
2088 * return failure immediately. */
2090 usbi_dbg("first URB failed, easy peasy");
2091 free_iso_urbs(tpriv);
2095 /* if it's not the first URB that failed, the situation is a bit
2096 * tricky. we must discard all previous URBs. there are
2098 * - discarding is asynchronous - discarded urbs will be reaped
2099 * later. the user must not have freed the transfer when the
2100 * discarded URBs are reaped, otherwise libusb will be using
2102 * - the earlier URBs may have completed successfully and we do
2103 * not want to throw away any data.
2104 * so, in this case we discard all the previous URBs BUT we report
2105 * that the transfer was submitted successfully. then later when
2106 * the final discard completes we can report error to the user.
2108 tpriv->reap_action = SUBMIT_FAILED;
2110 /* The URBs we haven't submitted yet we count as already
2112 tpriv->num_retired = num_urbs - i;
2113 discard_urbs(itransfer, 0, i);
2115 usbi_dbg("reporting successful submission but waiting for %d "
2116 "discards before reporting error", i);
2123 static int submit_control_transfer(struct usbi_transfer *itransfer)
2125 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2126 struct libusb_transfer *transfer =
2127 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2128 struct linux_device_handle_priv *hpriv =
2129 usbi_get_device_handle_priv(transfer->dev_handle);
2130 struct usbfs_urb *urb;
2133 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
2134 return LIBUSB_ERROR_INVALID_PARAM;
2136 urb = calloc(1, sizeof(*urb));
2138 return LIBUSB_ERROR_NO_MEM;
2140 tpriv->num_urbs = 1;
2141 tpriv->reap_action = NORMAL;
2143 urb->usercontext = itransfer;
2144 urb->type = USBFS_URB_TYPE_CONTROL;
2145 urb->endpoint = transfer->endpoint;
2146 urb->buffer = transfer->buffer;
2147 urb->buffer_length = transfer->length;
2149 r = ioctl(hpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2153 if (errno == ENODEV)
2154 return LIBUSB_ERROR_NO_DEVICE;
2156 usbi_err(TRANSFER_CTX(transfer), "submiturb failed, errno=%d", errno);
2157 return LIBUSB_ERROR_IO;
2162 static int op_submit_transfer(struct usbi_transfer *itransfer)
2164 struct libusb_transfer *transfer =
2165 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2167 switch (transfer->type) {
2168 case LIBUSB_TRANSFER_TYPE_CONTROL:
2169 return submit_control_transfer(itransfer);
2170 case LIBUSB_TRANSFER_TYPE_BULK:
2171 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2172 return submit_bulk_transfer(itransfer);
2173 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2174 return submit_bulk_transfer(itransfer);
2175 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2176 return submit_iso_transfer(itransfer);
2178 usbi_err(TRANSFER_CTX(transfer), "unknown transfer type %u", transfer->type);
2179 return LIBUSB_ERROR_INVALID_PARAM;
2183 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2185 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2186 struct libusb_transfer *transfer =
2187 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2191 return LIBUSB_ERROR_NOT_FOUND;
2193 r = discard_urbs(itransfer, 0, tpriv->num_urbs);
2197 switch (transfer->type) {
2198 case LIBUSB_TRANSFER_TYPE_BULK:
2199 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2200 if (tpriv->reap_action == ERROR)
2202 /* else, fall through */
2204 tpriv->reap_action = CANCELLED;
2210 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2212 struct libusb_transfer *transfer =
2213 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2214 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2216 switch (transfer->type) {
2217 case LIBUSB_TRANSFER_TYPE_CONTROL:
2218 case LIBUSB_TRANSFER_TYPE_BULK:
2219 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2220 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2226 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2227 if (tpriv->iso_urbs) {
2228 free_iso_urbs(tpriv);
2229 tpriv->iso_urbs = NULL;
2233 usbi_err(TRANSFER_CTX(transfer), "unknown transfer type %u", transfer->type);
2237 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2238 struct usbfs_urb *urb)
2240 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2241 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2242 int urb_idx = urb - tpriv->urbs;
2244 usbi_mutex_lock(&itransfer->lock);
2245 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2246 urb_idx + 1, tpriv->num_urbs);
2248 tpriv->num_retired++;
2250 if (tpriv->reap_action != NORMAL) {
2251 /* cancelled, submit_fail, or completed early */
2252 usbi_dbg("abnormal reap: urb status %d", urb->status);
2254 /* even though we're in the process of cancelling, it's possible that
2255 * we may receive some data in these URBs that we don't want to lose.
2257 * 1. while the kernel is cancelling all the packets that make up an
2258 * URB, a few of them might complete. so we get back a successful
2259 * cancellation *and* some data.
2260 * 2. we receive a short URB which marks the early completion condition,
2261 * so we start cancelling the remaining URBs. however, we're too
2262 * slow and another URB completes (or at least completes partially).
2263 * (this can't happen since we always use BULK_CONTINUATION.)
2265 * When this happens, our objectives are not to lose any "surplus" data,
2266 * and also to stick it at the end of the previously-received data
2267 * (closing any holes), so that libusb reports the total amount of
2268 * transferred data and presents it in a contiguous chunk.
2270 if (urb->actual_length > 0) {
2271 unsigned char *target = transfer->buffer + itransfer->transferred;
2273 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2274 if (urb->buffer != target) {
2275 usbi_dbg("moving surplus data from offset %zu to offset %zu",
2276 (unsigned char *) urb->buffer - transfer->buffer,
2277 target - transfer->buffer);
2278 memmove(target, urb->buffer, urb->actual_length);
2280 itransfer->transferred += urb->actual_length;
2283 if (tpriv->num_retired == tpriv->num_urbs) {
2284 usbi_dbg("abnormal reap: last URB handled, reporting");
2285 if (tpriv->reap_action != COMPLETED_EARLY &&
2286 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2287 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2293 itransfer->transferred += urb->actual_length;
2295 /* Many of these errors can occur on *any* urb of a multi-urb
2296 * transfer. When they do, we tear down the rest of the transfer.
2298 switch (urb->status) {
2301 case -EREMOTEIO: /* short transfer */
2303 case -ENOENT: /* cancelled */
2308 usbi_dbg("device removed");
2309 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2310 goto cancel_remaining;
2312 usbi_dbg("detected endpoint stall");
2313 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2314 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2315 goto cancel_remaining;
2317 /* overflow can only ever occur in the last urb */
2318 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2319 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2320 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2327 usbi_dbg("low-level bus error %d", urb->status);
2328 tpriv->reap_action = ERROR;
2329 goto cancel_remaining;
2331 usbi_warn(ITRANSFER_CTX(itransfer), "unrecognised urb status %d", urb->status);
2332 tpriv->reap_action = ERROR;
2333 goto cancel_remaining;
2336 /* if we've reaped all urbs or we got less data than requested then we're
2338 if (tpriv->num_retired == tpriv->num_urbs) {
2339 usbi_dbg("all URBs in transfer reaped --> complete!");
2341 } else if (urb->actual_length < urb->buffer_length) {
2342 usbi_dbg("short transfer %d/%d --> complete!",
2343 urb->actual_length, urb->buffer_length);
2344 if (tpriv->reap_action == NORMAL)
2345 tpriv->reap_action = COMPLETED_EARLY;
2351 if (tpriv->reap_action == ERROR && tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2352 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2354 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2357 /* cancel remaining urbs and wait for their completion before
2358 * reporting results */
2359 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2362 usbi_mutex_unlock(&itransfer->lock);
2368 usbi_mutex_unlock(&itransfer->lock);
2369 return tpriv->reap_action == CANCELLED ?
2370 usbi_handle_transfer_cancellation(itransfer) :
2371 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2374 static int handle_iso_completion(struct usbi_transfer *itransfer,
2375 struct usbfs_urb *urb)
2377 struct libusb_transfer *transfer =
2378 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2379 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2380 int num_urbs = tpriv->num_urbs;
2383 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2385 usbi_mutex_lock(&itransfer->lock);
2386 for (i = 0; i < num_urbs; i++) {
2387 if (urb == tpriv->iso_urbs[i]) {
2393 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2394 usbi_mutex_unlock(&itransfer->lock);
2395 return LIBUSB_ERROR_NOT_FOUND;
2398 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2401 /* copy isochronous results back in */
2403 for (i = 0; i < urb->number_of_packets; i++) {
2404 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2405 struct libusb_iso_packet_descriptor *lib_desc =
2406 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2408 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2409 switch (urb_desc->status) {
2412 case -ENOENT: /* cancelled */
2417 usbi_dbg("packet %d - device removed", i);
2418 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2421 usbi_dbg("packet %d - detected endpoint stall", i);
2422 lib_desc->status = LIBUSB_TRANSFER_STALL;
2425 usbi_dbg("packet %d - overflow error", i);
2426 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2434 usbi_dbg("packet %d - low-level USB error %d", i, urb_desc->status);
2435 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2438 usbi_warn(TRANSFER_CTX(transfer), "packet %d - unrecognised urb status %d",
2439 i, urb_desc->status);
2440 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2443 lib_desc->actual_length = urb_desc->actual_length;
2446 tpriv->num_retired++;
2448 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2449 usbi_dbg("CANCEL: urb status %d", urb->status);
2451 if (tpriv->num_retired == num_urbs) {
2452 usbi_dbg("CANCEL: last URB handled, reporting");
2453 free_iso_urbs(tpriv);
2454 if (tpriv->reap_action == CANCELLED) {
2455 usbi_mutex_unlock(&itransfer->lock);
2456 return usbi_handle_transfer_cancellation(itransfer);
2458 usbi_mutex_unlock(&itransfer->lock);
2459 return usbi_handle_transfer_completion(itransfer, LIBUSB_TRANSFER_ERROR);
2465 switch (urb->status) {
2468 case -ENOENT: /* cancelled */
2472 usbi_dbg("device removed");
2473 status = LIBUSB_TRANSFER_NO_DEVICE;
2476 usbi_warn(TRANSFER_CTX(transfer), "unrecognised urb status %d", urb->status);
2477 status = LIBUSB_TRANSFER_ERROR;
2481 /* if we've reaped all urbs then we're done */
2482 if (tpriv->num_retired == num_urbs) {
2483 usbi_dbg("all URBs in transfer reaped --> complete!");
2484 free_iso_urbs(tpriv);
2485 usbi_mutex_unlock(&itransfer->lock);
2486 return usbi_handle_transfer_completion(itransfer, status);
2490 usbi_mutex_unlock(&itransfer->lock);
2494 static int handle_control_completion(struct usbi_transfer *itransfer,
2495 struct usbfs_urb *urb)
2497 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2500 usbi_mutex_lock(&itransfer->lock);
2501 usbi_dbg("handling completion status %d", urb->status);
2503 itransfer->transferred += urb->actual_length;
2505 if (tpriv->reap_action == CANCELLED) {
2506 if (urb->status && urb->status != -ENOENT)
2507 usbi_warn(ITRANSFER_CTX(itransfer), "cancel: unrecognised urb status %d",
2511 usbi_mutex_unlock(&itransfer->lock);
2512 return usbi_handle_transfer_cancellation(itransfer);
2515 switch (urb->status) {
2517 status = LIBUSB_TRANSFER_COMPLETED;
2519 case -ENOENT: /* cancelled */
2520 status = LIBUSB_TRANSFER_CANCELLED;
2524 usbi_dbg("device removed");
2525 status = LIBUSB_TRANSFER_NO_DEVICE;
2528 usbi_dbg("unsupported control request");
2529 status = LIBUSB_TRANSFER_STALL;
2532 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2533 status = LIBUSB_TRANSFER_OVERFLOW;
2540 usbi_dbg("low-level bus error %d", urb->status);
2541 status = LIBUSB_TRANSFER_ERROR;
2544 usbi_warn(ITRANSFER_CTX(itransfer), "unrecognised urb status %d", urb->status);
2545 status = LIBUSB_TRANSFER_ERROR;
2551 usbi_mutex_unlock(&itransfer->lock);
2552 return usbi_handle_transfer_completion(itransfer, status);
2555 static int reap_for_handle(struct libusb_device_handle *handle)
2557 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
2559 struct usbfs_urb *urb = NULL;
2560 struct usbi_transfer *itransfer;
2561 struct libusb_transfer *transfer;
2563 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2565 if (errno == EAGAIN)
2567 if (errno == ENODEV)
2568 return LIBUSB_ERROR_NO_DEVICE;
2570 usbi_err(HANDLE_CTX(handle), "reap failed, errno=%d", errno);
2571 return LIBUSB_ERROR_IO;
2574 itransfer = urb->usercontext;
2575 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2577 usbi_dbg("urb type=%u status=%d transferred=%d", urb->type, urb->status, urb->actual_length);
2579 switch (transfer->type) {
2580 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2581 return handle_iso_completion(itransfer, urb);
2582 case LIBUSB_TRANSFER_TYPE_BULK:
2583 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2584 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2585 return handle_bulk_completion(itransfer, urb);
2586 case LIBUSB_TRANSFER_TYPE_CONTROL:
2587 return handle_control_completion(itransfer, urb);
2589 usbi_err(HANDLE_CTX(handle), "unrecognised transfer type %u", transfer->type);
2590 return LIBUSB_ERROR_OTHER;
2594 static int op_handle_events(struct libusb_context *ctx,
2595 struct pollfd *fds, usbi_nfds_t nfds, int num_ready)
2600 usbi_mutex_lock(&ctx->open_devs_lock);
2601 for (n = 0; n < nfds && num_ready > 0; n++) {
2602 struct pollfd *pollfd = &fds[n];
2603 struct libusb_device_handle *handle;
2604 struct linux_device_handle_priv *hpriv = NULL;
2606 if (!pollfd->revents)
2610 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2611 hpriv = usbi_get_device_handle_priv(handle);
2612 if (hpriv->fd == pollfd->fd)
2616 if (!hpriv || hpriv->fd != pollfd->fd) {
2617 usbi_err(ctx, "cannot find handle for fd %d",
2622 if (pollfd->revents & POLLERR) {
2623 /* remove the fd from the pollfd set so that it doesn't continuously
2624 * trigger an event, and flag that it has been removed so op_close()
2625 * doesn't try to remove it a second time */
2626 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2627 hpriv->fd_removed = 1;
2629 /* device will still be marked as attached if hotplug monitor thread
2630 * hasn't processed remove event yet */
2631 usbi_mutex_static_lock(&linux_hotplug_lock);
2632 if (handle->dev->attached)
2633 linux_device_disconnected(handle->dev->bus_number,
2634 handle->dev->device_address);
2635 usbi_mutex_static_unlock(&linux_hotplug_lock);
2637 if (hpriv->caps & USBFS_CAP_REAP_AFTER_DISCONNECT) {
2639 r = reap_for_handle(handle);
2643 usbi_handle_disconnect(handle);
2648 r = reap_for_handle(handle);
2650 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2658 usbi_mutex_unlock(&ctx->open_devs_lock);
2662 const struct usbi_os_backend usbi_backend = {
2663 .name = "Linux usbfs",
2664 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2667 .hotplug_poll = op_hotplug_poll,
2668 .get_device_descriptor = op_get_device_descriptor,
2669 .get_active_config_descriptor = op_get_active_config_descriptor,
2670 .get_config_descriptor = op_get_config_descriptor,
2671 .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2673 .wrap_sys_device = op_wrap_sys_device,
2676 .get_configuration = op_get_configuration,
2677 .set_configuration = op_set_configuration,
2678 .claim_interface = op_claim_interface,
2679 .release_interface = op_release_interface,
2681 .set_interface_altsetting = op_set_interface,
2682 .clear_halt = op_clear_halt,
2683 .reset_device = op_reset_device,
2685 .alloc_streams = op_alloc_streams,
2686 .free_streams = op_free_streams,
2688 .dev_mem_alloc = op_dev_mem_alloc,
2689 .dev_mem_free = op_dev_mem_free,
2691 .kernel_driver_active = op_kernel_driver_active,
2692 .detach_kernel_driver = op_detach_kernel_driver,
2693 .attach_kernel_driver = op_attach_kernel_driver,
2695 .destroy_device = op_destroy_device,
2697 .submit_transfer = op_submit_transfer,
2698 .cancel_transfer = op_cancel_transfer,
2699 .clear_transfer_priv = op_clear_transfer_priv,
2701 .handle_events = op_handle_events,
2703 .device_priv_size = sizeof(struct linux_device_priv),
2704 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2705 .transfer_priv_size = sizeof(struct linux_transfer_priv),