1 /* -*- Mode: C; c-basic-offset:8 ; indent-tabs-mode:t -*- */
3 * Linux usbfs backend for libusb
4 * Copyright © 2007-2009 Daniel Drake <dsd@gentoo.org>
5 * Copyright © 2001 Johannes Erdfelt <johannes@erdfelt.com>
6 * Copyright © 2013 Nathan Hjelm <hjelmn@mac.com>
7 * Copyright © 2012-2013 Hans de Goede <hdegoede@redhat.com>
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
35 #include <sys/ioctl.h>
38 #include <sys/types.h>
39 #include <sys/utsname.h>
44 #include <dd-usbhost.h>
48 #include "linux_usbfs.h"
51 * opening a usbfs node causes the device to be resumed, so we attempt to
52 * avoid this during enumeration.
54 * sysfs allows us to read the kernel's in-memory copies of device descriptors
55 * and so forth, avoiding the need to open the device:
56 * - The binary "descriptors" file contains all config descriptors since
57 * 2.6.26, commit 217a9081d8e69026186067711131b77f0ce219ed
58 * - The binary "descriptors" file was added in 2.6.23, commit
59 * 69d42a78f935d19384d1f6e4f94b65bb162b36df, but it only contains the
60 * active config descriptors
61 * - The "busnum" file was added in 2.6.22, commit
62 * 83f7d958eab2fbc6b159ee92bf1493924e1d0f72
63 * - The "devnum" file has been present since pre-2.6.18
64 * - the "bConfigurationValue" file has been present since pre-2.6.18
66 * If we have bConfigurationValue, busnum, and devnum, then we can determine
67 * the active configuration without having to open the usbfs node in RDWR mode.
68 * The busnum file is important as that is the only way we can relate sysfs
69 * devices to usbfs nodes.
71 * If we also have all descriptors, we can obtain the device descriptor and
72 * configuration without touching usbfs at all.
75 /* endianness for multi-byte fields:
77 * Descriptors exposed by usbfs have the multi-byte fields in the device
78 * descriptor as host endian. Multi-byte fields in the other descriptors are
79 * bus-endian. The kernel documentation says otherwise, but it is wrong.
81 * In sysfs all descriptors are bus-endian.
84 static const char *usbfs_path = NULL;
86 /* use usbdev*.* device names in /dev instead of the usbfs bus directories */
87 static int usbdev_names = 0;
89 /* Linux 2.6.32 adds support for a bulk continuation URB flag. this basically
90 * allows us to mark URBs as being part of a specific logical transfer when
91 * we submit them to the kernel. then, on any error except a cancellation, all
92 * URBs within that transfer will be cancelled and no more URBs will be
93 * accepted for the transfer, meaning that no more data can creep in.
95 * The BULK_CONTINUATION flag must be set on all URBs within a bulk transfer
96 * (in either direction) except the first.
97 * For IN transfers, we must also set SHORT_NOT_OK on all URBs except the
98 * last; it means that the kernel should treat a short reply as an error.
99 * For OUT transfers, SHORT_NOT_OK must not be set. it isn't needed (OUT
100 * transfers can't be short unless there's already some sort of error), and
101 * setting this flag is disallowed (a kernel with USB debugging enabled will
104 static int supports_flag_bulk_continuation = -1;
106 /* Linux 2.6.31 fixes support for the zero length packet URB flag. This
107 * allows us to mark URBs that should be followed by a zero length data
108 * packet, which can be required by device- or class-specific protocols.
110 static int supports_flag_zero_packet = -1;
112 /* clock ID for monotonic clock, as not all clock sources are available on all
113 * systems. appropriate choice made at initialization time. */
114 static clockid_t monotonic_clkid = -1;
116 /* Linux 2.6.22 (commit 83f7d958eab2fbc6b159ee92bf1493924e1d0f72) adds a busnum
117 * to sysfs, so we can relate devices. This also implies that we can read
118 * the active configuration through bConfigurationValue */
119 static int sysfs_can_relate_devices = -1;
121 /* Linux 2.6.26 (commit 217a9081d8e69026186067711131b77f0ce219ed) adds all
122 * config descriptors (rather then just the active config) to the sysfs
123 * descriptors file, so from then on we can use them. */
124 static int sysfs_has_descriptors = -1;
126 /* how many times have we initted (and not exited) ? */
127 static int init_count = 0;
129 /* Serialize hotplug start/stop */
130 static usbi_mutex_static_t linux_hotplug_startstop_lock = USBI_MUTEX_INITIALIZER;
131 /* Serialize scan-devices, event-thread, and poll */
132 usbi_mutex_static_t linux_hotplug_lock = USBI_MUTEX_INITIALIZER;
134 static int linux_start_event_monitor(void);
135 static int linux_stop_event_monitor(void);
136 static int linux_scan_devices(struct libusb_context *ctx);
137 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname);
138 static int detach_kernel_driver_and_claim(struct libusb_device_handle *, int);
140 #if !defined(USE_UDEV)
141 static int linux_default_scan_devices (struct libusb_context *ctx);
144 struct linux_device_priv {
146 unsigned char *descriptors;
148 int active_config; /* cache val for !sysfs_can_relate_devices */
151 struct linux_device_handle_priv {
159 /* submission failed after the first URB, so await cancellation/completion
160 * of all the others */
163 /* cancelled by user or timeout */
166 /* completed multi-URB transfer in non-final URB */
169 /* one or more urbs encountered a low-level error */
173 struct linux_transfer_priv {
175 struct usbfs_urb *urbs;
176 struct usbfs_urb **iso_urbs;
179 enum reap_action reap_action;
182 enum libusb_transfer_status reap_status;
184 /* next iso packet in user-supplied transfer to be populated */
185 int iso_packet_offset;
188 static int _direct_open_device(struct libusb_context *ctx, const char *path,
189 mode_t mode, int silent)
194 fd = open(path, mode);
196 return fd; /* Success */
198 if (errno == ENOENT) {
200 usbi_err(ctx, "File doesn't exist,"
201 "wait %d ms and try again\n", delay/1000);
203 /* Wait 10ms for USB device path creation.*/
206 fd = open(path, mode);
208 return fd; /* Success */
215 static int _ask_for_open(const char *path, mode_t mode, int silent)
220 ret = open_usb_device(path, &fd);
223 * We have an error so let's set errno correctly
224 * just like open does
234 #endif /* USE_DEVICED */
236 static int _get_usbfs_fd(struct libusb_device *dev, mode_t mode, int silent)
238 struct libusb_context *ctx = DEVICE_CTX(dev);
243 snprintf(path, PATH_MAX, "%s/usbdev%d.%d",
244 usbfs_path, dev->bus_number, dev->device_address);
246 snprintf(path, PATH_MAX, "%s/%03d/%03d",
247 usbfs_path, dev->bus_number, dev->device_address);
249 fd = _direct_open_device(ctx, path, mode, silent);
251 return fd; /* Success */
255 * If we are here, we were unable to go simple
256 * path and open the device directly. In Tizen
257 * we have USB security daemon (USD) which
258 * manages access rights to USB device nodes.
259 * Now let's ask him to open this device node
264 * USD is applicable only for RW access.
268 usbi_info(ctx, "No direct access to device node: %s. "
269 "Trying to use deviced", path);
271 fd = _ask_for_open(path, mode, silent);
275 #endif /* USE_DEVICED */
278 usbi_err(ctx, "libusb couldn't open USB device %s: %s",
279 path, strerror(errno));
280 if (errno == EACCES && mode == O_RDWR)
281 usbi_err(ctx, "libusb requires write access to USB "
286 return LIBUSB_ERROR_ACCESS;
288 return LIBUSB_ERROR_NO_DEVICE;
289 return LIBUSB_ERROR_IO;
292 static struct linux_device_priv *_device_priv(struct libusb_device *dev)
294 return (struct linux_device_priv *) dev->os_priv;
297 static struct linux_device_handle_priv *_device_handle_priv(
298 struct libusb_device_handle *handle)
300 return (struct linux_device_handle_priv *) handle->os_priv;
303 /* check dirent for a /dev/usbdev%d.%d name
304 * optionally return bus/device on success */
305 static int _is_usbdev_entry(struct dirent *entry, int *bus_p, int *dev_p)
309 if (sscanf(entry->d_name, "usbdev%d.%d", &busnum, &devnum) != 2)
312 usbi_dbg("found: %s", entry->d_name);
320 static int check_usb_vfs(const char *dirname)
323 struct dirent *entry;
326 dir = opendir(dirname);
330 while ((entry = readdir(dir)) != NULL) {
331 if (entry->d_name[0] == '.')
334 /* We assume if we find any files that it must be the right place */
343 static const char *find_usbfs_path(void)
345 const char *path = "/dev/bus/usb";
346 const char *ret = NULL;
348 if (check_usb_vfs(path)) {
351 path = "/proc/bus/usb";
352 if (check_usb_vfs(path))
356 /* look for /dev/usbdev*.* if the normal places fail */
358 struct dirent *entry;
364 while ((entry = readdir(dir)) != NULL) {
365 if (_is_usbdev_entry(entry, NULL, NULL)) {
366 /* found one; that's enough */
376 /* On udev based systems without any usb-devices /dev/bus/usb will not
377 * exist. So if we've not found anything and we're using udev for hotplug
378 * simply assume /dev/bus/usb rather then making libusb_init fail. */
379 #if defined(USE_UDEV)
381 ret = "/dev/bus/usb";
385 usbi_dbg("found usbfs at %s", ret);
390 /* the monotonic clock is not usable on all systems (e.g. embedded ones often
391 * seem to lack it). fall back to REALTIME if we have to. */
392 static clockid_t find_monotonic_clock(void)
394 #ifdef CLOCK_MONOTONIC
398 /* Linux 2.6.28 adds CLOCK_MONOTONIC_RAW but we don't use it
399 * because it's not available through timerfd */
400 r = clock_gettime(CLOCK_MONOTONIC, &ts);
402 return CLOCK_MONOTONIC;
403 usbi_dbg("monotonic clock doesn't work, errno %d", errno);
406 return CLOCK_REALTIME;
409 static int kernel_version_ge(int major, int minor, int sublevel)
412 int atoms, kmajor, kminor, ksublevel;
416 atoms = sscanf(uts.release, "%d.%d.%d", &kmajor, &kminor, &ksublevel);
425 /* kmajor == major */
427 return 0 == minor && 0 == sublevel;
433 /* kminor == minor */
435 return 0 == sublevel;
437 return ksublevel >= sublevel;
440 static int op_init(struct libusb_context *ctx)
445 usbfs_path = find_usbfs_path();
447 usbi_err(ctx, "could not find usbfs");
448 return LIBUSB_ERROR_OTHER;
451 if (monotonic_clkid == -1)
452 monotonic_clkid = find_monotonic_clock();
454 if (supports_flag_bulk_continuation == -1) {
455 /* bulk continuation URB flag available from Linux 2.6.32 */
456 supports_flag_bulk_continuation = kernel_version_ge(2,6,32);
457 if (supports_flag_bulk_continuation == -1) {
458 usbi_err(ctx, "error checking for bulk continuation support");
459 return LIBUSB_ERROR_OTHER;
463 if (supports_flag_bulk_continuation)
464 usbi_dbg("bulk continuation flag supported");
466 if (-1 == supports_flag_zero_packet) {
467 /* zero length packet URB flag fixed since Linux 2.6.31 */
468 supports_flag_zero_packet = kernel_version_ge(2,6,31);
469 if (-1 == supports_flag_zero_packet) {
470 usbi_err(ctx, "error checking for zero length packet support");
471 return LIBUSB_ERROR_OTHER;
475 if (supports_flag_zero_packet)
476 usbi_dbg("zero length packet flag supported");
478 if (-1 == sysfs_has_descriptors) {
479 /* sysfs descriptors has all descriptors since Linux 2.6.26 */
480 sysfs_has_descriptors = kernel_version_ge(2,6,26);
481 if (-1 == sysfs_has_descriptors) {
482 usbi_err(ctx, "error checking for sysfs descriptors");
483 return LIBUSB_ERROR_OTHER;
487 if (-1 == sysfs_can_relate_devices) {
488 /* sysfs has busnum since Linux 2.6.22 */
489 sysfs_can_relate_devices = kernel_version_ge(2,6,22);
490 if (-1 == sysfs_can_relate_devices) {
491 usbi_err(ctx, "error checking for sysfs busnum");
492 return LIBUSB_ERROR_OTHER;
496 if (sysfs_can_relate_devices || sysfs_has_descriptors) {
497 r = stat(SYSFS_DEVICE_PATH, &statbuf);
498 if (r != 0 || !S_ISDIR(statbuf.st_mode)) {
499 usbi_warn(ctx, "sysfs not mounted");
500 sysfs_can_relate_devices = 0;
501 sysfs_has_descriptors = 0;
505 if (sysfs_can_relate_devices)
506 usbi_dbg("sysfs can relate devices");
508 if (sysfs_has_descriptors)
509 usbi_dbg("sysfs has complete descriptors");
511 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
513 if (init_count == 0) {
514 /* start up hotplug event handler */
515 r = linux_start_event_monitor();
517 if (r == LIBUSB_SUCCESS) {
518 r = linux_scan_devices(ctx);
519 if (r == LIBUSB_SUCCESS)
521 else if (init_count == 0)
522 linux_stop_event_monitor();
524 usbi_err(ctx, "error starting hotplug event monitor");
525 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
530 static void op_exit(void)
532 usbi_mutex_static_lock(&linux_hotplug_startstop_lock);
533 assert(init_count != 0);
535 /* tear down event handler */
536 (void)linux_stop_event_monitor();
538 usbi_mutex_static_unlock(&linux_hotplug_startstop_lock);
541 static int linux_start_event_monitor(void)
543 #if defined(USE_UDEV)
544 return linux_udev_start_event_monitor();
546 return linux_netlink_start_event_monitor();
550 static int linux_stop_event_monitor(void)
552 #if defined(USE_UDEV)
553 return linux_udev_stop_event_monitor();
555 return linux_netlink_stop_event_monitor();
559 static int linux_scan_devices(struct libusb_context *ctx)
563 usbi_mutex_static_lock(&linux_hotplug_lock);
565 #if defined(USE_UDEV)
566 ret = linux_udev_scan_devices(ctx);
568 ret = linux_default_scan_devices(ctx);
571 usbi_mutex_static_unlock(&linux_hotplug_lock);
576 static void op_hotplug_poll(void)
578 #if defined(USE_UDEV)
579 linux_udev_hotplug_poll();
581 linux_netlink_hotplug_poll();
585 static int _open_sysfs_attr(struct libusb_device *dev, const char *attr)
587 struct linux_device_priv *priv = _device_priv(dev);
588 char filename[PATH_MAX];
591 snprintf(filename, PATH_MAX, "%s/%s/%s",
592 SYSFS_DEVICE_PATH, priv->sysfs_dir, attr);
593 fd = open(filename, O_RDONLY);
595 usbi_err(DEVICE_CTX(dev),
596 "open %s failed ret=%d errno=%d", filename, fd, errno);
597 return LIBUSB_ERROR_IO;
603 /* Note only suitable for attributes which always read >= 0, < 0 is error */
604 static int __read_sysfs_attr(struct libusb_context *ctx,
605 const char *devname, const char *attr)
607 char filename[PATH_MAX];
611 snprintf(filename, PATH_MAX, "%s/%s/%s", SYSFS_DEVICE_PATH,
613 f = fopen(filename, "r");
615 if (errno == ENOENT) {
616 /* File doesn't exist. Assume the device has been
617 disconnected (see trac ticket #70). */
618 return LIBUSB_ERROR_NO_DEVICE;
620 usbi_err(ctx, "open %s failed errno=%d", filename, errno);
621 return LIBUSB_ERROR_IO;
624 r = fscanf(f, "%d", &value);
627 usbi_err(ctx, "fscanf %s returned %d, errno=%d", attr, r, errno);
628 return LIBUSB_ERROR_NO_DEVICE; /* For unplug race (trac #70) */
631 usbi_err(ctx, "%s contains a negative value", filename);
632 return LIBUSB_ERROR_IO;
638 static int op_get_device_descriptor(struct libusb_device *dev,
639 unsigned char *buffer, int *host_endian)
641 struct linux_device_priv *priv = _device_priv(dev);
643 *host_endian = sysfs_has_descriptors ? 0 : 1;
644 memcpy(buffer, priv->descriptors, DEVICE_DESC_LENGTH);
649 /* read the bConfigurationValue for a device */
650 static int sysfs_get_active_config(struct libusb_device *dev, int *config)
653 char tmp[5] = {0, 0, 0, 0, 0};
658 fd = _open_sysfs_attr(dev, "bConfigurationValue");
662 r = read(fd, tmp, sizeof(tmp));
665 usbi_err(DEVICE_CTX(dev),
666 "read bConfigurationValue failed ret=%d errno=%d", r, errno);
667 return LIBUSB_ERROR_IO;
669 usbi_dbg("device unconfigured");
674 if (tmp[sizeof(tmp) - 1] != 0) {
675 usbi_err(DEVICE_CTX(dev), "not null-terminated?");
676 return LIBUSB_ERROR_IO;
677 } else if (tmp[0] == 0) {
678 usbi_err(DEVICE_CTX(dev), "no configuration value?");
679 return LIBUSB_ERROR_IO;
682 num = strtol(tmp, &endptr, 10);
684 usbi_err(DEVICE_CTX(dev), "error converting '%s' to integer", tmp);
685 return LIBUSB_ERROR_IO;
692 int linux_get_device_address (struct libusb_context *ctx, int detached,
693 uint8_t *busnum, uint8_t *devaddr,const char *dev_node,
694 const char *sys_name)
698 usbi_dbg("getting address for device: %s detached: %d", sys_name, detached);
699 /* can't use sysfs to read the bus and device number if the
700 * device has been detached */
701 if (!sysfs_can_relate_devices || detached || NULL == sys_name) {
702 if (NULL == dev_node) {
703 return LIBUSB_ERROR_OTHER;
706 /* will this work with all supported kernel versions? */
707 if (!strncmp(dev_node, "/dev/bus/usb", 12)) {
708 sscanf (dev_node, "/dev/bus/usb/%hhu/%hhu", busnum, devaddr);
709 } else if (!strncmp(dev_node, "/proc/bus/usb", 13)) {
710 sscanf (dev_node, "/proc/bus/usb/%hhu/%hhu", busnum, devaddr);
713 return LIBUSB_SUCCESS;
716 usbi_dbg("scan %s", sys_name);
718 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "busnum");
721 if (sysfs_attr > 255)
722 return LIBUSB_ERROR_INVALID_PARAM;
723 *busnum = (uint8_t) sysfs_attr;
725 sysfs_attr = __read_sysfs_attr(ctx, sys_name, "devnum");
728 if (sysfs_attr > 255)
729 return LIBUSB_ERROR_INVALID_PARAM;
731 *devaddr = (uint8_t) sysfs_attr;
733 usbi_dbg("bus=%d dev=%d", *busnum, *devaddr);
735 return LIBUSB_SUCCESS;
738 /* Return offset of the next descriptor with the given type */
739 static int seek_to_next_descriptor(struct libusb_context *ctx,
740 uint8_t descriptor_type, unsigned char *buffer, int size)
742 struct usb_descriptor_header header;
745 for (i = 0; size >= 0; i += header.bLength, size -= header.bLength) {
747 return LIBUSB_ERROR_NOT_FOUND;
750 usbi_err(ctx, "short descriptor read %d/2", size);
751 return LIBUSB_ERROR_IO;
753 usbi_parse_descriptor(buffer + i, "bb", &header, 0);
755 if (i && header.bDescriptorType == descriptor_type)
758 usbi_err(ctx, "bLength overflow by %d bytes", -size);
759 return LIBUSB_ERROR_IO;
762 /* Return offset to next config */
763 static int seek_to_next_config(struct libusb_context *ctx,
764 unsigned char *buffer, int size)
766 struct libusb_config_descriptor config;
769 return LIBUSB_ERROR_NOT_FOUND;
771 if (size < LIBUSB_DT_CONFIG_SIZE) {
772 usbi_err(ctx, "short descriptor read %d/%d",
773 size, LIBUSB_DT_CONFIG_SIZE);
774 return LIBUSB_ERROR_IO;
777 usbi_parse_descriptor(buffer, "bbwbbbbb", &config, 0);
778 if (config.bDescriptorType != LIBUSB_DT_CONFIG) {
779 usbi_err(ctx, "descriptor is not a config desc (type 0x%02x)",
780 config.bDescriptorType);
781 return LIBUSB_ERROR_IO;
785 * In usbfs the config descriptors are config.wTotalLength bytes apart,
786 * with any short reads from the device appearing as holes in the file.
788 * In sysfs wTotalLength is ignored, instead the kernel returns a
789 * config descriptor with verified bLength fields, with descriptors
790 * with an invalid bLength removed.
792 if (sysfs_has_descriptors) {
793 int next = seek_to_next_descriptor(ctx, LIBUSB_DT_CONFIG,
795 if (next == LIBUSB_ERROR_NOT_FOUND)
800 if (next != config.wTotalLength)
801 usbi_warn(ctx, "config length mismatch wTotalLength "
802 "%d real %d", config.wTotalLength, next);
805 if (config.wTotalLength < LIBUSB_DT_CONFIG_SIZE) {
806 usbi_err(ctx, "invalid wTotalLength %d",
807 config.wTotalLength);
808 return LIBUSB_ERROR_IO;
809 } else if (config.wTotalLength > size) {
810 usbi_warn(ctx, "short descriptor read %d/%d",
811 size, config.wTotalLength);
814 return config.wTotalLength;
818 static int op_get_config_descriptor_by_value(struct libusb_device *dev,
819 uint8_t value, unsigned char **buffer, int *host_endian)
821 struct libusb_context *ctx = DEVICE_CTX(dev);
822 struct linux_device_priv *priv = _device_priv(dev);
823 unsigned char *descriptors = priv->descriptors;
824 int size = priv->descriptors_len;
825 struct libusb_config_descriptor *config;
828 /* Unlike the device desc. config descs. are always in raw format */
831 /* Skip device header */
832 descriptors += DEVICE_DESC_LENGTH;
833 size -= DEVICE_DESC_LENGTH;
835 /* Seek till the config is found, or till "EOF" */
837 int next = seek_to_next_config(ctx, descriptors, size);
840 config = (struct libusb_config_descriptor *)descriptors;
841 if (config->bConfigurationValue == value) {
842 *buffer = descriptors;
850 static int op_get_active_config_descriptor(struct libusb_device *dev,
851 unsigned char *buffer, size_t len, int *host_endian)
854 unsigned char *config_desc;
856 if (sysfs_can_relate_devices) {
857 r = sysfs_get_active_config(dev, &config);
861 /* Use cached bConfigurationValue */
862 struct linux_device_priv *priv = _device_priv(dev);
863 config = priv->active_config;
866 return LIBUSB_ERROR_NOT_FOUND;
868 r = op_get_config_descriptor_by_value(dev, config, &config_desc,
874 memcpy(buffer, config_desc, len);
878 static int op_get_config_descriptor(struct libusb_device *dev,
879 uint8_t config_index, unsigned char *buffer, size_t len, int *host_endian)
881 struct linux_device_priv *priv = _device_priv(dev);
882 unsigned char *descriptors = priv->descriptors;
883 int i, r, size = priv->descriptors_len;
885 /* Unlike the device desc. config descs. are always in raw format */
888 /* Skip device header */
889 descriptors += DEVICE_DESC_LENGTH;
890 size -= DEVICE_DESC_LENGTH;
892 /* Seek till the config is found, or till "EOF" */
894 r = seek_to_next_config(DEVICE_CTX(dev), descriptors, size);
897 if (i == config_index)
904 memcpy(buffer, descriptors, len);
908 /* send a control message to retrieve active configuration */
909 static int usbfs_get_active_config(struct libusb_device *dev, int fd)
911 struct linux_device_priv *priv = _device_priv(dev);
912 unsigned char active_config = 0;
915 struct usbfs_ctrltransfer ctrl = {
916 .bmRequestType = LIBUSB_ENDPOINT_IN,
917 .bRequest = LIBUSB_REQUEST_GET_CONFIGURATION,
922 .data = &active_config
925 r = ioctl(fd, IOCTL_USBFS_CONTROL, &ctrl);
928 return LIBUSB_ERROR_NO_DEVICE;
930 /* we hit this error path frequently with buggy devices :( */
931 usbi_warn(DEVICE_CTX(dev),
932 "get_configuration failed ret=%d errno=%d", r, errno);
933 priv->active_config = -1;
935 if (active_config > 0) {
936 priv->active_config = active_config;
938 /* some buggy devices have a configuration 0, but we're
939 * reaching into the corner of a corner case here, so let's
940 * not support buggy devices in these circumstances.
941 * stick to the specs: a configuration value of 0 means
943 usbi_warn(DEVICE_CTX(dev),
944 "active cfg 0? assuming unconfigured device");
945 priv->active_config = -1;
949 return LIBUSB_SUCCESS;
952 static int initialize_device(struct libusb_device *dev, uint8_t busnum,
953 uint8_t devaddr, const char *sysfs_dir)
955 struct linux_device_priv *priv = _device_priv(dev);
956 struct libusb_context *ctx = DEVICE_CTX(dev);
957 int descriptors_size = 512; /* Begin with a 1024 byte alloc */
961 dev->bus_number = busnum;
962 dev->device_address = devaddr;
965 priv->sysfs_dir = strdup(sysfs_dir);
966 if (!priv->sysfs_dir)
967 return LIBUSB_ERROR_NO_MEM;
969 /* Note speed can contain 1.5, in this case __read_sysfs_attr
970 will stop parsing at the '.' and return 1 */
971 speed = __read_sysfs_attr(DEVICE_CTX(dev), sysfs_dir, "speed");
974 case 1: dev->speed = LIBUSB_SPEED_LOW; break;
975 case 12: dev->speed = LIBUSB_SPEED_FULL; break;
976 case 480: dev->speed = LIBUSB_SPEED_HIGH; break;
977 case 5000: dev->speed = LIBUSB_SPEED_SUPER; break;
979 usbi_warn(DEVICE_CTX(dev), "Unknown device speed: %d Mbps", speed);
984 /* cache descriptors in memory */
985 if (sysfs_has_descriptors)
986 fd = _open_sysfs_attr(dev, "descriptors");
988 fd = _get_usbfs_fd(dev, O_RDONLY, 0);
993 descriptors_size *= 2;
994 priv->descriptors = usbi_reallocf(priv->descriptors,
996 if (!priv->descriptors) {
998 return LIBUSB_ERROR_NO_MEM;
1000 /* usbfs has holes in the file */
1001 if (!sysfs_has_descriptors) {
1002 memset(priv->descriptors + priv->descriptors_len,
1003 0, descriptors_size - priv->descriptors_len);
1005 r = read(fd, priv->descriptors + priv->descriptors_len,
1006 descriptors_size - priv->descriptors_len);
1008 usbi_err(ctx, "read descriptor failed ret=%d errno=%d",
1011 return LIBUSB_ERROR_IO;
1013 priv->descriptors_len += r;
1014 } while (priv->descriptors_len == descriptors_size);
1018 if (priv->descriptors_len < DEVICE_DESC_LENGTH) {
1019 usbi_err(ctx, "short descriptor read (%d)",
1020 priv->descriptors_len);
1021 return LIBUSB_ERROR_IO;
1024 if (sysfs_can_relate_devices)
1025 return LIBUSB_SUCCESS;
1027 /* cache active config */
1028 fd = _get_usbfs_fd(dev, O_RDWR, 1);
1030 /* cannot send a control message to determine the active
1031 * config. just assume the first one is active. */
1032 usbi_warn(ctx, "Missing rw usbfs access; cannot determine "
1033 "active configuration descriptor");
1034 if (priv->descriptors_len >=
1035 (DEVICE_DESC_LENGTH + LIBUSB_DT_CONFIG_SIZE)) {
1036 struct libusb_config_descriptor config;
1037 usbi_parse_descriptor(
1038 priv->descriptors + DEVICE_DESC_LENGTH,
1039 "bbwbbbbb", &config, 0);
1040 priv->active_config = config.bConfigurationValue;
1042 priv->active_config = -1; /* No config dt */
1044 return LIBUSB_SUCCESS;
1047 r = usbfs_get_active_config(dev, fd);
1053 static int linux_get_parent_info(struct libusb_device *dev, const char *sysfs_dir)
1055 struct libusb_context *ctx = DEVICE_CTX(dev);
1056 struct libusb_device *it;
1057 char *parent_sysfs_dir, *tmp;
1058 int ret, add_parent = 1;
1060 /* XXX -- can we figure out the topology when using usbfs? */
1061 if (NULL == sysfs_dir || 0 == strncmp(sysfs_dir, "usb", 3)) {
1062 /* either using usbfs or finding the parent of a root hub */
1063 return LIBUSB_SUCCESS;
1066 parent_sysfs_dir = strdup(sysfs_dir);
1067 if (NULL == parent_sysfs_dir) {
1068 return LIBUSB_ERROR_NO_MEM;
1070 if (NULL != (tmp = strrchr(parent_sysfs_dir, '.')) ||
1071 NULL != (tmp = strrchr(parent_sysfs_dir, '-'))) {
1072 dev->port_number = atoi(tmp + 1);
1075 usbi_warn(ctx, "Can not parse sysfs_dir: %s, no parent info",
1077 free (parent_sysfs_dir);
1078 return LIBUSB_SUCCESS;
1081 /* is the parent a root hub? */
1082 if (NULL == strchr(parent_sysfs_dir, '-')) {
1083 tmp = parent_sysfs_dir;
1084 ret = asprintf (&parent_sysfs_dir, "usb%s", tmp);
1087 return LIBUSB_ERROR_NO_MEM;
1092 /* find the parent in the context */
1093 usbi_mutex_lock(&ctx->usb_devs_lock);
1094 list_for_each_entry(it, &ctx->usb_devs, list, struct libusb_device) {
1095 struct linux_device_priv *priv = _device_priv(it);
1096 if (0 == strcmp (priv->sysfs_dir, parent_sysfs_dir)) {
1097 dev->parent_dev = libusb_ref_device(it);
1101 usbi_mutex_unlock(&ctx->usb_devs_lock);
1103 if (!dev->parent_dev && add_parent) {
1104 usbi_dbg("parent_dev %s not enumerated yet, enumerating now",
1106 sysfs_scan_device(ctx, parent_sysfs_dir);
1111 usbi_dbg("Dev %p (%s) has parent %p (%s) port %d", dev, sysfs_dir,
1112 dev->parent_dev, parent_sysfs_dir, dev->port_number);
1114 free (parent_sysfs_dir);
1116 return LIBUSB_SUCCESS;
1119 int linux_enumerate_device(struct libusb_context *ctx,
1120 uint8_t busnum, uint8_t devaddr, const char *sysfs_dir)
1122 unsigned long session_id;
1123 struct libusb_device *dev;
1126 /* FIXME: session ID is not guaranteed unique as addresses can wrap and
1127 * will be reused. instead we should add a simple sysfs attribute with
1129 session_id = busnum << 8 | devaddr;
1130 usbi_dbg("busnum %d devaddr %d session_id %ld", busnum, devaddr,
1133 dev = usbi_get_device_by_session_id(ctx, session_id);
1135 /* device already exists in the context */
1136 usbi_dbg("session_id %ld already exists", session_id);
1137 libusb_unref_device(dev);
1138 return LIBUSB_SUCCESS;
1141 usbi_dbg("allocating new device for %d/%d (session %ld)",
1142 busnum, devaddr, session_id);
1143 dev = usbi_alloc_device(ctx, session_id);
1145 return LIBUSB_ERROR_NO_MEM;
1147 r = initialize_device(dev, busnum, devaddr, sysfs_dir);
1150 r = usbi_sanitize_device(dev);
1154 r = linux_get_parent_info(dev, sysfs_dir);
1159 libusb_unref_device(dev);
1161 usbi_connect_device(dev);
1166 void linux_hotplug_enumerate(uint8_t busnum, uint8_t devaddr, const char *sys_name)
1168 struct libusb_context *ctx;
1170 usbi_mutex_static_lock(&active_contexts_lock);
1171 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1172 linux_enumerate_device(ctx, busnum, devaddr, sys_name);
1174 usbi_mutex_static_unlock(&active_contexts_lock);
1177 void linux_device_disconnected(uint8_t busnum, uint8_t devaddr)
1179 struct libusb_context *ctx;
1180 struct libusb_device *dev;
1181 unsigned long session_id = busnum << 8 | devaddr;
1183 usbi_mutex_static_lock(&active_contexts_lock);
1184 list_for_each_entry(ctx, &active_contexts_list, list, struct libusb_context) {
1185 dev = usbi_get_device_by_session_id (ctx, session_id);
1187 usbi_disconnect_device (dev);
1188 libusb_unref_device(dev);
1190 usbi_dbg("device not found for session %x", session_id);
1193 usbi_mutex_static_unlock(&active_contexts_lock);
1196 #if !defined(USE_UDEV)
1197 /* open a bus directory and adds all discovered devices to the context */
1198 static int usbfs_scan_busdir(struct libusb_context *ctx, uint8_t busnum)
1201 char dirpath[PATH_MAX];
1202 struct dirent *entry;
1203 int r = LIBUSB_ERROR_IO;
1205 snprintf(dirpath, PATH_MAX, "%s/%03d", usbfs_path, busnum);
1206 usbi_dbg("%s", dirpath);
1207 dir = opendir(dirpath);
1209 usbi_err(ctx, "opendir '%s' failed, errno=%d", dirpath, errno);
1210 /* FIXME: should handle valid race conditions like hub unplugged
1211 * during directory iteration - this is not an error */
1215 while ((entry = readdir(dir))) {
1218 if (entry->d_name[0] == '.')
1221 devaddr = atoi(entry->d_name);
1223 usbi_dbg("unknown dir entry %s", entry->d_name);
1227 if (linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL)) {
1228 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1239 static int usbfs_get_device_list(struct libusb_context *ctx)
1241 struct dirent *entry;
1242 DIR *buses = opendir(usbfs_path);
1246 usbi_err(ctx, "opendir buses failed errno=%d", errno);
1247 return LIBUSB_ERROR_IO;
1250 while ((entry = readdir(buses))) {
1253 if (entry->d_name[0] == '.')
1258 if (!_is_usbdev_entry(entry, &busnum, &devaddr))
1261 r = linux_enumerate_device(ctx, busnum, (uint8_t) devaddr, NULL);
1263 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1267 busnum = atoi(entry->d_name);
1269 usbi_dbg("unknown dir entry %s", entry->d_name);
1273 r = usbfs_scan_busdir(ctx, busnum);
1285 static int sysfs_scan_device(struct libusb_context *ctx, const char *devname)
1287 uint8_t busnum, devaddr;
1290 ret = linux_get_device_address (ctx, 0, &busnum, &devaddr, NULL, devname);
1291 if (LIBUSB_SUCCESS != ret) {
1295 return linux_enumerate_device(ctx, busnum & 0xff, devaddr & 0xff,
1299 #if !defined(USE_UDEV)
1300 static int sysfs_get_device_list(struct libusb_context *ctx)
1302 DIR *devices = opendir(SYSFS_DEVICE_PATH);
1303 struct dirent *entry;
1304 int r = LIBUSB_ERROR_IO;
1307 usbi_err(ctx, "opendir devices failed errno=%d", errno);
1311 while ((entry = readdir(devices))) {
1312 if ((!isdigit(entry->d_name[0]) && strncmp(entry->d_name, "usb", 3))
1313 || strchr(entry->d_name, ':'))
1316 if (sysfs_scan_device(ctx, entry->d_name)) {
1317 usbi_dbg("failed to enumerate dir entry %s", entry->d_name);
1328 static int linux_default_scan_devices (struct libusb_context *ctx)
1330 /* we can retrieve device list and descriptors from sysfs or usbfs.
1331 * sysfs is preferable, because if we use usbfs we end up resuming
1332 * any autosuspended USB devices. however, sysfs is not available
1333 * everywhere, so we need a usbfs fallback too.
1335 * as described in the "sysfs vs usbfs" comment at the top of this
1336 * file, sometimes we have sysfs but not enough information to
1337 * relate sysfs devices to usbfs nodes. op_init() determines the
1338 * adequacy of sysfs and sets sysfs_can_relate_devices.
1340 if (sysfs_can_relate_devices != 0)
1341 return sysfs_get_device_list(ctx);
1343 return usbfs_get_device_list(ctx);
1347 static int op_open(struct libusb_device_handle *handle)
1349 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1352 hpriv->fd = _get_usbfs_fd(handle->dev, O_RDWR, 0);
1353 if (hpriv->fd < 0) {
1354 if (hpriv->fd == LIBUSB_ERROR_NO_DEVICE) {
1355 /* device will still be marked as attached if hotplug monitor thread
1356 * hasn't processed remove event yet */
1357 usbi_mutex_static_lock(&linux_hotplug_lock);
1358 if (handle->dev->attached) {
1359 usbi_dbg("open failed with no device, but device still attached");
1360 linux_device_disconnected(handle->dev->bus_number,
1361 handle->dev->device_address);
1363 usbi_mutex_static_unlock(&linux_hotplug_lock);
1368 r = ioctl(hpriv->fd, IOCTL_USBFS_GET_CAPABILITIES, &hpriv->caps);
1370 if (errno == ENOTTY)
1371 usbi_dbg("getcap not available");
1373 usbi_err(HANDLE_CTX(handle), "getcap failed (%d)", errno);
1375 if (supports_flag_zero_packet)
1376 hpriv->caps |= USBFS_CAP_ZERO_PACKET;
1377 if (supports_flag_bulk_continuation)
1378 hpriv->caps |= USBFS_CAP_BULK_CONTINUATION;
1381 r = usbi_add_pollfd(HANDLE_CTX(handle), hpriv->fd, POLLOUT);
1388 static void op_close(struct libusb_device_handle *dev_handle)
1390 struct linux_device_handle_priv *hpriv = _device_handle_priv(dev_handle);
1391 /* fd may have already been removed by POLLERR condition in op_handle_events() */
1392 if (!hpriv->fd_removed)
1393 usbi_remove_pollfd(HANDLE_CTX(dev_handle), hpriv->fd);
1397 static int op_get_configuration(struct libusb_device_handle *handle,
1402 if (sysfs_can_relate_devices) {
1403 r = sysfs_get_active_config(handle->dev, config);
1405 r = usbfs_get_active_config(handle->dev,
1406 _device_handle_priv(handle)->fd);
1407 if (r == LIBUSB_SUCCESS)
1408 *config = _device_priv(handle->dev)->active_config;
1413 if (*config == -1) {
1414 usbi_err(HANDLE_CTX(handle), "device unconfigured");
1421 static int op_set_configuration(struct libusb_device_handle *handle, int config)
1423 struct linux_device_priv *priv = _device_priv(handle->dev);
1424 int fd = _device_handle_priv(handle)->fd;
1425 int r = ioctl(fd, IOCTL_USBFS_SETCONFIG, &config);
1427 if (errno == EINVAL)
1428 return LIBUSB_ERROR_NOT_FOUND;
1429 else if (errno == EBUSY)
1430 return LIBUSB_ERROR_BUSY;
1431 else if (errno == ENODEV)
1432 return LIBUSB_ERROR_NO_DEVICE;
1434 usbi_err(HANDLE_CTX(handle), "failed, error %d errno %d", r, errno);
1435 return LIBUSB_ERROR_OTHER;
1438 /* update our cached active config descriptor */
1439 priv->active_config = config;
1441 return LIBUSB_SUCCESS;
1444 static int claim_interface(struct libusb_device_handle *handle, int iface)
1446 int fd = _device_handle_priv(handle)->fd;
1447 int r = ioctl(fd, IOCTL_USBFS_CLAIMINTF, &iface);
1449 if (errno == ENOENT)
1450 return LIBUSB_ERROR_NOT_FOUND;
1451 else if (errno == EBUSY)
1452 return LIBUSB_ERROR_BUSY;
1453 else if (errno == ENODEV)
1454 return LIBUSB_ERROR_NO_DEVICE;
1456 usbi_err(HANDLE_CTX(handle),
1457 "claim interface failed, error %d errno %d", r, errno);
1458 return LIBUSB_ERROR_OTHER;
1463 static int release_interface(struct libusb_device_handle *handle, int iface)
1465 int fd = _device_handle_priv(handle)->fd;
1466 int r = ioctl(fd, IOCTL_USBFS_RELEASEINTF, &iface);
1468 if (errno == ENODEV)
1469 return LIBUSB_ERROR_NO_DEVICE;
1471 usbi_err(HANDLE_CTX(handle),
1472 "release interface failed, error %d errno %d", r, errno);
1473 return LIBUSB_ERROR_OTHER;
1478 static int op_set_interface(struct libusb_device_handle *handle, int iface,
1481 int fd = _device_handle_priv(handle)->fd;
1482 struct usbfs_setinterface setintf;
1485 setintf.interface = iface;
1486 setintf.altsetting = altsetting;
1487 r = ioctl(fd, IOCTL_USBFS_SETINTF, &setintf);
1489 if (errno == EINVAL)
1490 return LIBUSB_ERROR_NOT_FOUND;
1491 else if (errno == ENODEV)
1492 return LIBUSB_ERROR_NO_DEVICE;
1494 usbi_err(HANDLE_CTX(handle),
1495 "setintf failed error %d errno %d", r, errno);
1496 return LIBUSB_ERROR_OTHER;
1502 static int op_clear_halt(struct libusb_device_handle *handle,
1503 unsigned char endpoint)
1505 int fd = _device_handle_priv(handle)->fd;
1506 unsigned int _endpoint = endpoint;
1507 int r = ioctl(fd, IOCTL_USBFS_CLEAR_HALT, &_endpoint);
1509 if (errno == ENOENT)
1510 return LIBUSB_ERROR_NOT_FOUND;
1511 else if (errno == ENODEV)
1512 return LIBUSB_ERROR_NO_DEVICE;
1514 usbi_err(HANDLE_CTX(handle),
1515 "clear_halt failed error %d errno %d", r, errno);
1516 return LIBUSB_ERROR_OTHER;
1522 static int op_reset_device(struct libusb_device_handle *handle)
1524 int fd = _device_handle_priv(handle)->fd;
1527 /* Doing a device reset will cause the usbfs driver to get unbound
1528 from any interfaces it is bound to. By voluntarily unbinding
1529 the usbfs driver ourself, we stop the kernel from rebinding
1530 the interface after reset (which would end up with the interface
1531 getting bound to the in kernel driver if any). */
1532 for (i = 0; i < USB_MAXINTERFACES; i++) {
1533 if (handle->claimed_interfaces & (1L << i)) {
1534 release_interface(handle, i);
1538 usbi_mutex_lock(&handle->lock);
1539 r = ioctl(fd, IOCTL_USBFS_RESET, NULL);
1541 if (errno == ENODEV) {
1542 ret = LIBUSB_ERROR_NOT_FOUND;
1546 usbi_err(HANDLE_CTX(handle),
1547 "reset failed error %d errno %d", r, errno);
1548 ret = LIBUSB_ERROR_OTHER;
1552 /* And re-claim any interfaces which were claimed before the reset */
1553 for (i = 0; i < USB_MAXINTERFACES; i++) {
1554 if (handle->claimed_interfaces & (1L << i)) {
1556 * A driver may have completed modprobing during
1557 * IOCTL_USBFS_RESET, and bound itself as soon as
1558 * IOCTL_USBFS_RESET released the device lock
1560 r = detach_kernel_driver_and_claim(handle, i);
1562 usbi_warn(HANDLE_CTX(handle),
1563 "failed to re-claim interface %d after reset: %s",
1564 i, libusb_error_name(r));
1565 handle->claimed_interfaces &= ~(1L << i);
1566 ret = LIBUSB_ERROR_NOT_FOUND;
1571 usbi_mutex_unlock(&handle->lock);
1575 static int do_streams_ioctl(struct libusb_device_handle *handle, long req,
1576 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1578 int r, fd = _device_handle_priv(handle)->fd;
1579 struct usbfs_streams *streams;
1581 if (num_endpoints > 30) /* Max 15 in + 15 out eps */
1582 return LIBUSB_ERROR_INVALID_PARAM;
1584 streams = malloc(sizeof(struct usbfs_streams) + num_endpoints);
1586 return LIBUSB_ERROR_NO_MEM;
1588 streams->num_streams = num_streams;
1589 streams->num_eps = num_endpoints;
1590 memcpy(streams->eps, endpoints, num_endpoints);
1592 r = ioctl(fd, req, streams);
1597 if (errno == ENOTTY)
1598 return LIBUSB_ERROR_NOT_SUPPORTED;
1599 else if (errno == EINVAL)
1600 return LIBUSB_ERROR_INVALID_PARAM;
1601 else if (errno == ENODEV)
1602 return LIBUSB_ERROR_NO_DEVICE;
1604 usbi_err(HANDLE_CTX(handle),
1605 "streams-ioctl failed error %d errno %d", r, errno);
1606 return LIBUSB_ERROR_OTHER;
1611 static int op_alloc_streams(struct libusb_device_handle *handle,
1612 uint32_t num_streams, unsigned char *endpoints, int num_endpoints)
1614 return do_streams_ioctl(handle, IOCTL_USBFS_ALLOC_STREAMS,
1615 num_streams, endpoints, num_endpoints);
1618 static int op_free_streams(struct libusb_device_handle *handle,
1619 unsigned char *endpoints, int num_endpoints)
1621 return do_streams_ioctl(handle, IOCTL_USBFS_FREE_STREAMS, 0,
1622 endpoints, num_endpoints);
1625 static unsigned char *op_dev_mem_alloc(struct libusb_device_handle *handle,
1628 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
1629 unsigned char *buffer = (unsigned char *)mmap(NULL, len,
1630 PROT_READ | PROT_WRITE, MAP_SHARED, hpriv->fd, 0);
1631 if (buffer == MAP_FAILED) {
1632 usbi_err(HANDLE_CTX(handle), "alloc dev mem failed errno %d",
1639 static int op_dev_mem_free(struct libusb_device_handle *handle,
1640 unsigned char *buffer, size_t len)
1642 if (munmap(buffer, len) != 0) {
1643 usbi_err(HANDLE_CTX(handle), "free dev mem failed errno %d",
1645 return LIBUSB_ERROR_OTHER;
1647 return LIBUSB_SUCCESS;
1651 static int op_kernel_driver_active(struct libusb_device_handle *handle,
1654 int fd = _device_handle_priv(handle)->fd;
1655 struct usbfs_getdriver getdrv;
1658 getdrv.interface = interface;
1659 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1661 if (errno == ENODATA)
1663 else if (errno == ENODEV)
1664 return LIBUSB_ERROR_NO_DEVICE;
1666 usbi_err(HANDLE_CTX(handle),
1667 "get driver failed error %d errno %d", r, errno);
1668 return LIBUSB_ERROR_OTHER;
1671 return (strcmp(getdrv.driver, "usbfs") == 0) ? 0 : 1;
1674 static int op_detach_kernel_driver(struct libusb_device_handle *handle,
1677 int fd = _device_handle_priv(handle)->fd;
1678 struct usbfs_ioctl command;
1679 struct usbfs_getdriver getdrv;
1682 command.ifno = interface;
1683 command.ioctl_code = IOCTL_USBFS_DISCONNECT;
1684 command.data = NULL;
1686 getdrv.interface = interface;
1687 r = ioctl(fd, IOCTL_USBFS_GETDRIVER, &getdrv);
1688 if (r == 0 && strcmp(getdrv.driver, "usbfs") == 0)
1689 return LIBUSB_ERROR_NOT_FOUND;
1691 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1693 if (errno == ENODATA)
1694 return LIBUSB_ERROR_NOT_FOUND;
1695 else if (errno == EINVAL)
1696 return LIBUSB_ERROR_INVALID_PARAM;
1697 else if (errno == ENODEV)
1698 return LIBUSB_ERROR_NO_DEVICE;
1700 usbi_err(HANDLE_CTX(handle),
1701 "detach failed error %d errno %d", r, errno);
1702 return LIBUSB_ERROR_OTHER;
1708 static int op_attach_kernel_driver(struct libusb_device_handle *handle,
1711 int fd = _device_handle_priv(handle)->fd;
1712 struct usbfs_ioctl command;
1715 command.ifno = interface;
1716 command.ioctl_code = IOCTL_USBFS_CONNECT;
1717 command.data = NULL;
1719 r = ioctl(fd, IOCTL_USBFS_IOCTL, &command);
1721 if (errno == ENODATA)
1722 return LIBUSB_ERROR_NOT_FOUND;
1723 else if (errno == EINVAL)
1724 return LIBUSB_ERROR_INVALID_PARAM;
1725 else if (errno == ENODEV)
1726 return LIBUSB_ERROR_NO_DEVICE;
1727 else if (errno == EBUSY)
1728 return LIBUSB_ERROR_BUSY;
1730 usbi_err(HANDLE_CTX(handle),
1731 "attach failed error %d errno %d", r, errno);
1732 return LIBUSB_ERROR_OTHER;
1733 } else if (r == 0) {
1734 return LIBUSB_ERROR_NOT_FOUND;
1740 static int detach_kernel_driver_and_claim(struct libusb_device_handle *handle,
1743 struct usbfs_disconnect_claim dc;
1744 int r, fd = _device_handle_priv(handle)->fd;
1746 dc.interface = interface;
1747 strcpy(dc.driver, "usbfs");
1748 dc.flags = USBFS_DISCONNECT_CLAIM_EXCEPT_DRIVER;
1749 r = ioctl(fd, IOCTL_USBFS_DISCONNECT_CLAIM, &dc);
1750 if (r == 0 || (r != 0 && errno != ENOTTY)) {
1756 return LIBUSB_ERROR_BUSY;
1758 return LIBUSB_ERROR_INVALID_PARAM;
1760 return LIBUSB_ERROR_NO_DEVICE;
1762 usbi_err(HANDLE_CTX(handle),
1763 "disconnect-and-claim failed errno %d", errno);
1764 return LIBUSB_ERROR_OTHER;
1767 /* Fallback code for kernels which don't support the
1768 disconnect-and-claim ioctl */
1769 r = op_detach_kernel_driver(handle, interface);
1770 if (r != 0 && r != LIBUSB_ERROR_NOT_FOUND)
1773 return claim_interface(handle, interface);
1776 static int op_claim_interface(struct libusb_device_handle *handle, int iface)
1778 if (handle->auto_detach_kernel_driver)
1779 return detach_kernel_driver_and_claim(handle, iface);
1781 return claim_interface(handle, iface);
1784 static int op_release_interface(struct libusb_device_handle *handle, int iface)
1788 r = release_interface(handle, iface);
1792 if (handle->auto_detach_kernel_driver)
1793 op_attach_kernel_driver(handle, iface);
1798 static void op_destroy_device(struct libusb_device *dev)
1800 struct linux_device_priv *priv = _device_priv(dev);
1801 if (priv->descriptors)
1802 free(priv->descriptors);
1803 if (priv->sysfs_dir)
1804 free(priv->sysfs_dir);
1807 /* URBs are discarded in reverse order of submission to avoid races. */
1808 static int discard_urbs(struct usbi_transfer *itransfer, int first, int last_plus_one)
1810 struct libusb_transfer *transfer =
1811 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1812 struct linux_transfer_priv *tpriv =
1813 usbi_transfer_get_os_priv(itransfer);
1814 struct linux_device_handle_priv *dpriv =
1815 _device_handle_priv(transfer->dev_handle);
1817 struct usbfs_urb *urb;
1819 for (i = last_plus_one - 1; i >= first; i--) {
1820 if (LIBUSB_TRANSFER_TYPE_ISOCHRONOUS == transfer->type)
1821 urb = tpriv->iso_urbs[i];
1823 urb = &tpriv->urbs[i];
1825 if (0 == ioctl(dpriv->fd, IOCTL_USBFS_DISCARDURB, urb))
1828 if (EINVAL == errno) {
1829 usbi_dbg("URB not found --> assuming ready to be reaped");
1830 if (i == (last_plus_one - 1))
1831 ret = LIBUSB_ERROR_NOT_FOUND;
1832 } else if (ENODEV == errno) {
1833 usbi_dbg("Device not found for URB --> assuming ready to be reaped");
1834 ret = LIBUSB_ERROR_NO_DEVICE;
1836 usbi_warn(TRANSFER_CTX(transfer),
1837 "unrecognised discard errno %d", errno);
1838 ret = LIBUSB_ERROR_OTHER;
1844 static void free_iso_urbs(struct linux_transfer_priv *tpriv)
1847 for (i = 0; i < tpriv->num_urbs; i++) {
1848 struct usbfs_urb *urb = tpriv->iso_urbs[i];
1854 free(tpriv->iso_urbs);
1855 tpriv->iso_urbs = NULL;
1858 static int submit_bulk_transfer(struct usbi_transfer *itransfer)
1860 struct libusb_transfer *transfer =
1861 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
1862 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
1863 struct linux_device_handle_priv *dpriv =
1864 _device_handle_priv(transfer->dev_handle);
1865 struct usbfs_urb *urbs;
1866 int is_out = (transfer->endpoint & LIBUSB_ENDPOINT_DIR_MASK)
1867 == LIBUSB_ENDPOINT_OUT;
1868 int bulk_buffer_len, use_bulk_continuation;
1872 if (is_out && (transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET) &&
1873 !(dpriv->caps & USBFS_CAP_ZERO_PACKET))
1874 return LIBUSB_ERROR_NOT_SUPPORTED;
1877 * Older versions of usbfs place a 16kb limit on bulk URBs. We work
1878 * around this by splitting large transfers into 16k blocks, and then
1879 * submit all urbs at once. it would be simpler to submit one urb at
1880 * a time, but there is a big performance gain doing it this way.
1882 * Newer versions lift the 16k limit (USBFS_CAP_NO_PACKET_SIZE_LIM),
1883 * using arbritary large transfers can still be a bad idea though, as
1884 * the kernel needs to allocate physical contiguous memory for this,
1885 * which may fail for large buffers.
1887 * The kernel solves this problem by splitting the transfer into
1888 * blocks itself when the host-controller is scatter-gather capable
1889 * (USBFS_CAP_BULK_SCATTER_GATHER), which most controllers are.
1891 * Last, there is the issue of short-transfers when splitting, for
1892 * short split-transfers to work reliable USBFS_CAP_BULK_CONTINUATION
1893 * is needed, but this is not always available.
1895 if (dpriv->caps & USBFS_CAP_BULK_SCATTER_GATHER) {
1896 /* Good! Just submit everything in one go */
1897 bulk_buffer_len = transfer->length ? transfer->length : 1;
1898 use_bulk_continuation = 0;
1899 } else if (dpriv->caps & USBFS_CAP_BULK_CONTINUATION) {
1900 /* Split the transfers and use bulk-continuation to
1901 avoid issues with short-transfers */
1902 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1903 use_bulk_continuation = 1;
1904 } else if (dpriv->caps & USBFS_CAP_NO_PACKET_SIZE_LIM) {
1905 /* Don't split, assume the kernel can alloc the buffer
1906 (otherwise the submit will fail with -ENOMEM) */
1907 bulk_buffer_len = transfer->length ? transfer->length : 1;
1908 use_bulk_continuation = 0;
1910 /* Bad, splitting without bulk-continuation, short transfers
1911 which end before the last urb will not work reliable! */
1912 /* Note we don't warn here as this is "normal" on kernels <
1913 2.6.32 and not a problem for most applications */
1914 bulk_buffer_len = MAX_BULK_BUFFER_LENGTH;
1915 use_bulk_continuation = 0;
1918 int num_urbs = transfer->length / bulk_buffer_len;
1919 int last_urb_partial = 0;
1921 if (transfer->length == 0) {
1923 } else if ((transfer->length % bulk_buffer_len) > 0) {
1924 last_urb_partial = 1;
1927 usbi_dbg("need %d urbs for new transfer with length %d", num_urbs,
1929 urbs = calloc(num_urbs, sizeof(struct usbfs_urb));
1931 return LIBUSB_ERROR_NO_MEM;
1933 tpriv->num_urbs = num_urbs;
1934 tpriv->num_retired = 0;
1935 tpriv->reap_action = NORMAL;
1936 tpriv->reap_status = LIBUSB_TRANSFER_COMPLETED;
1938 for (i = 0; i < num_urbs; i++) {
1939 struct usbfs_urb *urb = &urbs[i];
1940 urb->usercontext = itransfer;
1941 switch (transfer->type) {
1942 case LIBUSB_TRANSFER_TYPE_BULK:
1943 urb->type = USBFS_URB_TYPE_BULK;
1946 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
1947 urb->type = USBFS_URB_TYPE_BULK;
1948 urb->stream_id = itransfer->stream_id;
1950 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
1951 urb->type = USBFS_URB_TYPE_INTERRUPT;
1954 urb->endpoint = transfer->endpoint;
1955 urb->buffer = transfer->buffer + (i * bulk_buffer_len);
1956 /* don't set the short not ok flag for the last URB */
1957 if (use_bulk_continuation && !is_out && (i < num_urbs - 1))
1958 urb->flags = USBFS_URB_SHORT_NOT_OK;
1959 if (i == num_urbs - 1 && last_urb_partial)
1960 urb->buffer_length = transfer->length % bulk_buffer_len;
1961 else if (transfer->length == 0)
1962 urb->buffer_length = 0;
1964 urb->buffer_length = bulk_buffer_len;
1966 if (i > 0 && use_bulk_continuation)
1967 urb->flags |= USBFS_URB_BULK_CONTINUATION;
1969 /* we have already checked that the flag is supported */
1970 if (is_out && i == num_urbs - 1 &&
1971 transfer->flags & LIBUSB_TRANSFER_ADD_ZERO_PACKET)
1972 urb->flags |= USBFS_URB_ZERO_PACKET;
1974 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
1976 if (errno == ENODEV) {
1977 r = LIBUSB_ERROR_NO_DEVICE;
1979 usbi_err(TRANSFER_CTX(transfer),
1980 "submiturb failed error %d errno=%d", r, errno);
1981 r = LIBUSB_ERROR_IO;
1984 /* if the first URB submission fails, we can simply free up and
1985 * return failure immediately. */
1987 usbi_dbg("first URB failed, easy peasy");
1993 /* if it's not the first URB that failed, the situation is a bit
1994 * tricky. we may need to discard all previous URBs. there are
1996 * - discarding is asynchronous - discarded urbs will be reaped
1997 * later. the user must not have freed the transfer when the
1998 * discarded URBs are reaped, otherwise libusb will be using
2000 * - the earlier URBs may have completed successfully and we do
2001 * not want to throw away any data.
2002 * - this URB failing may be no error; EREMOTEIO means that
2003 * this transfer simply didn't need all the URBs we submitted
2004 * so, we report that the transfer was submitted successfully and
2005 * in case of error we discard all previous URBs. later when
2006 * the final reap completes we can report error to the user,
2007 * or success if an earlier URB was completed successfully.
2009 tpriv->reap_action = EREMOTEIO == errno ? COMPLETED_EARLY : SUBMIT_FAILED;
2011 /* The URBs we haven't submitted yet we count as already
2013 tpriv->num_retired += num_urbs - i;
2015 /* If we completed short then don't try to discard. */
2016 if (COMPLETED_EARLY == tpriv->reap_action)
2019 discard_urbs(itransfer, 0, i);
2021 usbi_dbg("reporting successful submission but waiting for %d "
2022 "discards before reporting error", i);
2030 static int submit_iso_transfer(struct usbi_transfer *itransfer)
2032 struct libusb_transfer *transfer =
2033 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2034 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2035 struct linux_device_handle_priv *dpriv =
2036 _device_handle_priv(transfer->dev_handle);
2037 struct usbfs_urb **urbs;
2039 int num_packets = transfer->num_iso_packets;
2041 int this_urb_len = 0;
2043 int packet_offset = 0;
2044 unsigned int packet_len;
2045 unsigned char *urb_buffer = transfer->buffer;
2047 /* usbfs places arbitrary limits on iso URBs. this limit has changed
2048 * at least three times, and it's difficult to accurately detect which
2049 * limit this running kernel might impose. so we attempt to submit
2050 * whatever the user has provided. if the kernel rejects the request
2051 * due to its size, we return an error indicating such to the user.
2054 /* calculate how many URBs we need */
2055 for (i = 0; i < num_packets; i++) {
2056 unsigned int space_remaining = MAX_ISO_BUFFER_LENGTH - this_urb_len;
2057 packet_len = transfer->iso_packet_desc[i].length;
2059 if (packet_len > space_remaining) {
2061 this_urb_len = packet_len;
2062 /* check that we can actually support this packet length */
2063 if (this_urb_len > MAX_ISO_BUFFER_LENGTH)
2064 return LIBUSB_ERROR_INVALID_PARAM;
2066 this_urb_len += packet_len;
2069 usbi_dbg("need %d %dk URBs for transfer", num_urbs, MAX_ISO_BUFFER_LENGTH / 1024);
2071 urbs = calloc(num_urbs, sizeof(*urbs));
2073 return LIBUSB_ERROR_NO_MEM;
2075 tpriv->iso_urbs = urbs;
2076 tpriv->num_urbs = num_urbs;
2077 tpriv->num_retired = 0;
2078 tpriv->reap_action = NORMAL;
2079 tpriv->iso_packet_offset = 0;
2081 /* allocate + initialize each URB with the correct number of packets */
2082 for (i = 0; i < num_urbs; i++) {
2083 struct usbfs_urb *urb;
2084 unsigned int space_remaining_in_urb = MAX_ISO_BUFFER_LENGTH;
2085 int urb_packet_offset = 0;
2086 unsigned char *urb_buffer_orig = urb_buffer;
2090 /* swallow up all the packets we can fit into this URB */
2091 while (packet_offset < transfer->num_iso_packets) {
2092 packet_len = transfer->iso_packet_desc[packet_offset].length;
2093 if (packet_len <= space_remaining_in_urb) {
2095 urb_packet_offset++;
2097 space_remaining_in_urb -= packet_len;
2098 urb_buffer += packet_len;
2100 /* it can't fit, save it for the next URB */
2105 alloc_size = sizeof(*urb)
2106 + (urb_packet_offset * sizeof(struct usbfs_iso_packet_desc));
2107 urb = calloc(1, alloc_size);
2109 free_iso_urbs(tpriv);
2110 return LIBUSB_ERROR_NO_MEM;
2114 /* populate packet lengths */
2115 for (j = 0, k = packet_offset - urb_packet_offset;
2116 k < packet_offset; k++, j++) {
2117 packet_len = transfer->iso_packet_desc[k].length;
2118 urb->iso_frame_desc[j].length = packet_len;
2121 urb->usercontext = itransfer;
2122 urb->type = USBFS_URB_TYPE_ISO;
2123 /* FIXME: interface for non-ASAP data? */
2124 urb->flags = USBFS_URB_ISO_ASAP;
2125 urb->endpoint = transfer->endpoint;
2126 urb->number_of_packets = urb_packet_offset;
2127 urb->buffer = urb_buffer_orig;
2131 for (i = 0; i < num_urbs; i++) {
2132 int r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urbs[i]);
2134 if (errno == ENODEV) {
2135 r = LIBUSB_ERROR_NO_DEVICE;
2136 } else if (errno == EINVAL) {
2137 usbi_warn(TRANSFER_CTX(transfer),
2138 "submiturb failed, transfer too large");
2139 r = LIBUSB_ERROR_INVALID_PARAM;
2141 usbi_err(TRANSFER_CTX(transfer),
2142 "submiturb failed error %d errno=%d", r, errno);
2143 r = LIBUSB_ERROR_IO;
2146 /* if the first URB submission fails, we can simply free up and
2147 * return failure immediately. */
2149 usbi_dbg("first URB failed, easy peasy");
2150 free_iso_urbs(tpriv);
2154 /* if it's not the first URB that failed, the situation is a bit
2155 * tricky. we must discard all previous URBs. there are
2157 * - discarding is asynchronous - discarded urbs will be reaped
2158 * later. the user must not have freed the transfer when the
2159 * discarded URBs are reaped, otherwise libusb will be using
2161 * - the earlier URBs may have completed successfully and we do
2162 * not want to throw away any data.
2163 * so, in this case we discard all the previous URBs BUT we report
2164 * that the transfer was submitted successfully. then later when
2165 * the final discard completes we can report error to the user.
2167 tpriv->reap_action = SUBMIT_FAILED;
2169 /* The URBs we haven't submitted yet we count as already
2171 tpriv->num_retired = num_urbs - i;
2172 discard_urbs(itransfer, 0, i);
2174 usbi_dbg("reporting successful submission but waiting for %d "
2175 "discards before reporting error", i);
2183 static int submit_control_transfer(struct usbi_transfer *itransfer)
2185 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2186 struct libusb_transfer *transfer =
2187 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2188 struct linux_device_handle_priv *dpriv =
2189 _device_handle_priv(transfer->dev_handle);
2190 struct usbfs_urb *urb;
2193 if (transfer->length - LIBUSB_CONTROL_SETUP_SIZE > MAX_CTRL_BUFFER_LENGTH)
2194 return LIBUSB_ERROR_INVALID_PARAM;
2196 urb = calloc(1, sizeof(struct usbfs_urb));
2198 return LIBUSB_ERROR_NO_MEM;
2200 tpriv->num_urbs = 1;
2201 tpriv->reap_action = NORMAL;
2203 urb->usercontext = itransfer;
2204 urb->type = USBFS_URB_TYPE_CONTROL;
2205 urb->endpoint = transfer->endpoint;
2206 urb->buffer = transfer->buffer;
2207 urb->buffer_length = transfer->length;
2209 r = ioctl(dpriv->fd, IOCTL_USBFS_SUBMITURB, urb);
2213 if (errno == ENODEV)
2214 return LIBUSB_ERROR_NO_DEVICE;
2216 usbi_err(TRANSFER_CTX(transfer),
2217 "submiturb failed error %d errno=%d", r, errno);
2218 return LIBUSB_ERROR_IO;
2223 static int op_submit_transfer(struct usbi_transfer *itransfer)
2225 struct libusb_transfer *transfer =
2226 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2228 switch (transfer->type) {
2229 case LIBUSB_TRANSFER_TYPE_CONTROL:
2230 return submit_control_transfer(itransfer);
2231 case LIBUSB_TRANSFER_TYPE_BULK:
2232 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2233 return submit_bulk_transfer(itransfer);
2234 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2235 return submit_bulk_transfer(itransfer);
2236 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2237 return submit_iso_transfer(itransfer);
2239 usbi_err(TRANSFER_CTX(transfer),
2240 "unknown endpoint type %d", transfer->type);
2241 return LIBUSB_ERROR_INVALID_PARAM;
2245 static int op_cancel_transfer(struct usbi_transfer *itransfer)
2247 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2248 struct libusb_transfer *transfer =
2249 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2253 return LIBUSB_ERROR_NOT_FOUND;
2255 r = discard_urbs(itransfer, 0, tpriv->num_urbs);
2259 switch (transfer->type) {
2260 case LIBUSB_TRANSFER_TYPE_BULK:
2261 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2262 if (tpriv->reap_action == ERROR)
2264 /* else, fall through */
2266 tpriv->reap_action = CANCELLED;
2272 static void op_clear_transfer_priv(struct usbi_transfer *itransfer)
2274 struct libusb_transfer *transfer =
2275 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2276 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2278 /* urbs can be freed also in submit_transfer so lock mutex first */
2279 switch (transfer->type) {
2280 case LIBUSB_TRANSFER_TYPE_CONTROL:
2281 case LIBUSB_TRANSFER_TYPE_BULK:
2282 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2283 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2289 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2290 if (tpriv->iso_urbs) {
2291 free_iso_urbs(tpriv);
2292 tpriv->iso_urbs = NULL;
2296 usbi_err(TRANSFER_CTX(transfer),
2297 "unknown endpoint type %d", transfer->type);
2301 static int handle_bulk_completion(struct usbi_transfer *itransfer,
2302 struct usbfs_urb *urb)
2304 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2305 struct libusb_transfer *transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2306 int urb_idx = urb - tpriv->urbs;
2308 usbi_mutex_lock(&itransfer->lock);
2309 usbi_dbg("handling completion status %d of bulk urb %d/%d", urb->status,
2310 urb_idx + 1, tpriv->num_urbs);
2312 tpriv->num_retired++;
2314 if (tpriv->reap_action != NORMAL) {
2315 /* cancelled, submit_fail, or completed early */
2316 usbi_dbg("abnormal reap: urb status %d", urb->status);
2318 /* even though we're in the process of cancelling, it's possible that
2319 * we may receive some data in these URBs that we don't want to lose.
2321 * 1. while the kernel is cancelling all the packets that make up an
2322 * URB, a few of them might complete. so we get back a successful
2323 * cancellation *and* some data.
2324 * 2. we receive a short URB which marks the early completion condition,
2325 * so we start cancelling the remaining URBs. however, we're too
2326 * slow and another URB completes (or at least completes partially).
2327 * (this can't happen since we always use BULK_CONTINUATION.)
2329 * When this happens, our objectives are not to lose any "surplus" data,
2330 * and also to stick it at the end of the previously-received data
2331 * (closing any holes), so that libusb reports the total amount of
2332 * transferred data and presents it in a contiguous chunk.
2334 if (urb->actual_length > 0) {
2335 unsigned char *target = transfer->buffer + itransfer->transferred;
2336 usbi_dbg("received %d bytes of surplus data", urb->actual_length);
2337 if (urb->buffer != target) {
2338 usbi_dbg("moving surplus data from offset %d to offset %d",
2339 (unsigned char *) urb->buffer - transfer->buffer,
2340 target - transfer->buffer);
2341 memmove(target, urb->buffer, urb->actual_length);
2343 itransfer->transferred += urb->actual_length;
2346 if (tpriv->num_retired == tpriv->num_urbs) {
2347 usbi_dbg("abnormal reap: last URB handled, reporting");
2348 if (tpriv->reap_action != COMPLETED_EARLY &&
2349 tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2350 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2356 itransfer->transferred += urb->actual_length;
2358 /* Many of these errors can occur on *any* urb of a multi-urb
2359 * transfer. When they do, we tear down the rest of the transfer.
2361 switch (urb->status) {
2364 case -EREMOTEIO: /* short transfer */
2366 case -ENOENT: /* cancelled */
2371 usbi_dbg("device removed");
2372 tpriv->reap_status = LIBUSB_TRANSFER_NO_DEVICE;
2373 goto cancel_remaining;
2375 usbi_dbg("detected endpoint stall");
2376 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2377 tpriv->reap_status = LIBUSB_TRANSFER_STALL;
2378 goto cancel_remaining;
2380 /* overflow can only ever occur in the last urb */
2381 usbi_dbg("overflow, actual_length=%d", urb->actual_length);
2382 if (tpriv->reap_status == LIBUSB_TRANSFER_COMPLETED)
2383 tpriv->reap_status = LIBUSB_TRANSFER_OVERFLOW;
2390 usbi_dbg("low level error %d", urb->status);
2391 tpriv->reap_action = ERROR;
2392 goto cancel_remaining;
2394 usbi_warn(ITRANSFER_CTX(itransfer),
2395 "unrecognised urb status %d", urb->status);
2396 tpriv->reap_action = ERROR;
2397 goto cancel_remaining;
2400 /* if we're the last urb or we got less data than requested then we're
2402 if (urb_idx == tpriv->num_urbs - 1) {
2403 usbi_dbg("last URB in transfer --> complete!");
2405 } else if (urb->actual_length < urb->buffer_length) {
2406 usbi_dbg("short transfer %d/%d --> complete!",
2407 urb->actual_length, urb->buffer_length);
2408 if (tpriv->reap_action == NORMAL)
2409 tpriv->reap_action = COMPLETED_EARLY;
2414 if (ERROR == tpriv->reap_action && LIBUSB_TRANSFER_COMPLETED == tpriv->reap_status)
2415 tpriv->reap_status = LIBUSB_TRANSFER_ERROR;
2417 if (tpriv->num_retired == tpriv->num_urbs) /* nothing to cancel */
2420 /* cancel remaining urbs and wait for their completion before
2421 * reporting results */
2422 discard_urbs(itransfer, urb_idx + 1, tpriv->num_urbs);
2425 usbi_mutex_unlock(&itransfer->lock);
2431 usbi_mutex_unlock(&itransfer->lock);
2432 return CANCELLED == tpriv->reap_action ?
2433 usbi_handle_transfer_cancellation(itransfer) :
2434 usbi_handle_transfer_completion(itransfer, tpriv->reap_status);
2437 static int handle_iso_completion(struct usbi_transfer *itransfer,
2438 struct usbfs_urb *urb)
2440 struct libusb_transfer *transfer =
2441 USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2442 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2443 int num_urbs = tpriv->num_urbs;
2446 enum libusb_transfer_status status = LIBUSB_TRANSFER_COMPLETED;
2448 usbi_mutex_lock(&itransfer->lock);
2449 for (i = 0; i < num_urbs; i++) {
2450 if (urb == tpriv->iso_urbs[i]) {
2456 usbi_err(TRANSFER_CTX(transfer), "could not locate urb!");
2457 usbi_mutex_unlock(&itransfer->lock);
2458 return LIBUSB_ERROR_NOT_FOUND;
2461 usbi_dbg("handling completion status %d of iso urb %d/%d", urb->status,
2464 /* copy isochronous results back in */
2466 for (i = 0; i < urb->number_of_packets; i++) {
2467 struct usbfs_iso_packet_desc *urb_desc = &urb->iso_frame_desc[i];
2468 struct libusb_iso_packet_descriptor *lib_desc =
2469 &transfer->iso_packet_desc[tpriv->iso_packet_offset++];
2470 lib_desc->status = LIBUSB_TRANSFER_COMPLETED;
2471 switch (urb_desc->status) {
2474 case -ENOENT: /* cancelled */
2479 usbi_dbg("device removed");
2480 lib_desc->status = LIBUSB_TRANSFER_NO_DEVICE;
2483 usbi_dbg("detected endpoint stall");
2484 lib_desc->status = LIBUSB_TRANSFER_STALL;
2487 usbi_dbg("overflow error");
2488 lib_desc->status = LIBUSB_TRANSFER_OVERFLOW;
2496 usbi_dbg("low-level USB error %d", urb_desc->status);
2497 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2500 usbi_warn(TRANSFER_CTX(transfer),
2501 "unrecognised urb status %d", urb_desc->status);
2502 lib_desc->status = LIBUSB_TRANSFER_ERROR;
2505 lib_desc->actual_length = urb_desc->actual_length;
2508 tpriv->num_retired++;
2510 if (tpriv->reap_action != NORMAL) { /* cancelled or submit_fail */
2511 usbi_dbg("CANCEL: urb status %d", urb->status);
2513 if (tpriv->num_retired == num_urbs) {
2514 usbi_dbg("CANCEL: last URB handled, reporting");
2515 free_iso_urbs(tpriv);
2516 if (tpriv->reap_action == CANCELLED) {
2517 usbi_mutex_unlock(&itransfer->lock);
2518 return usbi_handle_transfer_cancellation(itransfer);
2520 usbi_mutex_unlock(&itransfer->lock);
2521 return usbi_handle_transfer_completion(itransfer,
2522 LIBUSB_TRANSFER_ERROR);
2528 switch (urb->status) {
2531 case -ENOENT: /* cancelled */
2535 usbi_dbg("device removed");
2536 status = LIBUSB_TRANSFER_NO_DEVICE;
2539 usbi_warn(TRANSFER_CTX(transfer),
2540 "unrecognised urb status %d", urb->status);
2541 status = LIBUSB_TRANSFER_ERROR;
2545 /* if we're the last urb then we're done */
2546 if (urb_idx == num_urbs) {
2547 usbi_dbg("last URB in transfer --> complete!");
2548 free_iso_urbs(tpriv);
2549 usbi_mutex_unlock(&itransfer->lock);
2550 return usbi_handle_transfer_completion(itransfer, status);
2554 usbi_mutex_unlock(&itransfer->lock);
2558 static int handle_control_completion(struct usbi_transfer *itransfer,
2559 struct usbfs_urb *urb)
2561 struct linux_transfer_priv *tpriv = usbi_transfer_get_os_priv(itransfer);
2564 usbi_mutex_lock(&itransfer->lock);
2565 usbi_dbg("handling completion status %d", urb->status);
2567 itransfer->transferred += urb->actual_length;
2569 if (tpriv->reap_action == CANCELLED) {
2570 if (urb->status != 0 && urb->status != -ENOENT)
2571 usbi_warn(ITRANSFER_CTX(itransfer),
2572 "cancel: unrecognised urb status %d", urb->status);
2575 usbi_mutex_unlock(&itransfer->lock);
2576 return usbi_handle_transfer_cancellation(itransfer);
2579 switch (urb->status) {
2581 status = LIBUSB_TRANSFER_COMPLETED;
2583 case -ENOENT: /* cancelled */
2584 status = LIBUSB_TRANSFER_CANCELLED;
2588 usbi_dbg("device removed");
2589 status = LIBUSB_TRANSFER_NO_DEVICE;
2592 usbi_dbg("unsupported control request");
2593 status = LIBUSB_TRANSFER_STALL;
2596 usbi_dbg("control overflow error");
2597 status = LIBUSB_TRANSFER_OVERFLOW;
2604 usbi_dbg("low-level bus error occurred");
2605 status = LIBUSB_TRANSFER_ERROR;
2608 usbi_warn(ITRANSFER_CTX(itransfer),
2609 "unrecognised urb status %d", urb->status);
2610 status = LIBUSB_TRANSFER_ERROR;
2616 usbi_mutex_unlock(&itransfer->lock);
2617 return usbi_handle_transfer_completion(itransfer, status);
2620 static int reap_for_handle(struct libusb_device_handle *handle)
2622 struct linux_device_handle_priv *hpriv = _device_handle_priv(handle);
2624 struct usbfs_urb *urb;
2625 struct usbi_transfer *itransfer;
2626 struct libusb_transfer *transfer;
2628 r = ioctl(hpriv->fd, IOCTL_USBFS_REAPURBNDELAY, &urb);
2629 if (r == -1 && errno == EAGAIN)
2632 if (errno == ENODEV)
2633 return LIBUSB_ERROR_NO_DEVICE;
2635 usbi_err(HANDLE_CTX(handle), "reap failed error %d errno=%d",
2637 return LIBUSB_ERROR_IO;
2640 itransfer = urb->usercontext;
2641 transfer = USBI_TRANSFER_TO_LIBUSB_TRANSFER(itransfer);
2643 usbi_dbg("urb type=%d status=%d transferred=%d", urb->type, urb->status,
2644 urb->actual_length);
2646 switch (transfer->type) {
2647 case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
2648 return handle_iso_completion(itransfer, urb);
2649 case LIBUSB_TRANSFER_TYPE_BULK:
2650 case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
2651 case LIBUSB_TRANSFER_TYPE_INTERRUPT:
2652 return handle_bulk_completion(itransfer, urb);
2653 case LIBUSB_TRANSFER_TYPE_CONTROL:
2654 return handle_control_completion(itransfer, urb);
2656 usbi_err(HANDLE_CTX(handle), "unrecognised endpoint type %x",
2658 return LIBUSB_ERROR_OTHER;
2662 static int op_handle_events(struct libusb_context *ctx,
2663 struct pollfd *fds, POLL_NFDS_TYPE nfds, int num_ready)
2668 usbi_mutex_lock(&ctx->open_devs_lock);
2669 for (i = 0; i < nfds && num_ready > 0; i++) {
2670 struct pollfd *pollfd = &fds[i];
2671 struct libusb_device_handle *handle;
2672 struct linux_device_handle_priv *hpriv = NULL;
2674 if (!pollfd->revents)
2678 list_for_each_entry(handle, &ctx->open_devs, list, struct libusb_device_handle) {
2679 hpriv = _device_handle_priv(handle);
2680 if (hpriv->fd == pollfd->fd)
2684 if (!hpriv || hpriv->fd != pollfd->fd) {
2685 usbi_err(ctx, "cannot find handle for fd %d",
2690 if (pollfd->revents & POLLERR) {
2691 /* remove the fd from the pollfd set so that it doesn't continuously
2692 * trigger an event, and flag that it has been removed so op_close()
2693 * doesn't try to remove it a second time */
2694 usbi_remove_pollfd(HANDLE_CTX(handle), hpriv->fd);
2695 hpriv->fd_removed = 1;
2697 /* device will still be marked as attached if hotplug monitor thread
2698 * hasn't processed remove event yet */
2699 usbi_mutex_static_lock(&linux_hotplug_lock);
2700 if (handle->dev->attached)
2701 linux_device_disconnected(handle->dev->bus_number,
2702 handle->dev->device_address);
2703 usbi_mutex_static_unlock(&linux_hotplug_lock);
2705 if (hpriv->caps & USBFS_CAP_REAP_AFTER_DISCONNECT) {
2707 r = reap_for_handle(handle);
2711 usbi_handle_disconnect(handle);
2716 r = reap_for_handle(handle);
2718 if (r == 1 || r == LIBUSB_ERROR_NO_DEVICE)
2726 usbi_mutex_unlock(&ctx->open_devs_lock);
2730 static int op_clock_gettime(int clk_id, struct timespec *tp)
2733 case USBI_CLOCK_MONOTONIC:
2734 return clock_gettime(monotonic_clkid, tp);
2735 case USBI_CLOCK_REALTIME:
2736 return clock_gettime(CLOCK_REALTIME, tp);
2738 return LIBUSB_ERROR_INVALID_PARAM;
2742 #ifdef USBI_TIMERFD_AVAILABLE
2743 static clockid_t op_get_timerfd_clockid(void)
2745 return monotonic_clkid;
2750 const struct usbi_os_backend linux_usbfs_backend = {
2751 .name = "Linux usbfs",
2752 .caps = USBI_CAP_HAS_HID_ACCESS|USBI_CAP_SUPPORTS_DETACH_KERNEL_DRIVER,
2755 .get_device_list = NULL,
2756 .hotplug_poll = op_hotplug_poll,
2757 .get_device_descriptor = op_get_device_descriptor,
2758 .get_active_config_descriptor = op_get_active_config_descriptor,
2759 .get_config_descriptor = op_get_config_descriptor,
2760 .get_config_descriptor_by_value = op_get_config_descriptor_by_value,
2764 .get_configuration = op_get_configuration,
2765 .set_configuration = op_set_configuration,
2766 .claim_interface = op_claim_interface,
2767 .release_interface = op_release_interface,
2769 .set_interface_altsetting = op_set_interface,
2770 .clear_halt = op_clear_halt,
2771 .reset_device = op_reset_device,
2773 .alloc_streams = op_alloc_streams,
2774 .free_streams = op_free_streams,
2776 .dev_mem_alloc = op_dev_mem_alloc,
2777 .dev_mem_free = op_dev_mem_free,
2779 .kernel_driver_active = op_kernel_driver_active,
2780 .detach_kernel_driver = op_detach_kernel_driver,
2781 .attach_kernel_driver = op_attach_kernel_driver,
2783 .destroy_device = op_destroy_device,
2785 .submit_transfer = op_submit_transfer,
2786 .cancel_transfer = op_cancel_transfer,
2787 .clear_transfer_priv = op_clear_transfer_priv,
2789 .handle_events = op_handle_events,
2791 .clock_gettime = op_clock_gettime,
2793 #ifdef USBI_TIMERFD_AVAILABLE
2794 .get_timerfd_clockid = op_get_timerfd_clockid,
2797 .device_priv_size = sizeof(struct linux_device_priv),
2798 .device_handle_priv_size = sizeof(struct linux_device_handle_priv),
2799 .transfer_priv_size = sizeof(struct linux_transfer_priv),