1 /* -*- Mode: C; c-basic-offset:8 ; indent-tabs-mode:t -*- */
3 * Linux usbfs backend for libusb
4 * Copyright © 2007-2009 Daniel Drake <dsd@gentoo.org>
5 * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
6 * Copyright © 2013 Nathan Hjelm <hjelmn@mac.com>
7 * Copyright © 2012-2013 Hans de Goede <hdegoede@redhat.com>
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
35 #include <sys/ioctl.h>
37 #include <sys/types.h>
38 #include <sys/utsname.h>
43 #include "linux_usbfs.h"
46 * opening a usbfs node causes the device to be resumed, so we attempt to
47 * avoid this during enumeration.
49 * sysfs allows us to read the kernel's in-memory copies of device descriptors
50 * and so forth, avoiding the need to open the device:
51 * - The binary "descriptors" file contains all config descriptors since
52 * 2.6.26, commit 217a9081d8e69026186067711131b77f0ce219ed
53 * - The binary "descriptors" file was added in 2.6.23, commit
54 * 69d42a78f935d19384d1f6e4f94b65bb162b36df, but it only contains the
55 * active config descriptors
56 * - The "busnum" file was added in 2.6.22, commit
57 * 83f7d958eab2fbc6b159ee92bf1493924e1d0f72
58 * - The "devnum" file has been present since pre-2.6.18
59 * - the "bConfigurationValue" file has been present since pre-2.6.18
61 * If we have bConfigurationValue, busnum, and devnum, then we can determine
62 * the active configuration without having to open the usbfs node in RDWR mode.
63 * The busnum file is important as that is the only way we can relate sysfs
64 * devices to usbfs nodes.
66 * If we also have all descriptors, we can obtain the device descriptor and
67 * configuration without touching usbfs at all.
70 /* endianness for multi-byte fields:
72 * Descriptors exposed by usbfs have the multi-byte fields in the device
73 * descriptor as host endian. Multi-byte fields in the other descriptors are
74 * bus-endian. The kernel documentation says otherwise, but it is wrong.
76 * In sysfs all descriptors are bus-endian.
79 static const char *usbfs_path = NULL;
81 /* use usbdev*.* device names in /dev instead of the usbfs bus directories */
82 static int usbdev_names = 0;
84 /* Linux 2.6.32 adds support for a bulk continuation URB flag. this basically
85 * allows us to mark URBs as being part of a specific logical transfer when
86 * we submit them to the kernel. then, on any error except a cancellation, all
87 * URBs within that transfer will be cancelled and no more URBs will be
88 * accepted for the transfer, meaning that no more data can creep in.
90 * The BULK_CONTINUATION flag must be set on all URBs within a bulk transfer
91 * (in either direction) except the first.
92 * For IN transfers, we must also set SHORT_NOT_OK on all URBs except the
93 * last; it means that the kernel should treat a short reply as an error.
94 * For OUT transfers, SHORT_NOT_OK must not be set. it isn't needed (OUT
95 * transfers can't be short unless there's already some sort of error), and
96 * setting this flag is disallowed (a kernel with USB debugging enabled will
99 static int supports_flag_bulk_continuation = -1;
101 /* Linux 2.6.31 fixes support for the zero length packet URB flag. This
102 * allows us to mark URBs that should be followed by a zero length data
103 * packet, which can be required by device- or class-specific protocols.
105 static int supports_flag_zero_packet = -1;
107 /* clock ID for monotonic clock, as not all clock sources are available on all
108 * systems. appropriate choice made at initialization time. */
109 static clockid_t monotonic_clkid = -1;
111 /* Linux 2.6.22 (commit 83f7d958eab2fbc6b159ee92bf1493924e1d0f72) adds a busnum
112 * to sysfs, so we can relate devices. This also implies that we can read
113 * the active configuration through bConfigurationValue */
114 static int sysfs_can_relate_devices = -1;
116 /* Linux 2.6.26 (commit 217a9081d8e69026186067711131b77f0ce219ed) adds all
117 * config descriptors (rather then just the active config) to the sysfs
118 * descriptors file, so from then on we can use them. */
119 static int sysfs_has_descriptors = -1;
121 /* how many times have we initted (and not exited) ? */
122 static volatile int init_count = 0;
124 /* Serialize hotplug start/stop */
125 usbi_mutex_static_t linux_hotplug_startstop_lock = USBI_MUTEX_INITIALIZER;
126 /* Serialize scan-devices, event-thread, and poll */
127 usbi_mutex_static_t linux_hotplug_lock = USBI_MUTEX_INITIALIZER;
129 static int linux_start_event_monitor(void);
130 static int linux_stop_event_monitor(void);
131 static int linux_scan_devices(struct libusb_context *ctx);
132 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname);
133 static int detach_kernel_driver_and_claim(struct libusb_device_handle *, int);
135 #if !defined(USE_UDEV)
136 static int linux_default_scan_devices (struct libusb_context *ctx);
139 struct linux_device_priv {
141 unsigned char *descriptors;
143 int active_config; /* cache val for !sysfs_can_relate_devices */
146 struct linux_device_handle_priv {
153 /* submission failed after the first URB, so await cancellation/completion
154 * of all the others */
157 /* cancelled by user or timeout */
160 /* completed multi-URB transfer in non-final URB */
163 /* one or more urbs encountered a low-level error */
167 struct linux_transfer_priv {
169 struct usbfs_urb *urbs;
170 struct usbfs_urb **iso_urbs;
173 enum reap_action reap_action;
176 enum libusb_transfer_status reap_status;
178 /* next iso packet in user-supplied transfer to be populated */
179 int iso_packet_offset;
182 static int _get_usbfs_fd(struct libusb_device *dev, mode_t mode, int silent)
184 struct libusb_context *ctx = DEVICE_CTX(dev);
190 snprintf(path, PATH_MAX, "%s/usbdev%d.%d",
191 usbfs_path, dev->bus_number, dev->device_address);
193 snprintf(path, PATH_MAX, "%s/%03d/%03d",
194 usbfs_path, dev->bus_number, dev->device_address);
196 fd = open(path, mode);
198 return fd; /* Success */
200 if (errno == ENOENT) {
202 usbi_err(ctx, "File doesn't exist, wait %d ms and try again\n", delay/1000);
204 /* Wait 10ms for USB device path creation.*/
207 fd = open(path, mode);
209 return fd; /* Success */
213 usbi_err(ctx, "libusb couldn't open USB device %s: %s",
214 path, strerror(errno));
215 if (errno == EACCES && mode == O_RDWR)
216 usbi_err(ctx, "libusb requires write access to USB "
221 return LIBUSB_ERROR_ACCESS;
223 return LIBUSB_ERROR_NO_DEVICE;
224 return LIBUSB_ERROR_IO;
227 static struct linux_device_priv *_device_priv(struct libusb_device *dev)
229 return (struct linux_device_priv *) dev->os_priv;
232 static struct linux_device_handle_priv *_device_handle_priv(
233 struct libusb_device_handle *handle)
235 return (struct linux_device_handle_priv *) handle->os_priv;
238 /* check dirent for a /dev/usbdev%d.%d name
239 * optionally return bus/device on success */
240 static int _is_usbdev_entry(struct dirent *entry, int *bus_p, int *dev_p)
244 if (sscanf(entry->d_name, "usbdev%d.%d", &busnum, &devnum) != 2)
247 usbi_dbg("found: %s", entry->d_name);
255 static int check_usb_vfs(const char *dirname)
258 struct dirent *entry;
261 dir = opendir(dirname);
265 while ((entry = readdir(dir)) != NULL) {
266 if (entry->d_name[0] == '.')
269 /* We assume if we find any files that it must be the right place */
278 static const char *find_usbfs_path(void)
280 const char *path = "/dev/bus/usb";
281 const char *ret = NULL;
283 if (check_usb_vfs(path)) {
286 path = "/proc/bus/usb";
287 if (check_usb_vfs(path))
291 /* look for /dev/usbdev*.* if the normal places fail */
293 struct dirent *entry;
299 while ((entry = readdir(dir)) != NULL) {
300 if (_is_usbdev_entry(entry, NULL, NULL)) {
301 /* found one; that's enough */
312 usbi_dbg("found usbfs at %s", ret);
317 /* the monotonic clock is not usable on all systems (e.g. embedded ones often
318 * seem to lack it). fall back to REALTIME if we have to. */
319 static clockid_t find_monotonic_clock(void)
321 #ifdef CLOCK_MONOTONIC
325 /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
326 * because it's not available through timerfd */
327 r = clock_gettime(CLOCK_MONOTONIC, &ts);
329 return CLOCK_MONOTONIC;
330 usbi_dbg("monotonic clock doesn't work, errno %d", errno);
333 return CLOCK_REALTIME;
336 static int kernel_version_ge(int major, int minor, int sublevel)
339 int atoms, kmajor, kminor, ksublevel;
343 atoms = sscanf(uts.release, "%d.%d.%d", &kmajor, &kminor, &ksublevel);
352 /* kmajor == major */
354 return 0 == minor && 0 == sublevel;
360 /* kminor == minor */
362 return 0 == sublevel;
364 return ksublevel >= sublevel;
367 static int op_init(struct libusb_context *ctx)
372 usbfs_path = find_usbfs_path();
374 usbi_err(ctx, "could not find usbfs");
375 return LIBUSB_ERROR_OTHER;
378 if (monotonic_clkid == -1)
379 monotonic_clkid = find_monotonic_clock();
381 if (supports_flag_bulk_continuation == -1) {
382 /* bulk continuation URB flag available from Linux 2.6.32 */
383 supports_flag_bulk_continuation = kernel_version_ge(2,6,32);
384 if (supports_flag_bulk_continuation == -1) {
385 usbi_err(ctx, "error checking for bulk continuation support");
386 return LIBUSB_ERROR_OTHER;
390 if (supports_flag_bulk_continuation)
391 usbi_dbg("bulk continuation flag supported");
393 if (-1 == supports_flag_zero_packet) {
394 /* zero length packet URB flag fixed since Linux 2.6.31 */
395 supports_flag_zero_packet = kernel_version_ge(2,6,31);
396 if (-1 == supports_flag_zero_packet) {
397 usbi_err(ctx, "error checking for zero length packet support");
398 return LIBUSB_ERROR_OTHER;
402 if (supports_flag_zero_packet)
403 usbi_dbg("zero length packet flag supported");
405 if (-1 == sysfs_has_descriptors) {
406 /* sysfs descriptors has all descriptors since Linux 2.6.26 */
407 sysfs_has_descriptors = kernel_version_ge(2,6,26);
408 if (-1 == sysfs_has_descriptors) {
409 usbi_err(ctx, "error checking for sysfs descriptors");
410 return LIBUSB_ERROR_OTHER;
414 if (-1 == sysfs_can_relate_devices) {
415 /* sysfs has busnum since Linux 2.6.22 */
416 sysfs_can_relate_devices = kernel_version_ge(2,6,22);
417 if (-1 == sysfs_can_relate_devices) {
418 usbi_err(ctx, "error checking for sysfs busnum");
419 return LIBUSB_ERROR_OTHER;
423 if (sysfs_can_relate_devices || sysfs_has_descriptors) {
424 r = stat(SYSFS_DEVICE_PATH, &statbuf);
425 if (r != 0 || !S_ISDIR(statbuf.st_mode)) {
426 usbi_warn(ctx, "sysfs not mounted");
427 sysfs_can_relate_devices = 0;
428 sysfs_has_descriptors = 0;
432 if (sysfs_can_relate_devices)
433 usbi_dbg("sysfs can relate devices");
435 if (sysfs_has_descriptors)
436 usbi_dbg("sysfs has complete descriptors");
438 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
440 if (init_count == 0) {
441 /* start up hotplug event handler */
442 r = linux_start_event_monitor();
444 if (r == LIBUSB_SUCCESS) {
445 r = linux_scan_devices(ctx);
446 if (r == LIBUSB_SUCCESS)
448 else if (init_count == 0)
449 linux_stop_event_monitor();
451 usbi_err(ctx, "error starting hotplug event monitor");
452 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
457 static void op_exit(void)
459 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
460 assert(init_count != 0);
462 /* tear down event handler */
463 (void)linux_stop_event_monitor();
465 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
468 static int linux_start_event_monitor(void)
470 #if defined(USE_UDEV)
471 return linux_udev_start_event_monitor();
473 return linux_netlink_start_event_monitor();
477 static int linux_stop_event_monitor(void)
479 #if defined(USE_UDEV)
480 return linux_udev_stop_event_monitor();
482 return linux_netlink_stop_event_monitor();
486 static int linux_scan_devices(struct libusb_context *ctx)
490 usbi_mutex_static_lock(&linux_hotplug_lock);
492 #if defined(USE_UDEV)
493 ret = linux_udev_scan_devices(ctx);
495 ret = linux_default_scan_devices(ctx);
498 usbi_mutex_static_unlock(&linux_hotplug_lock);
503 static void op_hotplug_poll(void)
505 #if defined(USE_UDEV)
506 linux_udev_hotplug_poll();
508 linux_netlink_hotplug_poll();
512 static int _open_sysfs_attr(struct libusb_device *dev, const char *attr)
514 struct linux_device_priv *priv = _device_priv(dev);
515 char filename[PATH_MAX];
518 snprintf(filename, PATH_MAX, "%s/%s/%s",
519 SYSFS_DEVICE_PATH, priv->sysfs_dir, attr);
520 fd = open(filename, O_RDONLY);
522 usbi_err(DEVICE_CTX(dev),
523 "open %s failed ret=%d errno=%d", filename, fd, errno);
524 return LIBUSB_ERROR_IO;
530 /* Note only suitable for attributes which always read >= 0, < 0 is error */
531 static int __read_sysfs_attr(struct libusb_context *ctx,
532 const char *devname, const char *attr)
534 char filename[PATH_MAX];
538 snprintf(filename, PATH_MAX, "%s/%s/%s", SYSFS_DEVICE_PATH,
540 f = fopen(filename, "r");
542 if (errno == ENOENT) {
543 /* File doesn't exist. Assume the device has been
544 disconnected (see trac ticket #70). */
545 return LIBUSB_ERROR_NO_DEVICE;
547 usbi_err(ctx, "open %s failed errno=%d", filename, errno);
548 return LIBUSB_ERROR_IO;
551 r = fscanf(f, "%d", &value);
554 usbi_err(ctx, "fscanf %s returned %d, errno=%d", attr, r, errno);
555 return LIBUSB_ERROR_NO_DEVICE; /* For unplug race (trac #70) */
558 usbi_err(ctx, "%s contains a negative value", filename);
559 return LIBUSB_ERROR_IO;
565 static int op_get_device_descriptor(struct libusb_device *dev,
566 unsigned char *buffer, int *host_endian)
568 struct linux_device_priv *priv = _device_priv(dev);
570 *host_endian = sysfs_has_descriptors ? 0 : 1;
571 memcpy(buffer, priv->descriptors, DEVICE_DESC_LENGTH);
576 /* read the bConfigurationValue for a device */
577 static int sysfs_get_active_config(struct libusb_device *dev, int *config)
580 char tmp[5] = {0, 0, 0, 0, 0};
585 fd = _open_sysfs_attr(dev, "bConfigurationValue");
589 r = read(fd, tmp, sizeof(tmp));
592 usbi_err(DEVICE_CTX(dev),
593 "read bConfigurationValue failed ret=%d errno=%d", r, errno);
594 return LIBUSB_ERROR_IO;
596 usbi_dbg("device unconfigured");
601 if (tmp[sizeof(tmp) - 1] != 0) {
602 usbi_err(DEVICE_CTX(dev), "not null-terminated?");
603 return LIBUSB_ERROR_IO;
604 } else if (tmp[0] == 0) {
605 usbi_err(DEVICE_CTX(dev), "no configuration value?");
606 return LIBUSB_ERROR_IO;
609 num = strtol(tmp, &endptr, 10);
611 usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp);
612 return LIBUSB_ERROR_IO;
619 int linux_get_device_address (struct libusb_context *ctx, int detached,
620 uint8_t *busnum, uint8_t *devaddr,const char *dev_node,
621 const char *sys_name)
625 usbi_dbg("getting address for device: %s detached: %d", sys_name, detached);
626 /* can't use sysfs to read the bus and device number if the
627 * device has been detached */
628 if (!sysfs_can_relate_devices || detached || NULL == sys_name) {
629 if (NULL == dev_node) {
630 return LIBUSB_ERROR_OTHER;
633 /* will this work with all supported kernel versions? */
634 if (!strncmp(dev_node, "/dev/bus/usb", 12)) {
635 sscanf (dev_node, "/dev/bus/usb/%hhd/%hhd", busnum, devaddr);
636 } else if (!strncmp(dev_node, "/proc/bus/usb", 13)) {
637 sscanf (dev_node, "/proc/bus/usb/%hhd/%hhd", busnum, devaddr);
640 return LIBUSB_SUCCESS;
643 usbi_dbg("scan %s", sys_name);
645 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "busnum");
648 if (sysfs_attr > 255)
649 return LIBUSB_ERROR_INVALID_PARAM;
650 *busnum = (uint8_t) sysfs_attr;
652 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "devnum");
655 if (sysfs_attr > 255)
656 return LIBUSB_ERROR_INVALID_PARAM;
658 *devaddr = (uint8_t) sysfs_attr;
660 usbi_dbg("bus=%d dev=%d", *busnum, *devaddr);
662 return LIBUSB_SUCCESS;
665 /* Return offset of the next descriptor with the given type */
666 static int seek_to_next_descriptor(struct libusb_context *ctx,
667 uint8_t descriptor_type, unsigned char *buffer, int size)
669 struct usb_descriptor_header header;
672 for (i = 0; size >= 0; i += header.bLength, size -= header.bLength) {
674 return LIBUSB_ERROR_NOT_FOUND;
677 usbi_err(ctx, "short descriptor read %d/2", size);
678 return LIBUSB_ERROR_IO;
680 usbi_parse_descriptor(buffer + i, "bb", &header, 0);
682 if (i && header.bDescriptorType == descriptor_type)
685 usbi_err(ctx, "bLength overflow by %d bytes", -size);
686 return LIBUSB_ERROR_IO;
689 /* Return offset to next config */
690 static int seek_to_next_config(struct libusb_context *ctx,
691 unsigned char *buffer, int size)
693 struct libusb_config_descriptor config;
696 return LIBUSB_ERROR_NOT_FOUND;
698 if (size < LIBUSB_DT_CONFIG_SIZE) {
699 usbi_err(ctx, "short descriptor read %d/%d",
700 size, LIBUSB_DT_CONFIG_SIZE);
701 return LIBUSB_ERROR_IO;
704 usbi_parse_descriptor(buffer, "bbwbbbbb", &config, 0);
705 if (config.bDescriptorType != LIBUSB_DT_CONFIG) {
706 usbi_err(ctx, "descriptor is not a config desc (type 0x%02x)",
707 config.bDescriptorType);
708 return LIBUSB_ERROR_IO;
712 * In usbfs the config descriptors are config.wTotalLength bytes apart,
713 * with any short reads from the device appearing as holes in the file.
715 * In sysfs wTotalLength is ignored, instead the kernel returns a
716 * config descriptor with verified bLength fields, with descriptors
717 * with an invalid bLength removed.
719 if (sysfs_has_descriptors) {
720 int next = seek_to_next_descriptor(ctx, LIBUSB_DT_CONFIG,
722 if (next == LIBUSB_ERROR_NOT_FOUND)
727 if (next != config.wTotalLength)
728 usbi_warn(ctx, "config length mismatch wTotalLength "
729 "%d real %d", config.wTotalLength, next);
732 if (config.wTotalLength < LIBUSB_DT_CONFIG_SIZE) {
733 usbi_err(ctx, "invalid wTotalLength %d",
734 config.wTotalLength);
735 return LIBUSB_ERROR_IO;
736 } else if (config.wTotalLength > size) {
737 usbi_warn(ctx, "short descriptor read %d/%d",
738 size, config.wTotalLength);
741 return config.wTotalLength;
745 static int op_get_config_descriptor_by_value(struct libusb_device *dev,
746 uint8_t value, unsigned char **buffer, int *host_endian)
748 struct libusb_context *ctx = DEVICE_CTX(dev);
749 struct linux_device_priv *priv = _device_priv(dev);
750 unsigned char *descriptors = priv->descriptors;
751 int size = priv->descriptors_len;
752 struct libusb_config_descriptor *config;
755 /* Unlike the device desc. config descs. are always in raw format */
758 /* Skip device header */
759 descriptors += DEVICE_DESC_LENGTH;
760 size -= DEVICE_DESC_LENGTH;
762 /* Seek till the config is found, or till "EOF" */
764 int next = seek_to_next_config(ctx, descriptors, size);
767 config = (struct libusb_config_descriptor *)descriptors;
768 if (config->bConfigurationValue == value) {
769 *buffer = descriptors;
777 static int op_get_active_config_descriptor(struct libusb_device *dev,
778 unsigned char *buffer, size_t len, int *host_endian)
781 unsigned char *config_desc;
783 if (sysfs_can_relate_devices) {
784 r = sysfs_get_active_config(dev, &config);
788 /* Use cached bConfigurationValue */
789 struct linux_device_priv *priv = _device_priv(dev);
790 config = priv->active_config;
793 return LIBUSB_ERROR_NOT_FOUND;
795 r = op_get_config_descriptor_by_value(dev, config, &config_desc,
801 memcpy(buffer, config_desc, len);
805 static int op_get_config_descriptor(struct libusb_device *dev,
806 uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
808 struct linux_device_priv *priv = _device_priv(dev);
809 unsigned char *descriptors = priv->descriptors;
810 int i, r, size = priv->descriptors_len;
812 /* Unlike the device desc. config descs. are always in raw format */
815 /* Skip device header */
816 descriptors += DEVICE_DESC_LENGTH;
817 size -= DEVICE_DESC_LENGTH;
819 /* Seek till the config is found, or till "EOF" */
821 r = seek_to_next_config(DEVICE_CTX(dev), descriptors, size);
824 if (i == config_index)
831 memcpy(buffer, descriptors, len);
835 /* send a control message to retrieve active configuration */
836 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
838 unsigned char active_config = 0;
841 struct usbfs_ctrltransfer ctrl = {
842 .bmRequestType = LIBUSB_ENDPOINT_IN,
843 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
848 .data = &active_config
851 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
854 return LIBUSB_ERROR_NO_DEVICE;
856 /* we hit this error path frequently with buggy devices :( */
857 usbi_warn(DEVICE_CTX(dev),
858 "get_configuration failed ret=%d errno=%d", r, errno);
859 return LIBUSB_ERROR_IO;
862 return active_config;
865 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
866 uint8_t devaddr, const char *sysfs_dir)
868 struct linux_device_priv *priv = _device_priv(dev);
869 struct libusb_context *ctx = DEVICE_CTX(dev);
870 int descriptors_size = 512; /* Begin with a 1024 byte alloc */
874 dev->bus_number = busnum;
875 dev->device_address = devaddr;
878 priv->sysfs_dir = malloc(strlen(sysfs_dir) + 1);
879 if (!priv->sysfs_dir)
880 return LIBUSB_ERROR_NO_MEM;
881 strcpy(priv->sysfs_dir, sysfs_dir);
883 /* Note speed can contain 1.5, in this case __read_sysfs_attr
884 will stop parsing at the '.' and return 1 */
885 speed = __read_sysfs_attr(DEVICE_CTX(dev), sysfs_dir, "speed");
888 case 1: dev->speed = LIBUSB_SPEED_LOW; break;
889 case 12: dev->speed = LIBUSB_SPEED_FULL; break;
890 case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
891 case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
893 usbi_warn(DEVICE_CTX(dev), "Unknown device speed: %d Mbps", speed);
898 /* cache descriptors in memory */
899 if (sysfs_has_descriptors)
900 fd = _open_sysfs_attr(dev, "descriptors");
902 fd = _get_usbfs_fd(dev, O_RDONLY, 0);
907 descriptors_size *= 2;
908 priv->descriptors = usbi_reallocf(priv->descriptors,
910 if (!priv->descriptors) {
912 return LIBUSB_ERROR_NO_MEM;
914 /* usbfs has holes in the file */
915 if (!sysfs_has_descriptors) {
916 memset(priv->descriptors + priv->descriptors_len,
917 0, descriptors_size - priv->descriptors_len);
919 r = read(fd, priv->descriptors + priv->descriptors_len,
920 descriptors_size - priv->descriptors_len);
922 usbi_err(ctx, "read descriptor failed ret=%d errno=%d",
925 return LIBUSB_ERROR_IO;
927 priv->descriptors_len += r;
928 } while (priv->descriptors_len == descriptors_size);
932 if (priv->descriptors_len < DEVICE_DESC_LENGTH) {
933 usbi_err(ctx, "short descriptor read (%d)",
934 priv->descriptors_len);
935 return LIBUSB_ERROR_IO;
938 if (sysfs_can_relate_devices)
939 return LIBUSB_SUCCESS;
941 /* cache active config */
942 fd = _get_usbfs_fd(dev, O_RDWR, 1);
944 /* cannot send a control message to determine the active
945 * config. just assume the first one is active. */
946 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
947 "active configuration descriptor");
948 if (priv->descriptors_len >=
949 (DEVICE_DESC_LENGTH + LIBUSB_DT_CONFIG_SIZE)) {
950 struct libusb_config_descriptor config;
951 usbi_parse_descriptor(
952 priv->descriptors + DEVICE_DESC_LENGTH,
953 "bbwbbbbb", &config, 0);
954 priv->active_config = config.bConfigurationValue;
956 priv->active_config = -1; /* No config dt */
958 return LIBUSB_SUCCESS;
961 r = usbfs_get_active_config(dev, fd);
963 priv->active_config = r;
966 /* some buggy devices have a configuration 0, but we're
967 * reaching into the corner of a corner case here, so let's
968 * not support buggy devices in these circumstances.
969 * stick to the specs: a configuration value of 0 means
971 usbi_dbg("active cfg 0? assuming unconfigured device");
972 priv->active_config = -1;
974 } else if (r == LIBUSB_ERROR_IO) {
975 /* buggy devices sometimes fail to report their active config.
976 * assume unconfigured and continue the probing */
977 usbi_warn(ctx, "couldn't query active configuration, assuming"
979 priv->active_config = -1;
981 } /* else r < 0, just return the error code */
987 static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir)
989 struct libusb_context *ctx = DEVICE_CTX(dev);
990 struct libusb_device *it;
991 char *parent_sysfs_dir, *tmp;
992 int ret, add_parent = 1;
994 /* XXX -- can we figure out the topology when using usbfs? */
995 if (NULL == sysfs_dir || 0 == strncmp(sysfs_dir, "usb", 3)) {
996 /* either using usbfs or finding the parent of a root hub */
997 return LIBUSB_SUCCESS;
1000 parent_sysfs_dir = strdup(sysfs_dir);
1001 if (NULL != (tmp = strrchr(parent_sysfs_dir, '.')) ||
1002 NULL != (tmp = strrchr(parent_sysfs_dir, '-'))) {
1003 dev->port_number = atoi(tmp + 1);
1006 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
1008 free (parent_sysfs_dir);
1009 return LIBUSB_SUCCESS;
1012 /* is the parent a root hub? */
1013 if (NULL == strchr(parent_sysfs_dir, '-')) {
1014 tmp = parent_sysfs_dir;
1015 ret = asprintf (&parent_sysfs_dir, "usb%s", tmp);
1018 return LIBUSB_ERROR_NO_MEM;
1023 /* find the parent in the context */
1024 usbi_mutex_lock(&ctx->usb_devs_lock);
1025 list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device) {
1026 struct linux_device_priv *priv = _device_priv(it);
1027 if (0 == strcmp (priv->sysfs_dir, parent_sysfs_dir)) {
1028 dev->parent_dev = libusb_ref_device(it);
1032 usbi_mutex_unlock(&ctx->usb_devs_lock);
1034 if (!dev->parent_dev && add_parent) {
1035 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1037 sysfs_scan_device(ctx, parent_sysfs_dir);
1042 usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev, sysfs_dir,
1043 dev->parent_dev, parent_sysfs_dir, dev->port_number);
1045 free (parent_sysfs_dir);
1047 return LIBUSB_SUCCESS;
1050 int linux_enumerate_device(struct libusb_context *ctx,
1051 uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1053 unsigned long session_id;
1054 struct libusb_device *dev;
1057 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1058 * will be reused. instead we should add a simple sysfs attribute with
1060 session_id = busnum << 8 | devaddr;
1061 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
1064 dev = usbi_get_device_by_session_id(ctx, session_id);
1066 /* device already exists in the context */
1067 usbi_dbg("session_id %ld already exists", session_id);
1068 libusb_unref_device(dev);
1069 return LIBUSB_SUCCESS;
1072 usbi_dbg("allocating new device for %d/%d (session %ld)",
1073 busnum, devaddr, session_id);
1074 dev = usbi_alloc_device(ctx, session_id);
1076 return LIBUSB_ERROR_NO_MEM;
1078 r = initialize_device(dev, busnum, devaddr, sysfs_dir);
1081 r = usbi_sanitize_device(dev);
1085 r = linux_get_parent_info(dev, sysfs_dir);
1090 libusb_unref_device(dev);
1092 usbi_connect_device(dev);
1097 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1099 struct libusb_context *ctx;
1101 usbi_mutex_static_lock(&active_contexts_lock);
1102 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1103 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1105 usbi_mutex_static_unlock(&active_contexts_lock);
1108 void linux_device_disconnected(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1110 struct libusb_context *ctx;
1111 struct libusb_device *dev;
1112 unsigned long session_id = busnum << 8 | devaddr;
1114 usbi_mutex_static_lock(&active_contexts_lock);
1115 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1116 dev = usbi_get_device_by_session_id (ctx, session_id);
1118 usbi_disconnect_device (dev);
1119 libusb_unref_device(dev);
1121 usbi_dbg("device not found for session %x", session_id);
1124 usbi_mutex_static_unlock(&active_contexts_lock);
1127 #if !defined(USE_UDEV)
1128 /* open a bus directory and adds all discovered devices to the context */
1129 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1132 char dirpath[PATH_MAX];
1133 struct dirent *entry;
1134 int r = LIBUSB_ERROR_IO;
1136 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1137 usbi_dbg("%s", dirpath);
1138 dir = opendir(dirpath);
1140 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1141 /* FIXME: should handle valid race conditions like hub unplugged
1142 * during directory iteration - this is not an error */
1146 while ((entry = readdir(dir))) {
1149 if (entry->d_name[0] == '.')
1152 devaddr = atoi(entry->d_name);
1154 usbi_dbg("unknown dir entry %s", entry->d_name);
1158 if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1159 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1170 static int usbfs_get_device_list(struct libusb_context *ctx)
1172 struct dirent *entry;
1173 DIR *buses = opendir(usbfs_path);
1177 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1178 return LIBUSB_ERROR_IO;
1181 while ((entry = readdir(buses))) {
1184 if (entry->d_name[0] == '.')
1189 if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1192 r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
1194 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1198 busnum = atoi(entry->d_name);
1200 usbi_dbg("unknown dir entry %s", entry->d_name);
1204 r = usbfs_scan_busdir(ctx, busnum);
1216 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
1218 uint8_t busnum, devaddr;
1221 ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname);
1222 if (LIBUSB_SUCCESS != ret) {
1226 return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff,
1230 #if !defined(USE_UDEV)
1231 static int sysfs_get_device_list(struct libusb_context *ctx)
1233 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1234 struct dirent *entry;
1235 int r = LIBUSB_ERROR_IO;
1238 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1242 while ((entry = readdir(devices))) {
1243 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1244 || strchr(entry->d_name, ':'))
1247 if (sysfs_scan_device(ctx, entry->d_name)) {
1248 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1259 static int linux_default_scan_devices (struct libusb_context *ctx)
1261 /* we can retrieve device list and descriptors from sysfs or usbfs.
1262 * sysfs is preferable, because if we use usbfs we end up resuming
1263 * any autosuspended USB devices. however, sysfs is not available
1264 * everywhere, so we need a usbfs fallback too.
1266 * as described in the "sysfs vs usbfs" comment at the top of this
1267 * file, sometimes we have sysfs but not enough information to
1268 * relate sysfs devices to usbfs nodes. op_init() determines the
1269 * adequacy of sysfs and sets sysfs_can_relate_devices.
1271 if (sysfs_can_relate_devices != 0)
1272 return sysfs_get_device_list(ctx);
1274 return usbfs_get_device_list(ctx);
1278 static int op_open(struct libusb_device_handle *handle)
1280 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1283 hpriv->fd = _get_usbfs_fd(handle->dev, O_RDWR, 0);
1284 if (hpriv->fd < 0) {
1285 if (hpriv->fd == LIBUSB_ERROR_NO_DEVICE) {
1286 /* device will still be marked as attached if hotplug monitor thread
1287 * hasn't processed remove event yet */
1288 usbi_mutex_static_lock(&linux_hotplug_lock);
1289 if (handle->dev->attached) {
1290 usbi_dbg("open failed with no device, but device still attached");
1291 linux_device_disconnected(handle->dev->bus_number,
1292 handle->dev->device_address, NULL);
1294 usbi_mutex_static_unlock(&linux_hotplug_lock);
1299 r = ioctl(hpriv->fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1301 if (errno == ENOTTY)
1302 usbi_dbg("getcap not available");
1304 usbi_err(HANDLE_CTX(handle), "getcap failed (%d)", errno);
1306 if (supports_flag_zero_packet)
1307 hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1308 if (supports_flag_bulk_continuation)
1309 hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1312 return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1315 static void op_close(struct libusb_device_handle *dev_handle)
1317 int fd = _device_handle_priv(dev_handle)->fd;
1318 usbi_remove_pollfd(HANDLE_CTX(dev_handle), fd);
1322 static int op_get_configuration(struct libusb_device_handle *handle,
1327 if (sysfs_can_relate_devices) {
1328 r = sysfs_get_active_config(handle->dev, config);
1330 r = usbfs_get_active_config(handle->dev,
1331 _device_handle_priv(handle)->fd);
1336 if (*config == -1) {
1337 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1344 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1346 struct linux_device_priv *priv = _device_priv(handle->dev);
1347 int fd = _device_handle_priv(handle)->fd;
1348 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1350 if (errno == EINVAL)
1351 return LIBUSB_ERROR_NOT_FOUND;
1352 else if (errno == EBUSY)
1353 return LIBUSB_ERROR_BUSY;
1354 else if (errno == ENODEV)
1355 return LIBUSB_ERROR_NO_DEVICE;
1357 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1358 return LIBUSB_ERROR_OTHER;
1361 /* update our cached active config descriptor */
1362 priv->active_config = config;
1364 return LIBUSB_SUCCESS;
1367 static int claim_interface(struct libusb_device_handle *handle, int iface)
1369 int fd = _device_handle_priv(handle)->fd;
1370 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1372 if (errno == ENOENT)
1373 return LIBUSB_ERROR_NOT_FOUND;
1374 else if (errno == EBUSY)
1375 return LIBUSB_ERROR_BUSY;
1376 else if (errno == ENODEV)
1377 return LIBUSB_ERROR_NO_DEVICE;
1379 usbi_err(HANDLE_CTX(handle),
1380 "claim interface failed, error %d errno %d", r, errno);
1381 return LIBUSB_ERROR_OTHER;
1386 static int release_interface(struct libusb_device_handle *handle, int iface)
1388 int fd = _device_handle_priv(handle)->fd;
1389 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1391 if (errno == ENODEV)
1392 return LIBUSB_ERROR_NO_DEVICE;
1394 usbi_err(HANDLE_CTX(handle),
1395 "release interface failed, error %d errno %d", r, errno);
1396 return LIBUSB_ERROR_OTHER;
1401 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1404 int fd = _device_handle_priv(handle)->fd;
1405 struct usbfs_setinterface setintf;
1408 setintf.interface = iface;
1409 setintf.altsetting = altsetting;
1410 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1412 if (errno == EINVAL)
1413 return LIBUSB_ERROR_NOT_FOUND;
1414 else if (errno == ENODEV)
1415 return LIBUSB_ERROR_NO_DEVICE;
1417 usbi_err(HANDLE_CTX(handle),
1418 "setintf failed error %d errno %d", r, errno);
1419 return LIBUSB_ERROR_OTHER;
1425 static int op_clear_halt(struct libusb_device_handle *handle,
1426 unsigned char endpoint)
1428 int fd = _device_handle_priv(handle)->fd;
1429 unsigned int _endpoint = endpoint;
1430 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1432 if (errno == ENOENT)
1433 return LIBUSB_ERROR_NOT_FOUND;
1434 else if (errno == ENODEV)
1435 return LIBUSB_ERROR_NO_DEVICE;
1437 usbi_err(HANDLE_CTX(handle),
1438 "clear_halt failed error %d errno %d", r, errno);
1439 return LIBUSB_ERROR_OTHER;
1445 static int op_reset_device(struct libusb_device_handle *handle)
1447 int fd = _device_handle_priv(handle)->fd;
1450 /* Doing a device reset will cause the usbfs driver to get unbound
1451 from any interfaces it is bound to. By voluntarily unbinding
1452 the usbfs driver ourself, we stop the kernel from rebinding
1453 the interface after reset (which would end up with the interface
1454 getting bound to the in kernel driver if any). */
1455 for (i = 0; i < USB_MAXINTERFACES; i++) {
1456 if (handle->claimed_interfaces & (1L << i)) {
1457 release_interface(handle, i);
1461 usbi_mutex_lock(&handle->lock);
1462 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1464 if (errno == ENODEV) {
1465 ret = LIBUSB_ERROR_NOT_FOUND;
1469 usbi_err(HANDLE_CTX(handle),
1470 "reset failed error %d errno %d", r, errno);
1471 ret = LIBUSB_ERROR_OTHER;
1475 /* And re-claim any interfaces which were claimed before the reset */
1476 for (i = 0; i < USB_MAXINTERFACES; i++) {
1477 if (handle->claimed_interfaces & (1L << i)) {
1479 * A driver may have completed modprobing during
1480 * IOCTL_USBFS_RESET, and bound itself as soon as
1481 * IOCTL_USBFS_RESET released the device lock
1483 r = detach_kernel_driver_and_claim(handle, i);
1485 usbi_warn(HANDLE_CTX(handle),
1486 "failed to re-claim interface %d after reset: %s",
1487 i, libusb_error_name(r));
1488 handle->claimed_interfaces &= ~(1L << i);
1489 ret = LIBUSB_ERROR_NOT_FOUND;
1494 usbi_mutex_unlock(&handle->lock);
1498 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1501 int fd = _device_handle_priv(handle)->fd;
1502 struct usbfs_getdriver getdrv;
1505 getdrv.interface = interface;
1506 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1508 if (errno == ENODATA)
1510 else if (errno == ENODEV)
1511 return LIBUSB_ERROR_NO_DEVICE;
1513 usbi_err(HANDLE_CTX(handle),
1514 "get driver failed error %d errno %d", r, errno);
1515 return LIBUSB_ERROR_OTHER;
1518 return (strcmp(getdrv.driver, "usbfs") == 0) ? 0 : 1;
1521 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1524 int fd = _device_handle_priv(handle)->fd;
1525 struct usbfs_ioctl command;
1526 struct usbfs_getdriver getdrv;
1529 command.ifno = interface;
1530 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1531 command.data = NULL;
1533 getdrv.interface = interface;
1534 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1535 if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1536 return LIBUSB_ERROR_NOT_FOUND;
1538 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1540 if (errno == ENODATA)
1541 return LIBUSB_ERROR_NOT_FOUND;
1542 else if (errno == EINVAL)
1543 return LIBUSB_ERROR_INVALID_PARAM;
1544 else if (errno == ENODEV)
1545 return LIBUSB_ERROR_NO_DEVICE;
1547 usbi_err(HANDLE_CTX(handle),
1548 "detach failed error %d errno %d", r, errno);
1549 return LIBUSB_ERROR_OTHER;
1555 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1558 int fd = _device_handle_priv(handle)->fd;
1559 struct usbfs_ioctl command;
1562 command.ifno = interface;
1563 command.ioctl_code = IOCTL_USBFS_CONNECT;
1564 command.data = NULL;
1566 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1568 if (errno == ENODATA)
1569 return LIBUSB_ERROR_NOT_FOUND;
1570 else if (errno == EINVAL)
1571 return LIBUSB_ERROR_INVALID_PARAM;
1572 else if (errno == ENODEV)
1573 return LIBUSB_ERROR_NO_DEVICE;
1574 else if (errno == EBUSY)
1575 return LIBUSB_ERROR_BUSY;
1577 usbi_err(HANDLE_CTX(handle),
1578 "attach failed error %d errno %d", r, errno);
1579 return LIBUSB_ERROR_OTHER;
1580 } else if (r == 0) {
1581 return LIBUSB_ERROR_NOT_FOUND;
1587 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle,
1590 struct usbfs_disconnect_claim dc;
1591 int r, fd = _device_handle_priv(handle)->fd;
1593 dc.interface = interface;
1594 strcpy(dc.driver, "usbfs");
1595 dc.flags = USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER;
1596 r = ioctl(fd, IOCTL_USBFS_DISCONNECT_CLAIM, &dc);
1597 if (r == 0 || (r != 0 && errno != ENOTTY)) {
1603 return LIBUSB_ERROR_BUSY;
1605 return LIBUSB_ERROR_INVALID_PARAM;
1607 return LIBUSB_ERROR_NO_DEVICE;
1609 usbi_err(HANDLE_CTX(handle),
1610 "disconnect-and-claim failed errno %d", errno);
1611 return LIBUSB_ERROR_OTHER;
1614 /* Fallback code for kernels which don't support the
1615 disconnect-and-claim ioctl */
1616 r = op_detach_kernel_driver(handle, interface);
1617 if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND)
1620 return claim_interface(handle, interface);
1623 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1625 if (handle->auto_detach_kernel_driver)
1626 return detach_kernel_driver_and_claim(handle, iface);
1628 return claim_interface(handle, iface);
1631 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1635 r = release_interface(handle, iface);
1639 if (handle->auto_detach_kernel_driver)
1640 op_attach_kernel_driver(handle, iface);
1645 static void op_destroy_device(struct libusb_device *dev)
1647 struct linux_device_priv *priv = _device_priv(dev);
1648 if (priv->descriptors)
1649 free(priv->descriptors);
1650 if (priv->sysfs_dir)
1651 free(priv->sysfs_dir);
1654 /* URBs are discarded in reverse order of submission to avoid races. */
1655 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1657 struct libusb_transfer *transfer =
1658 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1659 struct linux_transfer_priv *tpriv =
1660 usbi_transfer_get_os_priv(itransfer);
1661 struct linux_device_handle_priv *dpriv =
1662 _device_handle_priv(transfer->dev_handle);
1664 struct usbfs_urb *urb;
1666 for (i = last_plus_one - 1; i >= first; i--) {
1667 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
1668 urb = tpriv->iso_urbs[i];
1670 urb = &tpriv->urbs[i];
1672 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
1675 if (EINVAL == errno) {
1676 usbi_dbg("URB not found --> assuming ready to be reaped");
1677 if (i == (last_plus_one - 1))
1678 ret = LIBUSB_ERROR_NOT_FOUND;
1679 } else if (ENODEV == errno) {
1680 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1681 ret = LIBUSB_ERROR_NO_DEVICE;
1683 usbi_warn(TRANSFER_CTX(transfer),
1684 "unrecognised discard errno %d", errno);
1685 ret = LIBUSB_ERROR_OTHER;
1691 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1694 for (i = 0; i < tpriv->num_urbs; i++) {
1695 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1701 free(tpriv->iso_urbs);
1702 tpriv->iso_urbs = NULL;
1705 static int submit_bulk_transfer(struct usbi_transfer *itransfer,
1706 unsigned char urb_type)
1708 struct libusb_transfer *transfer =
1709 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1710 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1711 struct linux_device_handle_priv *dpriv =
1712 _device_handle_priv(transfer->dev_handle);
1713 struct usbfs_urb *urbs;
1714 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1715 == LIBUSB_ENDPOINT_OUT;
1716 int bulk_buffer_len, use_bulk_continuation;
1722 return LIBUSB_ERROR_BUSY;
1724 if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1725 !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
1726 return LIBUSB_ERROR_NOT_SUPPORTED;
1729 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1730 * around this by splitting large transfers into 16k blocks, and then
1731 * submit all urbs at once. it would be simpler to submit one urb at
1732 * a time, but there is a big performance gain doing it this way.
1734 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1735 * using arbritary large transfers can still be a bad idea though, as
1736 * the kernel needs to allocate physical contiguous memory for this,
1737 * which may fail for large buffers.
1739 * The kernel solves this problem by splitting the transfer into
1740 * blocks itself when the host-controller is scatter-gather capable
1741 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1743 * Last, there is the issue of short-transfers when splitting, for
1744 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1745 * is needed, but this is not always available.
1747 if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1748 /* Good! Just submit everything in one go */
1749 bulk_buffer_len = transfer->length ? transfer->length : 1;
1750 use_bulk_continuation = 0;
1751 } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1752 /* Split the transfers and use bulk-continuation to
1753 avoid issues with short-transfers */
1754 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1755 use_bulk_continuation = 1;
1756 } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1757 /* Don't split, assume the kernel can alloc the buffer
1758 (otherwise the submit will fail with -ENOMEM) */
1759 bulk_buffer_len = transfer->length ? transfer->length : 1;
1760 use_bulk_continuation = 0;
1762 /* Bad, splitting without bulk-continuation, short transfers
1763 which end before the last urb will not work reliable! */
1764 /* Note we don't warn here as this is "normal" on kernels <
1765 2.6.32 and not a problem for most applications */
1766 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1767 use_bulk_continuation = 0;
1770 int num_urbs = transfer->length / bulk_buffer_len;
1771 int last_urb_partial = 0;
1773 if (transfer->length == 0) {
1775 } else if ((transfer->length % bulk_buffer_len) > 0) {
1776 last_urb_partial = 1;
1779 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
1781 alloc_size = num_urbs * sizeof(struct usbfs_urb);
1782 urbs = calloc(1, alloc_size);
1784 return LIBUSB_ERROR_NO_MEM;
1786 tpriv->num_urbs = num_urbs;
1787 tpriv->num_retired = 0;
1788 tpriv->reap_action = NORMAL;
1789 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1791 for (i = 0; i < num_urbs; i++) {
1792 struct usbfs_urb *urb = &urbs[i];
1793 urb->usercontext = itransfer;
1794 urb->type = urb_type;
1795 urb->endpoint = transfer->endpoint;
1796 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
1797 /* don't set the short not ok flag for the last URB */
1798 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
1799 urb->flags = USBFS_URB_SHORT_NOT_OK;
1800 if (i == num_urbs - 1 && last_urb_partial)
1801 urb->buffer_length = transfer->length % bulk_buffer_len;
1802 else if (transfer->length == 0)
1803 urb->buffer_length = 0;
1805 urb->buffer_length = bulk_buffer_len;
1807 if (i > 0 && use_bulk_continuation)
1808 urb->flags |= USBFS_URB_BULK_CONTINUATION;
1810 /* we have already checked that the flag is supported */
1811 if (is_out && i == num_urbs - 1 &&
1812 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
1813 urb->flags |= USBFS_URB_ZERO_PACKET;
1815 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1817 if (errno == ENODEV) {
1818 r = LIBUSB_ERROR_NO_DEVICE;
1820 usbi_err(TRANSFER_CTX(transfer),
1821 "submiturb failed error %d errno=%d", r, errno);
1822 r = LIBUSB_ERROR_IO;
1825 /* if the first URB submission fails, we can simply free up and
1826 * return failure immediately. */
1828 usbi_dbg("first URB failed, easy peasy");
1834 /* if it's not the first URB that failed, the situation is a bit
1835 * tricky. we may need to discard all previous URBs. there are
1837 * - discarding is asynchronous - discarded urbs will be reaped
1838 * later. the user must not have freed the transfer when the
1839 * discarded URBs are reaped, otherwise libusb will be using
1841 * - the earlier URBs may have completed successfully and we do
1842 * not want to throw away any data.
1843 * - this URB failing may be no error; EREMOTEIO means that
1844 * this transfer simply didn't need all the URBs we submitted
1845 * so, we report that the transfer was submitted successfully and
1846 * in case of error we discard all previous URBs. later when
1847 * the final reap completes we can report error to the user,
1848 * or success if an earlier URB was completed successfully.
1850 tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
1852 /* The URBs we haven't submitted yet we count as already
1854 tpriv->num_retired += num_urbs - i;
1856 /* If we completed short then don't try to discard. */
1857 if (COMPLETED_EARLY == tpriv->reap_action)
1860 discard_urbs(itransfer, 0, i);
1862 usbi_dbg("reporting successful submission but waiting for %d "
1863 "discards before reporting error", i);
1871 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1873 struct libusb_transfer *transfer =
1874 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1875 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1876 struct linux_device_handle_priv *dpriv =
1877 _device_handle_priv(transfer->dev_handle);
1878 struct usbfs_urb **urbs;
1880 int num_packets = transfer->num_iso_packets;
1882 int this_urb_len = 0;
1884 int packet_offset = 0;
1885 unsigned int packet_len;
1886 unsigned char *urb_buffer = transfer->buffer;
1888 if (tpriv->iso_urbs)
1889 return LIBUSB_ERROR_BUSY;
1891 /* usbfs places a 32kb limit on iso URBs. we divide up larger requests
1892 * into smaller units to meet such restriction, then fire off all the
1893 * units at once. it would be simpler if we just fired one unit at a time,
1894 * but there is a big performance gain through doing it this way.
1896 * Newer kernels lift the 32k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1897 * using arbritary large transfers is still be a bad idea though, as
1898 * the kernel needs to allocate physical contiguous memory for this,
1899 * which may fail for large buffers.
1902 /* calculate how many URBs we need */
1903 for (i = 0; i < num_packets; i++) {
1904 unsigned int space_remaining = MAX_ISO_BUFFER_LENGTH - this_urb_len;
1905 packet_len = transfer->iso_packet_desc[i].length;
1907 if (packet_len > space_remaining) {
1909 this_urb_len = packet_len;
1911 this_urb_len += packet_len;
1914 usbi_dbg("need %d 32k URBs for transfer", num_urbs);
1916 alloc_size = num_urbs * sizeof(*urbs);
1917 urbs = calloc(1, alloc_size);
1919 return LIBUSB_ERROR_NO_MEM;
1921 tpriv->iso_urbs = urbs;
1922 tpriv->num_urbs = num_urbs;
1923 tpriv->num_retired = 0;
1924 tpriv->reap_action = NORMAL;
1925 tpriv->iso_packet_offset = 0;
1927 /* allocate + initialize each URB with the correct number of packets */
1928 for (i = 0; i < num_urbs; i++) {
1929 struct usbfs_urb *urb;
1930 unsigned int space_remaining_in_urb = MAX_ISO_BUFFER_LENGTH;
1931 int urb_packet_offset = 0;
1932 unsigned char *urb_buffer_orig = urb_buffer;
1936 /* swallow up all the packets we can fit into this URB */
1937 while (packet_offset < transfer->num_iso_packets) {
1938 packet_len = transfer->iso_packet_desc[packet_offset].length;
1939 if (packet_len <= space_remaining_in_urb) {
1941 urb_packet_offset++;
1943 space_remaining_in_urb -= packet_len;
1944 urb_buffer += packet_len;
1946 /* it can't fit, save it for the next URB */
1951 alloc_size = sizeof(*urb)
1952 + (urb_packet_offset * sizeof(struct usbfs_iso_packet_desc));
1953 urb = calloc(1, alloc_size);
1955 free_iso_urbs(tpriv);
1956 return LIBUSB_ERROR_NO_MEM;
1960 /* populate packet lengths */
1961 for (j = 0, k = packet_offset - urb_packet_offset;
1962 k < packet_offset; k++, j++) {
1963 packet_len = transfer->iso_packet_desc[k].length;
1964 urb->iso_frame_desc[j].length = packet_len;
1967 urb->usercontext = itransfer;
1968 urb->type = USBFS_URB_TYPE_ISO;
1969 /* FIXME: interface for non-ASAP data? */
1970 urb->flags = USBFS_URB_ISO_ASAP;
1971 urb->endpoint = transfer->endpoint;
1972 urb->number_of_packets = urb_packet_offset;
1973 urb->buffer = urb_buffer_orig;
1977 for (i = 0; i < num_urbs; i++) {
1978 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
1980 if (errno == ENODEV) {
1981 r = LIBUSB_ERROR_NO_DEVICE;
1983 usbi_err(TRANSFER_CTX(transfer),
1984 "submiturb failed error %d errno=%d", r, errno);
1985 r = LIBUSB_ERROR_IO;
1988 /* if the first URB submission fails, we can simply free up and
1989 * return failure immediately. */
1991 usbi_dbg("first URB failed, easy peasy");
1992 free_iso_urbs(tpriv);
1996 /* if it's not the first URB that failed, the situation is a bit
1997 * tricky. we must discard all previous URBs. there are
1999 * - discarding is asynchronous - discarded urbs will be reaped
2000 * later. the user must not have freed the transfer when the
2001 * discarded URBs are reaped, otherwise libusb will be using
2003 * - the earlier URBs may have completed successfully and we do
2004 * not want to throw away any data.
2005 * so, in this case we discard all the previous URBs BUT we report
2006 * that the transfer was submitted successfully. then later when
2007 * the final discard completes we can report error to the user.
2009 tpriv->reap_action = SUBMIT_FAILED;
2011 /* The URBs we haven't submitted yet we count as already
2013 tpriv->num_retired = num_urbs - i;
2014 discard_urbs(itransfer, 0, i);
2016 usbi_dbg("reporting successful submission but waiting for %d "
2017 "discards before reporting error", i);
2025 static int submit_control_transfer(struct usbi_transfer *itransfer)
2027 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2028 struct libusb_transfer *transfer =
2029 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2030 struct linux_device_handle_priv *dpriv =
2031 _device_handle_priv(transfer->dev_handle);
2032 struct usbfs_urb *urb;
2036 return LIBUSB_ERROR_BUSY;
2038 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
2039 return LIBUSB_ERROR_INVALID_PARAM;
2041 urb = calloc(1, sizeof(struct usbfs_urb));
2043 return LIBUSB_ERROR_NO_MEM;
2045 tpriv->num_urbs = 1;
2046 tpriv->reap_action = NORMAL;
2048 urb->usercontext = itransfer;
2049 urb->type = USBFS_URB_TYPE_CONTROL;
2050 urb->endpoint = transfer->endpoint;
2051 urb->buffer = transfer->buffer;
2052 urb->buffer_length = transfer->length;
2054 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2058 if (errno == ENODEV)
2059 return LIBUSB_ERROR_NO_DEVICE;
2061 usbi_err(TRANSFER_CTX(transfer),
2062 "submiturb failed error %d errno=%d", r, errno);
2063 return LIBUSB_ERROR_IO;
2068 static int op_submit_transfer(struct usbi_transfer *itransfer)
2070 struct libusb_transfer *transfer =
2071 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2073 switch (transfer->type) {
2074 case LIBUSB_TRANSFER_TYPE_CONTROL:
2075 return submit_control_transfer(itransfer);
2076 case LIBUSB_TRANSFER_TYPE_BULK:
2077 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_BULK);
2078 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2079 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_INTERRUPT);
2080 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2081 return submit_iso_transfer(itransfer);
2083 usbi_err(TRANSFER_CTX(transfer),
2084 "unknown endpoint type %d", transfer->type);
2085 return LIBUSB_ERROR_INVALID_PARAM;
2089 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2091 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2092 struct libusb_transfer *transfer =
2093 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2095 switch (transfer->type) {
2096 case LIBUSB_TRANSFER_TYPE_BULK:
2097 if (tpriv->reap_action == ERROR)
2099 /* else, fall through */
2100 case LIBUSB_TRANSFER_TYPE_CONTROL:
2101 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2102 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2103 tpriv->reap_action = CANCELLED;
2106 usbi_err(TRANSFER_CTX(transfer),
2107 "unknown endpoint type %d", transfer->type);
2108 return LIBUSB_ERROR_INVALID_PARAM;
2112 return LIBUSB_ERROR_NOT_FOUND;
2114 return discard_urbs(itransfer, 0, tpriv->num_urbs);
2117 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2119 struct libusb_transfer *transfer =
2120 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2121 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2123 /* urbs can be freed also in submit_transfer so lock mutex first */
2124 switch (transfer->type) {
2125 case LIBUSB_TRANSFER_TYPE_CONTROL:
2126 case LIBUSB_TRANSFER_TYPE_BULK:
2127 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2128 usbi_mutex_lock(&itransfer->lock);
2132 usbi_mutex_unlock(&itransfer->lock);
2134 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2135 usbi_mutex_lock(&itransfer->lock);
2136 if (tpriv->iso_urbs)
2137 free_iso_urbs(tpriv);
2138 usbi_mutex_unlock(&itransfer->lock);
2141 usbi_err(TRANSFER_CTX(transfer),
2142 "unknown endpoint type %d", transfer->type);
2146 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2147 struct usbfs_urb *urb)
2149 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2150 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2151 int urb_idx = urb - tpriv->urbs;
2153 usbi_mutex_lock(&itransfer->lock);
2154 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2155 urb_idx + 1, tpriv->num_urbs);
2157 tpriv->num_retired++;
2159 if (tpriv->reap_action != NORMAL) {
2160 /* cancelled, submit_fail, or completed early */
2161 usbi_dbg("abnormal reap: urb status %d", urb->status);
2163 /* even though we're in the process of cancelling, it's possible that
2164 * we may receive some data in these URBs that we don't want to lose.
2166 * 1. while the kernel is cancelling all the packets that make up an
2167 * URB, a few of them might complete. so we get back a successful
2168 * cancellation *and* some data.
2169 * 2. we receive a short URB which marks the early completion condition,
2170 * so we start cancelling the remaining URBs. however, we're too
2171 * slow and another URB completes (or at least completes partially).
2172 * (this can't happen since we always use BULK_CONTINUATION.)
2174 * When this happens, our objectives are not to lose any "surplus" data,
2175 * and also to stick it at the end of the previously-received data
2176 * (closing any holes), so that libusb reports the total amount of
2177 * transferred data and presents it in a contiguous chunk.
2179 if (urb->actual_length > 0) {
2180 unsigned char *target = transfer->buffer + itransfer->transferred;
2181 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2182 if (urb->buffer != target) {
2183 usbi_dbg("moving surplus data from offset %d to offset %d",
2184 (unsigned char *) urb->buffer - transfer->buffer,
2185 target - transfer->buffer);
2186 memmove(target, urb->buffer, urb->actual_length);
2188 itransfer->transferred += urb->actual_length;
2191 if (tpriv->num_retired == tpriv->num_urbs) {
2192 usbi_dbg("abnormal reap: last URB handled, reporting");
2193 if (tpriv->reap_action != COMPLETED_EARLY &&
2194 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2195 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2201 itransfer->transferred += urb->actual_length;
2203 /* Many of these errors can occur on *any* urb of a multi-urb
2204 * transfer. When they do, we tear down the rest of the transfer.
2206 switch (urb->status) {
2209 case -EREMOTEIO: /* short transfer */
2211 case -ENOENT: /* cancelled */
2216 usbi_dbg("device removed");
2217 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2218 goto cancel_remaining;
2220 usbi_dbg("detected endpoint stall");
2221 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2222 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2223 goto cancel_remaining;
2225 /* overflow can only ever occur in the last urb */
2226 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2227 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2228 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2235 usbi_dbg("low level error %d", urb->status);
2236 tpriv->reap_action = ERROR;
2237 goto cancel_remaining;
2239 usbi_warn(ITRANSFER_CTX(itransfer),
2240 "unrecognised urb status %d", urb->status);
2241 tpriv->reap_action = ERROR;
2242 goto cancel_remaining;
2245 /* if we're the last urb or we got less data than requested then we're
2247 if (urb_idx == tpriv->num_urbs - 1) {
2248 usbi_dbg("last URB in transfer --> complete!");
2250 } else if (urb->actual_length < urb->buffer_length) {
2251 usbi_dbg("short transfer %d/%d --> complete!",
2252 urb->actual_length, urb->buffer_length);
2253 if (tpriv->reap_action == NORMAL)
2254 tpriv->reap_action = COMPLETED_EARLY;
2259 if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2260 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2262 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2265 /* cancel remaining urbs and wait for their completion before
2266 * reporting results */
2267 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2270 usbi_mutex_unlock(&itransfer->lock);
2276 usbi_mutex_unlock(&itransfer->lock);
2277 return CANCELLED == tpriv->reap_action ?
2278 usbi_handle_transfer_cancellation(itransfer) :
2279 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2282 static int handle_iso_completion(struct usbi_transfer *itransfer,
2283 struct usbfs_urb *urb)
2285 struct libusb_transfer *transfer =
2286 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2287 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2288 int num_urbs = tpriv->num_urbs;
2291 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2293 usbi_mutex_lock(&itransfer->lock);
2294 for (i = 0; i < num_urbs; i++) {
2295 if (urb == tpriv->iso_urbs[i]) {
2301 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2302 usbi_mutex_unlock(&itransfer->lock);
2303 return LIBUSB_ERROR_NOT_FOUND;
2306 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2309 /* copy isochronous results back in */
2311 for (i = 0; i < urb->number_of_packets; i++) {
2312 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2313 struct libusb_iso_packet_descriptor *lib_desc =
2314 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2315 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2316 switch (urb_desc->status) {
2319 case -ENOENT: /* cancelled */
2324 usbi_dbg("device removed");
2325 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2328 usbi_dbg("detected endpoint stall");
2329 lib_desc->status = LIBUSB_TRANSFER_STALL;
2332 usbi_dbg("overflow error");
2333 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2341 usbi_dbg("low-level USB error %d", urb_desc->status);
2342 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2345 usbi_warn(TRANSFER_CTX(transfer),
2346 "unrecognised urb status %d", urb_desc->status);
2347 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2350 lib_desc->actual_length = urb_desc->actual_length;
2353 tpriv->num_retired++;
2355 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2356 usbi_dbg("CANCEL: urb status %d", urb->status);
2358 if (tpriv->num_retired == num_urbs) {
2359 usbi_dbg("CANCEL: last URB handled, reporting");
2360 free_iso_urbs(tpriv);
2361 if (tpriv->reap_action == CANCELLED) {
2362 usbi_mutex_unlock(&itransfer->lock);
2363 return usbi_handle_transfer_cancellation(itransfer);
2365 usbi_mutex_unlock(&itransfer->lock);
2366 return usbi_handle_transfer_completion(itransfer,
2367 LIBUSB_TRANSFER_ERROR);
2373 switch (urb->status) {
2376 case -ENOENT: /* cancelled */
2380 usbi_dbg("device removed");
2381 status = LIBUSB_TRANSFER_NO_DEVICE;
2384 usbi_warn(TRANSFER_CTX(transfer),
2385 "unrecognised urb status %d", urb->status);
2386 status = LIBUSB_TRANSFER_ERROR;
2390 /* if we're the last urb then we're done */
2391 if (urb_idx == num_urbs) {
2392 usbi_dbg("last URB in transfer --> complete!");
2393 free_iso_urbs(tpriv);
2394 usbi_mutex_unlock(&itransfer->lock);
2395 return usbi_handle_transfer_completion(itransfer, status);
2399 usbi_mutex_unlock(&itransfer->lock);
2403 static int handle_control_completion(struct usbi_transfer *itransfer,
2404 struct usbfs_urb *urb)
2406 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2409 usbi_mutex_lock(&itransfer->lock);
2410 usbi_dbg("handling completion status %d", urb->status);
2412 itransfer->transferred += urb->actual_length;
2414 if (tpriv->reap_action == CANCELLED) {
2415 if (urb->status != 0 && urb->status != -ENOENT)
2416 usbi_warn(ITRANSFER_CTX(itransfer),
2417 "cancel: unrecognised urb status %d", urb->status);
2420 usbi_mutex_unlock(&itransfer->lock);
2421 return usbi_handle_transfer_cancellation(itransfer);
2424 switch (urb->status) {
2426 status = LIBUSB_TRANSFER_COMPLETED;
2428 case -ENOENT: /* cancelled */
2429 status = LIBUSB_TRANSFER_CANCELLED;
2433 usbi_dbg("device removed");
2434 status = LIBUSB_TRANSFER_NO_DEVICE;
2437 usbi_dbg("unsupported control request");
2438 status = LIBUSB_TRANSFER_STALL;
2441 usbi_dbg("control overflow error");
2442 status = LIBUSB_TRANSFER_OVERFLOW;
2449 usbi_dbg("low-level bus error occurred");
2450 status = LIBUSB_TRANSFER_ERROR;
2453 usbi_warn(ITRANSFER_CTX(itransfer),
2454 "unrecognised urb status %d", urb->status);
2455 status = LIBUSB_TRANSFER_ERROR;
2461 usbi_mutex_unlock(&itransfer->lock);
2462 return usbi_handle_transfer_completion(itransfer, status);
2465 static int reap_for_handle(struct libusb_device_handle *handle)
2467 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2469 struct usbfs_urb *urb;
2470 struct usbi_transfer *itransfer;
2471 struct libusb_transfer *transfer;
2473 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2474 if (r == -1 && errno == EAGAIN)
2477 if (errno == ENODEV)
2478 return LIBUSB_ERROR_NO_DEVICE;
2480 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2482 return LIBUSB_ERROR_IO;
2485 itransfer = urb->usercontext;
2486 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2488 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2489 urb->actual_length);
2491 switch (transfer->type) {
2492 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2493 return handle_iso_completion(itransfer, urb);
2494 case LIBUSB_TRANSFER_TYPE_BULK:
2495 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2496 return handle_bulk_completion(itransfer, urb);
2497 case LIBUSB_TRANSFER_TYPE_CONTROL:
2498 return handle_control_completion(itransfer, urb);
2500 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2502 return LIBUSB_ERROR_OTHER;
2506 static int op_handle_events(struct libusb_context *ctx,
2507 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2512 usbi_mutex_lock(&ctx->open_devs_lock);
2513 for (i = 0; i < nfds && num_ready > 0; i++) {
2514 struct pollfd *pollfd = &fds[i];
2515 struct libusb_device_handle *handle;
2516 struct linux_device_handle_priv *hpriv = NULL;
2518 if (!pollfd->revents)
2522 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2523 hpriv = _device_handle_priv(handle);
2524 if (hpriv->fd == pollfd->fd)
2528 if (pollfd->revents & POLLERR) {
2529 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2530 usbi_handle_disconnect(handle);
2531 /* device will still be marked as attached if hotplug monitor thread
2532 * hasn't processed remove event yet */
2533 usbi_mutex_static_lock(&linux_hotplug_lock);
2534 if (handle->dev->attached)
2535 linux_device_disconnected(handle->dev->bus_number,
2536 handle->dev->device_address, NULL);
2537 usbi_mutex_static_unlock(&linux_hotplug_lock);
2542 r = reap_for_handle(handle);
2544 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2552 usbi_mutex_unlock(&ctx->open_devs_lock);
2556 static int op_clock_gettime(int clk_id, struct timespec *tp)
2559 case USBI_CLOCK_MONOTONIC:
2560 return clock_gettime(monotonic_clkid, tp);
2561 case USBI_CLOCK_REALTIME:
2562 return clock_gettime(CLOCK_REALTIME, tp);
2564 return LIBUSB_ERROR_INVALID_PARAM;
2568 #ifdef USBI_TIMERFD_AVAILABLE
2569 static clockid_t op_get_timerfd_clockid(void)
2571 return monotonic_clkid;
2576 const struct usbi_os_backend linux_usbfs_backend = {
2577 .name = "Linux usbfs",
2578 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2581 .get_device_list = NULL,
2582 .hotplug_poll = op_hotplug_poll,
2583 .get_device_descriptor = op_get_device_descriptor,
2584 .get_active_config_descriptor = op_get_active_config_descriptor,
2585 .get_config_descriptor = op_get_config_descriptor,
2586 .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2590 .get_configuration = op_get_configuration,
2591 .set_configuration = op_set_configuration,
2592 .claim_interface = op_claim_interface,
2593 .release_interface = op_release_interface,
2595 .set_interface_altsetting = op_set_interface,
2596 .clear_halt = op_clear_halt,
2597 .reset_device = op_reset_device,
2599 .kernel_driver_active = op_kernel_driver_active,
2600 .detach_kernel_driver = op_detach_kernel_driver,
2601 .attach_kernel_driver = op_attach_kernel_driver,
2603 .destroy_device = op_destroy_device,
2605 .submit_transfer = op_submit_transfer,
2606 .cancel_transfer = op_cancel_transfer,
2607 .clear_transfer_priv = op_clear_transfer_priv,
2609 .handle_events = op_handle_events,
2611 .clock_gettime = op_clock_gettime,
2613 #ifdef USBI_TIMERFD_AVAILABLE
2614 .get_timerfd_clockid = op_get_timerfd_clockid,
2617 .device_priv_size = sizeof(struct linux_device_priv),
2618 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2619 .transfer_priv_size = sizeof(struct linux_transfer_priv),
2620 .add_iso_packet_size = 0,