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, int *host_endian)
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;
705 /* Unlike the device desc. config descs. are always in raw format */
708 /* Skip device header */
709 descriptors += LIBUSB_DT_DEVICE_SIZE;
710 size -= LIBUSB_DT_DEVICE_SIZE;
712 /* Seek till the config is found, or till "EOF" */
714 int next = seek_to_next_config(dev, descriptors, size);
718 config = (struct usbi_configuration_descriptor *)descriptors;
719 if (config->bConfigurationValue == value) {
720 *buffer = descriptors;
728 static int op_get_active_config_descriptor(struct libusb_device *dev,
729 unsigned char *buffer, size_t len, int *host_endian)
731 struct linux_device_priv *priv = usbi_get_device_priv(dev);
733 unsigned char *config_desc;
735 if (priv->sysfs_dir) {
736 r = sysfs_get_active_config(dev, &config);
740 /* Use cached bConfigurationValue */
741 config = priv->active_config;
744 return LIBUSB_ERROR_NOT_FOUND;
746 r = op_get_config_descriptor_by_value(dev, config, &config_desc,
751 len = MIN(len, (size_t)r);
752 memcpy(buffer, config_desc, len);
756 static int op_get_config_descriptor(struct libusb_device *dev,
757 uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
759 struct linux_device_priv *priv = usbi_get_device_priv(dev);
760 unsigned char *descriptors = priv->descriptors;
761 int i, r, size = priv->descriptors_len;
763 /* Unlike the device desc. config descs. are always in raw format */
766 /* Skip device header */
767 descriptors += LIBUSB_DT_DEVICE_SIZE;
768 size -= LIBUSB_DT_DEVICE_SIZE;
770 /* Seek till the config is found, or till "EOF" */
772 r = seek_to_next_config(dev, descriptors, size);
775 if (i == config_index)
781 len = MIN(len, (size_t)r);
782 memcpy(buffer, descriptors, len);
786 /* send a control message to retrieve active configuration */
787 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
789 struct linux_device_priv *priv = usbi_get_device_priv(dev);
790 unsigned char active_config = 0;
793 struct usbfs_ctrltransfer ctrl = {
794 .bmRequestType = LIBUSB_ENDPOINT_IN,
795 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
800 .data = &active_config
803 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
806 return LIBUSB_ERROR_NO_DEVICE;
808 /* we hit this error path frequently with buggy devices :( */
809 usbi_warn(DEVICE_CTX(dev), "get configuration failed, errno=%d", errno);
810 priv->active_config = -1;
812 if (active_config > 0) {
813 priv->active_config = active_config;
815 /* some buggy devices have a configuration 0, but we're
816 * reaching into the corner of a corner case here, so let's
817 * not support buggy devices in these circumstances.
818 * stick to the specs: a configuration value of 0 means
820 usbi_warn(DEVICE_CTX(dev), "active cfg 0? assuming unconfigured device");
821 priv->active_config = -1;
825 return LIBUSB_SUCCESS;
828 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
829 uint8_t devaddr, const char *sysfs_dir, int wrapped_fd)
831 struct linux_device_priv *priv = usbi_get_device_priv(dev);
832 struct libusb_context *ctx = DEVICE_CTX(dev);
833 int descriptors_size = 0;
837 dev->bus_number = busnum;
838 dev->device_address = devaddr;
841 priv->sysfs_dir = strdup(sysfs_dir);
842 if (!priv->sysfs_dir)
843 return LIBUSB_ERROR_NO_MEM;
845 /* Note speed can contain 1.5, in this case read_sysfs_attr()
846 will stop parsing at the '.' and return 1 */
847 if (read_sysfs_attr(ctx, sysfs_dir, "speed", INT_MAX, &speed) == 0) {
849 case 1: dev->speed = LIBUSB_SPEED_LOW; break;
850 case 12: dev->speed = LIBUSB_SPEED_FULL; break;
851 case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
852 case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
853 case 10000: dev->speed = LIBUSB_SPEED_SUPER_PLUS; break;
855 usbi_warn(ctx, "unknown device speed: %d Mbps", speed);
860 /* cache descriptors in memory */
862 fd = open_sysfs_attr(ctx, sysfs_dir, "descriptors");
863 } else if (wrapped_fd < 0) {
864 fd = get_usbfs_fd(dev, O_RDONLY, 0);
867 r = lseek(fd, 0, SEEK_SET);
869 usbi_err(ctx, "lseek failed, errno=%d", errno);
870 return LIBUSB_ERROR_IO;
877 descriptors_size += 256;
878 priv->descriptors = usbi_reallocf(priv->descriptors, descriptors_size);
879 if (!priv->descriptors) {
880 if (fd != wrapped_fd)
882 return LIBUSB_ERROR_NO_MEM;
884 /* usbfs has holes in the file */
886 memset(priv->descriptors + priv->descriptors_len,
887 0, descriptors_size - priv->descriptors_len);
889 r = read(fd, priv->descriptors + priv->descriptors_len,
890 descriptors_size - priv->descriptors_len);
892 usbi_err(ctx, "read descriptor failed, errno=%d", errno);
893 if (fd != wrapped_fd)
895 return LIBUSB_ERROR_IO;
897 priv->descriptors_len += r;
898 } while (priv->descriptors_len == descriptors_size);
900 if (fd != wrapped_fd)
903 if (priv->descriptors_len < LIBUSB_DT_DEVICE_SIZE) {
904 usbi_err(ctx, "short descriptor read (%d)", priv->descriptors_len);
905 return LIBUSB_ERROR_IO;
909 return LIBUSB_SUCCESS;
911 /* cache active config */
913 fd = get_usbfs_fd(dev, O_RDWR, 1);
917 /* cannot send a control message to determine the active
918 * config. just assume the first one is active. */
919 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
920 "active configuration descriptor");
921 if (priv->descriptors_len >= (LIBUSB_DT_DEVICE_SIZE + LIBUSB_DT_CONFIG_SIZE)) {
922 struct usbi_configuration_descriptor *config;
924 config = (struct usbi_configuration_descriptor *)(priv->descriptors + LIBUSB_DT_DEVICE_SIZE);
925 priv->active_config = config->bConfigurationValue;
927 priv->active_config = -1; /* No config dt */
930 return LIBUSB_SUCCESS;
933 r = usbfs_get_active_config(dev, fd);
934 if (fd != wrapped_fd)
940 static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir)
942 struct libusb_context *ctx = DEVICE_CTX(dev);
943 struct libusb_device *it;
944 char *parent_sysfs_dir, *tmp;
945 int ret, add_parent = 1;
947 /* XXX -- can we figure out the topology when using usbfs? */
948 if (!sysfs_dir || !strncmp(sysfs_dir, "usb", 3)) {
949 /* either using usbfs or finding the parent of a root hub */
950 return LIBUSB_SUCCESS;
953 parent_sysfs_dir = strdup(sysfs_dir);
954 if (!parent_sysfs_dir)
955 return LIBUSB_ERROR_NO_MEM;
957 if ((tmp = strrchr(parent_sysfs_dir, '.')) ||
958 (tmp = strrchr(parent_sysfs_dir, '-'))) {
959 dev->port_number = atoi(tmp + 1);
962 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
964 free(parent_sysfs_dir);
965 return LIBUSB_SUCCESS;
968 /* is the parent a root hub? */
969 if (!strchr(parent_sysfs_dir, '-')) {
970 tmp = parent_sysfs_dir;
971 ret = asprintf(&parent_sysfs_dir, "usb%s", tmp);
974 return LIBUSB_ERROR_NO_MEM;
978 /* find the parent in the context */
979 usbi_mutex_lock(&ctx->usb_devs_lock);
980 list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device) {
981 struct linux_device_priv *priv = usbi_get_device_priv(it);
983 if (priv->sysfs_dir) {
984 if (!strcmp(priv->sysfs_dir, parent_sysfs_dir)) {
985 dev->parent_dev = libusb_ref_device(it);
990 usbi_mutex_unlock(&ctx->usb_devs_lock);
992 if (!dev->parent_dev && add_parent) {
993 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
995 sysfs_scan_device(ctx, parent_sysfs_dir);
1000 usbi_dbg("dev %p (%s) has parent %p (%s) port %u", dev, sysfs_dir,
1001 dev->parent_dev, parent_sysfs_dir, dev->port_number);
1003 free(parent_sysfs_dir);
1005 return LIBUSB_SUCCESS;
1008 int linux_enumerate_device(struct libusb_context *ctx,
1009 uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1011 unsigned long session_id;
1012 struct libusb_device *dev;
1015 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1016 * will be reused. instead we should add a simple sysfs attribute with
1018 session_id = busnum << 8 | devaddr;
1019 usbi_dbg("busnum %u devaddr %u session_id %lu", busnum, devaddr, session_id);
1021 dev = usbi_get_device_by_session_id(ctx, session_id);
1023 /* device already exists in the context */
1024 usbi_dbg("session_id %lu already exists", session_id);
1025 libusb_unref_device(dev);
1026 return LIBUSB_SUCCESS;
1029 usbi_dbg("allocating new device for %u/%u (session %lu)",
1030 busnum, devaddr, session_id);
1031 dev = usbi_alloc_device(ctx, session_id);
1033 return LIBUSB_ERROR_NO_MEM;
1035 r = initialize_device(dev, busnum, devaddr, sysfs_dir, -1);
1038 r = usbi_sanitize_device(dev);
1042 r = linux_get_parent_info(dev, sysfs_dir);
1047 libusb_unref_device(dev);
1049 usbi_connect_device(dev);
1054 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1056 struct libusb_context *ctx;
1058 usbi_mutex_static_lock(&active_contexts_lock);
1059 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1060 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1062 usbi_mutex_static_unlock(&active_contexts_lock);
1065 void linux_device_disconnected(uint8_t busnum, uint8_t devaddr)
1067 struct libusb_context *ctx;
1068 struct libusb_device *dev;
1069 unsigned long session_id = busnum << 8 | devaddr;
1071 usbi_mutex_static_lock(&active_contexts_lock);
1072 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1073 dev = usbi_get_device_by_session_id (ctx, session_id);
1075 usbi_disconnect_device(dev);
1076 libusb_unref_device(dev);
1078 usbi_dbg("device not found for session %lx", session_id);
1081 usbi_mutex_static_unlock(&active_contexts_lock);
1084 #if !defined(HAVE_LIBUDEV)
1085 static int parse_u8(const char *str, uint8_t *val_p)
1091 num = strtol(str, &endptr, 10);
1092 if (num < 0 || num > UINT8_MAX || errno)
1094 if (endptr == str || *endptr != '\0')
1097 *val_p = (uint8_t)num;
1101 /* open a bus directory and adds all discovered devices to the context */
1102 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1106 struct dirent *entry;
1107 int r = LIBUSB_ERROR_IO;
1109 sprintf(dirpath, USB_DEVTMPFS_PATH "/%03u", busnum);
1110 usbi_dbg("%s", dirpath);
1111 dir = opendir(dirpath);
1113 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1114 /* FIXME: should handle valid race conditions like hub unplugged
1115 * during directory iteration - this is not an error */
1119 while ((entry = readdir(dir))) {
1122 if (entry->d_name[0] == '.')
1125 if (!parse_u8(entry->d_name, &devaddr)) {
1126 usbi_dbg("unknown dir entry %s", entry->d_name);
1130 if (linux_enumerate_device(ctx, busnum, devaddr, NULL)) {
1131 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1142 static int usbfs_get_device_list(struct libusb_context *ctx)
1144 struct dirent *entry;
1146 uint8_t busnum, devaddr;
1150 buses = opendir(USBDEV_PATH);
1152 buses = opendir(USB_DEVTMPFS_PATH);
1155 usbi_err(ctx, "opendir buses failed, errno=%d", errno);
1156 return LIBUSB_ERROR_IO;
1159 while ((entry = readdir(buses))) {
1160 if (entry->d_name[0] == '.')
1164 if (!is_usbdev_entry(entry->d_name, &busnum, &devaddr))
1167 r = linux_enumerate_device(ctx, busnum, devaddr, NULL);
1169 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1173 if (!parse_u8(entry->d_name, &busnum)) {
1174 usbi_dbg("unknown dir entry %s", entry->d_name);
1178 r = usbfs_scan_busdir(ctx, busnum);
1189 static int sysfs_get_device_list(struct libusb_context *ctx)
1191 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1192 struct dirent *entry;
1193 int num_devices = 0;
1194 int num_enumerated = 0;
1197 usbi_err(ctx, "opendir devices failed, errno=%d", errno);
1198 return LIBUSB_ERROR_IO;
1201 while ((entry = readdir(devices))) {
1202 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1203 || strchr(entry->d_name, ':'))
1208 if (sysfs_scan_device(ctx, entry->d_name)) {
1209 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1218 /* successful if at least one device was enumerated or no devices were found */
1219 if (num_enumerated || !num_devices)
1220 return LIBUSB_SUCCESS;
1222 return LIBUSB_ERROR_IO;
1225 static int linux_default_scan_devices(struct libusb_context *ctx)
1227 /* we can retrieve device list and descriptors from sysfs or usbfs.
1228 * sysfs is preferable, because if we use usbfs we end up resuming
1229 * any autosuspended USB devices. however, sysfs is not available
1230 * everywhere, so we need a usbfs fallback too.
1232 if (sysfs_available)
1233 return sysfs_get_device_list(ctx);
1235 return usbfs_get_device_list(ctx);
1239 static int initialize_handle(struct libusb_device_handle *handle, int fd)
1241 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1246 r = ioctl(fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1248 if (errno == ENOTTY)
1249 usbi_dbg("getcap not available");
1251 usbi_err(HANDLE_CTX(handle), "getcap failed, errno=%d", errno);
1252 hpriv->caps = USBFS_CAP_BULK_CONTINUATION;
1255 return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1258 static int op_wrap_sys_device(struct libusb_context *ctx,
1259 struct libusb_device_handle *handle, intptr_t sys_dev)
1261 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1262 int fd = (int)sys_dev;
1263 uint8_t busnum, devaddr;
1264 struct usbfs_connectinfo ci;
1265 struct libusb_device *dev;
1268 r = linux_get_device_address(ctx, 1, &busnum, &devaddr, NULL, NULL, fd);
1270 r = ioctl(fd, IOCTL_USBFS_CONNECTINFO, &ci);
1272 usbi_err(ctx, "connectinfo failed, errno=%d", errno);
1273 return LIBUSB_ERROR_IO;
1275 /* There is no ioctl to get the bus number. We choose 0 here
1276 * as linux starts numbering buses from 1. */
1278 devaddr = ci.devnum;
1281 /* Session id is unused as we do not add the device to the list of
1282 * connected devices. */
1283 usbi_dbg("allocating new device for fd %d", fd);
1284 dev = usbi_alloc_device(ctx, 0);
1286 return LIBUSB_ERROR_NO_MEM;
1288 r = initialize_device(dev, busnum, devaddr, NULL, fd);
1291 r = usbi_sanitize_device(dev);
1294 /* Consider the device as connected, but do not add it to the managed
1299 r = initialize_handle(handle, fd);
1304 libusb_unref_device(dev);
1308 static int op_open(struct libusb_device_handle *handle)
1312 fd = get_usbfs_fd(handle->dev, O_RDWR, 0);
1314 if (fd == LIBUSB_ERROR_NO_DEVICE) {
1315 /* device will still be marked as attached if hotplug monitor thread
1316 * hasn't processed remove event yet */
1317 usbi_mutex_static_lock(&linux_hotplug_lock);
1318 if (handle->dev->attached) {
1319 usbi_dbg("open failed with no device, but device still attached");
1320 linux_device_disconnected(handle->dev->bus_number,
1321 handle->dev->device_address);
1323 usbi_mutex_static_unlock(&linux_hotplug_lock);
1328 r = initialize_handle(handle, fd);
1335 static void op_close(struct libusb_device_handle *dev_handle)
1337 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(dev_handle);
1339 /* fd may have already been removed by POLLERR condition in op_handle_events() */
1340 if (!hpriv->fd_removed)
1341 usbi_remove_pollfd(HANDLE_CTX(dev_handle), hpriv->fd);
1342 if (!hpriv->fd_keep)
1346 static int op_get_configuration(struct libusb_device_handle *handle,
1349 struct linux_device_priv *priv = usbi_get_device_priv(handle->dev);
1352 if (priv->sysfs_dir) {
1353 r = sysfs_get_active_config(handle->dev, config);
1355 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1357 r = usbfs_get_active_config(handle->dev, hpriv->fd);
1358 if (r == LIBUSB_SUCCESS)
1359 *config = priv->active_config;
1364 if (*config == -1) {
1365 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1372 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1374 struct linux_device_priv *priv = usbi_get_device_priv(handle->dev);
1375 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1377 int r = ioctl(fd, IOCTL_USBFS_SETCONFIGURATION, &config);
1380 if (errno == EINVAL)
1381 return LIBUSB_ERROR_NOT_FOUND;
1382 else if (errno == EBUSY)
1383 return LIBUSB_ERROR_BUSY;
1384 else if (errno == ENODEV)
1385 return LIBUSB_ERROR_NO_DEVICE;
1387 usbi_err(HANDLE_CTX(handle), "set configuration failed, errno=%d", errno);
1388 return LIBUSB_ERROR_OTHER;
1391 /* update our cached active config descriptor */
1392 priv->active_config = config;
1394 return LIBUSB_SUCCESS;
1397 static int claim_interface(struct libusb_device_handle *handle, int iface)
1399 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1401 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTERFACE, &iface);
1404 if (errno == ENOENT)
1405 return LIBUSB_ERROR_NOT_FOUND;
1406 else if (errno == EBUSY)
1407 return LIBUSB_ERROR_BUSY;
1408 else if (errno == ENODEV)
1409 return LIBUSB_ERROR_NO_DEVICE;
1411 usbi_err(HANDLE_CTX(handle), "claim interface failed, errno=%d", errno);
1412 return LIBUSB_ERROR_OTHER;
1417 static int release_interface(struct libusb_device_handle *handle, int iface)
1419 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1421 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTERFACE, &iface);
1424 if (errno == ENODEV)
1425 return LIBUSB_ERROR_NO_DEVICE;
1427 usbi_err(HANDLE_CTX(handle), "release interface failed, errno=%d", errno);
1428 return LIBUSB_ERROR_OTHER;
1433 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1436 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1438 struct usbfs_setinterface setintf;
1441 setintf.interface = iface;
1442 setintf.altsetting = altsetting;
1443 r = ioctl(fd, IOCTL_USBFS_SETINTERFACE, &setintf);
1445 if (errno == EINVAL)
1446 return LIBUSB_ERROR_NOT_FOUND;
1447 else if (errno == ENODEV)
1448 return LIBUSB_ERROR_NO_DEVICE;
1450 usbi_err(HANDLE_CTX(handle), "set interface failed, errno=%d", errno);
1451 return LIBUSB_ERROR_OTHER;
1457 static int op_clear_halt(struct libusb_device_handle *handle,
1458 unsigned char endpoint)
1460 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1462 unsigned int _endpoint = endpoint;
1463 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1466 if (errno == ENOENT)
1467 return LIBUSB_ERROR_NOT_FOUND;
1468 else if (errno == ENODEV)
1469 return LIBUSB_ERROR_NO_DEVICE;
1471 usbi_err(HANDLE_CTX(handle), "clear halt failed, errno=%d", errno);
1472 return LIBUSB_ERROR_OTHER;
1478 static int op_reset_device(struct libusb_device_handle *handle)
1480 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1484 /* Doing a device reset will cause the usbfs driver to get unbound
1485 * from any interfaces it is bound to. By voluntarily unbinding
1486 * the usbfs driver ourself, we stop the kernel from rebinding
1487 * the interface after reset (which would end up with the interface
1488 * getting bound to the in kernel driver if any). */
1489 for (i = 0; i < USB_MAXINTERFACES; i++) {
1490 if (handle->claimed_interfaces & (1UL << i))
1491 release_interface(handle, i);
1494 usbi_mutex_lock(&handle->lock);
1495 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1497 if (errno == ENODEV) {
1498 ret = LIBUSB_ERROR_NOT_FOUND;
1502 usbi_err(HANDLE_CTX(handle), "reset failed, errno=%d", errno);
1503 ret = LIBUSB_ERROR_OTHER;
1507 /* And re-claim any interfaces which were claimed before the reset */
1508 for (i = 0; i < USB_MAXINTERFACES; i++) {
1509 if (!(handle->claimed_interfaces & (1UL << i)))
1512 * A driver may have completed modprobing during
1513 * IOCTL_USBFS_RESET, and bound itself as soon as
1514 * IOCTL_USBFS_RESET released the device lock
1516 r = detach_kernel_driver_and_claim(handle, i);
1518 usbi_warn(HANDLE_CTX(handle), "failed to re-claim interface %d after reset: %s",
1519 i, libusb_error_name(r));
1520 handle->claimed_interfaces &= ~(1UL << i);
1521 ret = LIBUSB_ERROR_NOT_FOUND;
1525 usbi_mutex_unlock(&handle->lock);
1529 static int do_streams_ioctl(struct libusb_device_handle *handle, long req,
1530 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1532 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1533 int r, fd = hpriv->fd;
1534 struct usbfs_streams *streams;
1536 if (num_endpoints > 30) /* Max 15 in + 15 out eps */
1537 return LIBUSB_ERROR_INVALID_PARAM;
1539 streams = malloc(sizeof(*streams) + num_endpoints);
1541 return LIBUSB_ERROR_NO_MEM;
1543 streams->num_streams = num_streams;
1544 streams->num_eps = num_endpoints;
1545 memcpy(streams->eps, endpoints, num_endpoints);
1547 r = ioctl(fd, req, streams);
1552 if (errno == ENOTTY)
1553 return LIBUSB_ERROR_NOT_SUPPORTED;
1554 else if (errno == EINVAL)
1555 return LIBUSB_ERROR_INVALID_PARAM;
1556 else if (errno == ENODEV)
1557 return LIBUSB_ERROR_NO_DEVICE;
1559 usbi_err(HANDLE_CTX(handle), "streams-ioctl failed, errno=%d", errno);
1560 return LIBUSB_ERROR_OTHER;
1565 static int op_alloc_streams(struct libusb_device_handle *handle,
1566 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1568 return do_streams_ioctl(handle, IOCTL_USBFS_ALLOC_STREAMS,
1569 num_streams, endpoints, num_endpoints);
1572 static int op_free_streams(struct libusb_device_handle *handle,
1573 unsigned char *endpoints, int num_endpoints)
1575 return do_streams_ioctl(handle, IOCTL_USBFS_FREE_STREAMS, 0,
1576 endpoints, num_endpoints);
1579 static unsigned char *op_dev_mem_alloc(struct libusb_device_handle *handle,
1582 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1583 unsigned char *buffer;
1585 buffer = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, hpriv->fd, 0);
1586 if (buffer == MAP_FAILED) {
1587 usbi_err(HANDLE_CTX(handle), "alloc dev mem failed, errno=%d", errno);
1593 static int op_dev_mem_free(struct libusb_device_handle *handle,
1594 unsigned char *buffer, size_t len)
1596 if (munmap(buffer, len) != 0) {
1597 usbi_err(HANDLE_CTX(handle), "free dev mem failed, errno=%d", errno);
1598 return LIBUSB_ERROR_OTHER;
1600 return LIBUSB_SUCCESS;
1604 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1607 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1609 struct usbfs_getdriver getdrv;
1612 getdrv.interface = interface;
1613 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1615 if (errno == ENODATA)
1617 else if (errno == ENODEV)
1618 return LIBUSB_ERROR_NO_DEVICE;
1620 usbi_err(HANDLE_CTX(handle), "get driver failed, errno=%d", errno);
1621 return LIBUSB_ERROR_OTHER;
1624 return strcmp(getdrv.driver, "usbfs") != 0;
1627 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1630 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1632 struct usbfs_ioctl command;
1633 struct usbfs_getdriver getdrv;
1636 command.ifno = interface;
1637 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1638 command.data = NULL;
1640 getdrv.interface = interface;
1641 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1642 if (r == 0 && !strcmp(getdrv.driver, "usbfs"))
1643 return LIBUSB_ERROR_NOT_FOUND;
1645 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1647 if (errno == ENODATA)
1648 return LIBUSB_ERROR_NOT_FOUND;
1649 else if (errno == EINVAL)
1650 return LIBUSB_ERROR_INVALID_PARAM;
1651 else if (errno == ENODEV)
1652 return LIBUSB_ERROR_NO_DEVICE;
1654 usbi_err(HANDLE_CTX(handle), "detach failed, errno=%d", errno);
1655 return LIBUSB_ERROR_OTHER;
1661 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1664 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1666 struct usbfs_ioctl command;
1669 command.ifno = interface;
1670 command.ioctl_code = IOCTL_USBFS_CONNECT;
1671 command.data = NULL;
1673 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1675 if (errno == ENODATA)
1676 return LIBUSB_ERROR_NOT_FOUND;
1677 else if (errno == EINVAL)
1678 return LIBUSB_ERROR_INVALID_PARAM;
1679 else if (errno == ENODEV)
1680 return LIBUSB_ERROR_NO_DEVICE;
1681 else if (errno == EBUSY)
1682 return LIBUSB_ERROR_BUSY;
1684 usbi_err(HANDLE_CTX(handle), "attach failed, errno=%d", errno);
1685 return LIBUSB_ERROR_OTHER;
1686 } else if (r == 0) {
1687 return LIBUSB_ERROR_NOT_FOUND;
1693 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle,
1696 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
1697 struct usbfs_disconnect_claim dc;
1698 int r, fd = hpriv->fd;
1700 dc.interface = interface;
1701 strcpy(dc.driver, "usbfs");
1702 dc.flags = USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER;
1703 r = ioctl(fd, IOCTL_USBFS_DISCONNECT_CLAIM, &dc);
1710 return LIBUSB_ERROR_BUSY;
1712 return LIBUSB_ERROR_INVALID_PARAM;
1714 return LIBUSB_ERROR_NO_DEVICE;
1716 usbi_err(HANDLE_CTX(handle), "disconnect-and-claim failed, errno=%d", errno);
1717 return LIBUSB_ERROR_OTHER;
1720 /* Fallback code for kernels which don't support the
1721 disconnect-and-claim ioctl */
1722 r = op_detach_kernel_driver(handle, interface);
1723 if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND)
1726 return claim_interface(handle, interface);
1729 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1731 if (handle->auto_detach_kernel_driver)
1732 return detach_kernel_driver_and_claim(handle, iface);
1734 return claim_interface(handle, iface);
1737 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1741 r = release_interface(handle, iface);
1745 if (handle->auto_detach_kernel_driver)
1746 op_attach_kernel_driver(handle, iface);
1751 static void op_destroy_device(struct libusb_device *dev)
1753 struct linux_device_priv *priv = usbi_get_device_priv(dev);
1755 free(priv->descriptors);
1756 free(priv->sysfs_dir);
1759 /* URBs are discarded in reverse order of submission to avoid races. */
1760 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1762 struct libusb_transfer *transfer =
1763 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1764 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
1765 struct linux_device_handle_priv *hpriv =
1766 usbi_get_device_handle_priv(transfer->dev_handle);
1768 struct usbfs_urb *urb;
1770 for (i = last_plus_one - 1; i >= first; i--) {
1771 if (transfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS)
1772 urb = tpriv->iso_urbs[i];
1774 urb = &tpriv->urbs[i];
1776 if (ioctl(hpriv->fd, IOCTL_USBFS_DISCARDURB, urb) == 0)
1779 if (errno == EINVAL) {
1780 usbi_dbg("URB not found --> assuming ready to be reaped");
1781 if (i == (last_plus_one - 1))
1782 ret = LIBUSB_ERROR_NOT_FOUND;
1783 } else if (errno == ENODEV) {
1784 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1785 ret = LIBUSB_ERROR_NO_DEVICE;
1787 usbi_warn(TRANSFER_CTX(transfer), "unrecognised discard errno %d", errno);
1788 ret = LIBUSB_ERROR_OTHER;
1794 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1798 for (i = 0; i < tpriv->num_urbs; i++) {
1799 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1806 free(tpriv->iso_urbs);
1807 tpriv->iso_urbs = NULL;
1810 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1812 struct libusb_transfer *transfer =
1813 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1814 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
1815 struct linux_device_handle_priv *hpriv =
1816 usbi_get_device_handle_priv(transfer->dev_handle);
1817 struct usbfs_urb *urbs;
1818 int is_out = IS_XFEROUT(transfer);
1819 int bulk_buffer_len, use_bulk_continuation;
1821 int last_urb_partial = 0;
1826 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1827 * around this by splitting large transfers into 16k blocks, and then
1828 * submit all urbs at once. it would be simpler to submit one urb at
1829 * a time, but there is a big performance gain doing it this way.
1831 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1832 * using arbritary large transfers can still be a bad idea though, as
1833 * the kernel needs to allocate physical contiguous memory for this,
1834 * which may fail for large buffers.
1836 * The kernel solves this problem by splitting the transfer into
1837 * blocks itself when the host-controller is scatter-gather capable
1838 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1840 * Last, there is the issue of short-transfers when splitting, for
1841 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1842 * is needed, but this is not always available.
1844 if (hpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1845 /* Good! Just submit everything in one go */
1846 bulk_buffer_len = transfer->length ? transfer->length : 1;
1847 use_bulk_continuation = 0;
1848 } else if (hpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1849 /* Split the transfers and use bulk-continuation to
1850 avoid issues with short-transfers */
1851 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1852 use_bulk_continuation = 1;
1853 } else if (hpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1854 /* Don't split, assume the kernel can alloc the buffer
1855 (otherwise the submit will fail with -ENOMEM) */
1856 bulk_buffer_len = transfer->length ? transfer->length : 1;
1857 use_bulk_continuation = 0;
1859 /* Bad, splitting without bulk-continuation, short transfers
1860 which end before the last urb will not work reliable! */
1861 /* Note we don't warn here as this is "normal" on kernels <
1862 2.6.32 and not a problem for most applications */
1863 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1864 use_bulk_continuation = 0;
1867 num_urbs = transfer->length / bulk_buffer_len;
1869 if (transfer->length == 0) {
1871 } else if ((transfer->length % bulk_buffer_len) > 0) {
1872 last_urb_partial = 1;
1875 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs, transfer->length);
1876 urbs = calloc(num_urbs, sizeof(*urbs));
1878 return LIBUSB_ERROR_NO_MEM;
1880 tpriv->num_urbs = num_urbs;
1881 tpriv->num_retired = 0;
1882 tpriv->reap_action = NORMAL;
1883 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1885 for (i = 0; i < num_urbs; i++) {
1886 struct usbfs_urb *urb = &urbs[i];
1888 urb->usercontext = itransfer;
1889 switch (transfer->type) {
1890 case LIBUSB_TRANSFER_TYPE_BULK:
1891 urb->type = USBFS_URB_TYPE_BULK;
1894 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1895 urb->type = USBFS_URB_TYPE_BULK;
1896 urb->stream_id = itransfer->stream_id;
1898 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1899 urb->type = USBFS_URB_TYPE_INTERRUPT;
1902 urb->endpoint = transfer->endpoint;
1903 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
1905 /* don't set the short not ok flag for the last URB */
1906 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
1907 urb->flags = USBFS_URB_SHORT_NOT_OK;
1909 if (i == num_urbs - 1 && last_urb_partial)
1910 urb->buffer_length = transfer->length % bulk_buffer_len;
1911 else if (transfer->length == 0)
1912 urb->buffer_length = 0;
1914 urb->buffer_length = bulk_buffer_len;
1916 if (i > 0 && use_bulk_continuation)
1917 urb->flags |= USBFS_URB_BULK_CONTINUATION;
1919 /* we have already checked that the flag is supported */
1920 if (is_out && i == num_urbs - 1 &&
1921 (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET))
1922 urb->flags |= USBFS_URB_ZERO_PACKET;
1924 r = ioctl(hpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1928 if (errno == ENODEV) {
1929 r = LIBUSB_ERROR_NO_DEVICE;
1930 } else if (errno == ENOMEM) {
1931 r = LIBUSB_ERROR_NO_MEM;
1933 usbi_err(TRANSFER_CTX(transfer), "submiturb failed, errno=%d", errno);
1934 r = LIBUSB_ERROR_IO;
1937 /* if the first URB submission fails, we can simply free up and
1938 * return failure immediately. */
1940 usbi_dbg("first URB failed, easy peasy");
1946 /* if it's not the first URB that failed, the situation is a bit
1947 * tricky. we may need to discard all previous URBs. there are
1949 * - discarding is asynchronous - discarded urbs will be reaped
1950 * later. the user must not have freed the transfer when the
1951 * discarded URBs are reaped, otherwise libusb will be using
1953 * - the earlier URBs may have completed successfully and we do
1954 * not want to throw away any data.
1955 * - this URB failing may be no error; EREMOTEIO means that
1956 * this transfer simply didn't need all the URBs we submitted
1957 * so, we report that the transfer was submitted successfully and
1958 * in case of error we discard all previous URBs. later when
1959 * the final reap completes we can report error to the user,
1960 * or success if an earlier URB was completed successfully.
1962 tpriv->reap_action = errno == EREMOTEIO ? COMPLETED_EARLY : SUBMIT_FAILED;
1964 /* The URBs we haven't submitted yet we count as already
1966 tpriv->num_retired += num_urbs - i;
1968 /* If we completed short then don't try to discard. */
1969 if (tpriv->reap_action == COMPLETED_EARLY)
1972 discard_urbs(itransfer, 0, i);
1974 usbi_dbg("reporting successful submission but waiting for %d "
1975 "discards before reporting error", i);
1982 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1984 struct libusb_transfer *transfer =
1985 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1986 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
1987 struct linux_device_handle_priv *hpriv =
1988 usbi_get_device_handle_priv(transfer->dev_handle);
1989 struct usbfs_urb **urbs;
1990 int num_packets = transfer->num_iso_packets;
1991 int num_packets_remaining;
1994 unsigned int packet_len;
1995 unsigned int total_len = 0;
1996 unsigned char *urb_buffer = transfer->buffer;
1998 if (num_packets < 1)
1999 return LIBUSB_ERROR_INVALID_PARAM;
2001 /* usbfs places arbitrary limits on iso URBs. this limit has changed
2002 * at least three times, but we attempt to detect this limit during
2003 * init and check it here. if the kernel rejects the request due to
2004 * its size, we return an error indicating such to the user.
2006 for (i = 0; i < num_packets; i++) {
2007 packet_len = transfer->iso_packet_desc[i].length;
2009 if (packet_len > max_iso_packet_len) {
2010 usbi_warn(TRANSFER_CTX(transfer),
2011 "iso packet length of %u bytes exceeds maximum of %u bytes",
2012 packet_len, max_iso_packet_len);
2013 return LIBUSB_ERROR_INVALID_PARAM;
2016 total_len += packet_len;
2019 if (transfer->length < (int)total_len)
2020 return LIBUSB_ERROR_INVALID_PARAM;
2022 /* usbfs limits the number of iso packets per URB */
2023 num_urbs = (num_packets + (MAX_ISO_PACKETS_PER_URB - 1)) / MAX_ISO_PACKETS_PER_URB;
2025 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs, transfer->length);
2027 urbs = calloc(num_urbs, sizeof(*urbs));
2029 return LIBUSB_ERROR_NO_MEM;
2031 tpriv->iso_urbs = urbs;
2032 tpriv->num_urbs = num_urbs;
2033 tpriv->num_retired = 0;
2034 tpriv->reap_action = NORMAL;
2035 tpriv->iso_packet_offset = 0;
2037 /* allocate + initialize each URB with the correct number of packets */
2038 num_packets_remaining = num_packets;
2039 for (i = 0, j = 0; i < num_urbs; i++) {
2040 int num_packets_in_urb = MIN(num_packets_remaining, MAX_ISO_PACKETS_PER_URB);
2041 struct usbfs_urb *urb;
2045 alloc_size = sizeof(*urb)
2046 + (num_packets_in_urb * sizeof(struct usbfs_iso_packet_desc));
2047 urb = calloc(1, alloc_size);
2049 free_iso_urbs(tpriv);
2050 return LIBUSB_ERROR_NO_MEM;
2054 /* populate packet lengths */
2055 for (k = 0; k < num_packets_in_urb; j++, k++) {
2056 packet_len = transfer->iso_packet_desc[j].length;
2057 urb->buffer_length += packet_len;
2058 urb->iso_frame_desc[k].length = packet_len;
2061 urb->usercontext = itransfer;
2062 urb->type = USBFS_URB_TYPE_ISO;
2063 /* FIXME: interface for non-ASAP data? */
2064 urb->flags = USBFS_URB_ISO_ASAP;
2065 urb->endpoint = transfer->endpoint;
2066 urb->number_of_packets = num_packets_in_urb;
2067 urb->buffer = urb_buffer;
2069 urb_buffer += urb->buffer_length;
2070 num_packets_remaining -= num_packets_in_urb;
2074 for (i = 0; i < num_urbs; i++) {
2075 int r = ioctl(hpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
2080 if (errno == ENODEV) {
2081 r = LIBUSB_ERROR_NO_DEVICE;
2082 } else if (errno == EINVAL) {
2083 usbi_warn(TRANSFER_CTX(transfer), "submiturb failed, transfer too large");
2084 r = LIBUSB_ERROR_INVALID_PARAM;
2085 } else if (errno == EMSGSIZE) {
2086 usbi_warn(TRANSFER_CTX(transfer), "submiturb failed, iso packet length too large");
2087 r = LIBUSB_ERROR_INVALID_PARAM;
2089 usbi_err(TRANSFER_CTX(transfer), "submiturb failed, errno=%d", errno);
2090 r = LIBUSB_ERROR_IO;
2093 /* if the first URB submission fails, we can simply free up and
2094 * return failure immediately. */
2096 usbi_dbg("first URB failed, easy peasy");
2097 free_iso_urbs(tpriv);
2101 /* if it's not the first URB that failed, the situation is a bit
2102 * tricky. we must discard all previous URBs. there are
2104 * - discarding is asynchronous - discarded urbs will be reaped
2105 * later. the user must not have freed the transfer when the
2106 * discarded URBs are reaped, otherwise libusb will be using
2108 * - the earlier URBs may have completed successfully and we do
2109 * not want to throw away any data.
2110 * so, in this case we discard all the previous URBs BUT we report
2111 * that the transfer was submitted successfully. then later when
2112 * the final discard completes we can report error to the user.
2114 tpriv->reap_action = SUBMIT_FAILED;
2116 /* The URBs we haven't submitted yet we count as already
2118 tpriv->num_retired = num_urbs - i;
2119 discard_urbs(itransfer, 0, i);
2121 usbi_dbg("reporting successful submission but waiting for %d "
2122 "discards before reporting error", i);
2129 static int submit_control_transfer(struct usbi_transfer *itransfer)
2131 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2132 struct libusb_transfer *transfer =
2133 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2134 struct linux_device_handle_priv *hpriv =
2135 usbi_get_device_handle_priv(transfer->dev_handle);
2136 struct usbfs_urb *urb;
2139 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
2140 return LIBUSB_ERROR_INVALID_PARAM;
2142 urb = calloc(1, sizeof(*urb));
2144 return LIBUSB_ERROR_NO_MEM;
2146 tpriv->num_urbs = 1;
2147 tpriv->reap_action = NORMAL;
2149 urb->usercontext = itransfer;
2150 urb->type = USBFS_URB_TYPE_CONTROL;
2151 urb->endpoint = transfer->endpoint;
2152 urb->buffer = transfer->buffer;
2153 urb->buffer_length = transfer->length;
2155 r = ioctl(hpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2159 if (errno == ENODEV)
2160 return LIBUSB_ERROR_NO_DEVICE;
2162 usbi_err(TRANSFER_CTX(transfer), "submiturb failed, errno=%d", errno);
2163 return LIBUSB_ERROR_IO;
2168 static int op_submit_transfer(struct usbi_transfer *itransfer)
2170 struct libusb_transfer *transfer =
2171 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2173 switch (transfer->type) {
2174 case LIBUSB_TRANSFER_TYPE_CONTROL:
2175 return submit_control_transfer(itransfer);
2176 case LIBUSB_TRANSFER_TYPE_BULK:
2177 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2178 return submit_bulk_transfer(itransfer);
2179 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2180 return submit_bulk_transfer(itransfer);
2181 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2182 return submit_iso_transfer(itransfer);
2184 usbi_err(TRANSFER_CTX(transfer), "unknown transfer type %u", transfer->type);
2185 return LIBUSB_ERROR_INVALID_PARAM;
2189 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2191 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2192 struct libusb_transfer *transfer =
2193 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2197 return LIBUSB_ERROR_NOT_FOUND;
2199 r = discard_urbs(itransfer, 0, tpriv->num_urbs);
2203 switch (transfer->type) {
2204 case LIBUSB_TRANSFER_TYPE_BULK:
2205 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2206 if (tpriv->reap_action == ERROR)
2208 /* else, fall through */
2210 tpriv->reap_action = CANCELLED;
2216 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2218 struct libusb_transfer *transfer =
2219 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2220 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2222 switch (transfer->type) {
2223 case LIBUSB_TRANSFER_TYPE_CONTROL:
2224 case LIBUSB_TRANSFER_TYPE_BULK:
2225 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2226 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2232 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2233 if (tpriv->iso_urbs) {
2234 free_iso_urbs(tpriv);
2235 tpriv->iso_urbs = NULL;
2239 usbi_err(TRANSFER_CTX(transfer), "unknown transfer type %u", transfer->type);
2243 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2244 struct usbfs_urb *urb)
2246 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2247 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2248 int urb_idx = urb - tpriv->urbs;
2250 usbi_mutex_lock(&itransfer->lock);
2251 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2252 urb_idx + 1, tpriv->num_urbs);
2254 tpriv->num_retired++;
2256 if (tpriv->reap_action != NORMAL) {
2257 /* cancelled, submit_fail, or completed early */
2258 usbi_dbg("abnormal reap: urb status %d", urb->status);
2260 /* even though we're in the process of cancelling, it's possible that
2261 * we may receive some data in these URBs that we don't want to lose.
2263 * 1. while the kernel is cancelling all the packets that make up an
2264 * URB, a few of them might complete. so we get back a successful
2265 * cancellation *and* some data.
2266 * 2. we receive a short URB which marks the early completion condition,
2267 * so we start cancelling the remaining URBs. however, we're too
2268 * slow and another URB completes (or at least completes partially).
2269 * (this can't happen since we always use BULK_CONTINUATION.)
2271 * When this happens, our objectives are not to lose any "surplus" data,
2272 * and also to stick it at the end of the previously-received data
2273 * (closing any holes), so that libusb reports the total amount of
2274 * transferred data and presents it in a contiguous chunk.
2276 if (urb->actual_length > 0) {
2277 unsigned char *target = transfer->buffer + itransfer->transferred;
2279 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2280 if (urb->buffer != target) {
2281 usbi_dbg("moving surplus data from offset %zu to offset %zu",
2282 (unsigned char *) urb->buffer - transfer->buffer,
2283 target - transfer->buffer);
2284 memmove(target, urb->buffer, urb->actual_length);
2286 itransfer->transferred += urb->actual_length;
2289 if (tpriv->num_retired == tpriv->num_urbs) {
2290 usbi_dbg("abnormal reap: last URB handled, reporting");
2291 if (tpriv->reap_action != COMPLETED_EARLY &&
2292 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2293 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2299 itransfer->transferred += urb->actual_length;
2301 /* Many of these errors can occur on *any* urb of a multi-urb
2302 * transfer. When they do, we tear down the rest of the transfer.
2304 switch (urb->status) {
2307 case -EREMOTEIO: /* short transfer */
2309 case -ENOENT: /* cancelled */
2314 usbi_dbg("device removed");
2315 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2316 goto cancel_remaining;
2318 usbi_dbg("detected endpoint stall");
2319 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2320 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2321 goto cancel_remaining;
2323 /* overflow can only ever occur in the last urb */
2324 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2325 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2326 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2333 usbi_dbg("low-level bus error %d", urb->status);
2334 tpriv->reap_action = ERROR;
2335 goto cancel_remaining;
2337 usbi_warn(ITRANSFER_CTX(itransfer), "unrecognised urb status %d", urb->status);
2338 tpriv->reap_action = ERROR;
2339 goto cancel_remaining;
2342 /* if we've reaped all urbs or we got less data than requested then we're
2344 if (tpriv->num_retired == tpriv->num_urbs) {
2345 usbi_dbg("all URBs in transfer reaped --> complete!");
2347 } else if (urb->actual_length < urb->buffer_length) {
2348 usbi_dbg("short transfer %d/%d --> complete!",
2349 urb->actual_length, urb->buffer_length);
2350 if (tpriv->reap_action == NORMAL)
2351 tpriv->reap_action = COMPLETED_EARLY;
2357 if (tpriv->reap_action == ERROR && tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2358 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2360 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2363 /* cancel remaining urbs and wait for their completion before
2364 * reporting results */
2365 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2368 usbi_mutex_unlock(&itransfer->lock);
2374 usbi_mutex_unlock(&itransfer->lock);
2375 return tpriv->reap_action == CANCELLED ?
2376 usbi_handle_transfer_cancellation(itransfer) :
2377 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2380 static int handle_iso_completion(struct usbi_transfer *itransfer,
2381 struct usbfs_urb *urb)
2383 struct libusb_transfer *transfer =
2384 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2385 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2386 int num_urbs = tpriv->num_urbs;
2389 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2391 usbi_mutex_lock(&itransfer->lock);
2392 for (i = 0; i < num_urbs; i++) {
2393 if (urb == tpriv->iso_urbs[i]) {
2399 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2400 usbi_mutex_unlock(&itransfer->lock);
2401 return LIBUSB_ERROR_NOT_FOUND;
2404 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2407 /* copy isochronous results back in */
2409 for (i = 0; i < urb->number_of_packets; i++) {
2410 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2411 struct libusb_iso_packet_descriptor *lib_desc =
2412 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2414 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2415 switch (urb_desc->status) {
2418 case -ENOENT: /* cancelled */
2423 usbi_dbg("packet %d - device removed", i);
2424 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2427 usbi_dbg("packet %d - detected endpoint stall", i);
2428 lib_desc->status = LIBUSB_TRANSFER_STALL;
2431 usbi_dbg("packet %d - overflow error", i);
2432 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2440 usbi_dbg("packet %d - low-level USB error %d", i, urb_desc->status);
2441 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2444 usbi_warn(TRANSFER_CTX(transfer), "packet %d - unrecognised urb status %d",
2445 i, urb_desc->status);
2446 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2449 lib_desc->actual_length = urb_desc->actual_length;
2452 tpriv->num_retired++;
2454 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2455 usbi_dbg("CANCEL: urb status %d", urb->status);
2457 if (tpriv->num_retired == num_urbs) {
2458 usbi_dbg("CANCEL: last URB handled, reporting");
2459 free_iso_urbs(tpriv);
2460 if (tpriv->reap_action == CANCELLED) {
2461 usbi_mutex_unlock(&itransfer->lock);
2462 return usbi_handle_transfer_cancellation(itransfer);
2464 usbi_mutex_unlock(&itransfer->lock);
2465 return usbi_handle_transfer_completion(itransfer, LIBUSB_TRANSFER_ERROR);
2471 switch (urb->status) {
2474 case -ENOENT: /* cancelled */
2478 usbi_dbg("device removed");
2479 status = LIBUSB_TRANSFER_NO_DEVICE;
2482 usbi_warn(TRANSFER_CTX(transfer), "unrecognised urb status %d", urb->status);
2483 status = LIBUSB_TRANSFER_ERROR;
2487 /* if we've reaped all urbs then we're done */
2488 if (tpriv->num_retired == num_urbs) {
2489 usbi_dbg("all URBs in transfer reaped --> complete!");
2490 free_iso_urbs(tpriv);
2491 usbi_mutex_unlock(&itransfer->lock);
2492 return usbi_handle_transfer_completion(itransfer, status);
2496 usbi_mutex_unlock(&itransfer->lock);
2500 static int handle_control_completion(struct usbi_transfer *itransfer,
2501 struct usbfs_urb *urb)
2503 struct linux_transfer_priv *tpriv = usbi_get_transfer_priv(itransfer);
2506 usbi_mutex_lock(&itransfer->lock);
2507 usbi_dbg("handling completion status %d", urb->status);
2509 itransfer->transferred += urb->actual_length;
2511 if (tpriv->reap_action == CANCELLED) {
2512 if (urb->status && urb->status != -ENOENT)
2513 usbi_warn(ITRANSFER_CTX(itransfer), "cancel: unrecognised urb status %d",
2517 usbi_mutex_unlock(&itransfer->lock);
2518 return usbi_handle_transfer_cancellation(itransfer);
2521 switch (urb->status) {
2523 status = LIBUSB_TRANSFER_COMPLETED;
2525 case -ENOENT: /* cancelled */
2526 status = LIBUSB_TRANSFER_CANCELLED;
2530 usbi_dbg("device removed");
2531 status = LIBUSB_TRANSFER_NO_DEVICE;
2534 usbi_dbg("unsupported control request");
2535 status = LIBUSB_TRANSFER_STALL;
2538 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2539 status = LIBUSB_TRANSFER_OVERFLOW;
2546 usbi_dbg("low-level bus error %d", urb->status);
2547 status = LIBUSB_TRANSFER_ERROR;
2550 usbi_warn(ITRANSFER_CTX(itransfer), "unrecognised urb status %d", urb->status);
2551 status = LIBUSB_TRANSFER_ERROR;
2557 usbi_mutex_unlock(&itransfer->lock);
2558 return usbi_handle_transfer_completion(itransfer, status);
2561 static int reap_for_handle(struct libusb_device_handle *handle)
2563 struct linux_device_handle_priv *hpriv = usbi_get_device_handle_priv(handle);
2565 struct usbfs_urb *urb = NULL;
2566 struct usbi_transfer *itransfer;
2567 struct libusb_transfer *transfer;
2569 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2571 if (errno == EAGAIN)
2573 if (errno == ENODEV)
2574 return LIBUSB_ERROR_NO_DEVICE;
2576 usbi_err(HANDLE_CTX(handle), "reap failed, errno=%d", errno);
2577 return LIBUSB_ERROR_IO;
2580 itransfer = urb->usercontext;
2581 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2583 usbi_dbg("urb type=%u status=%d transferred=%d", urb->type, urb->status, urb->actual_length);
2585 switch (transfer->type) {
2586 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2587 return handle_iso_completion(itransfer, urb);
2588 case LIBUSB_TRANSFER_TYPE_BULK:
2589 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2590 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2591 return handle_bulk_completion(itransfer, urb);
2592 case LIBUSB_TRANSFER_TYPE_CONTROL:
2593 return handle_control_completion(itransfer, urb);
2595 usbi_err(HANDLE_CTX(handle), "unrecognised transfer type %u", transfer->type);
2596 return LIBUSB_ERROR_OTHER;
2600 static int op_handle_events(struct libusb_context *ctx,
2601 struct pollfd *fds, usbi_nfds_t nfds, int num_ready)
2606 usbi_mutex_lock(&ctx->open_devs_lock);
2607 for (n = 0; n < nfds && num_ready > 0; n++) {
2608 struct pollfd *pollfd = &fds[n];
2609 struct libusb_device_handle *handle;
2610 struct linux_device_handle_priv *hpriv = NULL;
2612 if (!pollfd->revents)
2616 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2617 hpriv = usbi_get_device_handle_priv(handle);
2618 if (hpriv->fd == pollfd->fd)
2622 if (!hpriv || hpriv->fd != pollfd->fd) {
2623 usbi_err(ctx, "cannot find handle for fd %d",
2628 if (pollfd->revents & POLLERR) {
2629 /* remove the fd from the pollfd set so that it doesn't continuously
2630 * trigger an event, and flag that it has been removed so op_close()
2631 * doesn't try to remove it a second time */
2632 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2633 hpriv->fd_removed = 1;
2635 /* device will still be marked as attached if hotplug monitor thread
2636 * hasn't processed remove event yet */
2637 usbi_mutex_static_lock(&linux_hotplug_lock);
2638 if (handle->dev->attached)
2639 linux_device_disconnected(handle->dev->bus_number,
2640 handle->dev->device_address);
2641 usbi_mutex_static_unlock(&linux_hotplug_lock);
2643 if (hpriv->caps & USBFS_CAP_REAP_AFTER_DISCONNECT) {
2645 r = reap_for_handle(handle);
2649 usbi_handle_disconnect(handle);
2654 r = reap_for_handle(handle);
2656 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2664 usbi_mutex_unlock(&ctx->open_devs_lock);
2668 const struct usbi_os_backend usbi_backend = {
2669 .name = "Linux usbfs",
2670 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2673 .hotplug_poll = op_hotplug_poll,
2674 .get_device_descriptor = op_get_device_descriptor,
2675 .get_active_config_descriptor = op_get_active_config_descriptor,
2676 .get_config_descriptor = op_get_config_descriptor,
2677 .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2679 .wrap_sys_device = op_wrap_sys_device,
2682 .get_configuration = op_get_configuration,
2683 .set_configuration = op_set_configuration,
2684 .claim_interface = op_claim_interface,
2685 .release_interface = op_release_interface,
2687 .set_interface_altsetting = op_set_interface,
2688 .clear_halt = op_clear_halt,
2689 .reset_device = op_reset_device,
2691 .alloc_streams = op_alloc_streams,
2692 .free_streams = op_free_streams,
2694 .dev_mem_alloc = op_dev_mem_alloc,
2695 .dev_mem_free = op_dev_mem_free,
2697 .kernel_driver_active = op_kernel_driver_active,
2698 .detach_kernel_driver = op_detach_kernel_driver,
2699 .attach_kernel_driver = op_attach_kernel_driver,
2701 .destroy_device = op_destroy_device,
2703 .submit_transfer = op_submit_transfer,
2704 .cancel_transfer = op_cancel_transfer,
2705 .clear_transfer_priv = op_clear_transfer_priv,
2707 .handle_events = op_handle_events,
2709 .device_priv_size = sizeof(struct linux_device_priv),
2710 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2711 .transfer_priv_size = sizeof(struct linux_transfer_priv),