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 /* Serialize hotplug start/stop, scan-devices, event-thread, and poll */
124 usbi_mutex_static_t linux_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(&linux_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(&linux_hotplug_lock);
440 static void op_exit(void)
442 usbi_mutex_static_lock(&linux_hotplug_lock);
443 assert(init_count != 0);
445 /* tear down event handler */
446 (void)linux_stop_event_monitor();
448 usbi_mutex_static_unlock(&linux_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 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1060 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1062 usbi_mutex_static_unlock(&active_contexts_lock);
1065 void linux_hotplug_disconnected(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1067 struct libusb_context *ctx;
1068 struct libusb_device *dev;
1069 unsigned long session_id = busnum << 8 | devaddr;
1071 usbi_mutex_static_lock(&active_contexts_lock);
1072 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1073 dev = usbi_get_device_by_session_id (ctx, session_id);
1075 usbi_disconnect_device (dev);
1077 usbi_dbg("device not found for session %x", session_id);
1080 usbi_mutex_static_unlock(&active_contexts_lock);
1083 #if !defined(USE_UDEV)
1084 /* open a bus directory and adds all discovered devices to the context */
1085 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1088 char dirpath[PATH_MAX];
1089 struct dirent *entry;
1090 int r = LIBUSB_ERROR_IO;
1092 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1093 usbi_dbg("%s", dirpath);
1094 dir = opendir(dirpath);
1096 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1097 /* FIXME: should handle valid race conditions like hub unplugged
1098 * during directory iteration - this is not an error */
1102 while ((entry = readdir(dir))) {
1105 if (entry->d_name[0] == '.')
1108 devaddr = atoi(entry->d_name);
1110 usbi_dbg("unknown dir entry %s", entry->d_name);
1114 if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1115 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1126 static int usbfs_get_device_list(struct libusb_context *ctx)
1128 struct dirent *entry;
1129 DIR *buses = opendir(usbfs_path);
1133 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1134 return LIBUSB_ERROR_IO;
1137 while ((entry = readdir(buses))) {
1140 if (entry->d_name[0] == '.')
1145 if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1148 r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
1150 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1154 busnum = atoi(entry->d_name);
1156 usbi_dbg("unknown dir entry %s", entry->d_name);
1160 r = usbfs_scan_busdir(ctx, busnum);
1172 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
1174 uint8_t busnum, devaddr;
1177 ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname);
1178 if (LIBUSB_SUCCESS != ret) {
1182 return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff,
1186 #if !defined(USE_UDEV)
1187 static int sysfs_get_device_list(struct libusb_context *ctx)
1189 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1190 struct dirent *entry;
1191 int r = LIBUSB_ERROR_IO;
1194 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1198 while ((entry = readdir(devices))) {
1199 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1200 || strchr(entry->d_name, ':'))
1203 if (sysfs_scan_device(ctx, entry->d_name)) {
1204 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1215 static int linux_default_scan_devices (struct libusb_context *ctx)
1217 /* we can retrieve device list and descriptors from sysfs or usbfs.
1218 * sysfs is preferable, because if we use usbfs we end up resuming
1219 * any autosuspended USB devices. however, sysfs is not available
1220 * everywhere, so we need a usbfs fallback too.
1222 * as described in the "sysfs vs usbfs" comment at the top of this
1223 * file, sometimes we have sysfs but not enough information to
1224 * relate sysfs devices to usbfs nodes. op_init() determines the
1225 * adequacy of sysfs and sets sysfs_can_relate_devices.
1227 if (sysfs_can_relate_devices != 0)
1228 return sysfs_get_device_list(ctx);
1230 return usbfs_get_device_list(ctx);
1234 static int op_open(struct libusb_device_handle *handle)
1236 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1239 hpriv->fd = _get_usbfs_fd(handle->dev, O_RDWR, 0);
1243 r = ioctl(hpriv->fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1245 if (errno == ENOTTY)
1246 usbi_dbg("getcap not available");
1248 usbi_err(HANDLE_CTX(handle), "getcap failed (%d)", errno);
1250 if (supports_flag_zero_packet)
1251 hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1252 if (supports_flag_bulk_continuation)
1253 hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1256 return usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1259 static void op_close(struct libusb_device_handle *dev_handle)
1261 int fd = _device_handle_priv(dev_handle)->fd;
1262 usbi_remove_pollfd(HANDLE_CTX(dev_handle), fd);
1266 static int op_get_configuration(struct libusb_device_handle *handle,
1271 if (sysfs_can_relate_devices) {
1272 r = sysfs_get_active_config(handle->dev, config);
1274 r = usbfs_get_active_config(handle->dev,
1275 _device_handle_priv(handle)->fd);
1280 if (*config == -1) {
1281 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1288 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1290 struct linux_device_priv *priv = _device_priv(handle->dev);
1291 int fd = _device_handle_priv(handle)->fd;
1292 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1294 if (errno == EINVAL)
1295 return LIBUSB_ERROR_NOT_FOUND;
1296 else if (errno == EBUSY)
1297 return LIBUSB_ERROR_BUSY;
1298 else if (errno == ENODEV)
1299 return LIBUSB_ERROR_NO_DEVICE;
1301 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1302 return LIBUSB_ERROR_OTHER;
1305 /* update our cached active config descriptor */
1306 priv->active_config = config;
1308 return LIBUSB_SUCCESS;
1311 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1313 int fd = _device_handle_priv(handle)->fd;
1314 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1316 if (errno == ENOENT)
1317 return LIBUSB_ERROR_NOT_FOUND;
1318 else if (errno == EBUSY)
1319 return LIBUSB_ERROR_BUSY;
1320 else if (errno == ENODEV)
1321 return LIBUSB_ERROR_NO_DEVICE;
1323 usbi_err(HANDLE_CTX(handle),
1324 "claim interface failed, error %d errno %d", r, errno);
1325 return LIBUSB_ERROR_OTHER;
1330 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1332 int fd = _device_handle_priv(handle)->fd;
1333 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1335 if (errno == ENODEV)
1336 return LIBUSB_ERROR_NO_DEVICE;
1338 usbi_err(HANDLE_CTX(handle),
1339 "release interface failed, error %d errno %d", r, errno);
1340 return LIBUSB_ERROR_OTHER;
1345 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1348 int fd = _device_handle_priv(handle)->fd;
1349 struct usbfs_setinterface setintf;
1352 setintf.interface = iface;
1353 setintf.altsetting = altsetting;
1354 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1356 if (errno == EINVAL)
1357 return LIBUSB_ERROR_NOT_FOUND;
1358 else if (errno == ENODEV)
1359 return LIBUSB_ERROR_NO_DEVICE;
1361 usbi_err(HANDLE_CTX(handle),
1362 "setintf failed error %d errno %d", r, errno);
1363 return LIBUSB_ERROR_OTHER;
1369 static int op_clear_halt(struct libusb_device_handle *handle,
1370 unsigned char endpoint)
1372 int fd = _device_handle_priv(handle)->fd;
1373 unsigned int _endpoint = endpoint;
1374 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1376 if (errno == ENOENT)
1377 return LIBUSB_ERROR_NOT_FOUND;
1378 else if (errno == ENODEV)
1379 return LIBUSB_ERROR_NO_DEVICE;
1381 usbi_err(HANDLE_CTX(handle),
1382 "clear_halt failed error %d errno %d", r, errno);
1383 return LIBUSB_ERROR_OTHER;
1389 static int op_reset_device(struct libusb_device_handle *handle)
1391 int fd = _device_handle_priv(handle)->fd;
1394 /* Doing a device reset will cause the usbfs driver to get unbound
1395 from any interfaces it is bound to. By voluntarily unbinding
1396 the usbfs driver ourself, we stop the kernel from rebinding
1397 the interface after reset (which would end up with the interface
1398 getting bound to the in kernel driver if any). */
1399 for (i = 0; i < USB_MAXINTERFACES; i++) {
1400 if (handle->claimed_interfaces & (1L << i)) {
1401 op_release_interface(handle, i);
1405 usbi_mutex_lock(&handle->lock);
1406 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1408 if (errno == ENODEV) {
1409 ret = LIBUSB_ERROR_NOT_FOUND;
1413 usbi_err(HANDLE_CTX(handle),
1414 "reset failed error %d errno %d", r, errno);
1415 ret = LIBUSB_ERROR_OTHER;
1419 /* And re-claim any interfaces which were claimed before the reset */
1420 for (i = 0; i < USB_MAXINTERFACES; i++) {
1421 if (handle->claimed_interfaces & (1L << i)) {
1422 r = op_claim_interface(handle, i);
1424 usbi_warn(HANDLE_CTX(handle),
1425 "failed to re-claim interface %d after reset", i);
1426 handle->claimed_interfaces &= ~(1L << i);
1431 usbi_mutex_unlock(&handle->lock);
1435 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1438 int fd = _device_handle_priv(handle)->fd;
1439 struct usbfs_getdriver getdrv;
1442 getdrv.interface = interface;
1443 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1445 if (errno == ENODATA)
1447 else if (errno == ENODEV)
1448 return LIBUSB_ERROR_NO_DEVICE;
1450 usbi_err(HANDLE_CTX(handle),
1451 "get driver failed error %d errno %d", r, errno);
1452 return LIBUSB_ERROR_OTHER;
1458 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1461 int fd = _device_handle_priv(handle)->fd;
1462 struct usbfs_ioctl command;
1463 struct usbfs_getdriver getdrv;
1466 command.ifno = interface;
1467 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1468 command.data = NULL;
1470 getdrv.interface = interface;
1471 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1472 if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1473 return LIBUSB_ERROR_NOT_FOUND;
1475 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1477 if (errno == ENODATA)
1478 return LIBUSB_ERROR_NOT_FOUND;
1479 else if (errno == EINVAL)
1480 return LIBUSB_ERROR_INVALID_PARAM;
1481 else if (errno == ENODEV)
1482 return LIBUSB_ERROR_NO_DEVICE;
1484 usbi_err(HANDLE_CTX(handle),
1485 "detach failed error %d errno %d", r, errno);
1486 return LIBUSB_ERROR_OTHER;
1492 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1495 int fd = _device_handle_priv(handle)->fd;
1496 struct usbfs_ioctl command;
1499 command.ifno = interface;
1500 command.ioctl_code = IOCTL_USBFS_CONNECT;
1501 command.data = NULL;
1503 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1505 if (errno == ENODATA)
1506 return LIBUSB_ERROR_NOT_FOUND;
1507 else if (errno == EINVAL)
1508 return LIBUSB_ERROR_INVALID_PARAM;
1509 else if (errno == ENODEV)
1510 return LIBUSB_ERROR_NO_DEVICE;
1511 else if (errno == EBUSY)
1512 return LIBUSB_ERROR_BUSY;
1514 usbi_err(HANDLE_CTX(handle),
1515 "attach failed error %d errno %d", r, errno);
1516 return LIBUSB_ERROR_OTHER;
1517 } else if (r == 0) {
1518 return LIBUSB_ERROR_NOT_FOUND;
1524 static void op_destroy_device(struct libusb_device *dev)
1526 struct linux_device_priv *priv = _device_priv(dev);
1527 if (priv->descriptors)
1528 free(priv->descriptors);
1529 if (priv->sysfs_dir)
1530 free(priv->sysfs_dir);
1533 /* URBs are discarded in reverse order of submission to avoid races. */
1534 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1536 struct libusb_transfer *transfer =
1537 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1538 struct linux_transfer_priv *tpriv =
1539 usbi_transfer_get_os_priv(itransfer);
1540 struct linux_device_handle_priv *dpriv =
1541 _device_handle_priv(transfer->dev_handle);
1543 struct usbfs_urb *urb;
1545 for (i = last_plus_one - 1; i >= first; i--) {
1546 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
1547 urb = tpriv->iso_urbs[i];
1549 urb = &tpriv->urbs[i];
1551 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
1554 if (EINVAL == errno) {
1555 usbi_dbg("URB not found --> assuming ready to be reaped");
1556 if (i == (last_plus_one - 1))
1557 ret = LIBUSB_ERROR_NOT_FOUND;
1558 } else if (ENODEV == errno) {
1559 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1560 ret = LIBUSB_ERROR_NO_DEVICE;
1562 usbi_warn(TRANSFER_CTX(transfer),
1563 "unrecognised discard errno %d", errno);
1564 ret = LIBUSB_ERROR_OTHER;
1570 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1573 for (i = 0; i < tpriv->num_urbs; i++) {
1574 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1580 free(tpriv->iso_urbs);
1581 tpriv->iso_urbs = NULL;
1584 static int submit_bulk_transfer(struct usbi_transfer *itransfer,
1585 unsigned char urb_type)
1587 struct libusb_transfer *transfer =
1588 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1589 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1590 struct linux_device_handle_priv *dpriv =
1591 _device_handle_priv(transfer->dev_handle);
1592 struct usbfs_urb *urbs;
1593 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1594 == LIBUSB_ENDPOINT_OUT;
1595 int bulk_buffer_len, use_bulk_continuation;
1601 return LIBUSB_ERROR_BUSY;
1603 if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1604 !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
1605 return LIBUSB_ERROR_NOT_SUPPORTED;
1608 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1609 * around this by splitting large transfers into 16k blocks, and then
1610 * submit all urbs at once. it would be simpler to submit one urb at
1611 * a time, but there is a big performance gain doing it this way.
1613 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1614 * using arbritary large transfers can still be a bad idea though, as
1615 * the kernel needs to allocate physical contiguous memory for this,
1616 * which may fail for large buffers.
1618 * The kernel solves this problem by splitting the transfer into
1619 * blocks itself when the host-controller is scatter-gather capable
1620 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1622 * Last, there is the issue of short-transfers when splitting, for
1623 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1624 * is needed, but this is not always available.
1626 if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1627 /* Good! Just submit everything in one go */
1628 bulk_buffer_len = transfer->length ? transfer->length : 1;
1629 use_bulk_continuation = 0;
1630 } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1631 /* Split the transfers and use bulk-continuation to
1632 avoid issues with short-transfers */
1633 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1634 use_bulk_continuation = 1;
1635 } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1636 /* Don't split, assume the kernel can alloc the buffer
1637 (otherwise the submit will fail with -ENOMEM) */
1638 bulk_buffer_len = transfer->length ? transfer->length : 1;
1639 use_bulk_continuation = 0;
1641 /* Bad, splitting without bulk-continuation, short transfers
1642 which end before the last urb will not work reliable! */
1643 /* Note we don't warn here as this is "normal" on kernels <
1644 2.6.32 and not a problem for most applications */
1645 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1646 use_bulk_continuation = 0;
1649 int num_urbs = transfer->length / bulk_buffer_len;
1650 int last_urb_partial = 0;
1652 if (transfer->length == 0) {
1654 } else if ((transfer->length % bulk_buffer_len) > 0) {
1655 last_urb_partial = 1;
1658 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
1660 alloc_size = num_urbs * sizeof(struct usbfs_urb);
1661 urbs = calloc(1, alloc_size);
1663 return LIBUSB_ERROR_NO_MEM;
1665 tpriv->num_urbs = num_urbs;
1666 tpriv->num_retired = 0;
1667 tpriv->reap_action = NORMAL;
1668 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1670 for (i = 0; i < num_urbs; i++) {
1671 struct usbfs_urb *urb = &urbs[i];
1672 urb->usercontext = itransfer;
1673 urb->type = urb_type;
1674 urb->endpoint = transfer->endpoint;
1675 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
1676 /* don't set the short not ok flag for the last URB */
1677 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
1678 urb->flags = USBFS_URB_SHORT_NOT_OK;
1679 if (i == num_urbs - 1 && last_urb_partial)
1680 urb->buffer_length = transfer->length % bulk_buffer_len;
1681 else if (transfer->length == 0)
1682 urb->buffer_length = 0;
1684 urb->buffer_length = bulk_buffer_len;
1686 if (i > 0 && use_bulk_continuation)
1687 urb->flags |= USBFS_URB_BULK_CONTINUATION;
1689 /* we have already checked that the flag is supported */
1690 if (is_out && i == num_urbs - 1 &&
1691 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
1692 urb->flags |= USBFS_URB_ZERO_PACKET;
1694 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1696 if (errno == ENODEV) {
1697 r = LIBUSB_ERROR_NO_DEVICE;
1699 usbi_err(TRANSFER_CTX(transfer),
1700 "submiturb failed error %d errno=%d", r, errno);
1701 r = LIBUSB_ERROR_IO;
1704 /* if the first URB submission fails, we can simply free up and
1705 * return failure immediately. */
1707 usbi_dbg("first URB failed, easy peasy");
1713 /* if it's not the first URB that failed, the situation is a bit
1714 * tricky. we may need to discard all previous URBs. there are
1716 * - discarding is asynchronous - discarded urbs will be reaped
1717 * later. the user must not have freed the transfer when the
1718 * discarded URBs are reaped, otherwise libusbx will be using
1720 * - the earlier URBs may have completed successfully and we do
1721 * not want to throw away any data.
1722 * - this URB failing may be no error; EREMOTEIO means that
1723 * this transfer simply didn't need all the URBs we submitted
1724 * so, we report that the transfer was submitted successfully and
1725 * in case of error we discard all previous URBs. later when
1726 * the final reap completes we can report error to the user,
1727 * or success if an earlier URB was completed successfully.
1729 tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
1731 /* The URBs we haven't submitted yet we count as already
1733 tpriv->num_retired += num_urbs - i;
1735 /* If we completed short then don't try to discard. */
1736 if (COMPLETED_EARLY == tpriv->reap_action)
1739 discard_urbs(itransfer, 0, i);
1741 usbi_dbg("reporting successful submission but waiting for %d "
1742 "discards before reporting error", i);
1750 static int submit_iso_transfer(struct usbi_transfer *itransfer)
1752 struct libusb_transfer *transfer =
1753 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1754 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1755 struct linux_device_handle_priv *dpriv =
1756 _device_handle_priv(transfer->dev_handle);
1757 struct usbfs_urb **urbs;
1759 int num_packets = transfer->num_iso_packets;
1761 int this_urb_len = 0;
1763 int packet_offset = 0;
1764 unsigned int packet_len;
1765 unsigned char *urb_buffer = transfer->buffer;
1767 if (tpriv->iso_urbs)
1768 return LIBUSB_ERROR_BUSY;
1770 /* usbfs places a 32kb limit on iso URBs. we divide up larger requests
1771 * into smaller units to meet such restriction, then fire off all the
1772 * units at once. it would be simpler if we just fired one unit at a time,
1773 * but there is a big performance gain through doing it this way.
1775 * Newer kernels lift the 32k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1776 * using arbritary large transfers is still be a bad idea though, as
1777 * the kernel needs to allocate physical contiguous memory for this,
1778 * which may fail for large buffers.
1781 /* calculate how many URBs we need */
1782 for (i = 0; i < num_packets; i++) {
1783 unsigned int space_remaining = MAX_ISO_BUFFER_LENGTH - this_urb_len;
1784 packet_len = transfer->iso_packet_desc[i].length;
1786 if (packet_len > space_remaining) {
1788 this_urb_len = packet_len;
1790 this_urb_len += packet_len;
1793 usbi_dbg("need %d 32k URBs for transfer", num_urbs);
1795 alloc_size = num_urbs * sizeof(*urbs);
1796 urbs = calloc(1, alloc_size);
1798 return LIBUSB_ERROR_NO_MEM;
1800 tpriv->iso_urbs = urbs;
1801 tpriv->num_urbs = num_urbs;
1802 tpriv->num_retired = 0;
1803 tpriv->reap_action = NORMAL;
1804 tpriv->iso_packet_offset = 0;
1806 /* allocate + initialize each URB with the correct number of packets */
1807 for (i = 0; i < num_urbs; i++) {
1808 struct usbfs_urb *urb;
1809 unsigned int space_remaining_in_urb = MAX_ISO_BUFFER_LENGTH;
1810 int urb_packet_offset = 0;
1811 unsigned char *urb_buffer_orig = urb_buffer;
1815 /* swallow up all the packets we can fit into this URB */
1816 while (packet_offset < transfer->num_iso_packets) {
1817 packet_len = transfer->iso_packet_desc[packet_offset].length;
1818 if (packet_len <= space_remaining_in_urb) {
1820 urb_packet_offset++;
1822 space_remaining_in_urb -= packet_len;
1823 urb_buffer += packet_len;
1825 /* it can't fit, save it for the next URB */
1830 alloc_size = sizeof(*urb)
1831 + (urb_packet_offset * sizeof(struct usbfs_iso_packet_desc));
1832 urb = calloc(1, alloc_size);
1834 free_iso_urbs(tpriv);
1835 return LIBUSB_ERROR_NO_MEM;
1839 /* populate packet lengths */
1840 for (j = 0, k = packet_offset - urb_packet_offset;
1841 k < packet_offset; k++, j++) {
1842 packet_len = transfer->iso_packet_desc[k].length;
1843 urb->iso_frame_desc[j].length = packet_len;
1846 urb->usercontext = itransfer;
1847 urb->type = USBFS_URB_TYPE_ISO;
1848 /* FIXME: interface for non-ASAP data? */
1849 urb->flags = USBFS_URB_ISO_ASAP;
1850 urb->endpoint = transfer->endpoint;
1851 urb->number_of_packets = urb_packet_offset;
1852 urb->buffer = urb_buffer_orig;
1856 for (i = 0; i < num_urbs; i++) {
1857 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
1859 if (errno == ENODEV) {
1860 r = LIBUSB_ERROR_NO_DEVICE;
1862 usbi_err(TRANSFER_CTX(transfer),
1863 "submiturb failed error %d errno=%d", r, errno);
1864 r = LIBUSB_ERROR_IO;
1867 /* if the first URB submission fails, we can simply free up and
1868 * return failure immediately. */
1870 usbi_dbg("first URB failed, easy peasy");
1871 free_iso_urbs(tpriv);
1875 /* if it's not the first URB that failed, the situation is a bit
1876 * tricky. we must discard all previous URBs. there are
1878 * - discarding is asynchronous - discarded urbs will be reaped
1879 * later. the user must not have freed the transfer when the
1880 * discarded URBs are reaped, otherwise libusbx will be using
1882 * - the earlier URBs may have completed successfully and we do
1883 * not want to throw away any data.
1884 * so, in this case we discard all the previous URBs BUT we report
1885 * that the transfer was submitted successfully. then later when
1886 * the final discard completes we can report error to the user.
1888 tpriv->reap_action = SUBMIT_FAILED;
1890 /* The URBs we haven't submitted yet we count as already
1892 tpriv->num_retired = num_urbs - i;
1893 discard_urbs(itransfer, 0, i);
1895 usbi_dbg("reporting successful submission but waiting for %d "
1896 "discards before reporting error", i);
1904 static int submit_control_transfer(struct usbi_transfer *itransfer)
1906 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1907 struct libusb_transfer *transfer =
1908 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1909 struct linux_device_handle_priv *dpriv =
1910 _device_handle_priv(transfer->dev_handle);
1911 struct usbfs_urb *urb;
1915 return LIBUSB_ERROR_BUSY;
1917 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
1918 return LIBUSB_ERROR_INVALID_PARAM;
1920 urb = calloc(1, sizeof(struct usbfs_urb));
1922 return LIBUSB_ERROR_NO_MEM;
1924 tpriv->num_urbs = 1;
1925 tpriv->reap_action = NORMAL;
1927 urb->usercontext = itransfer;
1928 urb->type = USBFS_URB_TYPE_CONTROL;
1929 urb->endpoint = transfer->endpoint;
1930 urb->buffer = transfer->buffer;
1931 urb->buffer_length = transfer->length;
1933 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1937 if (errno == ENODEV)
1938 return LIBUSB_ERROR_NO_DEVICE;
1940 usbi_err(TRANSFER_CTX(transfer),
1941 "submiturb failed error %d errno=%d", r, errno);
1942 return LIBUSB_ERROR_IO;
1947 static int op_submit_transfer(struct usbi_transfer *itransfer)
1949 struct libusb_transfer *transfer =
1950 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1952 switch (transfer->type) {
1953 case LIBUSB_TRANSFER_TYPE_CONTROL:
1954 return submit_control_transfer(itransfer);
1955 case LIBUSB_TRANSFER_TYPE_BULK:
1956 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_BULK);
1957 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1958 return submit_bulk_transfer(itransfer, USBFS_URB_TYPE_INTERRUPT);
1959 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1960 return submit_iso_transfer(itransfer);
1962 usbi_err(TRANSFER_CTX(transfer),
1963 "unknown endpoint type %d", transfer->type);
1964 return LIBUSB_ERROR_INVALID_PARAM;
1968 static int op_cancel_transfer(struct usbi_transfer *itransfer)
1970 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1971 struct libusb_transfer *transfer =
1972 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1974 switch (transfer->type) {
1975 case LIBUSB_TRANSFER_TYPE_BULK:
1976 if (tpriv->reap_action == ERROR)
1978 /* else, fall through */
1979 case LIBUSB_TRANSFER_TYPE_CONTROL:
1980 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1981 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
1982 tpriv->reap_action = CANCELLED;
1985 usbi_err(TRANSFER_CTX(transfer),
1986 "unknown endpoint type %d", transfer->type);
1987 return LIBUSB_ERROR_INVALID_PARAM;
1991 return LIBUSB_ERROR_NOT_FOUND;
1993 return discard_urbs(itransfer, 0, tpriv->num_urbs);
1996 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
1998 struct libusb_transfer *transfer =
1999 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2000 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2002 /* urbs can be freed also in submit_transfer so lock mutex first */
2003 switch (transfer->type) {
2004 case LIBUSB_TRANSFER_TYPE_CONTROL:
2005 case LIBUSB_TRANSFER_TYPE_BULK:
2006 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2007 usbi_mutex_lock(&itransfer->lock);
2011 usbi_mutex_unlock(&itransfer->lock);
2013 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2014 usbi_mutex_lock(&itransfer->lock);
2015 if (tpriv->iso_urbs)
2016 free_iso_urbs(tpriv);
2017 usbi_mutex_unlock(&itransfer->lock);
2020 usbi_err(TRANSFER_CTX(transfer),
2021 "unknown endpoint type %d", transfer->type);
2025 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2026 struct usbfs_urb *urb)
2028 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2029 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2030 int urb_idx = urb - tpriv->urbs;
2032 usbi_mutex_lock(&itransfer->lock);
2033 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2034 urb_idx + 1, tpriv->num_urbs);
2036 tpriv->num_retired++;
2038 if (tpriv->reap_action != NORMAL) {
2039 /* cancelled, submit_fail, or completed early */
2040 usbi_dbg("abnormal reap: urb status %d", urb->status);
2042 /* even though we're in the process of cancelling, it's possible that
2043 * we may receive some data in these URBs that we don't want to lose.
2045 * 1. while the kernel is cancelling all the packets that make up an
2046 * URB, a few of them might complete. so we get back a successful
2047 * cancellation *and* some data.
2048 * 2. we receive a short URB which marks the early completion condition,
2049 * so we start cancelling the remaining URBs. however, we're too
2050 * slow and another URB completes (or at least completes partially).
2051 * (this can't happen since we always use BULK_CONTINUATION.)
2053 * When this happens, our objectives are not to lose any "surplus" data,
2054 * and also to stick it at the end of the previously-received data
2055 * (closing any holes), so that libusbx reports the total amount of
2056 * transferred data and presents it in a contiguous chunk.
2058 if (urb->actual_length > 0) {
2059 unsigned char *target = transfer->buffer + itransfer->transferred;
2060 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2061 if (urb->buffer != target) {
2062 usbi_dbg("moving surplus data from offset %d to offset %d",
2063 (unsigned char *) urb->buffer - transfer->buffer,
2064 target - transfer->buffer);
2065 memmove(target, urb->buffer, urb->actual_length);
2067 itransfer->transferred += urb->actual_length;
2070 if (tpriv->num_retired == tpriv->num_urbs) {
2071 usbi_dbg("abnormal reap: last URB handled, reporting");
2072 if (tpriv->reap_action != COMPLETED_EARLY &&
2073 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2074 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2080 itransfer->transferred += urb->actual_length;
2082 /* Many of these errors can occur on *any* urb of a multi-urb
2083 * transfer. When they do, we tear down the rest of the transfer.
2085 switch (urb->status) {
2088 case -EREMOTEIO: /* short transfer */
2090 case -ENOENT: /* cancelled */
2095 usbi_dbg("device removed");
2096 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2097 goto cancel_remaining;
2099 usbi_dbg("detected endpoint stall");
2100 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2101 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2102 goto cancel_remaining;
2104 /* overflow can only ever occur in the last urb */
2105 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2106 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2107 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2114 usbi_dbg("low level error %d", urb->status);
2115 tpriv->reap_action = ERROR;
2116 goto cancel_remaining;
2118 usbi_warn(ITRANSFER_CTX(itransfer),
2119 "unrecognised urb status %d", urb->status);
2120 tpriv->reap_action = ERROR;
2121 goto cancel_remaining;
2124 /* if we're the last urb or we got less data than requested then we're
2126 if (urb_idx == tpriv->num_urbs - 1) {
2127 usbi_dbg("last URB in transfer --> complete!");
2129 } else if (urb->actual_length < urb->buffer_length) {
2130 usbi_dbg("short transfer %d/%d --> complete!",
2131 urb->actual_length, urb->buffer_length);
2132 if (tpriv->reap_action == NORMAL)
2133 tpriv->reap_action = COMPLETED_EARLY;
2138 if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2139 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2141 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2144 /* cancel remaining urbs and wait for their completion before
2145 * reporting results */
2146 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2149 usbi_mutex_unlock(&itransfer->lock);
2155 usbi_mutex_unlock(&itransfer->lock);
2156 return CANCELLED == tpriv->reap_action ?
2157 usbi_handle_transfer_cancellation(itransfer) :
2158 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2161 static int handle_iso_completion(struct usbi_transfer *itransfer,
2162 struct usbfs_urb *urb)
2164 struct libusb_transfer *transfer =
2165 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2166 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2167 int num_urbs = tpriv->num_urbs;
2170 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2172 usbi_mutex_lock(&itransfer->lock);
2173 for (i = 0; i < num_urbs; i++) {
2174 if (urb == tpriv->iso_urbs[i]) {
2180 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2181 usbi_mutex_unlock(&itransfer->lock);
2182 return LIBUSB_ERROR_NOT_FOUND;
2185 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2188 /* copy isochronous results back in */
2190 for (i = 0; i < urb->number_of_packets; i++) {
2191 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2192 struct libusb_iso_packet_descriptor *lib_desc =
2193 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2194 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2195 switch (urb_desc->status) {
2198 case -ENOENT: /* cancelled */
2203 usbi_dbg("device removed");
2204 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2207 usbi_dbg("detected endpoint stall");
2208 lib_desc->status = LIBUSB_TRANSFER_STALL;
2211 usbi_dbg("overflow error");
2212 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2220 usbi_dbg("low-level USB error %d", urb_desc->status);
2221 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2224 usbi_warn(TRANSFER_CTX(transfer),
2225 "unrecognised urb status %d", urb_desc->status);
2226 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2229 lib_desc->actual_length = urb_desc->actual_length;
2232 tpriv->num_retired++;
2234 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2235 usbi_dbg("CANCEL: urb status %d", urb->status);
2237 if (tpriv->num_retired == num_urbs) {
2238 usbi_dbg("CANCEL: last URB handled, reporting");
2239 free_iso_urbs(tpriv);
2240 if (tpriv->reap_action == CANCELLED) {
2241 usbi_mutex_unlock(&itransfer->lock);
2242 return usbi_handle_transfer_cancellation(itransfer);
2244 usbi_mutex_unlock(&itransfer->lock);
2245 return usbi_handle_transfer_completion(itransfer,
2246 LIBUSB_TRANSFER_ERROR);
2252 switch (urb->status) {
2255 case -ENOENT: /* cancelled */
2259 usbi_dbg("device removed");
2260 status = LIBUSB_TRANSFER_NO_DEVICE;
2263 usbi_warn(TRANSFER_CTX(transfer),
2264 "unrecognised urb status %d", urb->status);
2265 status = LIBUSB_TRANSFER_ERROR;
2269 /* if we're the last urb then we're done */
2270 if (urb_idx == num_urbs) {
2271 usbi_dbg("last URB in transfer --> complete!");
2272 free_iso_urbs(tpriv);
2273 usbi_mutex_unlock(&itransfer->lock);
2274 return usbi_handle_transfer_completion(itransfer, status);
2278 usbi_mutex_unlock(&itransfer->lock);
2282 static int handle_control_completion(struct usbi_transfer *itransfer,
2283 struct usbfs_urb *urb)
2285 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2288 usbi_mutex_lock(&itransfer->lock);
2289 usbi_dbg("handling completion status %d", urb->status);
2291 itransfer->transferred += urb->actual_length;
2293 if (tpriv->reap_action == CANCELLED) {
2294 if (urb->status != 0 && urb->status != -ENOENT)
2295 usbi_warn(ITRANSFER_CTX(itransfer),
2296 "cancel: unrecognised urb status %d", urb->status);
2299 usbi_mutex_unlock(&itransfer->lock);
2300 return usbi_handle_transfer_cancellation(itransfer);
2303 switch (urb->status) {
2305 status = LIBUSB_TRANSFER_COMPLETED;
2307 case -ENOENT: /* cancelled */
2308 status = LIBUSB_TRANSFER_CANCELLED;
2312 usbi_dbg("device removed");
2313 status = LIBUSB_TRANSFER_NO_DEVICE;
2316 usbi_dbg("unsupported control request");
2317 status = LIBUSB_TRANSFER_STALL;
2320 usbi_dbg("control overflow error");
2321 status = LIBUSB_TRANSFER_OVERFLOW;
2328 usbi_dbg("low-level bus error occurred");
2329 status = LIBUSB_TRANSFER_ERROR;
2332 usbi_warn(ITRANSFER_CTX(itransfer),
2333 "unrecognised urb status %d", urb->status);
2334 status = LIBUSB_TRANSFER_ERROR;
2340 usbi_mutex_unlock(&itransfer->lock);
2341 return usbi_handle_transfer_completion(itransfer, status);
2344 static int reap_for_handle(struct libusb_device_handle *handle)
2346 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2348 struct usbfs_urb *urb;
2349 struct usbi_transfer *itransfer;
2350 struct libusb_transfer *transfer;
2352 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2353 if (r == -1 && errno == EAGAIN)
2356 if (errno == ENODEV)
2357 return LIBUSB_ERROR_NO_DEVICE;
2359 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2361 return LIBUSB_ERROR_IO;
2364 itransfer = urb->usercontext;
2365 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2367 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2368 urb->actual_length);
2370 switch (transfer->type) {
2371 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2372 return handle_iso_completion(itransfer, urb);
2373 case LIBUSB_TRANSFER_TYPE_BULK:
2374 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2375 return handle_bulk_completion(itransfer, urb);
2376 case LIBUSB_TRANSFER_TYPE_CONTROL:
2377 return handle_control_completion(itransfer, urb);
2379 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2381 return LIBUSB_ERROR_OTHER;
2385 static int op_handle_events(struct libusb_context *ctx,
2386 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2391 usbi_mutex_lock(&ctx->open_devs_lock);
2392 for (i = 0; i < nfds && num_ready > 0; i++) {
2393 struct pollfd *pollfd = &fds[i];
2394 struct libusb_device_handle *handle;
2395 struct linux_device_handle_priv *hpriv = NULL;
2397 if (!pollfd->revents)
2401 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2402 hpriv = _device_handle_priv(handle);
2403 if (hpriv->fd == pollfd->fd)
2407 if (pollfd->revents & POLLERR) {
2408 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2409 usbi_handle_disconnect(handle);
2414 r = reap_for_handle(handle);
2416 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2424 usbi_mutex_unlock(&ctx->open_devs_lock);
2428 static int op_clock_gettime(int clk_id, struct timespec *tp)
2431 case USBI_CLOCK_MONOTONIC:
2432 return clock_gettime(monotonic_clkid, tp);
2433 case USBI_CLOCK_REALTIME:
2434 return clock_gettime(CLOCK_REALTIME, tp);
2436 return LIBUSB_ERROR_INVALID_PARAM;
2440 #ifdef USBI_TIMERFD_AVAILABLE
2441 static clockid_t op_get_timerfd_clockid(void)
2443 return monotonic_clkid;
2448 const struct usbi_os_backend linux_usbfs_backend = {
2449 .name = "Linux usbfs",
2450 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2453 .get_device_list = NULL,
2454 .get_device_descriptor = op_get_device_descriptor,
2455 .get_active_config_descriptor = op_get_active_config_descriptor,
2456 .get_config_descriptor = op_get_config_descriptor,
2457 .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2461 .get_configuration = op_get_configuration,
2462 .set_configuration = op_set_configuration,
2463 .claim_interface = op_claim_interface,
2464 .release_interface = op_release_interface,
2466 .set_interface_altsetting = op_set_interface,
2467 .clear_halt = op_clear_halt,
2468 .reset_device = op_reset_device,
2470 .kernel_driver_active = op_kernel_driver_active,
2471 .detach_kernel_driver = op_detach_kernel_driver,
2472 .attach_kernel_driver = op_attach_kernel_driver,
2474 .destroy_device = op_destroy_device,
2476 .submit_transfer = op_submit_transfer,
2477 .cancel_transfer = op_cancel_transfer,
2478 .clear_transfer_priv = op_clear_transfer_priv,
2480 .handle_events = op_handle_events,
2482 .clock_gettime = op_clock_gettime,
2484 #ifdef USBI_TIMERFD_AVAILABLE
2485 .get_timerfd_clockid = op_get_timerfd_clockid,
2488 .device_priv_size = sizeof(struct linux_device_priv),
2489 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2490 .transfer_priv_size = sizeof(struct linux_transfer_priv),
2491 .add_iso_packet_size = 0,