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 of the next descriptor with the given type */
625 static int seek_to_next_descriptor(struct libusb_context *ctx,
626 uint8_t descriptor_type, unsigned char *buffer, int size)
628 struct usb_descriptor_header header;
631 for (i = 0; size >= 0; i += header.bLength, size -= header.bLength) {
633 return LIBUSB_ERROR_NOT_FOUND;
636 usbi_err(ctx, "short descriptor read %d/2", size);
637 return LIBUSB_ERROR_IO;
639 usbi_parse_descriptor(buffer + i, "bb", &header, 0);
641 if (i && header.bDescriptorType == descriptor_type)
644 usbi_err(ctx, "bLength overflow by %d bytes", -size);
645 return LIBUSB_ERROR_IO;
648 /* Return offset to next config */
649 static int seek_to_next_config(struct libusb_context *ctx,
650 unsigned char *buffer, int size)
652 struct libusb_config_descriptor config;
655 return LIBUSB_ERROR_NOT_FOUND;
657 if (size < LIBUSB_DT_CONFIG_SIZE) {
658 usbi_err(ctx, "short descriptor read %d/%d",
659 size, LIBUSB_DT_CONFIG_SIZE);
660 return LIBUSB_ERROR_IO;
663 usbi_parse_descriptor(buffer, "bbwbbbbb", &config, 0);
664 if (config.bDescriptorType != LIBUSB_DT_CONFIG) {
665 usbi_err(ctx, "descriptor is not a config desc (type 0x%02x)",
666 config.bDescriptorType);
667 return LIBUSB_ERROR_IO;
671 * In usbfs the config descriptors are config.wTotalLength bytes apart,
672 * with any short reads from the device appearing as holes in the file.
674 * In sysfs wTotalLength is ignored, instead the kernel returns a
675 * config descriptor with verified bLength fields, with descriptors
676 * with an invalid bLength removed.
678 if (sysfs_has_descriptors) {
679 int next = seek_to_next_descriptor(ctx, LIBUSB_DT_CONFIG,
681 if (next == LIBUSB_ERROR_NOT_FOUND)
686 if (next != config.wTotalLength)
687 usbi_warn(ctx, "config length mismatch wTotalLength "
688 "%d real %d", config.wTotalLength, next);
691 if (config.wTotalLength < LIBUSB_DT_CONFIG_SIZE) {
692 usbi_err(ctx, "invalid wTotalLength %d",
693 config.wTotalLength);
694 return LIBUSB_ERROR_IO;
695 } else if (config.wTotalLength > size) {
696 usbi_warn(ctx, "short descriptor read %d/%d",
697 size, config.wTotalLength);
700 return config.wTotalLength;
704 static int op_get_config_descriptor_by_value(struct libusb_device *dev,
705 uint8_t value, unsigned char **buffer, int *host_endian)
707 struct libusb_context *ctx = DEVICE_CTX(dev);
708 struct linux_device_priv *priv = _device_priv(dev);
709 unsigned char *descriptors = priv->descriptors;
710 int size = priv->descriptors_len;
711 struct libusb_config_descriptor *config;
714 /* Unlike the device desc. config descs. are always in raw format */
717 /* Skip device header */
718 descriptors += DEVICE_DESC_LENGTH;
719 size -= DEVICE_DESC_LENGTH;
721 /* Seek till the config is found, or till "EOF" */
723 int next = seek_to_next_config(ctx, descriptors, size);
726 config = (struct libusb_config_descriptor *)descriptors;
727 if (config->bConfigurationValue == value) {
728 *buffer = descriptors;
736 static int op_get_active_config_descriptor(struct libusb_device *dev,
737 unsigned char *buffer, size_t len, int *host_endian)
740 unsigned char *config_desc;
742 if (sysfs_can_relate_devices) {
743 r = sysfs_get_active_config(dev, &config);
747 /* Use cached bConfigurationValue */
748 struct linux_device_priv *priv = _device_priv(dev);
749 config = priv->active_config;
752 return LIBUSB_ERROR_NOT_FOUND;
754 r = op_get_config_descriptor_by_value(dev, config, &config_desc,
760 memcpy(buffer, config_desc, len);
764 static int op_get_config_descriptor(struct libusb_device *dev,
765 uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
767 struct linux_device_priv *priv = _device_priv(dev);
768 unsigned char *descriptors = priv->descriptors;
769 int i, r, size = priv->descriptors_len;
771 /* Unlike the device desc. config descs. are always in raw format */
774 /* Skip device header */
775 descriptors += DEVICE_DESC_LENGTH;
776 size -= DEVICE_DESC_LENGTH;
778 /* Seek till the config is found, or till "EOF" */
780 r = seek_to_next_config(DEVICE_CTX(dev), descriptors, size);
783 if (i == config_index)
790 memcpy(buffer, descriptors, len);
794 /* send a control message to retrieve active configuration */
795 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
797 unsigned char active_config = 0;
800 struct usbfs_ctrltransfer ctrl = {
801 .bmRequestType = LIBUSB_ENDPOINT_IN,
802 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
807 .data = &active_config
810 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
813 return LIBUSB_ERROR_NO_DEVICE;
815 /* we hit this error path frequently with buggy devices :( */
816 usbi_warn(DEVICE_CTX(dev),
817 "get_configuration failed ret=%d errno=%d", r, errno);
818 return LIBUSB_ERROR_IO;
821 return active_config;
824 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
825 uint8_t devaddr, const char *sysfs_dir)
827 struct linux_device_priv *priv = _device_priv(dev);
828 struct libusb_context *ctx = DEVICE_CTX(dev);
829 int descriptors_size = 512; /* Begin with a 1024 byte alloc */
833 dev->bus_number = busnum;
834 dev->device_address = devaddr;
837 priv->sysfs_dir = malloc(strlen(sysfs_dir) + 1);
838 if (!priv->sysfs_dir)
839 return LIBUSB_ERROR_NO_MEM;
840 strcpy(priv->sysfs_dir, sysfs_dir);
842 /* Note speed can contain 1.5, in this case __read_sysfs_attr
843 will stop parsing at the '.' and return 1 */
844 speed = __read_sysfs_attr(DEVICE_CTX(dev), sysfs_dir, "speed");
847 case 1: dev->speed = LIBUSB_SPEED_LOW; break;
848 case 12: dev->speed = LIBUSB_SPEED_FULL; break;
849 case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
850 case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
852 usbi_warn(DEVICE_CTX(dev), "Unknown device speed: %d Mbps", speed);
857 /* cache descriptors in memory */
858 if (sysfs_has_descriptors)
859 fd = _open_sysfs_attr(dev, "descriptors");
861 fd = _get_usbfs_fd(dev, O_RDONLY, 0);
866 descriptors_size *= 2;
867 priv->descriptors = usbi_reallocf(priv->descriptors,
869 if (!priv->descriptors) {
871 return LIBUSB_ERROR_NO_MEM;
873 /* usbfs has holes in the file */
874 if (!sysfs_has_descriptors) {
875 memset(priv->descriptors + priv->descriptors_len,
876 0, descriptors_size - priv->descriptors_len);
878 r = read(fd, priv->descriptors + priv->descriptors_len,
879 descriptors_size - priv->descriptors_len);
881 usbi_err(ctx, "read descriptor failed ret=%d errno=%d",
884 return LIBUSB_ERROR_IO;
886 priv->descriptors_len += r;
887 } while (priv->descriptors_len == descriptors_size);
891 if (priv->descriptors_len < DEVICE_DESC_LENGTH) {
892 usbi_err(ctx, "short descriptor read (%d)",
893 priv->descriptors_len);
894 return LIBUSB_ERROR_IO;
897 if (sysfs_can_relate_devices)
898 return LIBUSB_SUCCESS;
900 /* cache active config */
901 fd = _get_usbfs_fd(dev, O_RDWR, 1);
903 /* cannot send a control message to determine the active
904 * config. just assume the first one is active. */
905 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
906 "active configuration descriptor");
907 if (priv->descriptors_len >=
908 (DEVICE_DESC_LENGTH + LIBUSB_DT_CONFIG_SIZE)) {
909 struct libusb_config_descriptor config;
910 usbi_parse_descriptor(
911 priv->descriptors + DEVICE_DESC_LENGTH,
912 "bbwbbbbb", &config, 0);
913 priv->active_config = config.bConfigurationValue;
915 priv->active_config = -1; /* No config dt */
917 return LIBUSB_SUCCESS;
920 r = usbfs_get_active_config(dev, fd);
922 priv->active_config = r;
925 /* some buggy devices have a configuration 0, but we're
926 * reaching into the corner of a corner case here, so let's
927 * not support buggy devices in these circumstances.
928 * stick to the specs: a configuration value of 0 means
930 usbi_dbg("active cfg 0? assuming unconfigured device");
931 priv->active_config = -1;
933 } else if (r == LIBUSB_ERROR_IO) {
934 /* buggy devices sometimes fail to report their active config.
935 * assume unconfigured and continue the probing */
936 usbi_warn(ctx, "couldn't query active configuration, assuming"
938 priv->active_config = -1;
940 } /* else r < 0, just return the error code */
946 static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir)
948 struct libusb_context *ctx = DEVICE_CTX(dev);
949 struct libusb_device *it;
950 char *parent_sysfs_dir, *tmp;
951 int ret, add_parent = 1;
953 /* XXX -- can we figure out the topology when using usbfs? */
954 if (NULL == sysfs_dir || 0 == strncmp(sysfs_dir, "usb", 3)) {
955 /* either using usbfs or finding the parent of a root hub */
956 return LIBUSB_SUCCESS;
959 parent_sysfs_dir = strdup(sysfs_dir);
960 if (NULL != (tmp = strrchr(parent_sysfs_dir, '.')) ||
961 NULL != (tmp = strrchr(parent_sysfs_dir, '-'))) {
962 dev->port_number = atoi(tmp + 1);
965 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
967 free (parent_sysfs_dir);
968 return LIBUSB_SUCCESS;
971 /* is the parent a root hub? */
972 if (NULL == strchr(parent_sysfs_dir, '-')) {
973 tmp = parent_sysfs_dir;
974 ret = asprintf (&parent_sysfs_dir, "usb%s", tmp);
977 return LIBUSB_ERROR_NO_MEM;
982 /* find the parent in the context */
983 usbi_mutex_lock(&ctx->usb_devs_lock);
984 list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device) {
985 struct linux_device_priv *priv = _device_priv(it);
986 if (0 == strcmp (priv->sysfs_dir, parent_sysfs_dir)) {
987 dev->parent_dev = libusb_ref_device(it);
991 usbi_mutex_unlock(&ctx->usb_devs_lock);
993 if (!dev->parent_dev && add_parent) {
994 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
996 sysfs_scan_device(ctx, parent_sysfs_dir);
1001 usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev, sysfs_dir,
1002 dev->parent_dev, parent_sysfs_dir, dev->port_number);
1004 free (parent_sysfs_dir);
1006 return LIBUSB_SUCCESS;
1009 int linux_enumerate_device(struct libusb_context *ctx,
1010 uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1012 unsigned long session_id;
1013 struct libusb_device *dev;
1016 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1017 * will be reused. instead we should add a simple sysfs attribute with
1019 session_id = busnum << 8 | devaddr;
1020 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
1023 if (usbi_get_device_by_session_id(ctx, session_id)) {
1024 /* device already exists in the context */
1025 usbi_dbg("session_id %ld already exists", session_id);
1026 return LIBUSB_SUCCESS;
1029 usbi_dbg("allocating new device for %d/%d (session %ld)",
1030 busnum, devaddr, session_id);
1031 dev = usbi_alloc_device(ctx, session_id);
1033 return LIBUSB_ERROR_NO_MEM;
1035 r = initialize_device(dev, busnum, devaddr, sysfs_dir);
1038 r = usbi_sanitize_device(dev);
1042 r = linux_get_parent_info(dev, sysfs_dir);
1047 libusb_unref_device(dev);
1049 usbi_connect_device(dev);
1054 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1056 struct libusb_context *ctx;
1058 usbi_mutex_static_lock(&active_contexts_lock);
1059 usbi_mutex_static_lock(&hotplug_lock);
1060 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1061 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1063 usbi_mutex_static_unlock(&hotplug_lock);
1064 usbi_mutex_static_unlock(&active_contexts_lock);
1067 void linux_hotplug_disconnected(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1069 struct libusb_context *ctx;
1070 struct libusb_device *dev;
1071 unsigned long session_id = busnum << 8 | devaddr;
1073 usbi_mutex_static_lock(&active_contexts_lock);
1074 usbi_mutex_static_lock(&hotplug_lock);
1075 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1076 dev = usbi_get_device_by_session_id (ctx, session_id);
1078 usbi_disconnect_device (dev);
1080 usbi_dbg("device not found for session %x", session_id);
1083 usbi_mutex_static_unlock(&hotplug_lock);
1084 usbi_mutex_static_unlock(&active_contexts_lock);
1087 #if !defined(USE_UDEV)
1088 /* open a bus directory and adds all discovered devices to the context */
1089 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1092 char dirpath[PATH_MAX];
1093 struct dirent *entry;
1094 int r = LIBUSB_ERROR_IO;
1096 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1097 usbi_dbg("%s", dirpath);
1098 dir = opendir(dirpath);
1100 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1101 /* FIXME: should handle valid race conditions like hub unplugged
1102 * during directory iteration - this is not an error */
1106 while ((entry = readdir(dir))) {
1109 if (entry->d_name[0] == '.')
1112 devaddr = atoi(entry->d_name);
1114 usbi_dbg("unknown dir entry %s", entry->d_name);
1118 if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1119 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1130 static int usbfs_get_device_list(struct libusb_context *ctx)
1132 struct dirent *entry;
1133 DIR *buses = opendir(usbfs_path);
1137 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1138 return LIBUSB_ERROR_IO;
1141 while ((entry = readdir(buses))) {
1144 if (entry->d_name[0] == '.')
1149 if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1152 r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
1154 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1158 busnum = atoi(entry->d_name);
1160 usbi_dbg("unknown dir entry %s", entry->d_name);
1164 r = usbfs_scan_busdir(ctx, busnum);
1176 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
1178 uint8_t busnum, devaddr;
1181 ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname);
1182 if (LIBUSB_SUCCESS != ret) {
1186 return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff,
1190 #if !defined(USE_UDEV)
1191 static int sysfs_get_device_list(struct libusb_context *ctx)
1193 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1194 struct dirent *entry;
1195 int r = LIBUSB_ERROR_IO;
1198 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1202 while ((entry = readdir(devices))) {
1203 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1204 || strchr(entry->d_name, ':'))
1207 if (sysfs_scan_device(ctx, entry->d_name)) {
1208 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1219 static int linux_default_scan_devices (struct libusb_context *ctx)
1221 /* we can retrieve device list and descriptors from sysfs or usbfs.
1222 * sysfs is preferable, because if we use usbfs we end up resuming
1223 * any autosuspended USB devices. however, sysfs is not available
1224 * everywhere, so we need a usbfs fallback too.
1226 * as described in the "sysfs vs usbfs" comment at the top of this
1227 * file, sometimes we have sysfs but not enough information to
1228 * relate sysfs devices to usbfs nodes. op_init() determines the
1229 * adequacy of sysfs and sets sysfs_can_relate_devices.
1231 if (sysfs_can_relate_devices != 0)
1232 return sysfs_get_device_list(ctx);
1234 return usbfs_get_device_list(ctx);
1238 static int op_open(struct libusb_device_handle *handle)
1240 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1243 hpriv->fd = _get_usbfs_fd(handle->dev, O_RDWR, 0);
1247 r = ioctl(hpriv->fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1249 if (errno == ENOTTY)
1250 usbi_dbg("getcap not available");
1252 usbi_err(HANDLE_CTX(handle), "getcap failed (%d)", errno);
1254 if (supports_flag_zero_packet)
1255 hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1256 if (supports_flag_bulk_continuation)
1257 hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1260 return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1263 static void op_close(struct libusb_device_handle *dev_handle)
1265 int fd = _device_handle_priv(dev_handle)->fd;
1266 usbi_remove_pollfd(HANDLE_CTX(dev_handle), fd);
1270 static int op_get_configuration(struct libusb_device_handle *handle,
1275 if (sysfs_can_relate_devices) {
1276 r = sysfs_get_active_config(handle->dev, config);
1278 r = usbfs_get_active_config(handle->dev,
1279 _device_handle_priv(handle)->fd);
1284 if (*config == -1) {
1285 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1292 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1294 struct linux_device_priv *priv = _device_priv(handle->dev);
1295 int fd = _device_handle_priv(handle)->fd;
1296 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1298 if (errno == EINVAL)
1299 return LIBUSB_ERROR_NOT_FOUND;
1300 else if (errno == EBUSY)
1301 return LIBUSB_ERROR_BUSY;
1302 else if (errno == ENODEV)
1303 return LIBUSB_ERROR_NO_DEVICE;
1305 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1306 return LIBUSB_ERROR_OTHER;
1309 /* update our cached active config descriptor */
1310 priv->active_config = config;
1312 return LIBUSB_SUCCESS;
1315 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1317 int fd = _device_handle_priv(handle)->fd;
1318 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1320 if (errno == ENOENT)
1321 return LIBUSB_ERROR_NOT_FOUND;
1322 else if (errno == EBUSY)
1323 return LIBUSB_ERROR_BUSY;
1324 else if (errno == ENODEV)
1325 return LIBUSB_ERROR_NO_DEVICE;
1327 usbi_err(HANDLE_CTX(handle),
1328 "claim interface failed, error %d errno %d", r, errno);
1329 return LIBUSB_ERROR_OTHER;
1334 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1336 int fd = _device_handle_priv(handle)->fd;
1337 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1339 if (errno == ENODEV)
1340 return LIBUSB_ERROR_NO_DEVICE;
1342 usbi_err(HANDLE_CTX(handle),
1343 "release interface failed, error %d errno %d", r, errno);
1344 return LIBUSB_ERROR_OTHER;
1349 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1352 int fd = _device_handle_priv(handle)->fd;
1353 struct usbfs_setinterface setintf;
1356 setintf.interface = iface;
1357 setintf.altsetting = altsetting;
1358 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1360 if (errno == EINVAL)
1361 return LIBUSB_ERROR_NOT_FOUND;
1362 else if (errno == ENODEV)
1363 return LIBUSB_ERROR_NO_DEVICE;
1365 usbi_err(HANDLE_CTX(handle),
1366 "setintf failed error %d errno %d", r, errno);
1367 return LIBUSB_ERROR_OTHER;
1373 static int op_clear_halt(struct libusb_device_handle *handle,
1374 unsigned char endpoint)
1376 int fd = _device_handle_priv(handle)->fd;
1377 unsigned int _endpoint = endpoint;
1378 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1380 if (errno == ENOENT)
1381 return LIBUSB_ERROR_NOT_FOUND;
1382 else if (errno == ENODEV)
1383 return LIBUSB_ERROR_NO_DEVICE;
1385 usbi_err(HANDLE_CTX(handle),
1386 "clear_halt failed error %d errno %d", r, errno);
1387 return LIBUSB_ERROR_OTHER;
1393 static int op_reset_device(struct libusb_device_handle *handle)
1395 int fd = _device_handle_priv(handle)->fd;
1398 /* Doing a device reset will cause the usbfs driver to get unbound
1399 from any interfaces it is bound to. By voluntarily unbinding
1400 the usbfs driver ourself, we stop the kernel from rebinding
1401 the interface after reset (which would end up with the interface
1402 getting bound to the in kernel driver if any). */
1403 for (i = 0; i < USB_MAXINTERFACES; i++) {
1404 if (handle->claimed_interfaces & (1L << i)) {
1405 op_release_interface(handle, i);
1409 usbi_mutex_lock(&handle->lock);
1410 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1412 if (errno == ENODEV) {
1413 ret = LIBUSB_ERROR_NOT_FOUND;
1417 usbi_err(HANDLE_CTX(handle),
1418 "reset failed error %d errno %d", r, errno);
1419 ret = LIBUSB_ERROR_OTHER;
1423 /* And re-claim any interfaces which were claimed before the reset */
1424 for (i = 0; i < USB_MAXINTERFACES; i++) {
1425 if (handle->claimed_interfaces & (1L << i)) {
1426 r = op_claim_interface(handle, i);
1428 usbi_warn(HANDLE_CTX(handle),
1429 "failed to re-claim interface %d after reset", i);
1430 handle->claimed_interfaces &= ~(1L << i);
1435 usbi_mutex_unlock(&handle->lock);
1439 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1442 int fd = _device_handle_priv(handle)->fd;
1443 struct usbfs_getdriver getdrv;
1446 getdrv.interface = interface;
1447 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1449 if (errno == ENODATA)
1451 else if (errno == ENODEV)
1452 return LIBUSB_ERROR_NO_DEVICE;
1454 usbi_err(HANDLE_CTX(handle),
1455 "get driver failed error %d errno %d", r, errno);
1456 return LIBUSB_ERROR_OTHER;
1462 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1465 int fd = _device_handle_priv(handle)->fd;
1466 struct usbfs_ioctl command;
1467 struct usbfs_getdriver getdrv;
1470 command.ifno = interface;
1471 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1472 command.data = NULL;
1474 getdrv.interface = interface;
1475 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1476 if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1477 return LIBUSB_ERROR_NOT_FOUND;
1479 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1481 if (errno == ENODATA)
1482 return LIBUSB_ERROR_NOT_FOUND;
1483 else if (errno == EINVAL)
1484 return LIBUSB_ERROR_INVALID_PARAM;
1485 else if (errno == ENODEV)
1486 return LIBUSB_ERROR_NO_DEVICE;
1488 usbi_err(HANDLE_CTX(handle),
1489 "detach failed error %d errno %d", r, errno);
1490 return LIBUSB_ERROR_OTHER;
1496 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1499 int fd = _device_handle_priv(handle)->fd;
1500 struct usbfs_ioctl command;
1503 command.ifno = interface;
1504 command.ioctl_code = IOCTL_USBFS_CONNECT;
1505 command.data = NULL;
1507 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1509 if (errno == ENODATA)
1510 return LIBUSB_ERROR_NOT_FOUND;
1511 else if (errno == EINVAL)
1512 return LIBUSB_ERROR_INVALID_PARAM;
1513 else if (errno == ENODEV)
1514 return LIBUSB_ERROR_NO_DEVICE;
1515 else if (errno == EBUSY)
1516 return LIBUSB_ERROR_BUSY;
1518 usbi_err(HANDLE_CTX(handle),
1519 "attach failed error %d errno %d", r, errno);
1520 return LIBUSB_ERROR_OTHER;
1521 } else if (r == 0) {
1522 return LIBUSB_ERROR_NOT_FOUND;
1528 static void op_destroy_device(struct libusb_device *dev)
1530 struct linux_device_priv *priv = _device_priv(dev);
1531 if (priv->descriptors)
1532 free(priv->descriptors);
1533 if (priv->sysfs_dir)
1534 free(priv->sysfs_dir);
1537 /* URBs are discarded in reverse order of submission to avoid races. */
1538 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1540 struct libusb_transfer *transfer =
1541 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1542 struct linux_transfer_priv *tpriv =
1543 usbi_transfer_get_os_priv(itransfer);
1544 struct linux_device_handle_priv *dpriv =
1545 _device_handle_priv(transfer->dev_handle);
1547 struct usbfs_urb *urb;
1549 for (i = last_plus_one - 1; i >= first; i--) {
1550 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
1551 urb = tpriv->iso_urbs[i];
1553 urb = &tpriv->urbs[i];
1555 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
1558 if (EINVAL == errno) {
1559 usbi_dbg("URB not found --> assuming ready to be reaped");
1560 if (i == (last_plus_one - 1))
1561 ret = LIBUSB_ERROR_NOT_FOUND;
1562 } else if (ENODEV == errno) {
1563 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1564 ret = LIBUSB_ERROR_NO_DEVICE;
1566 usbi_warn(TRANSFER_CTX(transfer),
1567 "unrecognised discard errno %d", errno);
1568 ret = LIBUSB_ERROR_OTHER;
1574 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1577 for (i = 0; i < tpriv->num_urbs; i++) {
1578 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1584 free(tpriv->iso_urbs);
1585 tpriv->iso_urbs = NULL;
1588 static int submit_bulk_transfer(struct usbi_transfer *itransfer,
1589 unsigned char urb_type)
1591 struct libusb_transfer *transfer =
1592 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1593 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1594 struct linux_device_handle_priv *dpriv =
1595 _device_handle_priv(transfer->dev_handle);
1596 struct usbfs_urb *urbs;
1597 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1598 == LIBUSB_ENDPOINT_OUT;
1599 int bulk_buffer_len, use_bulk_continuation;
1605 return LIBUSB_ERROR_BUSY;
1607 if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1608 !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
1609 return LIBUSB_ERROR_NOT_SUPPORTED;
1612 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1613 * around this by splitting large transfers into 16k blocks, and then
1614 * submit all urbs at once. it would be simpler to submit one urb at
1615 * a time, but there is a big performance gain doing it this way.
1617 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1618 * using arbritary large transfers can still be a bad idea though, as
1619 * the kernel needs to allocate physical contiguous memory for this,
1620 * which may fail for large buffers.
1622 * The kernel solves this problem by splitting the transfer into
1623 * blocks itself when the host-controller is scatter-gather capable
1624 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1626 * Last, there is the issue of short-transfers when splitting, for
1627 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1628 * is needed, but this is not always available.
1630 if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1631 /* Good! Just submit everything in one go */
1632 bulk_buffer_len = transfer->length ? transfer->length : 1;
1633 use_bulk_continuation = 0;
1634 } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1635 /* Split the transfers and use bulk-continuation to
1636 avoid issues with short-transfers */
1637 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1638 use_bulk_continuation = 1;
1639 } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1640 /* Don't split, assume the kernel can alloc the buffer
1641 (otherwise the submit will fail with -ENOMEM) */
1642 bulk_buffer_len = transfer->length ? transfer->length : 1;
1643 use_bulk_continuation = 0;
1645 /* Bad, splitting without bulk-continuation, short transfers
1646 which end before the last urb will not work reliable! */
1647 /* Note we don't warn here as this is "normal" on kernels <
1648 2.6.32 and not a problem for most applications */
1649 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1650 use_bulk_continuation = 0;
1653 int num_urbs = transfer->length / bulk_buffer_len;
1654 int last_urb_partial = 0;
1656 if (transfer->length == 0) {
1658 } else if ((transfer->length % bulk_buffer_len) > 0) {
1659 last_urb_partial = 1;
1662 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
1664 alloc_size = num_urbs * sizeof(struct usbfs_urb);
1665 urbs = calloc(1, alloc_size);
1667 return LIBUSB_ERROR_NO_MEM;
1669 tpriv->num_urbs = num_urbs;
1670 tpriv->num_retired = 0;
1671 tpriv->reap_action = NORMAL;
1672 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1674 for (i = 0; i < num_urbs; i++) {
1675 struct usbfs_urb *urb = &urbs[i];
1676 urb->usercontext = itransfer;
1677 urb->type = urb_type;
1678 urb->endpoint = transfer->endpoint;
1679 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
1680 /* don't set the short not ok flag for the last URB */
1681 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
1682 urb->flags = USBFS_URB_SHORT_NOT_OK;
1683 if (i == num_urbs - 1 && last_urb_partial)
1684 urb->buffer_length = transfer->length % bulk_buffer_len;
1685 else if (transfer->length == 0)
1686 urb->buffer_length = 0;
1688 urb->buffer_length = bulk_buffer_len;
1690 if (i > 0 && use_bulk_continuation)
1691 urb->flags |= USBFS_URB_BULK_CONTINUATION;
1693 /* we have already checked that the flag is supported */
1694 if (is_out && i == num_urbs - 1 &&
1695 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
1696 urb->flags |= USBFS_URB_ZERO_PACKET;
1698 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1700 if (errno == ENODEV) {
1701 r = LIBUSB_ERROR_NO_DEVICE;
1703 usbi_err(TRANSFER_CTX(transfer),
1704 "submiturb failed error %d errno=%d", r, errno);
1705 r = LIBUSB_ERROR_IO;
1708 /* if the first URB submission fails, we can simply free up and
1709 * return failure immediately. */
1711 usbi_dbg("first URB failed, easy peasy");
1717 /* if it's not the first URB that failed, the situation is a bit
1718 * tricky. we may need to discard all previous URBs. there are
1720 * - discarding is asynchronous - discarded urbs will be reaped
1721 * later. the user must not have freed the transfer when the
1722 * discarded URBs are reaped, otherwise libusbx will be using
1724 * - the earlier URBs may have completed successfully and we do
1725 * not want to throw away any data.
1726 * - this URB failing may be no error; EREMOTEIO means that
1727 * this transfer simply didn't need all the URBs we submitted
1728 * so, we report that the transfer was submitted successfully and
1729 * in case of error we discard all previous URBs. later when
1730 * the final reap completes we can report error to the user,
1731 * or success if an earlier URB was completed successfully.
1733 tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
1735 /* The URBs we haven't submitted yet we count as already
1737 tpriv->num_retired += num_urbs - i;
1739 /* If we completed short then don't try to discard. */
1740 if (COMPLETED_EARLY == tpriv->reap_action)
1743 discard_urbs(itransfer, 0, i);
1745 usbi_dbg("reporting successful submission but waiting for %d "
1746 "discards before reporting error", i);
1754 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1756 struct libusb_transfer *transfer =
1757 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1758 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1759 struct linux_device_handle_priv *dpriv =
1760 _device_handle_priv(transfer->dev_handle);
1761 struct usbfs_urb **urbs;
1763 int num_packets = transfer->num_iso_packets;
1765 int this_urb_len = 0;
1767 int packet_offset = 0;
1768 unsigned int packet_len;
1769 unsigned char *urb_buffer = transfer->buffer;
1771 if (tpriv->iso_urbs)
1772 return LIBUSB_ERROR_BUSY;
1774 /* usbfs places a 32kb limit on iso URBs. we divide up larger requests
1775 * into smaller units to meet such restriction, then fire off all the
1776 * units at once. it would be simpler if we just fired one unit at a time,
1777 * but there is a big performance gain through doing it this way.
1779 * Newer kernels lift the 32k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1780 * using arbritary large transfers is still be a bad idea though, as
1781 * the kernel needs to allocate physical contiguous memory for this,
1782 * which may fail for large buffers.
1785 /* calculate how many URBs we need */
1786 for (i = 0; i < num_packets; i++) {
1787 unsigned int space_remaining = MAX_ISO_BUFFER_LENGTH - this_urb_len;
1788 packet_len = transfer->iso_packet_desc[i].length;
1790 if (packet_len > space_remaining) {
1792 this_urb_len = packet_len;
1794 this_urb_len += packet_len;
1797 usbi_dbg("need %d 32k URBs for transfer", num_urbs);
1799 alloc_size = num_urbs * sizeof(*urbs);
1800 urbs = calloc(1, alloc_size);
1802 return LIBUSB_ERROR_NO_MEM;
1804 tpriv->iso_urbs = urbs;
1805 tpriv->num_urbs = num_urbs;
1806 tpriv->num_retired = 0;
1807 tpriv->reap_action = NORMAL;
1808 tpriv->iso_packet_offset = 0;
1810 /* allocate + initialize each URB with the correct number of packets */
1811 for (i = 0; i < num_urbs; i++) {
1812 struct usbfs_urb *urb;
1813 unsigned int space_remaining_in_urb = MAX_ISO_BUFFER_LENGTH;
1814 int urb_packet_offset = 0;
1815 unsigned char *urb_buffer_orig = urb_buffer;
1819 /* swallow up all the packets we can fit into this URB */
1820 while (packet_offset < transfer->num_iso_packets) {
1821 packet_len = transfer->iso_packet_desc[packet_offset].length;
1822 if (packet_len <= space_remaining_in_urb) {
1824 urb_packet_offset++;
1826 space_remaining_in_urb -= packet_len;
1827 urb_buffer += packet_len;
1829 /* it can't fit, save it for the next URB */
1834 alloc_size = sizeof(*urb)
1835 + (urb_packet_offset * sizeof(struct usbfs_iso_packet_desc));
1836 urb = calloc(1, alloc_size);
1838 free_iso_urbs(tpriv);
1839 return LIBUSB_ERROR_NO_MEM;
1843 /* populate packet lengths */
1844 for (j = 0, k = packet_offset - urb_packet_offset;
1845 k < packet_offset; k++, j++) {
1846 packet_len = transfer->iso_packet_desc[k].length;
1847 urb->iso_frame_desc[j].length = packet_len;
1850 urb->usercontext = itransfer;
1851 urb->type = USBFS_URB_TYPE_ISO;
1852 /* FIXME: interface for non-ASAP data? */
1853 urb->flags = USBFS_URB_ISO_ASAP;
1854 urb->endpoint = transfer->endpoint;
1855 urb->number_of_packets = urb_packet_offset;
1856 urb->buffer = urb_buffer_orig;
1860 for (i = 0; i < num_urbs; i++) {
1861 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
1863 if (errno == ENODEV) {
1864 r = LIBUSB_ERROR_NO_DEVICE;
1866 usbi_err(TRANSFER_CTX(transfer),
1867 "submiturb failed error %d errno=%d", r, errno);
1868 r = LIBUSB_ERROR_IO;
1871 /* if the first URB submission fails, we can simply free up and
1872 * return failure immediately. */
1874 usbi_dbg("first URB failed, easy peasy");
1875 free_iso_urbs(tpriv);
1879 /* if it's not the first URB that failed, the situation is a bit
1880 * tricky. we must discard all previous URBs. there are
1882 * - discarding is asynchronous - discarded urbs will be reaped
1883 * later. the user must not have freed the transfer when the
1884 * discarded URBs are reaped, otherwise libusbx will be using
1886 * - the earlier URBs may have completed successfully and we do
1887 * not want to throw away any data.
1888 * so, in this case we discard all the previous URBs BUT we report
1889 * that the transfer was submitted successfully. then later when
1890 * the final discard completes we can report error to the user.
1892 tpriv->reap_action = SUBMIT_FAILED;
1894 /* The URBs we haven't submitted yet we count as already
1896 tpriv->num_retired = num_urbs - i;
1897 discard_urbs(itransfer, 0, i);
1899 usbi_dbg("reporting successful submission but waiting for %d "
1900 "discards before reporting error", i);
1908 static int submit_control_transfer(struct usbi_transfer *itransfer)
1910 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1911 struct libusb_transfer *transfer =
1912 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1913 struct linux_device_handle_priv *dpriv =
1914 _device_handle_priv(transfer->dev_handle);
1915 struct usbfs_urb *urb;
1919 return LIBUSB_ERROR_BUSY;
1921 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
1922 return LIBUSB_ERROR_INVALID_PARAM;
1924 urb = calloc(1, sizeof(struct usbfs_urb));
1926 return LIBUSB_ERROR_NO_MEM;
1928 tpriv->num_urbs = 1;
1929 tpriv->reap_action = NORMAL;
1931 urb->usercontext = itransfer;
1932 urb->type = USBFS_URB_TYPE_CONTROL;
1933 urb->endpoint = transfer->endpoint;
1934 urb->buffer = transfer->buffer;
1935 urb->buffer_length = transfer->length;
1937 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1941 if (errno == ENODEV)
1942 return LIBUSB_ERROR_NO_DEVICE;
1944 usbi_err(TRANSFER_CTX(transfer),
1945 "submiturb failed error %d errno=%d", r, errno);
1946 return LIBUSB_ERROR_IO;
1951 static int op_submit_transfer(struct usbi_transfer *itransfer)
1953 struct libusb_transfer *transfer =
1954 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1956 switch (transfer->type) {
1957 case LIBUSB_TRANSFER_TYPE_CONTROL:
1958 return submit_control_transfer(itransfer);
1959 case LIBUSB_TRANSFER_TYPE_BULK:
1960 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_BULK);
1961 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1962 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_INTERRUPT);
1963 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1964 return submit_iso_transfer(itransfer);
1966 usbi_err(TRANSFER_CTX(transfer),
1967 "unknown endpoint type %d", transfer->type);
1968 return LIBUSB_ERROR_INVALID_PARAM;
1972 static int op_cancel_transfer(struct usbi_transfer *itransfer)
1974 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1975 struct libusb_transfer *transfer =
1976 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1978 switch (transfer->type) {
1979 case LIBUSB_TRANSFER_TYPE_BULK:
1980 if (tpriv->reap_action == ERROR)
1982 /* else, fall through */
1983 case LIBUSB_TRANSFER_TYPE_CONTROL:
1984 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1985 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1986 tpriv->reap_action = CANCELLED;
1989 usbi_err(TRANSFER_CTX(transfer),
1990 "unknown endpoint type %d", transfer->type);
1991 return LIBUSB_ERROR_INVALID_PARAM;
1995 return LIBUSB_ERROR_NOT_FOUND;
1997 return discard_urbs(itransfer, 0, tpriv->num_urbs);
2000 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2002 struct libusb_transfer *transfer =
2003 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2004 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2006 /* urbs can be freed also in submit_transfer so lock mutex first */
2007 switch (transfer->type) {
2008 case LIBUSB_TRANSFER_TYPE_CONTROL:
2009 case LIBUSB_TRANSFER_TYPE_BULK:
2010 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2011 usbi_mutex_lock(&itransfer->lock);
2015 usbi_mutex_unlock(&itransfer->lock);
2017 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2018 usbi_mutex_lock(&itransfer->lock);
2019 if (tpriv->iso_urbs)
2020 free_iso_urbs(tpriv);
2021 usbi_mutex_unlock(&itransfer->lock);
2024 usbi_err(TRANSFER_CTX(transfer),
2025 "unknown endpoint type %d", transfer->type);
2029 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2030 struct usbfs_urb *urb)
2032 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2033 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2034 int urb_idx = urb - tpriv->urbs;
2036 usbi_mutex_lock(&itransfer->lock);
2037 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2038 urb_idx + 1, tpriv->num_urbs);
2040 tpriv->num_retired++;
2042 if (tpriv->reap_action != NORMAL) {
2043 /* cancelled, submit_fail, or completed early */
2044 usbi_dbg("abnormal reap: urb status %d", urb->status);
2046 /* even though we're in the process of cancelling, it's possible that
2047 * we may receive some data in these URBs that we don't want to lose.
2049 * 1. while the kernel is cancelling all the packets that make up an
2050 * URB, a few of them might complete. so we get back a successful
2051 * cancellation *and* some data.
2052 * 2. we receive a short URB which marks the early completion condition,
2053 * so we start cancelling the remaining URBs. however, we're too
2054 * slow and another URB completes (or at least completes partially).
2055 * (this can't happen since we always use BULK_CONTINUATION.)
2057 * When this happens, our objectives are not to lose any "surplus" data,
2058 * and also to stick it at the end of the previously-received data
2059 * (closing any holes), so that libusbx reports the total amount of
2060 * transferred data and presents it in a contiguous chunk.
2062 if (urb->actual_length > 0) {
2063 unsigned char *target = transfer->buffer + itransfer->transferred;
2064 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2065 if (urb->buffer != target) {
2066 usbi_dbg("moving surplus data from offset %d to offset %d",
2067 (unsigned char *) urb->buffer - transfer->buffer,
2068 target - transfer->buffer);
2069 memmove(target, urb->buffer, urb->actual_length);
2071 itransfer->transferred += urb->actual_length;
2074 if (tpriv->num_retired == tpriv->num_urbs) {
2075 usbi_dbg("abnormal reap: last URB handled, reporting");
2076 if (tpriv->reap_action != COMPLETED_EARLY &&
2077 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2078 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2084 itransfer->transferred += urb->actual_length;
2086 /* Many of these errors can occur on *any* urb of a multi-urb
2087 * transfer. When they do, we tear down the rest of the transfer.
2089 switch (urb->status) {
2092 case -EREMOTEIO: /* short transfer */
2094 case -ENOENT: /* cancelled */
2099 usbi_dbg("device removed");
2100 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2101 goto cancel_remaining;
2103 usbi_dbg("detected endpoint stall");
2104 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2105 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2106 goto cancel_remaining;
2108 /* overflow can only ever occur in the last urb */
2109 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2110 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2111 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2118 usbi_dbg("low level error %d", urb->status);
2119 tpriv->reap_action = ERROR;
2120 goto cancel_remaining;
2122 usbi_warn(ITRANSFER_CTX(itransfer),
2123 "unrecognised urb status %d", urb->status);
2124 tpriv->reap_action = ERROR;
2125 goto cancel_remaining;
2128 /* if we're the last urb or we got less data than requested then we're
2130 if (urb_idx == tpriv->num_urbs - 1) {
2131 usbi_dbg("last URB in transfer --> complete!");
2133 } else if (urb->actual_length < urb->buffer_length) {
2134 usbi_dbg("short transfer %d/%d --> complete!",
2135 urb->actual_length, urb->buffer_length);
2136 if (tpriv->reap_action == NORMAL)
2137 tpriv->reap_action = COMPLETED_EARLY;
2142 if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2143 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2145 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2148 /* cancel remaining urbs and wait for their completion before
2149 * reporting results */
2150 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2153 usbi_mutex_unlock(&itransfer->lock);
2159 usbi_mutex_unlock(&itransfer->lock);
2160 return CANCELLED == tpriv->reap_action ?
2161 usbi_handle_transfer_cancellation(itransfer) :
2162 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2165 static int handle_iso_completion(struct usbi_transfer *itransfer,
2166 struct usbfs_urb *urb)
2168 struct libusb_transfer *transfer =
2169 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2170 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2171 int num_urbs = tpriv->num_urbs;
2174 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2176 usbi_mutex_lock(&itransfer->lock);
2177 for (i = 0; i < num_urbs; i++) {
2178 if (urb == tpriv->iso_urbs[i]) {
2184 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2185 usbi_mutex_unlock(&itransfer->lock);
2186 return LIBUSB_ERROR_NOT_FOUND;
2189 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2192 /* copy isochronous results back in */
2194 for (i = 0; i < urb->number_of_packets; i++) {
2195 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2196 struct libusb_iso_packet_descriptor *lib_desc =
2197 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2198 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2199 switch (urb_desc->status) {
2202 case -ENOENT: /* cancelled */
2207 usbi_dbg("device removed");
2208 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2211 usbi_dbg("detected endpoint stall");
2212 lib_desc->status = LIBUSB_TRANSFER_STALL;
2215 usbi_dbg("overflow error");
2216 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2224 usbi_dbg("low-level USB error %d", urb_desc->status);
2225 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2228 usbi_warn(TRANSFER_CTX(transfer),
2229 "unrecognised urb status %d", urb_desc->status);
2230 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2233 lib_desc->actual_length = urb_desc->actual_length;
2236 tpriv->num_retired++;
2238 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2239 usbi_dbg("CANCEL: urb status %d", urb->status);
2241 if (tpriv->num_retired == num_urbs) {
2242 usbi_dbg("CANCEL: last URB handled, reporting");
2243 free_iso_urbs(tpriv);
2244 if (tpriv->reap_action == CANCELLED) {
2245 usbi_mutex_unlock(&itransfer->lock);
2246 return usbi_handle_transfer_cancellation(itransfer);
2248 usbi_mutex_unlock(&itransfer->lock);
2249 return usbi_handle_transfer_completion(itransfer,
2250 LIBUSB_TRANSFER_ERROR);
2256 switch (urb->status) {
2259 case -ENOENT: /* cancelled */
2263 usbi_dbg("device removed");
2264 status = LIBUSB_TRANSFER_NO_DEVICE;
2267 usbi_warn(TRANSFER_CTX(transfer),
2268 "unrecognised urb status %d", urb->status);
2269 status = LIBUSB_TRANSFER_ERROR;
2273 /* if we're the last urb then we're done */
2274 if (urb_idx == num_urbs) {
2275 usbi_dbg("last URB in transfer --> complete!");
2276 free_iso_urbs(tpriv);
2277 usbi_mutex_unlock(&itransfer->lock);
2278 return usbi_handle_transfer_completion(itransfer, status);
2282 usbi_mutex_unlock(&itransfer->lock);
2286 static int handle_control_completion(struct usbi_transfer *itransfer,
2287 struct usbfs_urb *urb)
2289 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2292 usbi_mutex_lock(&itransfer->lock);
2293 usbi_dbg("handling completion status %d", urb->status);
2295 itransfer->transferred += urb->actual_length;
2297 if (tpriv->reap_action == CANCELLED) {
2298 if (urb->status != 0 && urb->status != -ENOENT)
2299 usbi_warn(ITRANSFER_CTX(itransfer),
2300 "cancel: unrecognised urb status %d", urb->status);
2303 usbi_mutex_unlock(&itransfer->lock);
2304 return usbi_handle_transfer_cancellation(itransfer);
2307 switch (urb->status) {
2309 status = LIBUSB_TRANSFER_COMPLETED;
2311 case -ENOENT: /* cancelled */
2312 status = LIBUSB_TRANSFER_CANCELLED;
2316 usbi_dbg("device removed");
2317 status = LIBUSB_TRANSFER_NO_DEVICE;
2320 usbi_dbg("unsupported control request");
2321 status = LIBUSB_TRANSFER_STALL;
2324 usbi_dbg("control overflow error");
2325 status = LIBUSB_TRANSFER_OVERFLOW;
2332 usbi_dbg("low-level bus error occurred");
2333 status = LIBUSB_TRANSFER_ERROR;
2336 usbi_warn(ITRANSFER_CTX(itransfer),
2337 "unrecognised urb status %d", urb->status);
2338 status = LIBUSB_TRANSFER_ERROR;
2344 usbi_mutex_unlock(&itransfer->lock);
2345 return usbi_handle_transfer_completion(itransfer, status);
2348 static int reap_for_handle(struct libusb_device_handle *handle)
2350 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2352 struct usbfs_urb *urb;
2353 struct usbi_transfer *itransfer;
2354 struct libusb_transfer *transfer;
2356 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2357 if (r == -1 && errno == EAGAIN)
2360 if (errno == ENODEV)
2361 return LIBUSB_ERROR_NO_DEVICE;
2363 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2365 return LIBUSB_ERROR_IO;
2368 itransfer = urb->usercontext;
2369 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2371 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2372 urb->actual_length);
2374 switch (transfer->type) {
2375 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2376 return handle_iso_completion(itransfer, urb);
2377 case LIBUSB_TRANSFER_TYPE_BULK:
2378 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2379 return handle_bulk_completion(itransfer, urb);
2380 case LIBUSB_TRANSFER_TYPE_CONTROL:
2381 return handle_control_completion(itransfer, urb);
2383 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2385 return LIBUSB_ERROR_OTHER;
2389 static int op_handle_events(struct libusb_context *ctx,
2390 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2395 usbi_mutex_lock(&ctx->open_devs_lock);
2396 for (i = 0; i < nfds && num_ready > 0; i++) {
2397 struct pollfd *pollfd = &fds[i];
2398 struct libusb_device_handle *handle;
2399 struct linux_device_handle_priv *hpriv = NULL;
2401 if (!pollfd->revents)
2405 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2406 hpriv = _device_handle_priv(handle);
2407 if (hpriv->fd == pollfd->fd)
2411 if (pollfd->revents & POLLERR) {
2412 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2413 usbi_handle_disconnect(handle);
2418 r = reap_for_handle(handle);
2420 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2428 usbi_mutex_unlock(&ctx->open_devs_lock);
2432 static int op_clock_gettime(int clk_id, struct timespec *tp)
2435 case USBI_CLOCK_MONOTONIC:
2436 return clock_gettime(monotonic_clkid, tp);
2437 case USBI_CLOCK_REALTIME:
2438 return clock_gettime(CLOCK_REALTIME, tp);
2440 return LIBUSB_ERROR_INVALID_PARAM;
2444 #ifdef USBI_TIMERFD_AVAILABLE
2445 static clockid_t op_get_timerfd_clockid(void)
2447 return monotonic_clkid;
2452 const struct usbi_os_backend linux_usbfs_backend = {
2453 .name = "Linux usbfs",
2454 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2457 .get_device_list = NULL,
2458 .get_device_descriptor = op_get_device_descriptor,
2459 .get_active_config_descriptor = op_get_active_config_descriptor,
2460 .get_config_descriptor = op_get_config_descriptor,
2461 .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2465 .get_configuration = op_get_configuration,
2466 .set_configuration = op_set_configuration,
2467 .claim_interface = op_claim_interface,
2468 .release_interface = op_release_interface,
2470 .set_interface_altsetting = op_set_interface,
2471 .clear_halt = op_clear_halt,
2472 .reset_device = op_reset_device,
2474 .kernel_driver_active = op_kernel_driver_active,
2475 .detach_kernel_driver = op_detach_kernel_driver,
2476 .attach_kernel_driver = op_attach_kernel_driver,
2478 .destroy_device = op_destroy_device,
2480 .submit_transfer = op_submit_transfer,
2481 .cancel_transfer = op_cancel_transfer,
2482 .clear_transfer_priv = op_clear_transfer_priv,
2484 .handle_events = op_handle_events,
2486 .clock_gettime = op_clock_gettime,
2488 #ifdef USBI_TIMERFD_AVAILABLE
2489 .get_timerfd_clockid = op_get_timerfd_clockid,
2492 .device_priv_size = sizeof(struct linux_device_priv),
2493 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2494 .transfer_priv_size = sizeof(struct linux_transfer_priv),
2495 .add_iso_packet_size = 0,