2 * Linux usbfs backend for libusbx
3 * Copyright © 2007-2009 Daniel Drake <dsd@gentoo.org>
4 * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
5 * Copyright © 2013 Nathan Hjelm <hjelmn@mac.com>
6 * Copyright © 2012-2013 Hans de Goede <hdegoede@redhat.com>
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
34 #include <sys/ioctl.h>
36 #include <sys/types.h>
37 #include <sys/utsname.h>
42 #include "linux_usbfs.h"
45 * opening a usbfs node causes the device to be resumed, so we attempt to
46 * avoid this during enumeration.
48 * sysfs allows us to read the kernel's in-memory copies of device descriptors
49 * and so forth, avoiding the need to open the device:
50 * - The binary "descriptors" file contains all config descriptors since
51 * 2.6.26, commit 217a9081d8e69026186067711131b77f0ce219ed
52 * - The binary "descriptors" file was added in 2.6.23, commit
53 * 69d42a78f935d19384d1f6e4f94b65bb162b36df, but it only contains the
54 * active config descriptors
55 * - The "busnum" file was added in 2.6.22, commit
56 * 83f7d958eab2fbc6b159ee92bf1493924e1d0f72
57 * - The "devnum" file has been present since pre-2.6.18
58 * - the "bConfigurationValue" file has been present since pre-2.6.18
60 * If we have bConfigurationValue, busnum, and devnum, then we can determine
61 * the active configuration without having to open the usbfs node in RDWR mode.
62 * The busnum file is important as that is the only way we can relate sysfs
63 * devices to usbfs nodes.
65 * If we also have all descriptors, we can obtain the device descriptor and
66 * configuration without touching usbfs at all.
69 /* endianness for multi-byte fields:
71 * Descriptors exposed by usbfs have the multi-byte fields in the device
72 * descriptor as host endian. Multi-byte fields in the other descriptors are
73 * bus-endian. The kernel documentation says otherwise, but it is wrong.
75 * In sysfs all descriptors are bus-endian.
78 static const char *usbfs_path = NULL;
80 /* use usbdev*.* device names in /dev instead of the usbfs bus directories */
81 static int usbdev_names = 0;
83 /* Linux 2.6.32 adds support for a bulk continuation URB flag. this basically
84 * allows us to mark URBs as being part of a specific logical transfer when
85 * we submit them to the kernel. then, on any error except a cancellation, all
86 * URBs within that transfer will be cancelled and no more URBs will be
87 * accepted for the transfer, meaning that no more data can creep in.
89 * The BULK_CONTINUATION flag must be set on all URBs within a bulk transfer
90 * (in either direction) except the first.
91 * For IN transfers, we must also set SHORT_NOT_OK on all URBs except the
92 * last; it means that the kernel should treat a short reply as an error.
93 * For OUT transfers, SHORT_NOT_OK must not be set. it isn't needed (OUT
94 * transfers can't be short unless there's already some sort of error), and
95 * setting this flag is disallowed (a kernel with USB debugging enabled will
98 static int supports_flag_bulk_continuation = -1;
100 /* Linux 2.6.31 fixes support for the zero length packet URB flag. This
101 * allows us to mark URBs that should be followed by a zero length data
102 * packet, which can be required by device- or class-specific protocols.
104 static int supports_flag_zero_packet = -1;
106 /* clock ID for monotonic clock, as not all clock sources are available on all
107 * systems. appropriate choice made at initialization time. */
108 static clockid_t monotonic_clkid = -1;
110 /* Linux 2.6.22 (commit 83f7d958eab2fbc6b159ee92bf1493924e1d0f72) adds a busnum
111 * to sysfs, so we can relate devices. This also implies that we can read
112 * the active configuration through bConfigurationValue */
113 static int sysfs_can_relate_devices = -1;
115 /* Linux 2.6.26 (commit 217a9081d8e69026186067711131b77f0ce219ed) adds all
116 * config descriptors (rather then just the active config) to the sysfs
117 * descriptors file, so from then on we can use them. */
118 static int sysfs_has_descriptors = -1;
120 /* how many times have we initted (and not exited) ? */
121 static volatile int init_count = 0;
123 /* Protects init_count and serializes scan_devices versus the hotplug-thread */
124 static usbi_mutex_static_t hotplug_lock = USBI_MUTEX_INITIALIZER;
126 static int linux_start_event_monitor(void);
127 static int linux_stop_event_monitor(void);
128 static int linux_scan_devices(struct libusb_context *ctx);
129 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname);
131 #if !defined(USE_UDEV)
132 static int linux_default_scan_devices (struct libusb_context *ctx);
135 struct linux_device_priv {
137 unsigned char *descriptors;
139 int active_config; /* cache val for !sysfs_can_relate_devices */
142 struct linux_device_handle_priv {
149 /* submission failed after the first URB, so await cancellation/completion
150 * of all the others */
153 /* cancelled by user or timeout */
156 /* completed multi-URB transfer in non-final URB */
159 /* one or more urbs encountered a low-level error */
163 struct linux_transfer_priv {
165 struct usbfs_urb *urbs;
166 struct usbfs_urb **iso_urbs;
169 enum reap_action reap_action;
172 enum libusb_transfer_status reap_status;
174 /* next iso packet in user-supplied transfer to be populated */
175 int iso_packet_offset;
178 static int _get_usbfs_fd(struct libusb_device *dev, mode_t mode, int silent)
180 struct libusb_context *ctx = DEVICE_CTX(dev);
185 snprintf(path, PATH_MAX, "%s/usbdev%d.%d",
186 usbfs_path, dev->bus_number, dev->device_address);
188 snprintf(path, PATH_MAX, "%s/%03d/%03d",
189 usbfs_path, dev->bus_number, dev->device_address);
191 fd = open(path, mode);
193 return fd; /* Success */
196 usbi_err(ctx, "libusbx couldn't open USB device %s: %s",
197 path, strerror(errno));
198 if (errno == EACCES && mode == O_RDWR)
199 usbi_err(ctx, "libusbx requires write access to USB "
204 return LIBUSB_ERROR_ACCESS;
206 return LIBUSB_ERROR_NO_DEVICE;
207 return LIBUSB_ERROR_IO;
210 static struct linux_device_priv *_device_priv(struct libusb_device *dev)
212 return (struct linux_device_priv *) dev->os_priv;
215 static struct linux_device_handle_priv *_device_handle_priv(
216 struct libusb_device_handle *handle)
218 return (struct linux_device_handle_priv *) handle->os_priv;
221 /* check dirent for a /dev/usbdev%d.%d name
222 * optionally return bus/device on success */
223 static int _is_usbdev_entry(struct dirent *entry, int *bus_p, int *dev_p)
227 if (sscanf(entry->d_name, "usbdev%d.%d", &busnum, &devnum) != 2)
230 usbi_dbg("found: %s", entry->d_name);
238 static int check_usb_vfs(const char *dirname)
241 struct dirent *entry;
244 dir = opendir(dirname);
248 while ((entry = readdir(dir)) != NULL) {
249 if (entry->d_name[0] == '.')
252 /* We assume if we find any files that it must be the right place */
261 static const char *find_usbfs_path(void)
263 const char *path = "/dev/bus/usb";
264 const char *ret = NULL;
266 if (check_usb_vfs(path)) {
269 path = "/proc/bus/usb";
270 if (check_usb_vfs(path))
274 /* look for /dev/usbdev*.* if the normal places fail */
276 struct dirent *entry;
282 while ((entry = readdir(dir)) != NULL) {
283 if (_is_usbdev_entry(entry, NULL, NULL)) {
284 /* found one; that's enough */
295 usbi_dbg("found usbfs at %s", ret);
300 /* the monotonic clock is not usable on all systems (e.g. embedded ones often
301 * seem to lack it). fall back to REALTIME if we have to. */
302 static clockid_t find_monotonic_clock(void)
304 #ifdef CLOCK_MONOTONIC
308 /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
309 * because it's not available through timerfd */
310 r = clock_gettime(CLOCK_MONOTONIC, &ts);
312 return CLOCK_MONOTONIC;
313 usbi_dbg("monotonic clock doesn't work, errno %d", errno);
316 return CLOCK_REALTIME;
319 static int kernel_version_ge(int major, int minor, int sublevel)
322 int atoms, kmajor, kminor, ksublevel;
326 atoms = sscanf(uts.release, "%d.%d.%d", &kmajor, &kminor, &ksublevel);
335 /* kmajor == major */
337 return 0 == minor && 0 == sublevel;
343 /* kminor == minor */
345 return 0 == sublevel;
347 return ksublevel >= sublevel;
350 static int op_init(struct libusb_context *ctx)
355 usbfs_path = find_usbfs_path();
357 usbi_err(ctx, "could not find usbfs");
358 return LIBUSB_ERROR_OTHER;
361 if (monotonic_clkid == -1)
362 monotonic_clkid = find_monotonic_clock();
364 if (supports_flag_bulk_continuation == -1) {
365 /* bulk continuation URB flag available from Linux 2.6.32 */
366 supports_flag_bulk_continuation = kernel_version_ge(2,6,32);
367 if (supports_flag_bulk_continuation == -1) {
368 usbi_err(ctx, "error checking for bulk continuation support");
369 return LIBUSB_ERROR_OTHER;
373 if (supports_flag_bulk_continuation)
374 usbi_dbg("bulk continuation flag supported");
376 if (-1 == supports_flag_zero_packet) {
377 /* zero length packet URB flag fixed since Linux 2.6.31 */
378 supports_flag_zero_packet = kernel_version_ge(2,6,31);
379 if (-1 == supports_flag_zero_packet) {
380 usbi_err(ctx, "error checking for zero length packet support");
381 return LIBUSB_ERROR_OTHER;
385 if (supports_flag_zero_packet)
386 usbi_dbg("zero length packet flag supported");
388 if (-1 == sysfs_has_descriptors) {
389 /* sysfs descriptors has all descriptors since Linux 2.6.26 */
390 sysfs_has_descriptors = kernel_version_ge(2,6,26);
391 if (-1 == sysfs_has_descriptors) {
392 usbi_err(ctx, "error checking for sysfs descriptors");
393 return LIBUSB_ERROR_OTHER;
397 if (-1 == sysfs_can_relate_devices) {
398 /* sysfs has busnum since Linux 2.6.22 */
399 sysfs_can_relate_devices = kernel_version_ge(2,6,22);
400 if (-1 == sysfs_can_relate_devices) {
401 usbi_err(ctx, "error checking for sysfs busnum");
402 return LIBUSB_ERROR_OTHER;
406 if (sysfs_can_relate_devices || sysfs_has_descriptors) {
407 r = stat(SYSFS_DEVICE_PATH, &statbuf);
408 if (r != 0 || !S_ISDIR(statbuf.st_mode)) {
409 usbi_warn(ctx, "sysfs not mounted");
410 sysfs_can_relate_devices = 0;
411 sysfs_has_descriptors = 0;
415 if (sysfs_can_relate_devices)
416 usbi_dbg("sysfs can relate devices");
418 if (sysfs_has_descriptors)
419 usbi_dbg("sysfs has complete descriptors");
421 usbi_mutex_static_lock(&hotplug_lock);
423 if (init_count == 0) {
424 /* start up hotplug event handler */
425 r = linux_start_event_monitor();
427 if (r == LIBUSB_SUCCESS) {
428 r = linux_scan_devices(ctx);
429 if (r == LIBUSB_SUCCESS)
431 else if (init_count == 0)
432 linux_stop_event_monitor();
434 usbi_err(ctx, "error starting hotplug event monitor");
435 usbi_mutex_static_unlock(&hotplug_lock);
440 static void op_exit(void)
442 usbi_mutex_static_lock(&hotplug_lock);
443 assert(init_count != 0);
445 /* tear down event handler */
446 (void)linux_stop_event_monitor();
448 usbi_mutex_static_unlock(&hotplug_lock);
451 static int linux_start_event_monitor(void)
453 #if defined(USE_UDEV)
454 return linux_udev_start_event_monitor();
456 return linux_netlink_start_event_monitor();
460 static int linux_stop_event_monitor(void)
462 #if defined(USE_UDEV)
463 return linux_udev_stop_event_monitor();
465 return linux_netlink_stop_event_monitor();
469 static int linux_scan_devices(struct libusb_context *ctx)
471 #if defined(USE_UDEV)
472 return linux_udev_scan_devices(ctx);
474 return linux_default_scan_devices(ctx);
478 static int _open_sysfs_attr(struct libusb_device *dev, const char *attr)
480 struct linux_device_priv *priv = _device_priv(dev);
481 char filename[PATH_MAX];
484 snprintf(filename, PATH_MAX, "%s/%s/%s",
485 SYSFS_DEVICE_PATH, priv->sysfs_dir, attr);
486 fd = open(filename, O_RDONLY);
488 usbi_err(DEVICE_CTX(dev),
489 "open %s failed ret=%d errno=%d", filename, fd, errno);
490 return LIBUSB_ERROR_IO;
496 /* Note only suitable for attributes which always read >= 0, < 0 is error */
497 static int __read_sysfs_attr(struct libusb_context *ctx,
498 const char *devname, const char *attr)
500 char filename[PATH_MAX];
504 snprintf(filename, PATH_MAX, "%s/%s/%s", SYSFS_DEVICE_PATH,
506 f = fopen(filename, "r");
508 if (errno == ENOENT) {
509 /* File doesn't exist. Assume the device has been
510 disconnected (see trac ticket #70). */
511 return LIBUSB_ERROR_NO_DEVICE;
513 usbi_err(ctx, "open %s failed errno=%d", filename, errno);
514 return LIBUSB_ERROR_IO;
517 r = fscanf(f, "%d", &value);
520 usbi_err(ctx, "fscanf %s returned %d, errno=%d", attr, r, errno);
521 return LIBUSB_ERROR_NO_DEVICE; /* For unplug race (trac #70) */
524 usbi_err(ctx, "%s contains a negative value", filename);
525 return LIBUSB_ERROR_IO;
531 static int op_get_device_descriptor(struct libusb_device *dev,
532 unsigned char *buffer, int *host_endian)
534 struct linux_device_priv *priv = _device_priv(dev);
536 *host_endian = sysfs_has_descriptors ? 0 : 1;
537 memcpy(buffer, priv->descriptors, DEVICE_DESC_LENGTH);
542 /* read the bConfigurationValue for a device */
543 static int sysfs_get_active_config(struct libusb_device *dev, int *config)
546 char tmp[4] = {0, 0, 0, 0};
551 fd = _open_sysfs_attr(dev, "bConfigurationValue");
555 r = read(fd, tmp, sizeof(tmp));
558 usbi_err(DEVICE_CTX(dev),
559 "read bConfigurationValue failed ret=%d errno=%d", r, errno);
560 return LIBUSB_ERROR_IO;
562 usbi_dbg("device unconfigured");
567 if (tmp[sizeof(tmp) - 1] != 0) {
568 usbi_err(DEVICE_CTX(dev), "not null-terminated?");
569 return LIBUSB_ERROR_IO;
570 } else if (tmp[0] == 0) {
571 usbi_err(DEVICE_CTX(dev), "no configuration value?");
572 return LIBUSB_ERROR_IO;
575 num = strtol(tmp, &endptr, 10);
577 usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp);
578 return LIBUSB_ERROR_IO;
585 int linux_get_device_address (struct libusb_context *ctx, int detached,
586 uint8_t *busnum, uint8_t *devaddr,const char *dev_node,
587 const char *sys_name)
589 usbi_dbg("getting address for device: %s detached: %d", sys_name, detached);
590 /* can't use sysfs to read the bus and device number if the
591 * device has been detached */
592 if (!sysfs_can_relate_devices || detached || NULL == sys_name) {
593 if (NULL == dev_node) {
594 return LIBUSB_ERROR_OTHER;
597 /* will this work with all supported kernel versions? */
598 if (!strncmp(dev_node, "/dev/bus/usb", 12)) {
599 sscanf (dev_node, "/dev/bus/usb/%hhd/%hhd", busnum, devaddr);
600 } else if (!strncmp(dev_node, "/proc/bus/usb", 13)) {
601 sscanf (dev_node, "/proc/bus/usb/%hhd/%hhd", busnum, devaddr);
604 return LIBUSB_SUCCESS;
607 usbi_dbg("scan %s", sys_name);
609 *busnum = __read_sysfs_attr(ctx, sys_name, "busnum");
613 *devaddr = __read_sysfs_attr(ctx, sys_name, "devnum");
617 usbi_dbg("bus=%d dev=%d", *busnum, *devaddr);
618 if (*busnum > 255 || *devaddr > 255)
619 return LIBUSB_ERROR_INVALID_PARAM;
621 return LIBUSB_SUCCESS;
624 /* Return offset to next config */
625 static int seek_to_next_config(struct libusb_context *ctx,
626 unsigned char *buffer, int size)
628 struct libusb_config_descriptor config;
631 return LIBUSB_ERROR_NOT_FOUND;
633 if (size < LIBUSB_DT_CONFIG_SIZE) {
634 usbi_err(ctx, "short descriptor read %d/%d",
635 size, LIBUSB_DT_CONFIG_SIZE);
636 return LIBUSB_ERROR_IO;
639 usbi_parse_descriptor(buffer, "bbwbbbbb", &config, 0);
641 if (config.wTotalLength < LIBUSB_DT_CONFIG_SIZE) {
642 usbi_err(ctx, "invalid wTotalLength %d", config.wTotalLength);
643 return LIBUSB_ERROR_IO;
644 } else if (config.wTotalLength > size) {
645 usbi_warn(ctx, "short descriptor read %d/%d",
646 size, config.wTotalLength);
649 return config.wTotalLength;
652 static int get_config_descriptor_by_value(struct libusb_device *dev,
653 unsigned char **buffer, uint8_t value)
655 struct libusb_context *ctx = DEVICE_CTX(dev);
656 struct linux_device_priv *priv = _device_priv(dev);
657 unsigned char *descriptors = priv->descriptors;
658 int size = priv->descriptors_len;
659 struct libusb_config_descriptor *config;
663 /* Skip device header */
664 descriptors += DEVICE_DESC_LENGTH;
665 size -= DEVICE_DESC_LENGTH;
667 /* Seek till the config is found, or till "EOF" */
669 int next = seek_to_next_config(ctx, descriptors, size);
672 config = (struct libusb_config_descriptor *)descriptors;
673 if (config->bConfigurationValue == value) {
674 *buffer = descriptors;
682 static int op_get_active_config_descriptor(struct libusb_device *dev,
683 unsigned char *buffer, size_t len, int *host_endian)
686 unsigned char *config_desc;
688 /* Unlike the device desc. config descs. are always in raw format */
691 if (sysfs_can_relate_devices) {
692 r = sysfs_get_active_config(dev, &config);
696 /* Use cached bConfigurationValue */
697 struct linux_device_priv *priv = _device_priv(dev);
698 config = priv->active_config;
701 return LIBUSB_ERROR_NOT_FOUND;
703 r = get_config_descriptor_by_value(dev, &config_desc, config);
708 memcpy(buffer, config_desc, len);
712 static int op_get_config_descriptor(struct libusb_device *dev,
713 uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
715 struct linux_device_priv *priv = _device_priv(dev);
716 unsigned char *descriptors = priv->descriptors;
717 int i, r, size = priv->descriptors_len;
719 /* Unlike the device desc. config descs. are always in raw format */
722 /* Skip device header */
723 descriptors += DEVICE_DESC_LENGTH;
724 size -= DEVICE_DESC_LENGTH;
726 /* Seek till the config is found, or till "EOF" */
728 r = seek_to_next_config(DEVICE_CTX(dev), descriptors, size);
731 if (i == config_index)
738 memcpy(buffer, descriptors, len);
742 /* send a control message to retrieve active configuration */
743 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
745 unsigned char active_config = 0;
748 struct usbfs_ctrltransfer ctrl = {
749 .bmRequestType = LIBUSB_ENDPOINT_IN,
750 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
755 .data = &active_config
758 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
761 return LIBUSB_ERROR_NO_DEVICE;
763 /* we hit this error path frequently with buggy devices :( */
764 usbi_warn(DEVICE_CTX(dev),
765 "get_configuration failed ret=%d errno=%d", r, errno);
766 return LIBUSB_ERROR_IO;
769 return active_config;
772 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
773 uint8_t devaddr, const char *sysfs_dir)
775 struct linux_device_priv *priv = _device_priv(dev);
776 struct libusb_context *ctx = DEVICE_CTX(dev);
777 int descriptors_size = 512; /* Begin with a 1024 byte alloc */
781 dev->bus_number = busnum;
782 dev->device_address = devaddr;
785 priv->sysfs_dir = malloc(strlen(sysfs_dir) + 1);
786 if (!priv->sysfs_dir)
787 return LIBUSB_ERROR_NO_MEM;
788 strcpy(priv->sysfs_dir, sysfs_dir);
790 /* Note speed can contain 1.5, in this case __read_sysfs_attr
791 will stop parsing at the '.' and return 1 */
792 speed = __read_sysfs_attr(DEVICE_CTX(dev), sysfs_dir, "speed");
795 case 1: dev->speed = LIBUSB_SPEED_LOW; break;
796 case 12: dev->speed = LIBUSB_SPEED_FULL; break;
797 case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
798 case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
800 usbi_warn(DEVICE_CTX(dev), "Unknown device speed: %d Mbps", speed);
805 /* cache descriptors in memory */
806 if (sysfs_has_descriptors)
807 fd = _open_sysfs_attr(dev, "descriptors");
809 fd = _get_usbfs_fd(dev, O_RDONLY, 0);
814 descriptors_size *= 2;
815 priv->descriptors = usbi_reallocf(priv->descriptors,
817 if (!priv->descriptors) {
819 return LIBUSB_ERROR_NO_MEM;
821 /* usbfs has holes in the file */
822 if (!sysfs_has_descriptors) {
823 memset(priv->descriptors + priv->descriptors_len,
824 0, descriptors_size - priv->descriptors_len);
826 r = read(fd, priv->descriptors + priv->descriptors_len,
827 descriptors_size - priv->descriptors_len);
829 usbi_err(ctx, "read descriptor failed ret=%d errno=%d",
832 return LIBUSB_ERROR_IO;
834 priv->descriptors_len += r;
835 } while (priv->descriptors_len == descriptors_size);
839 if (priv->descriptors_len < DEVICE_DESC_LENGTH) {
840 usbi_err(ctx, "short descriptor read (%d)",
841 priv->descriptors_len);
842 return LIBUSB_ERROR_IO;
845 if (sysfs_can_relate_devices)
846 return LIBUSB_SUCCESS;
848 /* cache active config */
849 fd = _get_usbfs_fd(dev, O_RDWR, 1);
851 /* cannot send a control message to determine the active
852 * config. just assume the first one is active. */
853 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
854 "active configuration descriptor");
855 if (priv->descriptors_len >=
856 (DEVICE_DESC_LENGTH + LIBUSB_DT_CONFIG_SIZE)) {
857 struct libusb_config_descriptor config;
858 usbi_parse_descriptor(
859 priv->descriptors + DEVICE_DESC_LENGTH,
860 "bbwbbbbb", &config, 0);
861 priv->active_config = config.bConfigurationValue;
863 priv->active_config = -1; /* No config dt */
865 return LIBUSB_SUCCESS;
868 r = usbfs_get_active_config(dev, fd);
870 priv->active_config = r;
873 /* some buggy devices have a configuration 0, but we're
874 * reaching into the corner of a corner case here, so let's
875 * not support buggy devices in these circumstances.
876 * stick to the specs: a configuration value of 0 means
878 usbi_dbg("active cfg 0? assuming unconfigured device");
879 priv->active_config = -1;
881 } else if (r == LIBUSB_ERROR_IO) {
882 /* buggy devices sometimes fail to report their active config.
883 * assume unconfigured and continue the probing */
884 usbi_warn(ctx, "couldn't query active configuration, assuming"
886 priv->active_config = -1;
888 } /* else r < 0, just return the error code */
894 static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir)
896 struct libusb_context *ctx = DEVICE_CTX(dev);
897 struct libusb_device *it;
898 char *parent_sysfs_dir, *tmp;
899 int ret, add_parent = 1;
901 /* XXX -- can we figure out the topology when using usbfs? */
902 if (NULL == sysfs_dir || 0 == strncmp(sysfs_dir, "usb", 3)) {
903 /* either using usbfs or finding the parent of a root hub */
904 return LIBUSB_SUCCESS;
907 parent_sysfs_dir = strdup(sysfs_dir);
908 if (NULL != (tmp = strrchr(parent_sysfs_dir, '.')) ||
909 NULL != (tmp = strrchr(parent_sysfs_dir, '-'))) {
910 dev->port_number = atoi(tmp + 1);
913 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
915 free (parent_sysfs_dir);
916 return LIBUSB_SUCCESS;
919 /* is the parent a root hub? */
920 if (NULL == strchr(parent_sysfs_dir, '-')) {
921 tmp = parent_sysfs_dir;
922 ret = asprintf (&parent_sysfs_dir, "usb%s", tmp);
925 return LIBUSB_ERROR_NO_MEM;
930 /* find the parent in the context */
931 usbi_mutex_lock(&ctx->usb_devs_lock);
932 list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device) {
933 struct linux_device_priv *priv = _device_priv(it);
934 if (0 == strcmp (priv->sysfs_dir, parent_sysfs_dir)) {
935 dev->parent_dev = libusb_ref_device(it);
939 usbi_mutex_unlock(&ctx->usb_devs_lock);
941 if (!dev->parent_dev && add_parent) {
942 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
944 sysfs_scan_device(ctx, parent_sysfs_dir);
949 usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev, sysfs_dir,
950 dev->parent_dev, parent_sysfs_dir, dev->port_number);
952 free (parent_sysfs_dir);
954 return LIBUSB_SUCCESS;
957 int linux_enumerate_device(struct libusb_context *ctx,
958 uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
960 unsigned long session_id;
961 struct libusb_device *dev;
964 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
965 * will be reused. instead we should add a simple sysfs attribute with
967 session_id = busnum << 8 | devaddr;
968 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
971 if (usbi_get_device_by_session_id(ctx, session_id)) {
972 /* device already exists in the context */
973 usbi_dbg("session_id %ld already exists", session_id);
974 return LIBUSB_SUCCESS;
977 usbi_dbg("allocating new device for %d/%d (session %ld)",
978 busnum, devaddr, session_id);
979 dev = usbi_alloc_device(ctx, session_id);
981 return LIBUSB_ERROR_NO_MEM;
983 r = initialize_device(dev, busnum, devaddr, sysfs_dir);
986 r = usbi_sanitize_device(dev);
990 r = linux_get_parent_info(dev, sysfs_dir);
995 libusb_unref_device(dev);
997 usbi_connect_device(dev);
1002 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1004 struct libusb_context *ctx;
1006 usbi_mutex_static_lock(&active_contexts_lock);
1007 usbi_mutex_static_lock(&hotplug_lock);
1008 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1009 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1011 usbi_mutex_static_unlock(&hotplug_lock);
1012 usbi_mutex_static_unlock(&active_contexts_lock);
1015 void linux_hotplug_disconnected(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1017 struct libusb_context *ctx;
1018 struct libusb_device *dev;
1019 unsigned long session_id = busnum << 8 | devaddr;
1021 usbi_mutex_static_lock(&active_contexts_lock);
1022 usbi_mutex_static_lock(&hotplug_lock);
1023 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1024 dev = usbi_get_device_by_session_id (ctx, session_id);
1026 usbi_disconnect_device (dev);
1028 usbi_dbg("device not found for session %x", session_id);
1031 usbi_mutex_static_unlock(&hotplug_lock);
1032 usbi_mutex_static_unlock(&active_contexts_lock);
1035 #if !defined(USE_UDEV)
1036 /* open a bus directory and adds all discovered devices to the context */
1037 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1040 char dirpath[PATH_MAX];
1041 struct dirent *entry;
1042 int r = LIBUSB_ERROR_IO;
1044 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1045 usbi_dbg("%s", dirpath);
1046 dir = opendir(dirpath);
1048 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1049 /* FIXME: should handle valid race conditions like hub unplugged
1050 * during directory iteration - this is not an error */
1054 while ((entry = readdir(dir))) {
1057 if (entry->d_name[0] == '.')
1060 devaddr = atoi(entry->d_name);
1062 usbi_dbg("unknown dir entry %s", entry->d_name);
1066 if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1067 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1078 static int usbfs_get_device_list(struct libusb_context *ctx)
1080 struct dirent *entry;
1081 DIR *buses = opendir(usbfs_path);
1085 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1086 return LIBUSB_ERROR_IO;
1089 while ((entry = readdir(buses))) {
1092 if (entry->d_name[0] == '.')
1097 if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1100 r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
1102 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1106 busnum = atoi(entry->d_name);
1108 usbi_dbg("unknown dir entry %s", entry->d_name);
1112 r = usbfs_scan_busdir(ctx, busnum);
1124 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
1126 uint8_t busnum, devaddr;
1129 ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname);
1130 if (LIBUSB_SUCCESS != ret) {
1134 return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff,
1138 #if !defined(USE_UDEV)
1139 static int sysfs_get_device_list(struct libusb_context *ctx)
1141 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1142 struct dirent *entry;
1143 int r = LIBUSB_ERROR_IO;
1146 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1150 while ((entry = readdir(devices))) {
1151 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1152 || strchr(entry->d_name, ':'))
1155 if (sysfs_scan_device(ctx, entry->d_name)) {
1156 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1167 static int linux_default_scan_devices (struct libusb_context *ctx)
1169 /* we can retrieve device list and descriptors from sysfs or usbfs.
1170 * sysfs is preferable, because if we use usbfs we end up resuming
1171 * any autosuspended USB devices. however, sysfs is not available
1172 * everywhere, so we need a usbfs fallback too.
1174 * as described in the "sysfs vs usbfs" comment at the top of this
1175 * file, sometimes we have sysfs but not enough information to
1176 * relate sysfs devices to usbfs nodes. op_init() determines the
1177 * adequacy of sysfs and sets sysfs_can_relate_devices.
1179 if (sysfs_can_relate_devices != 0)
1180 return sysfs_get_device_list(ctx);
1182 return usbfs_get_device_list(ctx);
1186 static int op_open(struct libusb_device_handle *handle)
1188 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1191 hpriv->fd = _get_usbfs_fd(handle->dev, O_RDWR, 0);
1195 r = ioctl(hpriv->fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1197 if (errno == ENOTTY)
1198 usbi_dbg("getcap not available");
1200 usbi_err(HANDLE_CTX(handle), "getcap failed (%d)", errno);
1202 if (supports_flag_zero_packet)
1203 hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1204 if (supports_flag_bulk_continuation)
1205 hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1208 return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1211 static void op_close(struct libusb_device_handle *dev_handle)
1213 int fd = _device_handle_priv(dev_handle)->fd;
1214 usbi_remove_pollfd(HANDLE_CTX(dev_handle), fd);
1218 static int op_get_configuration(struct libusb_device_handle *handle,
1223 if (sysfs_can_relate_devices) {
1224 r = sysfs_get_active_config(handle->dev, config);
1226 r = usbfs_get_active_config(handle->dev,
1227 _device_handle_priv(handle)->fd);
1232 if (*config == -1) {
1233 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1240 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1242 struct linux_device_priv *priv = _device_priv(handle->dev);
1243 int fd = _device_handle_priv(handle)->fd;
1244 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1246 if (errno == EINVAL)
1247 return LIBUSB_ERROR_NOT_FOUND;
1248 else if (errno == EBUSY)
1249 return LIBUSB_ERROR_BUSY;
1250 else if (errno == ENODEV)
1251 return LIBUSB_ERROR_NO_DEVICE;
1253 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1254 return LIBUSB_ERROR_OTHER;
1257 /* update our cached active config descriptor */
1258 priv->active_config = config;
1260 return LIBUSB_SUCCESS;
1263 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1265 int fd = _device_handle_priv(handle)->fd;
1266 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1268 if (errno == ENOENT)
1269 return LIBUSB_ERROR_NOT_FOUND;
1270 else if (errno == EBUSY)
1271 return LIBUSB_ERROR_BUSY;
1272 else if (errno == ENODEV)
1273 return LIBUSB_ERROR_NO_DEVICE;
1275 usbi_err(HANDLE_CTX(handle),
1276 "claim interface failed, error %d errno %d", r, errno);
1277 return LIBUSB_ERROR_OTHER;
1282 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1284 int fd = _device_handle_priv(handle)->fd;
1285 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1287 if (errno == ENODEV)
1288 return LIBUSB_ERROR_NO_DEVICE;
1290 usbi_err(HANDLE_CTX(handle),
1291 "release interface failed, error %d errno %d", r, errno);
1292 return LIBUSB_ERROR_OTHER;
1297 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1300 int fd = _device_handle_priv(handle)->fd;
1301 struct usbfs_setinterface setintf;
1304 setintf.interface = iface;
1305 setintf.altsetting = altsetting;
1306 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1308 if (errno == EINVAL)
1309 return LIBUSB_ERROR_NOT_FOUND;
1310 else if (errno == ENODEV)
1311 return LIBUSB_ERROR_NO_DEVICE;
1313 usbi_err(HANDLE_CTX(handle),
1314 "setintf failed error %d errno %d", r, errno);
1315 return LIBUSB_ERROR_OTHER;
1321 static int op_clear_halt(struct libusb_device_handle *handle,
1322 unsigned char endpoint)
1324 int fd = _device_handle_priv(handle)->fd;
1325 unsigned int _endpoint = endpoint;
1326 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1328 if (errno == ENOENT)
1329 return LIBUSB_ERROR_NOT_FOUND;
1330 else if (errno == ENODEV)
1331 return LIBUSB_ERROR_NO_DEVICE;
1333 usbi_err(HANDLE_CTX(handle),
1334 "clear_halt failed error %d errno %d", r, errno);
1335 return LIBUSB_ERROR_OTHER;
1341 static int op_reset_device(struct libusb_device_handle *handle)
1343 int fd = _device_handle_priv(handle)->fd;
1346 /* Doing a device reset will cause the usbfs driver to get unbound
1347 from any interfaces it is bound to. By voluntarily unbinding
1348 the usbfs driver ourself, we stop the kernel from rebinding
1349 the interface after reset (which would end up with the interface
1350 getting bound to the in kernel driver if any). */
1351 for (i = 0; i < USB_MAXINTERFACES; i++) {
1352 if (handle->claimed_interfaces & (1L << i)) {
1353 op_release_interface(handle, i);
1357 usbi_mutex_lock(&handle->lock);
1358 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1360 if (errno == ENODEV) {
1361 ret = LIBUSB_ERROR_NOT_FOUND;
1365 usbi_err(HANDLE_CTX(handle),
1366 "reset failed error %d errno %d", r, errno);
1367 ret = LIBUSB_ERROR_OTHER;
1371 /* And re-claim any interfaces which were claimed before the reset */
1372 for (i = 0; i < USB_MAXINTERFACES; i++) {
1373 if (handle->claimed_interfaces & (1L << i)) {
1374 r = op_claim_interface(handle, i);
1376 usbi_warn(HANDLE_CTX(handle),
1377 "failed to re-claim interface %d after reset", i);
1378 handle->claimed_interfaces &= ~(1L << i);
1383 usbi_mutex_unlock(&handle->lock);
1387 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1390 int fd = _device_handle_priv(handle)->fd;
1391 struct usbfs_getdriver getdrv;
1394 getdrv.interface = interface;
1395 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1397 if (errno == ENODATA)
1399 else if (errno == ENODEV)
1400 return LIBUSB_ERROR_NO_DEVICE;
1402 usbi_err(HANDLE_CTX(handle),
1403 "get driver failed error %d errno %d", r, errno);
1404 return LIBUSB_ERROR_OTHER;
1410 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1413 int fd = _device_handle_priv(handle)->fd;
1414 struct usbfs_ioctl command;
1415 struct usbfs_getdriver getdrv;
1418 command.ifno = interface;
1419 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1420 command.data = NULL;
1422 getdrv.interface = interface;
1423 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1424 if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1425 return LIBUSB_ERROR_NOT_FOUND;
1427 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1429 if (errno == ENODATA)
1430 return LIBUSB_ERROR_NOT_FOUND;
1431 else if (errno == EINVAL)
1432 return LIBUSB_ERROR_INVALID_PARAM;
1433 else if (errno == ENODEV)
1434 return LIBUSB_ERROR_NO_DEVICE;
1436 usbi_err(HANDLE_CTX(handle),
1437 "detach failed error %d errno %d", r, errno);
1438 return LIBUSB_ERROR_OTHER;
1444 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1447 int fd = _device_handle_priv(handle)->fd;
1448 struct usbfs_ioctl command;
1451 command.ifno = interface;
1452 command.ioctl_code = IOCTL_USBFS_CONNECT;
1453 command.data = NULL;
1455 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1457 if (errno == ENODATA)
1458 return LIBUSB_ERROR_NOT_FOUND;
1459 else if (errno == EINVAL)
1460 return LIBUSB_ERROR_INVALID_PARAM;
1461 else if (errno == ENODEV)
1462 return LIBUSB_ERROR_NO_DEVICE;
1463 else if (errno == EBUSY)
1464 return LIBUSB_ERROR_BUSY;
1466 usbi_err(HANDLE_CTX(handle),
1467 "attach failed error %d errno %d", r, errno);
1468 return LIBUSB_ERROR_OTHER;
1469 } else if (r == 0) {
1470 return LIBUSB_ERROR_NOT_FOUND;
1476 static void op_destroy_device(struct libusb_device *dev)
1478 struct linux_device_priv *priv = _device_priv(dev);
1479 if (priv->descriptors)
1480 free(priv->descriptors);
1481 if (priv->sysfs_dir)
1482 free(priv->sysfs_dir);
1485 /* URBs are discarded in reverse order of submission to avoid races. */
1486 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1488 struct libusb_transfer *transfer =
1489 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1490 struct linux_transfer_priv *tpriv =
1491 usbi_transfer_get_os_priv(itransfer);
1492 struct linux_device_handle_priv *dpriv =
1493 _device_handle_priv(transfer->dev_handle);
1495 struct usbfs_urb *urb;
1497 for (i = last_plus_one - 1; i >= first; i--) {
1498 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
1499 urb = tpriv->iso_urbs[i];
1501 urb = &tpriv->urbs[i];
1503 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
1506 if (EINVAL == errno) {
1507 usbi_dbg("URB not found --> assuming ready to be reaped");
1508 if (i == (last_plus_one - 1))
1509 ret = LIBUSB_ERROR_NOT_FOUND;
1510 } else if (ENODEV == errno) {
1511 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1512 ret = LIBUSB_ERROR_NO_DEVICE;
1514 usbi_warn(TRANSFER_CTX(transfer),
1515 "unrecognised discard errno %d", errno);
1516 ret = LIBUSB_ERROR_OTHER;
1522 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1525 for (i = 0; i < tpriv->num_urbs; i++) {
1526 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1532 free(tpriv->iso_urbs);
1533 tpriv->iso_urbs = NULL;
1536 static int submit_bulk_transfer(struct usbi_transfer *itransfer,
1537 unsigned char urb_type)
1539 struct libusb_transfer *transfer =
1540 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1541 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1542 struct linux_device_handle_priv *dpriv =
1543 _device_handle_priv(transfer->dev_handle);
1544 struct usbfs_urb *urbs;
1545 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1546 == LIBUSB_ENDPOINT_OUT;
1547 int bulk_buffer_len, use_bulk_continuation;
1553 return LIBUSB_ERROR_BUSY;
1555 if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1556 !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
1557 return LIBUSB_ERROR_NOT_SUPPORTED;
1560 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1561 * around this by splitting large transfers into 16k blocks, and then
1562 * submit all urbs at once. it would be simpler to submit one urb at
1563 * a time, but there is a big performance gain doing it this way.
1565 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1566 * using arbritary large transfers can still be a bad idea though, as
1567 * the kernel needs to allocate physical contiguous memory for this,
1568 * which may fail for large buffers.
1570 * The kernel solves this problem by splitting the transfer into
1571 * blocks itself when the host-controller is scatter-gather capable
1572 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1574 * Last, there is the issue of short-transfers when splitting, for
1575 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1576 * is needed, but this is not always available.
1578 if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1579 /* Good! Just submit everything in one go */
1580 bulk_buffer_len = transfer->length ? transfer->length : 1;
1581 use_bulk_continuation = 0;
1582 } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1583 /* Split the transfers and use bulk-continuation to
1584 avoid issues with short-transfers */
1585 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1586 use_bulk_continuation = 1;
1587 } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1588 /* Don't split, assume the kernel can alloc the buffer
1589 (otherwise the submit will fail with -ENOMEM) */
1590 bulk_buffer_len = transfer->length ? transfer->length : 1;
1591 use_bulk_continuation = 0;
1593 /* Bad, splitting without bulk-continuation, short transfers
1594 which end before the last urb will not work reliable! */
1595 /* Note we don't warn here as this is "normal" on kernels <
1596 2.6.32 and not a problem for most applications */
1597 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1598 use_bulk_continuation = 0;
1601 int num_urbs = transfer->length / bulk_buffer_len;
1602 int last_urb_partial = 0;
1604 if (transfer->length == 0) {
1606 } else if ((transfer->length % bulk_buffer_len) > 0) {
1607 last_urb_partial = 1;
1610 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
1612 alloc_size = num_urbs * sizeof(struct usbfs_urb);
1613 urbs = calloc(1, alloc_size);
1615 return LIBUSB_ERROR_NO_MEM;
1617 tpriv->num_urbs = num_urbs;
1618 tpriv->num_retired = 0;
1619 tpriv->reap_action = NORMAL;
1620 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1622 for (i = 0; i < num_urbs; i++) {
1623 struct usbfs_urb *urb = &urbs[i];
1624 urb->usercontext = itransfer;
1625 urb->type = urb_type;
1626 urb->endpoint = transfer->endpoint;
1627 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
1628 /* don't set the short not ok flag for the last URB */
1629 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
1630 urb->flags = USBFS_URB_SHORT_NOT_OK;
1631 if (i == num_urbs - 1 && last_urb_partial)
1632 urb->buffer_length = transfer->length % bulk_buffer_len;
1633 else if (transfer->length == 0)
1634 urb->buffer_length = 0;
1636 urb->buffer_length = bulk_buffer_len;
1638 if (i > 0 && use_bulk_continuation)
1639 urb->flags |= USBFS_URB_BULK_CONTINUATION;
1641 /* we have already checked that the flag is supported */
1642 if (is_out && i == num_urbs - 1 &&
1643 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
1644 urb->flags |= USBFS_URB_ZERO_PACKET;
1646 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1648 if (errno == ENODEV) {
1649 r = LIBUSB_ERROR_NO_DEVICE;
1651 usbi_err(TRANSFER_CTX(transfer),
1652 "submiturb failed error %d errno=%d", r, errno);
1653 r = LIBUSB_ERROR_IO;
1656 /* if the first URB submission fails, we can simply free up and
1657 * return failure immediately. */
1659 usbi_dbg("first URB failed, easy peasy");
1665 /* if it's not the first URB that failed, the situation is a bit
1666 * tricky. we may need to discard all previous URBs. there are
1668 * - discarding is asynchronous - discarded urbs will be reaped
1669 * later. the user must not have freed the transfer when the
1670 * discarded URBs are reaped, otherwise libusbx will be using
1672 * - the earlier URBs may have completed successfully and we do
1673 * not want to throw away any data.
1674 * - this URB failing may be no error; EREMOTEIO means that
1675 * this transfer simply didn't need all the URBs we submitted
1676 * so, we report that the transfer was submitted successfully and
1677 * in case of error we discard all previous URBs. later when
1678 * the final reap completes we can report error to the user,
1679 * or success if an earlier URB was completed successfully.
1681 tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
1683 /* The URBs we haven't submitted yet we count as already
1685 tpriv->num_retired += num_urbs - i;
1687 /* If we completed short then don't try to discard. */
1688 if (COMPLETED_EARLY == tpriv->reap_action)
1691 discard_urbs(itransfer, 0, i);
1693 usbi_dbg("reporting successful submission but waiting for %d "
1694 "discards before reporting error", i);
1702 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1704 struct libusb_transfer *transfer =
1705 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1706 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1707 struct linux_device_handle_priv *dpriv =
1708 _device_handle_priv(transfer->dev_handle);
1709 struct usbfs_urb **urbs;
1711 int num_packets = transfer->num_iso_packets;
1713 int this_urb_len = 0;
1715 int packet_offset = 0;
1716 unsigned int packet_len;
1717 unsigned char *urb_buffer = transfer->buffer;
1719 if (tpriv->iso_urbs)
1720 return LIBUSB_ERROR_BUSY;
1722 /* usbfs places a 32kb limit on iso URBs. we divide up larger requests
1723 * into smaller units to meet such restriction, then fire off all the
1724 * units at once. it would be simpler if we just fired one unit at a time,
1725 * but there is a big performance gain through doing it this way.
1727 * Newer kernels lift the 32k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1728 * using arbritary large transfers is still be a bad idea though, as
1729 * the kernel needs to allocate physical contiguous memory for this,
1730 * which may fail for large buffers.
1733 /* calculate how many URBs we need */
1734 for (i = 0; i < num_packets; i++) {
1735 unsigned int space_remaining = MAX_ISO_BUFFER_LENGTH - this_urb_len;
1736 packet_len = transfer->iso_packet_desc[i].length;
1738 if (packet_len > space_remaining) {
1740 this_urb_len = packet_len;
1742 this_urb_len += packet_len;
1745 usbi_dbg("need %d 32k URBs for transfer", num_urbs);
1747 alloc_size = num_urbs * sizeof(*urbs);
1748 urbs = calloc(1, alloc_size);
1750 return LIBUSB_ERROR_NO_MEM;
1752 tpriv->iso_urbs = urbs;
1753 tpriv->num_urbs = num_urbs;
1754 tpriv->num_retired = 0;
1755 tpriv->reap_action = NORMAL;
1756 tpriv->iso_packet_offset = 0;
1758 /* allocate + initialize each URB with the correct number of packets */
1759 for (i = 0; i < num_urbs; i++) {
1760 struct usbfs_urb *urb;
1761 unsigned int space_remaining_in_urb = MAX_ISO_BUFFER_LENGTH;
1762 int urb_packet_offset = 0;
1763 unsigned char *urb_buffer_orig = urb_buffer;
1767 /* swallow up all the packets we can fit into this URB */
1768 while (packet_offset < transfer->num_iso_packets) {
1769 packet_len = transfer->iso_packet_desc[packet_offset].length;
1770 if (packet_len <= space_remaining_in_urb) {
1772 urb_packet_offset++;
1774 space_remaining_in_urb -= packet_len;
1775 urb_buffer += packet_len;
1777 /* it can't fit, save it for the next URB */
1782 alloc_size = sizeof(*urb)
1783 + (urb_packet_offset * sizeof(struct usbfs_iso_packet_desc));
1784 urb = calloc(1, alloc_size);
1786 free_iso_urbs(tpriv);
1787 return LIBUSB_ERROR_NO_MEM;
1791 /* populate packet lengths */
1792 for (j = 0, k = packet_offset - urb_packet_offset;
1793 k < packet_offset; k++, j++) {
1794 packet_len = transfer->iso_packet_desc[k].length;
1795 urb->iso_frame_desc[j].length = packet_len;
1798 urb->usercontext = itransfer;
1799 urb->type = USBFS_URB_TYPE_ISO;
1800 /* FIXME: interface for non-ASAP data? */
1801 urb->flags = USBFS_URB_ISO_ASAP;
1802 urb->endpoint = transfer->endpoint;
1803 urb->number_of_packets = urb_packet_offset;
1804 urb->buffer = urb_buffer_orig;
1808 for (i = 0; i < num_urbs; i++) {
1809 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
1811 if (errno == ENODEV) {
1812 r = LIBUSB_ERROR_NO_DEVICE;
1814 usbi_err(TRANSFER_CTX(transfer),
1815 "submiturb failed error %d errno=%d", r, errno);
1816 r = LIBUSB_ERROR_IO;
1819 /* if the first URB submission fails, we can simply free up and
1820 * return failure immediately. */
1822 usbi_dbg("first URB failed, easy peasy");
1823 free_iso_urbs(tpriv);
1827 /* if it's not the first URB that failed, the situation is a bit
1828 * tricky. we must discard all previous URBs. there are
1830 * - discarding is asynchronous - discarded urbs will be reaped
1831 * later. the user must not have freed the transfer when the
1832 * discarded URBs are reaped, otherwise libusbx will be using
1834 * - the earlier URBs may have completed successfully and we do
1835 * not want to throw away any data.
1836 * so, in this case we discard all the previous URBs BUT we report
1837 * that the transfer was submitted successfully. then later when
1838 * the final discard completes we can report error to the user.
1840 tpriv->reap_action = SUBMIT_FAILED;
1842 /* The URBs we haven't submitted yet we count as already
1844 tpriv->num_retired = num_urbs - i;
1845 discard_urbs(itransfer, 0, i);
1847 usbi_dbg("reporting successful submission but waiting for %d "
1848 "discards before reporting error", i);
1856 static int submit_control_transfer(struct usbi_transfer *itransfer)
1858 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1859 struct libusb_transfer *transfer =
1860 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1861 struct linux_device_handle_priv *dpriv =
1862 _device_handle_priv(transfer->dev_handle);
1863 struct usbfs_urb *urb;
1867 return LIBUSB_ERROR_BUSY;
1869 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
1870 return LIBUSB_ERROR_INVALID_PARAM;
1872 urb = calloc(1, sizeof(struct usbfs_urb));
1874 return LIBUSB_ERROR_NO_MEM;
1876 tpriv->num_urbs = 1;
1877 tpriv->reap_action = NORMAL;
1879 urb->usercontext = itransfer;
1880 urb->type = USBFS_URB_TYPE_CONTROL;
1881 urb->endpoint = transfer->endpoint;
1882 urb->buffer = transfer->buffer;
1883 urb->buffer_length = transfer->length;
1885 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1889 if (errno == ENODEV)
1890 return LIBUSB_ERROR_NO_DEVICE;
1892 usbi_err(TRANSFER_CTX(transfer),
1893 "submiturb failed error %d errno=%d", r, errno);
1894 return LIBUSB_ERROR_IO;
1899 static int op_submit_transfer(struct usbi_transfer *itransfer)
1901 struct libusb_transfer *transfer =
1902 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1904 switch (transfer->type) {
1905 case LIBUSB_TRANSFER_TYPE_CONTROL:
1906 return submit_control_transfer(itransfer);
1907 case LIBUSB_TRANSFER_TYPE_BULK:
1908 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_BULK);
1909 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1910 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_INTERRUPT);
1911 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1912 return submit_iso_transfer(itransfer);
1914 usbi_err(TRANSFER_CTX(transfer),
1915 "unknown endpoint type %d", transfer->type);
1916 return LIBUSB_ERROR_INVALID_PARAM;
1920 static int op_cancel_transfer(struct usbi_transfer *itransfer)
1922 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1923 struct libusb_transfer *transfer =
1924 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1926 switch (transfer->type) {
1927 case LIBUSB_TRANSFER_TYPE_BULK:
1928 if (tpriv->reap_action == ERROR)
1930 /* else, fall through */
1931 case LIBUSB_TRANSFER_TYPE_CONTROL:
1932 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1933 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1934 tpriv->reap_action = CANCELLED;
1937 usbi_err(TRANSFER_CTX(transfer),
1938 "unknown endpoint type %d", transfer->type);
1939 return LIBUSB_ERROR_INVALID_PARAM;
1943 return LIBUSB_ERROR_NOT_FOUND;
1945 return discard_urbs(itransfer, 0, tpriv->num_urbs);
1948 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
1950 struct libusb_transfer *transfer =
1951 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1952 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1954 /* urbs can be freed also in submit_transfer so lock mutex first */
1955 switch (transfer->type) {
1956 case LIBUSB_TRANSFER_TYPE_CONTROL:
1957 case LIBUSB_TRANSFER_TYPE_BULK:
1958 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1959 usbi_mutex_lock(&itransfer->lock);
1963 usbi_mutex_unlock(&itransfer->lock);
1965 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1966 usbi_mutex_lock(&itransfer->lock);
1967 if (tpriv->iso_urbs)
1968 free_iso_urbs(tpriv);
1969 usbi_mutex_unlock(&itransfer->lock);
1972 usbi_err(TRANSFER_CTX(transfer),
1973 "unknown endpoint type %d", transfer->type);
1977 static int handle_bulk_completion(struct usbi_transfer *itransfer,
1978 struct usbfs_urb *urb)
1980 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1981 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1982 int urb_idx = urb - tpriv->urbs;
1984 usbi_mutex_lock(&itransfer->lock);
1985 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
1986 urb_idx + 1, tpriv->num_urbs);
1988 tpriv->num_retired++;
1990 if (tpriv->reap_action != NORMAL) {
1991 /* cancelled, submit_fail, or completed early */
1992 usbi_dbg("abnormal reap: urb status %d", urb->status);
1994 /* even though we're in the process of cancelling, it's possible that
1995 * we may receive some data in these URBs that we don't want to lose.
1997 * 1. while the kernel is cancelling all the packets that make up an
1998 * URB, a few of them might complete. so we get back a successful
1999 * cancellation *and* some data.
2000 * 2. we receive a short URB which marks the early completion condition,
2001 * so we start cancelling the remaining URBs. however, we're too
2002 * slow and another URB completes (or at least completes partially).
2003 * (this can't happen since we always use BULK_CONTINUATION.)
2005 * When this happens, our objectives are not to lose any "surplus" data,
2006 * and also to stick it at the end of the previously-received data
2007 * (closing any holes), so that libusbx reports the total amount of
2008 * transferred data and presents it in a contiguous chunk.
2010 if (urb->actual_length > 0) {
2011 unsigned char *target = transfer->buffer + itransfer->transferred;
2012 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2013 if (urb->buffer != target) {
2014 usbi_dbg("moving surplus data from offset %d to offset %d",
2015 (unsigned char *) urb->buffer - transfer->buffer,
2016 target - transfer->buffer);
2017 memmove(target, urb->buffer, urb->actual_length);
2019 itransfer->transferred += urb->actual_length;
2022 if (tpriv->num_retired == tpriv->num_urbs) {
2023 usbi_dbg("abnormal reap: last URB handled, reporting");
2024 if (tpriv->reap_action != COMPLETED_EARLY &&
2025 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2026 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2032 itransfer->transferred += urb->actual_length;
2034 /* Many of these errors can occur on *any* urb of a multi-urb
2035 * transfer. When they do, we tear down the rest of the transfer.
2037 switch (urb->status) {
2040 case -EREMOTEIO: /* short transfer */
2042 case -ENOENT: /* cancelled */
2047 usbi_dbg("device removed");
2048 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2049 goto cancel_remaining;
2051 usbi_dbg("detected endpoint stall");
2052 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2053 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2054 goto cancel_remaining;
2056 /* overflow can only ever occur in the last urb */
2057 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2058 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2059 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2066 usbi_dbg("low level error %d", urb->status);
2067 tpriv->reap_action = ERROR;
2068 goto cancel_remaining;
2070 usbi_warn(ITRANSFER_CTX(itransfer),
2071 "unrecognised urb status %d", urb->status);
2072 tpriv->reap_action = ERROR;
2073 goto cancel_remaining;
2076 /* if we're the last urb or we got less data than requested then we're
2078 if (urb_idx == tpriv->num_urbs - 1) {
2079 usbi_dbg("last URB in transfer --> complete!");
2081 } else if (urb->actual_length < urb->buffer_length) {
2082 usbi_dbg("short transfer %d/%d --> complete!",
2083 urb->actual_length, urb->buffer_length);
2084 if (tpriv->reap_action == NORMAL)
2085 tpriv->reap_action = COMPLETED_EARLY;
2090 if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2091 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2093 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2096 /* cancel remaining urbs and wait for their completion before
2097 * reporting results */
2098 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2101 usbi_mutex_unlock(&itransfer->lock);
2107 usbi_mutex_unlock(&itransfer->lock);
2108 return CANCELLED == tpriv->reap_action ?
2109 usbi_handle_transfer_cancellation(itransfer) :
2110 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2113 static int handle_iso_completion(struct usbi_transfer *itransfer,
2114 struct usbfs_urb *urb)
2116 struct libusb_transfer *transfer =
2117 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2118 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2119 int num_urbs = tpriv->num_urbs;
2122 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2124 usbi_mutex_lock(&itransfer->lock);
2125 for (i = 0; i < num_urbs; i++) {
2126 if (urb == tpriv->iso_urbs[i]) {
2132 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2133 usbi_mutex_unlock(&itransfer->lock);
2134 return LIBUSB_ERROR_NOT_FOUND;
2137 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2140 /* copy isochronous results back in */
2142 for (i = 0; i < urb->number_of_packets; i++) {
2143 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2144 struct libusb_iso_packet_descriptor *lib_desc =
2145 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2146 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2147 switch (urb_desc->status) {
2150 case -ENOENT: /* cancelled */
2155 usbi_dbg("device removed");
2156 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2159 usbi_dbg("detected endpoint stall");
2160 lib_desc->status = LIBUSB_TRANSFER_STALL;
2163 usbi_dbg("overflow error");
2164 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2172 usbi_dbg("low-level USB error %d", urb_desc->status);
2173 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2176 usbi_warn(TRANSFER_CTX(transfer),
2177 "unrecognised urb status %d", urb_desc->status);
2178 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2181 lib_desc->actual_length = urb_desc->actual_length;
2184 tpriv->num_retired++;
2186 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2187 usbi_dbg("CANCEL: urb status %d", urb->status);
2189 if (tpriv->num_retired == num_urbs) {
2190 usbi_dbg("CANCEL: last URB handled, reporting");
2191 free_iso_urbs(tpriv);
2192 if (tpriv->reap_action == CANCELLED) {
2193 usbi_mutex_unlock(&itransfer->lock);
2194 return usbi_handle_transfer_cancellation(itransfer);
2196 usbi_mutex_unlock(&itransfer->lock);
2197 return usbi_handle_transfer_completion(itransfer,
2198 LIBUSB_TRANSFER_ERROR);
2204 switch (urb->status) {
2207 case -ENOENT: /* cancelled */
2211 usbi_dbg("device removed");
2212 status = LIBUSB_TRANSFER_NO_DEVICE;
2215 usbi_warn(TRANSFER_CTX(transfer),
2216 "unrecognised urb status %d", urb->status);
2217 status = LIBUSB_TRANSFER_ERROR;
2221 /* if we're the last urb then we're done */
2222 if (urb_idx == num_urbs) {
2223 usbi_dbg("last URB in transfer --> complete!");
2224 free_iso_urbs(tpriv);
2225 usbi_mutex_unlock(&itransfer->lock);
2226 return usbi_handle_transfer_completion(itransfer, status);
2230 usbi_mutex_unlock(&itransfer->lock);
2234 static int handle_control_completion(struct usbi_transfer *itransfer,
2235 struct usbfs_urb *urb)
2237 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2240 usbi_mutex_lock(&itransfer->lock);
2241 usbi_dbg("handling completion status %d", urb->status);
2243 itransfer->transferred += urb->actual_length;
2245 if (tpriv->reap_action == CANCELLED) {
2246 if (urb->status != 0 && urb->status != -ENOENT)
2247 usbi_warn(ITRANSFER_CTX(itransfer),
2248 "cancel: unrecognised urb status %d", urb->status);
2251 usbi_mutex_unlock(&itransfer->lock);
2252 return usbi_handle_transfer_cancellation(itransfer);
2255 switch (urb->status) {
2257 status = LIBUSB_TRANSFER_COMPLETED;
2259 case -ENOENT: /* cancelled */
2260 status = LIBUSB_TRANSFER_CANCELLED;
2264 usbi_dbg("device removed");
2265 status = LIBUSB_TRANSFER_NO_DEVICE;
2268 usbi_dbg("unsupported control request");
2269 status = LIBUSB_TRANSFER_STALL;
2272 usbi_dbg("control overflow error");
2273 status = LIBUSB_TRANSFER_OVERFLOW;
2280 usbi_dbg("low-level bus error occurred");
2281 status = LIBUSB_TRANSFER_ERROR;
2284 usbi_warn(ITRANSFER_CTX(itransfer),
2285 "unrecognised urb status %d", urb->status);
2286 status = LIBUSB_TRANSFER_ERROR;
2292 usbi_mutex_unlock(&itransfer->lock);
2293 return usbi_handle_transfer_completion(itransfer, status);
2296 static int reap_for_handle(struct libusb_device_handle *handle)
2298 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2300 struct usbfs_urb *urb;
2301 struct usbi_transfer *itransfer;
2302 struct libusb_transfer *transfer;
2304 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2305 if (r == -1 && errno == EAGAIN)
2308 if (errno == ENODEV)
2309 return LIBUSB_ERROR_NO_DEVICE;
2311 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2313 return LIBUSB_ERROR_IO;
2316 itransfer = urb->usercontext;
2317 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2319 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2320 urb->actual_length);
2322 switch (transfer->type) {
2323 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2324 return handle_iso_completion(itransfer, urb);
2325 case LIBUSB_TRANSFER_TYPE_BULK:
2326 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2327 return handle_bulk_completion(itransfer, urb);
2328 case LIBUSB_TRANSFER_TYPE_CONTROL:
2329 return handle_control_completion(itransfer, urb);
2331 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2333 return LIBUSB_ERROR_OTHER;
2337 static int op_handle_events(struct libusb_context *ctx,
2338 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2343 usbi_mutex_lock(&ctx->open_devs_lock);
2344 for (i = 0; i < nfds && num_ready > 0; i++) {
2345 struct pollfd *pollfd = &fds[i];
2346 struct libusb_device_handle *handle;
2347 struct linux_device_handle_priv *hpriv = NULL;
2349 if (!pollfd->revents)
2353 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2354 hpriv = _device_handle_priv(handle);
2355 if (hpriv->fd == pollfd->fd)
2359 if (pollfd->revents & POLLERR) {
2360 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2361 usbi_handle_disconnect(handle);
2366 r = reap_for_handle(handle);
2368 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2376 usbi_mutex_unlock(&ctx->open_devs_lock);
2380 static int op_clock_gettime(int clk_id, struct timespec *tp)
2383 case USBI_CLOCK_MONOTONIC:
2384 return clock_gettime(monotonic_clkid, tp);
2385 case USBI_CLOCK_REALTIME:
2386 return clock_gettime(CLOCK_REALTIME, tp);
2388 return LIBUSB_ERROR_INVALID_PARAM;
2392 #ifdef USBI_TIMERFD_AVAILABLE
2393 static clockid_t op_get_timerfd_clockid(void)
2395 return monotonic_clkid;
2400 const struct usbi_os_backend linux_usbfs_backend = {
2401 .name = "Linux usbfs",
2402 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2405 .get_device_list = NULL,
2406 .get_device_descriptor = op_get_device_descriptor,
2407 .get_active_config_descriptor = op_get_active_config_descriptor,
2408 .get_config_descriptor = op_get_config_descriptor,
2412 .get_configuration = op_get_configuration,
2413 .set_configuration = op_set_configuration,
2414 .claim_interface = op_claim_interface,
2415 .release_interface = op_release_interface,
2417 .set_interface_altsetting = op_set_interface,
2418 .clear_halt = op_clear_halt,
2419 .reset_device = op_reset_device,
2421 .kernel_driver_active = op_kernel_driver_active,
2422 .detach_kernel_driver = op_detach_kernel_driver,
2423 .attach_kernel_driver = op_attach_kernel_driver,
2425 .destroy_device = op_destroy_device,
2427 .submit_transfer = op_submit_transfer,
2428 .cancel_transfer = op_cancel_transfer,
2429 .clear_transfer_priv = op_clear_transfer_priv,
2431 .handle_events = op_handle_events,
2433 .clock_gettime = op_clock_gettime,
2435 #ifdef USBI_TIMERFD_AVAILABLE
2436 .get_timerfd_clockid = op_get_timerfd_clockid,
2439 .device_priv_size = sizeof(struct linux_device_priv),
2440 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2441 .transfer_priv_size = sizeof(struct linux_transfer_priv),
2442 .add_iso_packet_size = 0,